import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../../../core/servers/server_scope.dart'; import '../data/chat_repository.dart'; import 'chat_composer_send.dart'; import 'chat_deliveries.dart'; import 'chat_draft_store.dart'; import 'leave_guard/chat_leave_guard.dart'; export 'chat_composer_send.dart'; export 'chat_deliveries.dart'; typedef ChatSendCallback = void Function(ChatComposerSend send); typedef ChatSendRejected = void Function(ChatComposerSend send, String error); typedef ChatSendAccepted = void Function(ChatComposerSend send, bool queued); /// The composer state for one conversation: exact draft, the one plain prompt /// in flight, the reply's queued flag and Stop. It is not a transcript: /// [onOptimistic] and [onRejected] are the thread's seam; Stop settles nothing. /// /// A sent message stays in device storage until the server accepts it, so a /// reload or crash mid-request cannot lose it: [loadUnsent] reads it back and /// [deliveries] reports it as "Not sent" with Retry (the same operation id) /// and Edit, unless the server's history shows it arrived. class ChatComposerController extends ChangeNotifier { ChatComposerController( this.gateway, this.sessionId, { ChatDraftStore? drafts, this.onOptimistic, this.onRejected, this.onAccepted, this.newOperationId, }) : _drafts = drafts ?? SharedPreferencesChatDraftStore( serverId: serverStorageScope(serverIdentity(gateway)), ) { _subscription = gateway.frames.listen(_onFrame); } final ApiGateway gateway; final String sessionId; final ChatSendCallback? onOptimistic; final ChatSendRejected? onRejected; final ChatSendAccepted? onAccepted; final ChatDraftStore _drafts; /// Test/fixture seam; production mints a unique id per new intent. final String Function()? newOperationId; late final ChatRepository _repository = ChatRepository(gateway); StreamSubscription? _subscription; static const String draftSaveFailed = 'This draft could not be saved on this device.'; String _draft = ''; bool _edited = false; bool _sending = false; bool _stopping = false; bool _queued = false; String? _error; String? _draftError; int _operationSeq = 0; int _loadGeneration = 0; Future _writes = Future.value(); bool _disposed = false; /// Every intent the server has not accepted yet, as stored on the device. final List _stored = []; /// The delivery state of this conversation's own messages. final ChatDeliveries deliveries = ChatDeliveries(); /// The last intent sent from the composer while its text and chips may /// still be the composer's: a refusal puts its exact draft back, and an /// unchanged re-send (or its bubble's Retry) reuses its operation id. ChatComposerSend? _pending; String _pendingDraft = ''; int _composerSendsAccepted = 0; /// The exact text in the composer. A refusal restores it only when the /// operator has not typed anything newer. String get draft => _draft; /// Advances whenever the server accepts the message the composer's chips /// belong to, including through its bubble's Retry, so the bar can clear /// them. int get composerSendsAccepted => _composerSendsAccepted; /// Whether this unsent intent's text is back in the composer, so its bubble /// offers Retry but not Edit. bool isInComposer(String operationId) => _pending?.operationId == operationId && _draft.trim() == _pending!.text; /// One prompt request is awaiting its reply; a second send is refused. bool get sending => _sending; /// One `chat_interrupt` is awaiting its reply. bool get stopping => _stopping; /// The reply said the prompt waits behind the in-flight turn. bool get queued => _queued; /// The last send or Stop refusal, kept visible until the next action. String? get error => _error; /// Set when the draft could not be persisted; in-memory text still holds. String? get draftError => _draftError; /// Reads this session's saved draft. Text typed while the read is pending /// wins, so a slow store can never replace the operator's newer typing. Future loadDraft() async { if (_disposed) return; final generation = ++_loadGeneration; var saved = ''; try { saved = await _drafts.read(sessionId); } catch (_) { saved = ''; } if (_disposed || _edited || generation != _loadGeneration) return; if (saved == _draft) return; _draft = saved; _notify(); } /// Updates the draft exactly as typed and persists it. A save failure leaves /// the in-memory draft untouched and sets [draftError]. Future setDraft(String text) { if (_disposed || text == _draft) return Future.value(); _draft = text; _edited = true; _draftError = null; _notify(); return _persistDraft(text); } /// Sends the non-blank draft as one plain message, carrying [attachments] in /// draft order. Only the wire text is trimmed. The intent is stored on the /// device until the server accepts it. A refusal restores the exact draft /// (unless newer text is present) and shows the message as "Not sent"; an /// unchanged re-send (same text and parts) reuses its operation id, and a /// changed one replaces it. Returns whether the server accepted this prompt. Future send({List attachments = const []}) async { if (_disposed || _sending) return false; final exact = _draft; final text = exact.trim(); if (text.isEmpty) return false; final previous = _pending; late final ChatComposerSend intent; if (previous != null && previous.text == text && _sameAttachments(previous.attachments, attachments)) { intent = previous; } else { // The operator changed the refused message: the old one is replaced. if (previous != null) discard(previous.operationId); final operationId = _nextOperationId(); intent = ChatComposerSend( sessionId: sessionId, text: text, operationId: operationId, nativeMessageId: nativeChatMessageId(operationId), attachments: attachments, ); } _pending = intent; _pendingDraft = exact; _draft = ''; _edited = true; return _deliver(intent, clearDraft: true); } /// Sends an unsent intent again with its own operation id, so the server and /// the transcript see the same message rather than a second one. When its /// text is back in the composer, the composer is cleared as for a send. Future retry(String operationId) async { if (_disposed || _sending) return false; final intent = _unsentIntent(operationId); if (intent == null || !intent.canRetry) return false; if (isInComposer(operationId)) { _pendingDraft = _draft; _draft = ''; _edited = true; return _deliver(intent, clearDraft: true); } if (_pending?.operationId == operationId) _pending = null; return _deliver(intent, clearDraft: false); } /// Takes an unsent intent back into the composer: its text replaces an empty /// draft or follows newer typing, and the intent is no longer kept. Future edit(String operationId) async { if (_disposed) return; final intent = _unsentIntent(operationId); if (intent == null) return; discard(operationId); final current = _draft.trimRight(); final next = current.isEmpty ? intent.text : '$current\n${intent.text}'; await setDraft(next); } /// Drops an unsent intent without sending it or touching the draft. void discard(String operationId) { if (_disposed) return; if (_pending?.operationId == operationId) _pending = null; deliveries.forget(operationId); _forgetStored(operationId); } /// Reads the intents a previous visit stored but never saw accepted. They /// are settled by [reconcile] once an authoritative history read arrives. Future loadUnsent() async { if (_disposed) return; List saved; try { saved = await _drafts.readUnsent(sessionId); } catch (_) { saved = const []; } if (_disposed) return; final read = [ for (final entry in saved) if (ChatComposerSend.fromJson(entry) case final intent?) if (!_stored.any((item) => item.operationId == intent.operationId)) intent, ]; // One the server already reports queued is the server's: its device copy // is dropped rather than restored. final intents = [ for (final intent in read) if (!deliveries.serverHolds(intent.operationId)) intent, ]; if (intents.length != read.length) _persistUnsent(); if (intents.isEmpty) return; _stored.insertAll(0, intents); deliveries.restore(intents); } /// Settles unsent intents against an authoritative transcript: one the /// server recorded is cleared from device storage. void reconcile(List messages) { if (_disposed) return; final confirmed = deliveries.reconcile(messages); if (confirmed.isEmpty) return; _stored.removeWhere(confirmed.contains); _persistUnsent(); } Future _deliver( ChatComposerSend intent, { required bool clearDraft, }) async { _sending = true; setChatLeaveGuard(this, active: true); _error = null; if (!_stored.any((item) => item.operationId == intent.operationId)) { _stored.add(intent); } deliveries.sending(intent); _notify(); onOptimistic?.call(intent); // The intent is on the device before the request leaves, so a reload // while it is in flight still finds it. _persistUnsent(); if (clearDraft) await _persistDraft(''); if (_disposed) return false; try { final reply = await _repository.prompt( sessionId, intent.text, operationId: intent.operationId, attachments: intent.attachments, ); if (_disposed) return false; final queued = reply['chat_queued'] == true; final steered = reply['chat_steered'] == true; // Accepted (sent or queued) means the server holds it now: the device // copy is dropped, and a reload reads a queued prompt from the server. _forgetStored(intent.operationId); if (_pending?.operationId == intent.operationId) { _pending = null; _composerSendsAccepted++; } deliveries.accepted(intent, queued: queued, steered: steered); _queued = deliveries.isQueued(intent.operationId) || deliveries.ownQueued; onAccepted?.call(intent, queued); _settle(null); // The accepted intent's stored copy is gone before the send completes. await _writes; return !_disposed; } catch (error) { if (_disposed) return false; final message = '$error'; deliveries.failed(intent); if (_pending?.operationId == intent.operationId && _draft.isEmpty) { // The composer holds the message again (text and chips), so the // draft store keeps it across a reload instead of a second copy. _draft = _pendingDraft; _edited = true; _forgetStored(intent.operationId); _notify(); await _persistDraft(_pendingDraft); if (_disposed) return false; } else if (_pending?.operationId == intent.operationId) { // Newer typing owns the composer; the refused message stays its own // "Not sent" bubble (and stored) for Retry or Edit. _pending = null; } onRejected?.call(intent, message); _settle(message); return false; } } void _settle(String? error) { _sending = false; setChatLeaveGuard(this, active: false); _error = error; _notify(); } ChatComposerSend? _unsentIntent(String operationId) { for (final intent in deliveries.unsent) { if (intent.operationId == operationId) return intent; } return null; } /// Whether two prompts carry the same attachment parts, so a re-send after /// a refusal can keep the original operation id. Parts are the exact wire /// maps this composer built, so a shallow key-by-key comparison is enough. bool _sameAttachments(List a, List b) { if (identical(a, b)) return true; if (a.length != b.length) return false; for (var index = 0; index < a.length; index += 1) { final first = a[index]; final second = b[index]; if (first.length != second.length) return false; for (final key in first.keys) { if (!second.containsKey(key) || first[key] != second[key]) return false; } } return true; } void _forgetStored(String operationId) { final before = _stored.length; _stored.removeWhere((item) => item.operationId == operationId); if (_stored.length != before) _persistUnsent(); } /// Stops the running turn with the exact `chat_interrupt` query. A failure /// stays visible and settles nothing; only a reply or frame changes state. Future stop() async { if (_disposed || _stopping) return; _stopping = true; _error = null; _notify(); try { await _repository.interrupt(sessionId); } catch (error) { if (!_disposed) _error = '$error'; } finally { if (!_disposed) { _stopping = false; _notify(); } } } /// Follows the server's queue report: a prompt it lists is the server's /// (any stored device copy is dropped) and shows "Queued"; one that left /// the queue shows what happened to it. void applyServerQueue(JsonMap frame) { if (_disposed) return; final listed = deliveries.applyServerQueue(frame); for (final operationId in listed) { _forgetStored(operationId); } final queued = deliveries.ownQueued; if (queued != _queued) { _queued = queued; _notify(); } } /// Removes one of the server's queued prompts. A refusal (it was already /// sent) stays visible as the composer's error. Future unqueue(Future Function() remove) async { if (_disposed) return; _error = null; _notify(); try { await remove(); } catch (error) { if (_disposed) return; _error = '$error'; _notify(); } } void _onFrame(JsonMap envelope) { // A server that reports its queue moves prompts out of "Queued" itself; // the any-frame heuristic is only for one that does not. if (_disposed || !_queued || deliveries.serverQueueKnown) return; if (envelope['type'] != 'chat_event') return; final body = envelope['chat_event']; if (body is! Map || body['session_id'] != sessionId) return; // Usage or compaction does not admit a queued prompt; any other frame for // this session means the turn it waited behind moved on (web parity). final kind = body['kind']; if (kind == 'usage' || kind == 'compaction') return; _queued = false; deliveries.admitQueued(); _notify(); } String _nextOperationId() => newOperationId?.call() ?? 'native-chat-${DateTime.now().microsecondsSinceEpoch}-${_operationSeq++}'; Future _persistDraft(String text) { final write = _writes.then((_) async { var stored = false; try { stored = await _drafts.write(sessionId, text); } catch (_) { stored = false; } if (_disposed || text != _draft) return; final failure = stored ? null : draftSaveFailed; if (failure != _draftError) { _draftError = failure; _notify(); } }); _writes = write; return write; } /// Writes every not-yet-accepted intent, in order, after earlier writes. void _persistUnsent() { final snapshot = [for (final intent in _stored) intent.toJson()]; _writes = _writes.then((_) async { try { await _drafts.writeUnsent(sessionId, snapshot); } catch (_) { // The in-memory intent still shows; only a reload could lose it. } }); } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { if (_disposed) return; _disposed = true; _loadGeneration++; setChatLeaveGuard(this, active: false); deliveries.dispose(); unawaited(_subscription?.cancel()); super.dispose(); } }