import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../../core/api_gateway.dart'; import '../../../../core/transport/connection_state.dart'; import '../../data/chat_repository.dart'; import '../../domain/chat_sessions.dart'; import 'chat_session_local.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. class ChatSessionsController extends ChangeNotifier { ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore}) : _localStore = localStore ?? const SharedPreferencesChatSessionLocalStore() { _listenFrames(); } ChatRepository repository; final ChatSessionLocalStore _localStore; 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; StreamSubscription? _frameSubscription; String? activeSessionId; void _listenFrames() { _frameSubscription?.cancel(); _frameSubscription = repository.gateway.frames.listen(_onFrame); } void _onFrame(JsonMap frame) { final type = frame['type']; String? id; if (type == 'chat_event') { final event = frame['chat_event']; if (event is! Map || event['kind'] == 'usage') return; id = event['session_id'] is String ? event['session_id'] as String : null; } else if (type == 'chat_permission') { final permission = frame['chat_permission']; if (permission is! Map) return; id = permission['session_id'] is String ? permission['session_id'] as String : null; } else { return; } if (id == null || id.isEmpty || id == activeSessionId) return; unawaited(_markUnseen(id)); } Future _markUnseen(String id) async { await _ensureLocal(); 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['running'] == true || session['closed_at'] != null || session['closed'] == true) { return false; } if (_local.isUnseen(id)) return true; final updatedAt = chatSessionMillis(session['updated_at']); return updatedAt > 0 && updatedAt > _local.watermark(id); } void replaceRepository(ChatRepository next) { if (identical(next.gateway, repository.gateway)) return; repository = next; _listenFrames(); 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 sessions = await repository.sessions(); if (generation != _generation) return; _sessions = sessions; _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)); Future close(String sessionId) => _mutate(sessionId, () => repository.close(sessionId)); Future reopen(String sessionId) => _mutate(sessionId, () => repository.reopen(sessionId)); /// 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(); final next = _local.read(id, chatSessionMillis(session['updated_at'])); 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(); } Future _mutate( String sessionId, Future Function() action, ) async { try { await action(); _actionErrors.remove(sessionId); await refresh(); } catch (error) { _actionErrors[sessionId] = '$error'; _notify(); } } Future _ensureLocal() => _localLoading ??= _loadLocal(); Future _loadLocal() async { try { _local = await _localStore.load(); } catch (_) { _local = const ChatSessionLocal(); } _localLoaded = true; _seedLocal(); _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() async { try { await _localStore.save(_local); } catch (_) { // The in-memory choice still applies for this session. } } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; _generation++; unawaited(_frameSubscription?.cancel()); super.dispose(); } }