import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/chat_repository.dart'; import 'chat_draft_store.dart'; /// One plain-message send: the optimistic identity the thread shows and the /// exact wire intent. A lost response retries the same intent with these ids. class ChatComposerSend { const ChatComposerSend({ required this.sessionId, required this.text, required this.operationId, required this.nativeMessageId, this.attachments = const [], }); final String sessionId; /// The trimmed wire text. final String text; final String operationId; final String nativeMessageId; /// The `{name, mime, data}` parts already built from the composer's chips, /// in draft order. Empty for a text-only prompt. final List attachments; /// Mirrors the web's `nativeChatMessageId(operationId) || local-`. String get optimisticId => nativeMessageId.isEmpty ? 'local-$operationId' : nativeMessageId; } typedef ChatSendCallback = void Function(ChatComposerSend send); typedef ChatSendRejected = void Function(ChatComposerSend send, String error); /// 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. class ChatComposerController extends ChangeNotifier { ChatComposerController( this.gateway, this.sessionId, { ChatDraftStore? drafts, this.onOptimistic, this.onRejected, this.newOperationId, }) : _drafts = drafts ?? const SharedPreferencesChatDraftStore() { _subscription = gateway.frames.listen(_onFrame); } final ApiGateway gateway; final String sessionId; final ChatSendCallback? onOptimistic; final ChatSendRejected? onRejected; 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(); ChatComposerSend? _pending; bool _disposed = false; /// The exact text in the composer. A refusal restores it only when the /// operator has not typed anything newer. String get draft => _draft; /// 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. A refused unchanged intent /// (same text and parts) reuses its operation id; a refusal restores the /// exact draft unless newer text is already present. Returns whether the /// server accepted this prompt, so the composer can clear its chips only /// once the send is accepted. 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 { final operationId = _nextOperationId(); intent = ChatComposerSend( sessionId: sessionId, text: text, operationId: operationId, nativeMessageId: nativeChatMessageId(operationId), attachments: attachments, ); } _pending = intent; _sending = true; _error = null; _draft = ''; _edited = true; _notify(); await _persistDraft(''); if (_disposed) return false; onOptimistic?.call(intent); try { final reply = await _repository.prompt( sessionId, text, operationId: intent.operationId, attachments: intent.attachments, ); if (_disposed) return false; _queued = reply['chat_queued'] == true; _pending = null; _sending = false; _error = null; _notify(); return true; } catch (error) { if (_disposed) return false; final message = '$error'; _sending = false; _error = message; if (_draft.isEmpty) { _draft = exact; _edited = true; _notify(); await _persistDraft(exact); if (_disposed) return false; } onRejected?.call(intent, message); _notify(); return false; } } /// 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(); } } } void _onFrame(JsonMap envelope) { if (_disposed || !_queued) 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; _notify(); } String _nextOperationId() => newOperationId?.call() ?? 'native-chat-${DateTime.now().microsecondsSinceEpoch}-${_operationSeq++}'; /// Whether two prompts carry the same attachment parts, so a retry 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; } 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; } void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { if (_disposed) return; _disposed = true; _loadGeneration++; unawaited(_subscription?.cancel()); super.dispose(); } }