import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/chat_repository.dart'; import '../domain/chat_transcript.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`). 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); StreamSubscription? _subscription; List _messages = const []; bool _running = false; bool _loaded = false; bool _loading = false; bool _hasMore = false; String _cursor = ''; String _nativeTurnId = ''; 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; String? get error => _error; bool get subscribed => _subscribed; String? get subscriptionError => _subscriptionError; /// 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; final body = _eventBody(envelope); if (body == null || body['session_id'] != sessionId) return; if (body['kind'] == 'resync') { unawaited(resync()); 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(); } /// 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; void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; _generation++; unawaited(_subscription?.cancel()); super.dispose(); } }