import 'dart:async'; import 'dart:math'; import 'package:flutter/foundation.dart'; import '../../../../core/api_gateway.dart'; import '../../../../core/servers/server_scope.dart'; import '../../../../core/transport/connection_state.dart'; import '../../../attention/runtime/attention_ack_sync.dart'; import '../../data/chat_repository.dart'; import '../../domain/chat_sessions.dart'; import 'chat_session_local.dart'; import 'session_attention.dart'; /// Owns the session list, its refresh generation and the shared row actions. /// /// A refresh that finishes after a newer one (or after the screen is gone) is /// discarded, so a slow reply can never replace fresher state. Accepted /// mutations always re-read the server list; only this device's hidden ids and /// read watermark are local. /// /// With an [AttentionAckSync] (bound to the gateway by the app, or passed in), /// reading is shared: opening a chat acknowledges a `chat_seen` watermark to /// every device, and a watermark acknowledged elsewhere that is newer than this /// device's own clears the chat's New badge here. The local store remains the /// offline cache of both. class ChatSessionsController extends ChangeNotifier { ChatSessionsController( this.repository, { ChatSessionLocalStore? localStore, AttentionAckSync? ackSync, int Function()? nowMillis, this.activeAckDelay = const Duration(milliseconds: 1500), }) : _localStore = localStore ?? SharedPreferencesChatSessionLocalStore( serverId: serverStorageScope(serverIdentity(repository.gateway)), ), _nowMillis = nowMillis ?? _wallClockMillis { _listenFrames(); _bindAckSync(ackSync ?? attentionAckSyncOf(repository.gateway)); } static int _wallClockMillis() => DateTime.now().millisecondsSinceEpoch; /// How long the open chat stays quiet before its new content is /// acknowledged to the other devices; streaming text arrives in many frames. final Duration activeAckDelay; ChatRepository repository; final ChatSessionLocalStore _localStore; final int Function() _nowMillis; AttentionAckSync? _ackSync; Timer? _activeAck; ChatSessionLocal _local = const ChatSessionLocal(); final Map _actionErrors = {}; List _sessions = const []; String? _error; String? _lastHidden; bool _loading = true; bool _localLoaded = false; Future? _localLoading; bool _disposed = false; int _generation = 0; Future _persistTail = Future.value(); int _runningRevision = 0; final Map _runningFrames = {}; StreamSubscription? _frameSubscription; String? activeSessionId; void _listenFrames() { _frameSubscription?.cancel(); _frameSubscription = repository.gateway.frames.listen(_onFrame); } void _onFrame(JsonMap frame) { final effect = chatSessionFrameEffect(frame); if (effect == null) return; final id = effect.sessionId; final session = _sessions.where((row) => '${row['id'] ?? ''}' == id); if (session.isEmpty) return; final row = session.first; if (row['closed_at'] != null || row['closed'] == true) return; if (effect.running != null) _setRunning(id, effect.running!); if (effect.attention && id != activeSessionId) unawaited(_markUnseen(id)); if (effect.attention && id == activeSessionId) _scheduleActiveAck(id); } void _bindAckSync(AttentionAckSync? sync) { if (identical(sync, _ackSync)) return; _ackSync?.removeListener(_ackChanged); _ackSync = sync; sync?.addListener(_ackChanged); _ackChanged(); } /// Content arriving in the chat this device has open is read here, so it is /// acknowledged to the other devices once the stream goes quiet. void _scheduleActiveAck(String id) { if (_ackSync == null) return; _activeAck?.cancel(); _activeAck = Timer(activeAckDelay, () { if (_disposed || id != activeSessionId) return; unawaited(_acknowledgeSeen(id, 0)); }); } /// Applies watermarks acknowledged on any device: one newer than this /// device's own marks the chat read here (clearing its New badge) and raises /// the local watermark, so a later badge is not cleared by the same ack. void _ackChanged() { final seen = _ackSync?.acks.chatSeen; if (_disposed || !_localLoaded || seen == null) return; var next = _local; seen.forEach((id, at) { if (at > next.watermark(id)) next = next.read(id, at); }); if (identical(next, _local)) return; _local = next; _notify(); unawaited(_persist()); } /// Marks [id] read up to now here and acknowledges it to every device. The /// value is at least the row's own recency; the server lifts it further to /// the session's registry recency. Future _acknowledgeSeen(String id, int updatedAt) async { await _ensureLocal(); if (_disposed) return; final at = max(updatedAt, _nowMillis()); final next = _local.read(id, at); if (!identical(next, _local)) { _local = next; _notify(); await _persist(); } if (_disposed) return; await _ackSync?.acknowledge(chatSeen: {id: at}); } void _setRunning(String id, bool running) { if (_disposed) return; _runningFrames[id] = (revision: ++_runningRevision, running: running); var changed = false; _sessions = _sessions.map((session) { if ('${session['id'] ?? ''}' != id || session['running'] == running) { return session; } changed = true; return {...session, 'running': running}; }).toList(); if (changed) _notify(); } Future _markUnseen(String id) async { await _ensureLocal(); // Loading device preferences may race an operator opening this chat. The // open is authoritative even when the triggering frame arrived first. if (_disposed || id == activeSessionId) return; final next = _local.markUnseen(id); if (identical(next, _local)) return; _local = next; _notify(); await _persist(); } List get sessions => [ for (final session in _sessions) if (!_local.isHidden('${session['id'] ?? ''}')) session, ]; String? get error => _error; bool get loading => _loading; /// The row an action failed on; the message is the server's own words. String? errorFor(String sessionId) => _actionErrors[sessionId]; /// The operator acknowledged [sessionId]'s refusal; nothing is sent. void dismissError(String sessionId) { if (_actionErrors.remove(sessionId) != null) _notify(); } /// The last hidden session, while its Undo is still offered. String? get lastHidden => _lastHidden; bool isUnseen(JsonMap session) { final id = '${session['id'] ?? ''}'; if (id == activeSessionId) return false; // Closed chats keep their recency from the close, but they are not new // work: both the web list and the Android list suppress unseen there. if (!_localLoaded || id.isEmpty || session['closed_at'] != null || session['closed'] == true) { return false; } if (_local.isUnseen(id)) return true; return false; } void replaceRepository(ChatRepository next) { if (identical(next.gateway, repository.gateway)) return; repository = next; _runningFrames.clear(); _listenFrames(); _bindAckSync(attentionAckSyncOf(next.gateway) ?? _ackSync); refresh(); } Future refresh() async { if (_disposed) return; final generation = ++_generation; _loading = true; _error = null; _notify(); // Device preferences never gate the server read: a slow platform store // must not hide the list or delay the first request. unawaited(_ensureLocal()); try { final runningRevision = _runningRevision; final sessions = await repository.sessions(); if (generation != _generation) return; _sessions = [ for (final row in sessions) if ((_runningFrames['${row['id'] ?? ''}']?.revision ?? 0) > runningRevision) {...row, 'running': _runningFrames['${row['id'] ?? ''}']!.running} else row, ]; _seedLocal(); _loading = false; _notify(); } catch (error) { if (generation != _generation) return; _error = '$error'; _loading = false; _notify(); } } Future star(String sessionId, bool starred) => _mutate( sessionId, () => repository.star(sessionId, starred), patch: {'starred': starred}, ); Future close(String sessionId) => _mutate( sessionId, () => repository.close(sessionId), patch: {'closed_at': DateTime.now().toUtc().toIso8601String()}, ); Future reopen(String sessionId) => _mutate( sessionId, () => repository.reopen(sessionId), patch: {'closed_at': null}, ); /// Renames through the shared server field. Throws the server's refusal so the /// open dialog can keep it in view; success refreshes the list from the server. /// /// The dialog owns the refusal, so no row error is stored: the same sentence /// must not also stick under the list row. Future renameOrThrow(String sessionId, String title) async { await repository.rename(sessionId, title); _actionErrors.remove(sessionId); await refresh(); } /// Creates one session and returns the server's `chat_session`. A reply /// without one is refused rather than opening an invented row. Future createOrThrow({ required String title, required String directory, required String backend, required String instructions, required String operationId, }) async { final reply = await repository.create( title: title, directory: directory, backend: backend, operationId: operationId, instructions: instructions, ); final session = reply['chat_session']; if (session is! Map) { // The web reports exactly this refusal, so the dialog shows the same // sentence instead of a Dart `Bad state:` prefix. throw const ProtocolError( 'The server did not return the new chat session.', ); } // Opening the created chat must not wait for the list refresh: the dialog // has already closed, so a slow listing would look like a failed create. unawaited(refresh()); return Map.from(session); } /// Lists a session the server just created at the head of the loaded rows, /// so the row is present before its conversation opens; the caller re-reads /// the list from the server afterwards. A row with the same id is replaced, /// never duplicated. void insertCreated(JsonMap session) { final id = '${session['id'] ?? ''}'; _sessions = [ session, for (final row in _sessions) if ('${row['id'] ?? ''}' != id) row, ]; _seedLocal(); _notify(); } /// Records that this device has read [session]'s current recency. Future markOpened(JsonMap session) async { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; activeSessionId = id; await _ensureLocal(); if (_disposed) return; final updatedAt = chatSessionMillis(session['updated_at']); if (_ackSync != null) return _acknowledgeSeen(id, updatedAt); final next = _local.read(id, updatedAt); if (identical(next, _local)) return; _local = next; _notify(); await _persist(); } /// Hides one row on this device only; the server row is untouched. Future hide(String sessionId) async { await _ensureLocal(); final next = _local.hide(sessionId); if (identical(next, _local)) return; _local = next; _lastHidden = sessionId; _notify(); await _persist(); } Future undoHide() async { final id = _lastHidden; if (id == null) return; _local = _local.restore(id); _lastHidden = null; _notify(); await _persist(); } void dismissUndo() { if (_lastHidden == null) return; _lastHidden = null; _notify(); } /// Applies [patch] to the row at once, so the list answers the tap /// immediately, then saves it. The server's refusal puts the row back and /// shows the reason; success re-reads the list in the background. Future _mutate( String sessionId, Future Function() action, { JsonMap? patch, }) async { final before = _sessions; if (patch != null) { _sessions = [ for (final row in _sessions) if ('${row['id'] ?? ''}' == sessionId) {...row, ...patch} else row, ]; _actionErrors.remove(sessionId); _notify(); } try { await action(); _actionErrors.remove(sessionId); unawaited(refresh()); } catch (error) { if (patch != null) _sessions = before; _actionErrors[sessionId] = '$error'; _notify(); } } Future _ensureLocal() => _localLoading ??= _loadLocal(); Future _loadLocal() async { try { _local = await _localStore.load(); } catch (_) { _local = const ChatSessionLocal(); } _localLoaded = true; _seedLocal(); _ackChanged(); _notify(); } void _seedLocal() { if (!_localLoaded) return; final next = _local.seed([ for (final session in _sessions) ( id: '${session['id'] ?? ''}', updatedAt: chatSessionMillis(session['updated_at']), ), ]); if (identical(next, _local)) return; _local = next; unawaited(_persist()); } Future _persist() { final snapshot = _local; _persistTail = _persistTail.then((_) async { try { await _localStore.save(snapshot); } catch (_) { // The in-memory choice still applies for this session. } }); return _persistTail; } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; _generation++; unawaited(_frameSubscription?.cancel()); _activeAck?.cancel(); _ackSync?.removeListener(_ackChanged); super.dispose(); } }