import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/chat_repository.dart'; import '../domain/chat_account_usage.dart'; import '../domain/chat_sessions.dart'; import '../domain/chat_transcript.dart'; import 'chat_server_queue.dart'; import 'chat_thread_cards.dart'; import 'chat_transcript_cache.dart'; /// One open conversation's transcript and live turn state. /// /// The controller attaches to exactly one session: it subscribes that session /// with `chat_subscribe`, then reads the newest history page. Pushed frames for /// any other session are ignored, a superseded or disposed read never lands, and /// a reconnect/resync replaces the held turn with the newest authoritative page /// instead of merging stale state. The server detaches subscriptions when the /// socket closes, so disposal only cancels the local stream (there is no /// `chat_unsubscribe`). /// /// Approval requests and question forms are recorded cards rather than /// messages; [ChatThreadCards] owns their frames, answers and send gates. /// /// A [cached] transcript from an earlier visit is shown at once instead of a /// loading state, but it is only a starting point: [load] still subscribes and /// reads, and the newest page replaces every cached message no live frame has /// changed since (see [refreshCachedChatHistory]). class ChatThreadController extends ChangeNotifier { ChatThreadController( this.gateway, this.sessionId, { ChatTranscriptSnapshot? cached, }) { if (cached != null) { _messages = cached.messages; _cursor = cached.cursor; _hasMore = cached.hasMore; _loaded = true; _untouchedCached = { for (final message in cached.messages) if (message['id'] != null) message['id'] as Object, }; } _subscription = gateway.frames.listen(_onFrame); } final ApiGateway gateway; final String sessionId; late final ChatRepository _repository = ChatRepository(gateway); late final ChatThreadCards _cards = ChatThreadCards( repository: _repository, sessionId: sessionId, notify: _notify, isAlive: () => !_disposed, ); StreamSubscription? _subscription; final _transcriptChanges = ChangeNotifier(); final ChatServerQueue _queue = ChatServerQueue(); /// Told about every queue body the server sends (the subscribe reply's and /// each `chat_queue` frame), so delivery states follow the server. void Function(JsonMap queue)? onQueue; List _messages = const []; bool _running = false; bool _loaded = false; bool _loading = false; bool _hasMore = false; String _cursor = ''; String _nativeTurnId = ''; String? _liveAssistantMessageId; String? _awaitingResponseOperation; JsonMap? _usage; ChatAccountUsage? _accountUsage; String? _error; bool _subscribed = false; String? _subscriptionError; bool _disposed = false; int _generation = 0; bool _resyncing = false; bool _resyncAgain = false; /// Ids of cached messages that no frame or read has confirmed yet; null once /// a read replaced the cached transcript, or when there was none. Set? _untouchedCached; /// True while the held transcript came from a successful read on the current /// connection; a socket gap clears it until the repair's read succeeds. bool _authoritative = false; /// Whether this visit opened on a cached transcript that no read has /// replaced yet. bool get showingCached => _untouchedCached != null; /// The transcript to keep for a later visit, or null when the held one is /// not backed by a successful read on the current connection. ChatTranscriptSnapshot? get snapshot => _authoritative ? ChatTranscriptSnapshot( messages: _messages, cursor: _cursor, hasMore: _hasMore, ) : null; List get messages => _messages; /// The prompts the server still holds for this session, in delivery order. List get queuedPrompts => _queue.prompts; /// The queued prompts not already drawn in the transcript (this device's /// own optimistic bubble and another device's echo are drawn in place). /// They follow the transcript, since none has reached the harness yet. List get queuedOutsideTranscript => [ for (final prompt in _queue.prompts) if (!_messages.any( (message) => message['operation_id'] == prompt['operation_id'], )) prompt, ]; /// Whether [operationId] is still waiting in the server's queue. bool isQueued(String operationId) => _queue.holds(operationId); /// Removes one queued prompt on the server. A refusal (it was already sent) /// is thrown to the caller; the queue itself only changes from the reply. Future unqueue(String operationId) async { final reply = await _repository.unqueue(sessionId, operationId); if (_disposed) return; _applyQueue(reply['chat_queue']); } /// Usage-only snapshots refresh Info, not the expensive transcript tree. Listenable get transcriptChanges => _transcriptChanges; bool get running => _running; bool get awaitingResponse => _awaitingResponseOperation != null; String? get liveAssistantMessageId => _liveAssistantMessageId; bool get loaded => _loaded; bool get loading => _loading; bool get hasMore => _hasMore; /// The server's opaque older-page cursor. Never interpreted, only passed back. String get cursor => _cursor; /// The latest recorded usage snapshot, or null before the harness reports. /// Unknown fields stay null, so a viewer can distinguish them from zero. JsonMap? get usage => _usage; /// The harness account's latest reported quota, or null while unknown. It /// is account state: a frame without one keeps the last known value. ChatAccountUsage? get accountUsage => _accountUsage; String? get error => _error; bool get subscribed => _subscribed; String? get subscriptionError => _subscriptionError; /// Every retained permission request, settled or still open, in server order. List get permissionFrames => _cards.permissions; /// Every retained question form, including answered and expired ones. List get questionForms => _cards.forms; String permissionAnswerFor(String requestId) => _cards.answerFor(requestId); String? permissionErrorFor(String requestId) => _cards.permissionErrorFor(requestId); String? questionErrorFor(String formId) => _cards.formErrorFor(formId); /// Answer one pending approval through the card collaborator. Future replyPermission(String requestId, String decision) => _cards.replyPermission(requestId, decision); /// Answer or close a pending question through the card collaborator. Future answerQuestion( String formId, Map answers, String action, ) => _cards.answerQuestion(formId, answers, action); /// Subscribes this session, then loads its newest history page. Future load() async { if (_disposed) return; final token = ++_generation; _loading = true; _error = null; _notify(); await _attach(); if (!_owned(token)) return; await _readNewest(token, replaceHeldTurn: false); } /// Reads the next older page. Only offered while the server says `has_more`; /// the cursor is the server's own `next_cursor`, passed back verbatim. Future loadOlder() async { if (_disposed || _loading || !_hasMore) return; final token = ++_generation; _loading = true; _error = null; _notify(); try { final page = await _repository.history( sessionId, cursor: _cursor, limit: 200, ); if (!_owned(token)) return; final merged = mergeChatHistory( {'messages': _messages}, page, older: true, ); _applyPage(merged); } catch (error) { if (!_owned(token)) return; _loading = false; _error = '$error'; } _notify(); } /// The reconnect/resync repair: settle the held turn, re-attach the session, /// then replace the conversation with the newest authoritative page. Activity /// replayed while re-attaching (a running step) is fresh native state /// and survives the replacement. A resync frame also lands here. Future resync() async { if (_disposed) return; if (_resyncing) { _resyncAgain = true; return; } _resyncing = true; do { _resyncAgain = false; await _resyncOnce(); } while (_resyncAgain && !_disposed); _resyncing = false; } Future _resyncOnce() async { final token = ++_generation; _loading = true; // A socket drop removed the frames feeding the turn, so no held turn may // keep claiming to run until the re-subscribe proves otherwise. _running = false; _nativeTurnId = ''; _liveAssistantMessageId = null; _awaitingResponseOperation = null; _authoritative = false; _notify(); await _attach(force: true); if (!_owned(token)) return; await _readNewest(token, replaceHeldTurn: true); } Future _readNewest(int token, {required bool replaceHeldTurn}) async { try { final page = await _repository.history(sessionId, limit: 200); if (!_owned(token)) return; if (replaceHeldTurn) { _messages = (page['messages'] as List? ?? const []) .whereType() .map((message) => Map.from(message)) .toList(); _cursor = '${page['nextCursor'] ?? ''}'; _hasMore = page['hasMore'] == true; } else if (_untouchedCached case final untouched?) { // The cached transcript was a placeholder: the page decides what it // still holds, and live arrivals since reopening are kept after it. _applyPage(refreshCachedChatHistory(_messages, page, untouched)); } else { // A live frame may have arrived while the page was loading; merge it // over the held transcript instead of replacing it. _applyPage(mergeChatHistory({'messages': _messages}, page)); } _untouchedCached = null; _authoritative = true; _loaded = true; _loading = false; _error = null; } catch (error) { if (!_owned(token)) return; // A refused read is not an empty successful history: the reason stays // visible and the held transcript is kept. _loaded = true; _loading = false; _error = '$error'; } _notify(); } /// Attaches the session stream once per connection. A refusal leaves history /// usable (the live stream is simply not attached) and is retried on resync. Future _attach({bool force = false}) async { if (_disposed || (_subscribed && !force)) return; try { final reply = await _repository.subscribe(sessionId); if (_disposed) return; _subscribed = true; _subscriptionError = null; _applyQueue(reply['chat_queue']); } catch (error) { // History stays usable, but the UI must report that live updates failed. if (_disposed) return; _subscribed = false; _subscriptionError = '$error'; } } /// Adopts the server's queue. A prompt the server removed or could not /// deliver leaves the transcript: it never reached the harness. void _applyQueue(Object? body) { if (!_queue.apply(sessionId, body)) return; final frame = Map.from(body as Map); for (final key in const ['removed', 'failed']) { final operation = '${frame[key] ?? ''}'; if (operation.isEmpty) continue; _messages = [ for (final message in _messages) if (message['operation_id'] != operation) message, ]; if (_awaitingResponseOperation == operation) { _awaitingResponseOperation = null; } } onQueue?.call(frame); _notify(); } void _onFrame(JsonMap envelope) { if (_disposed) return; if (envelope['type'] == 'chat_queue') { _applyQueue(envelope['chat_queue']); return; } if (envelope['type'] == 'chat_permission') { final permission = envelope['chat_permission']; if (permission is! Map) return; final frame = Map.from(permission); if ('${frame['session_id'] ?? ''}' != sessionId) return; _cards.foldPermission(frame); return; } final body = _eventBody(envelope); if (body == null || body['session_id'] != sessionId) return; if (body['kind'] == 'resync') { unawaited(resync()); return; } if (body['kind'] == 'usage') { // Usage replaces the last snapshot and never adds a message, runs a turn // or admits a queued prompt. An unusable snapshot keeps the previous // recorded values instead of replacing them with fabricated zeros. final raw = body['usage']; final account = chatAccountUsage(raw is Map ? raw['account'] : null); if (account != null) _accountUsage = account; final usage = chatUsageSnapshot(raw); if (usage == null || !_reportedUsage(usage)) { if (account != null) _notify(transcript: false); return; } _usage = usage; _notify(transcript: false); return; } if (body['kind'] == 'form') { final form = body['form']; if (form is! Map) return; _cards.foldForm( Map.from(form), raisedIn: _answeringMessageId(), ); return; } final current = _thread; final next = applyChatEvent(current, body); if (identical(next, current)) return; // A frame for a cached message is fresh state the next read must not drop. final changed = body['message_id']; if (changed != null) _untouchedCached?.remove(changed); _messages = (next['messages'] as List? ?? const []) .whereType() .map((message) => Map.from(message)) .toList(); _running = next['running'] == true; if (!_running) { _liveAssistantMessageId = null; } else if (const ['text', 'reasoning', 'tool'].contains(body['kind']) && chatInjectedKind({'kind': body['message_kind']}) == null) { _liveAssistantMessageId = body['message_id'] as String?; } if (body['kind'] == 'step' && (body['step'] as Map?)?['status'] == 'ended' && (body['step'] as Map?)?['intermediate'] != true) { _awaitingResponseOperation = null; } _nativeTurnId = '${next['nativeTurnId'] ?? ''}'; _notify(); } /// Whether a normalized snapshot names a scope or carries a recorded fact. /// A window of zero reports no usable limit, and a rate basis alone reports /// no number at all, so neither counts as a fact on its own. bool _reportedUsage(JsonMap usage) { if ('${usage['scope'] ?? ''}'.isNotEmpty) return true; if (usage['context_window'] is int && (usage['context_window'] as int) > 0) { return true; } return const [ 'total_tokens', 'context_tokens', 'cost_usd', 'output_tokens_per_second', ].any((key) => usage[key] != null); } /// The agent message a question frame arrives during: the streamed reply, /// else the last answer when it is the agent's. A question raised before the /// reply starts names none rather than an older turn. String? _answeringMessageId() { final live = _liveAssistantMessageId; if (live != null && live.isNotEmpty) return live; for (final message in _messages.reversed) { if (chatInjectedKind(message) != null) continue; if (message['role'] != 'assistant') return null; final id = '${message['id'] ?? ''}'.trim(); return id.isEmpty ? null : id; } return null; } /// The pushed envelope body, or null for another message type. The server /// wraps `chat_event` in the typed envelope; domain code never sees the /// transport fields. JsonMap? _eventBody(JsonMap envelope) { if (envelope['type'] != 'chat_event') return null; final body = envelope['chat_event']; if (body is! Map) return null; return Map.from(body); } JsonMap get _thread => { 'sessionId': sessionId, 'messages': _messages, 'running': _running, 'nativeTurnId': _nativeTurnId, }; void _applyPage(JsonMap page) { _messages = (page['messages'] as List? ?? const []) .whereType() .map((message) => Map.from(message)) .toList(); _cursor = '${page['nextCursor'] ?? ''}'; _hasMore = page['hasMore'] == true; _loaded = true; _loading = false; } bool _owned(int token) => !_disposed && token == _generation; /// Puts a sent turn into the transcript where it was sent, as the web does: /// after everything held so far and before any reply frame that follows. It /// carries the id the harness will persist, so the live echo is ignored and /// the history copy replaces it in place instead of moving it. void insertLocal(JsonMap message) { if (_disposed) return; if (!_running) { _awaitingResponseOperation ??= message['operation_id'] as String?; } _messages = [..._messages, message]; _notify(); } /// Removes a sent turn the server refused. void removeLocal(String operationId) { if (_disposed) return; if (_awaitingResponseOperation == operationId) { _awaitingResponseOperation = null; } final next = [ for (final message in _messages) if (message['operation_id'] != operationId) message, ]; if (next.length == _messages.length) return; _messages = next; _notify(); } /// An accepted queued prompt waits behind another turn, not its own reply. void promptAccepted(String operationId, {required bool queued}) { if (_disposed || !queued || _awaitingResponseOperation != operationId) { return; } _awaitingResponseOperation = null; _notify(); } void _notify({bool transcript = true}) { if (_disposed) return; notifyListeners(); if (transcript && !_disposed) _transcriptChanges.notifyListeners(); } @override void dispose() { _disposed = true; _transcriptChanges.dispose(); _generation++; unawaited(_subscription?.cancel()); super.dispose(); } }