import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/chat_repository.dart'; import '../domain/chat_sessions.dart'; import '../domain/chat_transcript.dart'; import 'chat_thread_cards.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. class ChatThreadController extends ChangeNotifier { ChatThreadController(this.gateway, this.sessionId) { _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; List _messages = const []; bool _running = false; bool _loaded = false; bool _loading = false; bool _hasMore = false; String _cursor = ''; String _nativeTurnId = ''; JsonMap? _usage; String? _error; bool _subscribed = false; String? _subscriptionError; bool _disposed = false; int _generation = 0; bool _resyncing = false; bool _resyncAgain = false; List get messages => _messages; bool get running => _running; 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; 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 = ''; _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 { // 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)); } _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 { await _repository.subscribe(sessionId); if (_disposed) return; _subscribed = true; _subscriptionError = null; } catch (error) { // History stays usable, but the UI must report that live updates failed. if (_disposed) return; _subscribed = false; _subscriptionError = '$error'; } } void _onFrame(JsonMap envelope) { if (_disposed) 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 usage = chatUsageSnapshot(body['usage']); if (usage == null || !_reportedUsage(usage)) return; _usage = usage; _notify(); return; } if (body['kind'] == 'form') { final form = body['form']; if (form is! Map) return; _cards.foldForm(Map.from(form)); return; } final current = _thread; final next = applyChatEvent(current, body); if (identical(next, current)) return; _messages = (next['messages'] as List? ?? const []) .whereType() .map((message) => Map.from(message)) .toList(); _running = next['running'] == true; _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 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; _messages = [..._messages, message]; _notify(); } /// Removes a sent turn the server refused. void removeLocal(String operationId) { if (_disposed) return; final next = [ for (final message in _messages) if (message['operation_id'] != operationId) message, ]; if (next.length == _messages.length) return; _messages = next; _notify(); } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; _generation++; unawaited(_subscription?.cancel()); super.dispose(); } }