From 4bc99f490bbade1c52235b3d80dbd2754808d4bf Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 19:54:48 +0000 Subject: [PATCH] WIP: message delivery status and refresh safety; fix reconcile listener recursion The transcript listener read the lazily built _controller while _attach was still building it (load() notifies synchronously), so it built another controller, recursively, until the test process ran out of memory. --- .../chat/conversation/chat_composer_bar.dart | 13 +- .../chat_composer_controller.dart | 238 ++++++++++------- .../chat/conversation/chat_composer_send.dart | 115 ++++++++ .../chat/conversation/chat_deliveries.dart | 162 ++++++++++++ .../conversation/chat_delivery_indicator.dart | 104 ++++++++ .../chat/conversation/chat_draft_store.dart | 71 ++++- .../chat/conversation/chat_thread_view.dart | 157 ++++++++--- .../leave_guard/chat_leave_guard.dart | 9 + .../leave_guard/chat_leave_guard_stub.dart | 2 + .../leave_guard/chat_leave_guard_web.dart | 27 ++ .../chat/ui/transcript/chat_message_view.dart | 34 ++- .../chat_composer_draft_test.dart | 7 + .../conversation/chat_composer_send_test.dart | 77 +++--- .../chat/conversation/chat_delivery_test.dart | 247 ++++++++++++++++++ app/tool/chat_composer_probe_entry.dart | 47 +++- 15 files changed, 1133 insertions(+), 177 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_composer_send.dart create mode 100644 app/lib/features/chat/conversation/chat_deliveries.dart create mode 100644 app/lib/features/chat/conversation/chat_delivery_indicator.dart create mode 100644 app/lib/features/chat/conversation/leave_guard/chat_leave_guard.dart create mode 100644 app/lib/features/chat/conversation/leave_guard/chat_leave_guard_stub.dart create mode 100644 app/lib/features/chat/conversation/leave_guard/chat_leave_guard_web.dart create mode 100644 app/test/features/chat/conversation/chat_delivery_test.dart diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 57fdc2b6..260b3331 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -458,9 +458,8 @@ class _ChatComposerBarState extends State { } /// Builds the chips' exact wire parts and hands them to the composer with the - /// draft's text and operation id. The chips stay while the prompt is in - /// flight so a refusal leaves the draft and its files together; only an - /// accepted prompt clears them. + /// draft's text and operation id. The chips leave the composer with the + /// message; a refusal keeps them on its "Not sent" bubble for Retry. Future _send() async { final composer = widget.composer; if (_uploading || composer.sending || composer.draft.trim().isEmpty) { @@ -508,14 +507,16 @@ class _ChatComposerBarState extends State { if (_uploading) setState(() => _uploading = false); // Keep the caret in the field while the prompt is in flight, as before. _focus.requestFocus(); - final accepted = await composer.send(attachments: parts); - if (!mounted) return; - if (accepted) { + final sending = composer.send(attachments: parts); + // The sent message now owns its files: a refusal keeps them with its + // "Not sent" bubble for Retry, so the composer is free for the next one. + if (composer.sending) { setState(() { _replaceAttachments(const [], const []); _attachmentError = null; }); } + await sending; } /// Adds the operator's explicit selection through the host seam. A dismissed diff --git a/app/lib/features/chat/conversation/chat_composer_controller.dart b/app/lib/features/chat/conversation/chat_composer_controller.dart index 33c639b9..e5b4f42b 100644 --- a/app/lib/features/chat/conversation/chat_composer_controller.dart +++ b/app/lib/features/chat/conversation/chat_composer_controller.dart @@ -5,34 +5,13 @@ 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'; -/// 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; -} +export 'chat_composer_send.dart'; +export 'chat_deliveries.dart'; typedef ChatSendCallback = void Function(ChatComposerSend send); typedef ChatSendRejected = void Function(ChatComposerSend send, String error); @@ -41,6 +20,11 @@ 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, @@ -83,11 +67,16 @@ class ChatComposerController extends ChangeNotifier { 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. + /// 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 exact text in the composer. A refused message is not put back here; + /// it stays "Not sent" until the operator retries or edits it. String get draft => _draft; /// One prompt request is awaiting its reply; a second send is refused. @@ -134,74 +123,149 @@ class ChatComposerController extends ChangeNotifier { } /// 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. + /// draft order. Only the wire text is trimmed. The draft is cleared at once + /// and the intent is stored until the server accepts it; a refusal or lost + /// request leaves it in [deliveries] as "Not sent" for [retry] or [edit]. + /// 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(); + final text = _draft.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; + final operationId = _nextOperationId(); + final intent = ChatComposerSend( + sessionId: sessionId, + text: text, + operationId: operationId, + nativeMessageId: nativeChatMessageId(operationId), + attachments: attachments, + ); _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. + Future retry(String operationId) async { + if (_disposed || _sending) return false; + final intent = _unsentIntent(operationId); + if (intent == null || !intent.canRetry) return false; + 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; + 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 intents = [ + for (final entry in saved) + if (ChatComposerSend.fromJson(entry) case final intent?) + if (!_stored.any((item) => item.operationId == intent.operationId)) + intent, + ]; + 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); - await _persistDraft(''); + // 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, - text, + intent.text, operationId: intent.operationId, attachments: intent.attachments, ); if (_disposed) return false; _queued = reply['chat_queued'] == true; + _forgetStored(intent.operationId); + deliveries.accepted(intent, queued: _queued); onAccepted?.call(intent, _queued); - _pending = null; - _sending = false; - _error = null; - _notify(); + _settle(null); 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; - } + deliveries.failed(intent); onRejected?.call(intent, message); - _notify(); + _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; + } + + 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 { @@ -231,6 +295,7 @@ class ChatComposerController extends ChangeNotifier { final kind = body['kind']; if (kind == 'usage' || kind == 'compaction') return; _queued = false; + deliveries.admitQueued(); _notify(); } @@ -238,23 +303,6 @@ class ChatComposerController extends ChangeNotifier { 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; @@ -274,6 +322,18 @@ class ChatComposerController extends ChangeNotifier { 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(); } @@ -283,6 +343,8 @@ class ChatComposerController extends ChangeNotifier { if (_disposed) return; _disposed = true; _loadGeneration++; + setChatLeaveGuard(this, active: false); + deliveries.dispose(); unawaited(_subscription?.cancel()); super.dispose(); } diff --git a/app/lib/features/chat/conversation/chat_composer_send.dart b/app/lib/features/chat/conversation/chat_composer_send.dart new file mode 100644 index 00000000..4d6a63bf --- /dev/null +++ b/app/lib/features/chat/conversation/chat_composer_send.dart @@ -0,0 +1,115 @@ +import '../../../core/api_gateway.dart'; +import '../domain/chat_attachment_image.dart'; + +/// One plain-message send: the optimistic identity the thread shows and the +/// exact wire intent. A retry sends this same intent with these ids. +class ChatComposerSend { + const ChatComposerSend({ + required this.sessionId, + required this.text, + required this.operationId, + required this.nativeMessageId, + this.attachments = const [], + this.attachmentsOmitted = false, + }); + + 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; + + /// True for an intent read back from device storage whose attachment bytes + /// were too large to keep: [attachments] then carries names only, so the + /// intent cannot be re-sent as it was. + final bool attachmentsOmitted; + + /// Whether this exact intent can be sent again. + bool get canRetry => !attachmentsOmitted; + + /// Mirrors the web's `nativeChatMessageId(operationId) || local-`. + String get optimisticId => + nativeMessageId.isEmpty ? 'local-$operationId' : nativeMessageId; + + /// The local user message the thread draws for this intent. + JsonMap toMessage() => { + 'id': optimisticId, + 'session_id': sessionId, + 'role': 'user', + 'operation_id': operationId, + 'native_message_id': nativeMessageId, + 'parts': [ + {'type': 'text', 'text': text}, + for (final attachment in attachments) + { + 'type': 'file', + 'name': attachment['name'], + 'uri': chatOptimisticAttachmentUri(attachment), + 'mime': attachment['mime'], + }, + ], + }; + + /// Whether [message] is the server's record of this intent: the same + /// operation id, or the native message id the prompt carried. + bool recordedBy(JsonMap message) { + if (message['role'] != 'user') return false; + if (message['operation_id'] == operationId) return true; + if (nativeMessageId.isEmpty) return false; + return message['id'] == nativeMessageId || + message['native_message_id'] == nativeMessageId; + } + + /// The device-storage form. Attachment bytes are kept only while their + /// total stays under [maxStoredAttachmentData]; beyond that only names and + /// types are kept and the read-back intent reports [attachmentsOmitted]. + JsonMap toJson() { + var size = 0; + for (final attachment in attachments) { + size += '${attachment['data'] ?? ''}'.length; + } + final omit = attachmentsOmitted || size > maxStoredAttachmentData; + return { + 'session_id': sessionId, + 'text': text, + 'operation_id': operationId, + 'native_message_id': nativeMessageId, + 'attachments': [ + for (final attachment in attachments) + omit + ? {'name': attachment['name'], 'mime': attachment['mime']} + : Map.from(attachment), + ], + if (omit && attachments.isNotEmpty) 'attachments_omitted': true, + }; + } + + /// Reads a stored intent, or null when the entry is not a usable intent. + static ChatComposerSend? fromJson(Object? value) { + if (value is! Map) return null; + final text = '${value['text'] ?? ''}'; + final operationId = '${value['operation_id'] ?? ''}'; + if (text.trim().isEmpty || operationId.isEmpty) return null; + return ChatComposerSend( + sessionId: '${value['session_id'] ?? ''}', + text: text, + operationId: operationId, + nativeMessageId: '${value['native_message_id'] ?? ''}', + attachments: [ + for (final attachment in value['attachments'] as List? ?? const []) + if (attachment is Map) Map.from(attachment), + ], + attachmentsOmitted: value['attachments_omitted'] == true, + ); + } + + /// Base64 characters of attachment data kept on the device with an unsent + /// intent. Browser storage is small and shared, so larger files are named + /// but not kept. + static const int maxStoredAttachmentData = 512 * 1024; +} diff --git a/app/lib/features/chat/conversation/chat_deliveries.dart b/app/lib/features/chat/conversation/chat_deliveries.dart new file mode 100644 index 00000000..452423bc --- /dev/null +++ b/app/lib/features/chat/conversation/chat_deliveries.dart @@ -0,0 +1,162 @@ +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import 'chat_composer_send.dart'; + +/// Where one of the operator's own messages is on its way to the server. +enum ChatDelivery { + /// The prompt request is awaiting the server's reply. + sending, + + /// The server accepted the prompt. + sent, + + /// The server accepted the prompt behind the turn in flight. + queued, + + /// The server refused the prompt, or its request was lost. + failed, +} + +/// The delivery state of this conversation's own sends, and the messages that +/// were not sent. +/// +/// Messages read from history carry no state: they were sent. Only sends made +/// from this composer (and intents read back from device storage) are +/// tracked. An unsent intent is not a transcript message, so it is listed in +/// [unsent] and drawn after the transcript until it is re-sent, edited or +/// found in the server's history. +class ChatDeliveries extends ChangeNotifier { + final Map _states = {}; + final Map _operationByNative = {}; + final List _unsent = []; + + /// Intents read back from device storage that no history read has checked. + final List _unverified = []; + String? _latestSent; + bool _disposed = false; + + /// The intents the server has not accepted, in send order. + List get unsent => List.unmodifiable(_unsent); + + /// Whether any intent still waits for a history read to settle it. + bool get hasUnverified => _unverified.isNotEmpty; + + /// The state to draw under a transcript user [message], or null for a quiet + /// message. "Sent" is shown only on the newest accepted send. + ChatDelivery? stateFor(JsonMap message) { + final operation = _operationOf(message); + if (operation == null) return null; + final state = _states[operation]; + if (state == ChatDelivery.sent && operation != _latestSent) return null; + return state; + } + + String? _operationOf(JsonMap message) { + final operation = message['operation_id']; + if (operation is String && _states.containsKey(operation)) { + return operation; + } + for (final key in [message['native_message_id'], message['id']]) { + if (key is String && _operationByNative.containsKey(key)) { + return _operationByNative[key]; + } + } + return null; + } + + void sending(ChatComposerSend send) { + _unsent.removeWhere((item) => item.operationId == send.operationId); + _set(send, ChatDelivery.sending); + } + + void accepted(ChatComposerSend send, {required bool queued}) { + if (!queued) _latestSent = send.operationId; + _set(send, queued ? ChatDelivery.queued : ChatDelivery.sent); + } + + void failed(ChatComposerSend send) { + _unsent + ..removeWhere((item) => item.operationId == send.operationId) + ..add(send); + _set(send, ChatDelivery.failed); + } + + /// A queued prompt was admitted: the turn it waited behind moved on. + void admitQueued() { + var changed = false; + for (final entry in _states.entries.toList()) { + if (entry.value != ChatDelivery.queued) continue; + _states[entry.key] = ChatDelivery.sent; + _latestSent = entry.key; + changed = true; + } + if (changed) _notify(); + } + + /// Drops an unsent intent the operator took back into the composer. + void forget(String operationId) { + final before = _unsent.length + _unverified.length; + _unsent.removeWhere((item) => item.operationId == operationId); + _unverified.removeWhere((item) => item.operationId == operationId); + _states.remove(operationId); + if (_unsent.length + _unverified.length != before) _notify(); + } + + /// Adopts intents read back from device storage. They stay hidden until + /// [reconcile] has checked them against an authoritative history read. + void restore(List intents) { + var changed = false; + for (final intent in intents) { + if (_states.containsKey(intent.operationId)) continue; + _remember(intent); + _states[intent.operationId] = ChatDelivery.failed; + _unverified.add(intent); + changed = true; + } + if (changed) _notify(); + } + + /// Settles stored and unsent intents against an authoritative transcript: + /// one the server recorded was sent and is returned so its stored copy can + /// be cleared; an unchecked one that is absent becomes "Not sent". + List reconcile(List messages) { + bool recorded(ChatComposerSend intent) => + messages.any((message) => intent.recordedBy(message)); + final confirmed = [ + for (final intent in [..._unverified, ..._unsent]) + if (recorded(intent)) intent, + ]; + final changed = confirmed.isNotEmpty || _unverified.isNotEmpty; + for (final intent in confirmed) { + _states[intent.operationId] = ChatDelivery.sent; + } + _unsent.removeWhere(confirmed.contains); + _unverified.removeWhere(confirmed.contains); + _unsent.addAll(_unverified); + _unverified.clear(); + if (changed) _notify(); + return confirmed; + } + + void _remember(ChatComposerSend send) { + if (send.nativeMessageId.isEmpty) return; + _operationByNative[send.nativeMessageId] = send.operationId; + } + + void _set(ChatComposerSend send, ChatDelivery state) { + _remember(send); + _states[send.operationId] = state; + _notify(); + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} diff --git a/app/lib/features/chat/conversation/chat_delivery_indicator.dart b/app/lib/features/chat/conversation/chat_delivery_indicator.dart new file mode 100644 index 00000000..661ad6fa --- /dev/null +++ b/app/lib/features/chat/conversation/chat_delivery_indicator.dart @@ -0,0 +1,104 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'chat_deliveries.dart'; + +/// The words each delivery state reads as, beside its icon. +String chatDeliveryLabel(ChatDelivery state) => switch (state) { + ChatDelivery.sending => 'Sending…', + ChatDelivery.sent => 'Sent', + ChatDelivery.queued => 'Queued', + ChatDelivery.failed => 'Not sent', +}; + +/// A small muted line under the operator's own bubble saying whether the +/// server has the message. "Not sent" takes the error colour and offers the +/// native Retry (same operation id) and Edit (back into the composer) — or +/// Discard when the stored intent can no longer be sent as it was. +class ChatDeliveryIndicator extends StatelessWidget { + const ChatDeliveryIndicator({ + super.key, + required this.state, + required this.cupertino, + this.onRetry, + this.onEdit, + this.editLabel = 'Edit', + }); + + final ChatDelivery state; + final bool cupertino; + final VoidCallback? onRetry; + final VoidCallback? onEdit; + final String editLabel; + + @override + Widget build(BuildContext context) { + final failed = state == ChatDelivery.failed; + final color = failed + ? (cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error) + : (cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant); + final style = DefaultTextStyle.of( + context, + ).style.merge(TextStyle(fontSize: 12, color: color)); + final label = chatDeliveryLabel(state); + return Semantics( + container: true, + label: 'Delivery: $label', + child: Wrap( + key: Key('chat-delivery-${state.name}'), + spacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + ExcludeSemantics( + child: Icon(_icon, size: style.fontSize! + 2, color: color), + ), + ExcludeSemantics(child: Text(label, style: style)), + if (failed && onRetry != null) + _action('chat-delivery-retry', 'Retry', onRetry!, style), + if (failed && onEdit != null) + _action('chat-delivery-edit', editLabel, onEdit!, style), + ], + ), + ); + } + + IconData get _icon => switch (state) { + ChatDelivery.sending => cupertino ? CupertinoIcons.clock : Icons.schedule, + ChatDelivery.sent => cupertino ? CupertinoIcons.checkmark : Icons.done, + ChatDelivery.queued => + cupertino ? CupertinoIcons.hourglass : Icons.hourglass_empty, + ChatDelivery.failed => + cupertino ? CupertinoIcons.exclamationmark_circle : Icons.error_outline, + }; + + Widget _action( + String key, + String text, + VoidCallback onPressed, + TextStyle style, + ) { + if (cupertino) { + return CupertinoButton( + key: Key(key), + padding: const EdgeInsets.symmetric(horizontal: 6), + minimumSize: Size.zero, + onPressed: onPressed, + child: Text(text, style: style.copyWith(fontWeight: FontWeight.w600)), + ); + } + return TextButton( + key: Key(key), + style: TextButton.styleFrom( + foregroundColor: style.color, + visualDensity: VisualDensity.compact, + textStyle: style.copyWith(fontWeight: FontWeight.w600), + ), + onPressed: onPressed, + child: Text(text), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_draft_store.dart b/app/lib/features/chat/conversation/chat_draft_store.dart index 529073dc..0a8d4416 100644 --- a/app/lib/features/chat/conversation/chat_draft_store.dart +++ b/app/lib/features/chat/conversation/chat_draft_store.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:shared_preferences/shared_preferences.dart'; import '../../../core/servers/server_scope.dart'; @@ -15,12 +17,23 @@ abstract interface class ChatDraftStore { /// Stores [text] exactly. A blank draft removes the entry so the store does /// not grow without bound. Returns false when nothing was stored. Future write(String sessionId, String text); + + /// The messages sent from this device that the server has not yet accepted, + /// as stored JSON intents in send order. Empty when there are none. + Future> readUnsent(String sessionId); + + /// Replaces the stored unsent intents; an empty list removes the entry. + /// Returns false when nothing was stored. + Future writeUnsent(String sessionId, List intents); } /// The app's per-session draft keys. Independent of the legacy web/Android /// storage: no old draft is imported or written under an old key. const String chatDraftKeyPrefix = 'pipelines.next.chatDraft.v1.'; +/// The per-session key for messages still awaiting the server's acceptance. +const String chatUnsentKeyPrefix = 'pipelines.next.chatUnsent.v1.'; + /// `shared_preferences`-backed draft storage. /// /// Reads are tolerant and a write reports failure instead of throwing, so the @@ -62,14 +75,52 @@ class SharedPreferencesChatDraftStore implements ChatDraftStore { return false; } } + + String _unsentKey(String sessionId) => + scopedServerKey('$chatUnsentKeyPrefix$sessionId', serverId); + + @override + Future> readUnsent(String sessionId) async { + final preferences = await _preferences(); + if (preferences == null) return const []; + try { + final stored = preferences.getString(_unsentKey(sessionId)); + if (stored == null || stored.isEmpty) return const []; + final decoded = jsonDecode(stored); + return decoded is List ? decoded : const []; + } catch (_) { + return const []; + } + } + + @override + Future writeUnsent(String sessionId, List intents) async { + final preferences = await _preferences(); + if (preferences == null) return false; + try { + final key = _unsentKey(sessionId); + if (intents.isEmpty) return await preferences.remove(key); + return await preferences.setString(key, jsonEncode(intents)); + } catch (_) { + return false; + } + } } /// An in-memory store for tests and previews. It never touches the platform /// store, so no production preference can be mutated by a fixture. class MemoryChatDraftStore implements ChatDraftStore { - MemoryChatDraftStore({Map? drafts}) : _drafts = {...?drafts}; + MemoryChatDraftStore({ + Map? drafts, + Map>? unsent, + }) : _drafts = {...?drafts}, + _unsent = {...?unsent}; final Map _drafts; + final Map> _unsent; + + /// A snapshot of the stored unsent intents per session. + Map> get unsentEntries => Map.unmodifiable(_unsent); bool failReads = false; bool failWrites = false; @@ -93,4 +144,22 @@ class MemoryChatDraftStore implements ChatDraftStore { } return true; } + + @override + Future> readUnsent(String sessionId) async { + if (failReads) throw StateError('Draft storage is unavailable.'); + // A round trip through JSON, exactly as the device store keeps it. + return jsonDecode(jsonEncode(_unsent[sessionId] ?? const [])) as List; + } + + @override + Future writeUnsent(String sessionId, List intents) async { + if (failWrites) return false; + if (intents.isEmpty) { + _unsent.remove(sessionId); + } else { + _unsent[sessionId] = jsonDecode(jsonEncode(intents)) as List; + } + return true; + } } diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index d98a4c18..30479670 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -9,7 +9,6 @@ import '../../../shell/shell_bar.dart'; import '../data/chat_attachment_images.dart'; import '../data/chat_repository.dart'; import '../domain/chat_activity_detail.dart'; -import '../domain/chat_attachment_image.dart'; import '../domain/chat_notice.dart'; import '../domain/chat_attachment_picker.dart'; import '../domain/chat_transcript.dart'; @@ -21,6 +20,7 @@ import 'chat_background_tasks.dart'; import 'chat_command_actions.dart'; import 'chat_composer_bar.dart'; import 'chat_composer_controller.dart'; +import 'chat_delivery_indicator.dart'; import 'chat_draft_store.dart'; import 'chat_mode_control.dart'; import 'chat_model_control.dart'; @@ -203,11 +203,33 @@ class _ChatThreadViewState extends State { /// counted against it for the jump control's arrival count. String? _newestAtRelease; - ChatThreadController _attach() => ChatThreadController( - widget.gateway, - widget.sessionId, - cached: widget.transcripts?.read(widget.sessionId), - )..load(); + ChatThreadController _attach() { + final controller = ChatThreadController( + widget.gateway, + widget.sessionId, + cached: widget.transcripts?.read(widget.sessionId), + ); + // The listener names this controller: load() can notify before _attach + // returns, while reading _controller would build another one, and so on. + controller.transcriptChanges.addListener( + () => _reconcileUnsent(controller), + ); + unawaited(controller.load()); + return controller; + } + + /// Settles stored unsent messages once the transcript is an authoritative + /// read: a message the server recorded was sent after all. + void _reconcileUnsent(ChatThreadController controller) { + if (!mounted || + !controller.loaded || + controller.loading || + controller.error != null || + controller.showingCached) { + return; + } + _composer.reconcile(controller.messages); + } /// `/close` finished this conversation; its transcript is not kept. bool _closed = false; @@ -238,38 +260,39 @@ class _ChatThreadViewState extends State { widget.onSessionClosed?.call(); } - ChatComposerController _attachComposer() => ChatComposerController( - widget.gateway, - widget.sessionId, - drafts: widget.drafts, - newOperationId: widget.newOperationId, - onOptimistic: _onOptimistic, - onRejected: _onRejected, - onAccepted: (send, queued) => - _controller.promptAccepted(send.operationId, queued: queued), - ); - - void _onOptimistic(ChatComposerSend send) { - if (!mounted) return; - _controller.insertLocal({ - 'id': send.optimisticId, - 'session_id': send.sessionId, - 'role': 'user', - 'operation_id': send.operationId, - 'native_message_id': send.nativeMessageId, - 'parts': [ - {'type': 'text', 'text': send.text}, - for (final attachment in send.attachments) - { - 'type': 'file', - 'name': attachment['name'], - 'uri': chatOptimisticAttachmentUri(attachment), - 'mime': attachment['mime'], - }, - ], - }); + ChatComposerController _attachComposer() { + final composer = ChatComposerController( + widget.gateway, + widget.sessionId, + drafts: widget.drafts, + newOperationId: widget.newOperationId, + onOptimistic: _onOptimistic, + onRejected: _onRejected, + onAccepted: (send, queued) => + _controller.promptAccepted(send.operationId, queued: queued), + ); + // A message a previous visit sent but never saw accepted comes back as + // "Not sent" unless the history read shows the server has it. + unawaited( + composer.loadUnsent().then((_) { + if (mounted && identical(composer, _composer)) { + _reconcileUnsent(_controller); + } + }), + ); + return composer; } + /// Draws a sent (or retried) message where it was sent: a retry moves the + /// message to the end, since that is when it is sent. + void _onOptimistic(ChatComposerSend send) { + if (!mounted) return; + _controller.removeLocal(send.operationId); + _controller.insertLocal(send.toMessage()); + } + + /// A refused message leaves the transcript; it is drawn after it as "Not + /// sent" from the composer's deliveries instead. void _onRejected(ChatComposerSend send, String error) { if (!mounted) return; _controller.removeLocal(send.operationId); @@ -643,7 +666,10 @@ class _ChatThreadViewState extends State { @override Widget build(BuildContext context) => AnimatedBuilder( - animation: _controller.transcriptChanges, + animation: Listenable.merge([ + _controller.transcriptChanges, + _composer.deliveries, + ]), builder: (context, _) { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; @@ -845,6 +871,18 @@ class _ChatThreadViewState extends State { : null, ), ), + // Messages the server has not accepted follow the + // transcript until they are retried or edited. + for (final send in _composer.deliveries.unsent) + Padding( + key: ValueKey( + 'chat-unsent-${send.operationId}', + ), + padding: const EdgeInsets.symmetric( + horizontal: 16, + ), + child: _unsentRow(send, cupertino), + ), // The conversation's own command lines sit after the // turns, as on the web; they are never bubbles. for (final notice in _commandNotices) @@ -1024,13 +1062,56 @@ class _ChatThreadViewState extends State { child: chips.firstOrNull ?? const SizedBox.shrink(), ); } + final delivery = kind == 'user' && row['message'] is Map + ? _composer.deliveries.stateFor( + Map.from(row['message'] as Map), + ) + : null; return ChatMessageView( row: row, textBuilder: chatMarkdownText, - footer: chips, + footer: [ + ...chips, + if (delivery != null) + ChatDeliveryIndicator( + state: delivery, + cupertino: + chatControlsStyleOf(context) == ChatControlsStyle.cupertino, + ), + ], images: _images, ); } + + /// One message the server has not accepted, as the operator's bubble with + /// "Not sent" and its Retry and Edit. + Widget _unsentRow(ChatComposerSend send, bool cupertino) { + final composer = _composer; + return ChatMessageView( + row: { + 'kind': 'user', + 'key': send.optimisticId, + 'message': send.toMessage(), + }, + textBuilder: chatMarkdownText, + images: _images, + footer: [ + ChatDeliveryIndicator( + state: ChatDelivery.failed, + cupertino: cupertino, + onRetry: send.canRetry && !composer.sending + ? () => unawaited(composer.retry(send.operationId)) + : null, + // Attachment bytes cannot go back into the composer's chips, so an + // intent with files is discarded rather than silently trimmed. + editLabel: send.attachments.isEmpty ? 'Edit' : 'Discard', + onEdit: send.attachments.isEmpty + ? () => unawaited(composer.edit(send.operationId)) + : () => composer.discard(send.operationId), + ), + ], + ); + } } /// The native dismiss control shared by a local notice and a running diff --git a/app/lib/features/chat/conversation/leave_guard/chat_leave_guard.dart b/app/lib/features/chat/conversation/leave_guard/chat_leave_guard.dart new file mode 100644 index 00000000..89524256 --- /dev/null +++ b/app/lib/features/chat/conversation/leave_guard/chat_leave_guard.dart @@ -0,0 +1,9 @@ +import 'chat_leave_guard_stub.dart' + if (dart.library.js_interop) 'chat_leave_guard_web.dart' + as impl; + +/// Asks before the page is left or reloaded while [owner] holds a prompt in +/// flight. Only the web build can be reloaded mid-request; elsewhere this does +/// nothing. Each owner releases its own hold with `active: false`. +void setChatLeaveGuard(Object owner, {required bool active}) => + impl.setChatLeaveGuard(owner, active: active); diff --git a/app/lib/features/chat/conversation/leave_guard/chat_leave_guard_stub.dart b/app/lib/features/chat/conversation/leave_guard/chat_leave_guard_stub.dart new file mode 100644 index 00000000..47e2869e --- /dev/null +++ b/app/lib/features/chat/conversation/leave_guard/chat_leave_guard_stub.dart @@ -0,0 +1,2 @@ +/// Non-web hosts have no page to reload, so there is nothing to guard. +void setChatLeaveGuard(Object owner, {required bool active}) {} diff --git a/app/lib/features/chat/conversation/leave_guard/chat_leave_guard_web.dart b/app/lib/features/chat/conversation/leave_guard/chat_leave_guard_web.dart new file mode 100644 index 00000000..a7be0bb7 --- /dev/null +++ b/app/lib/features/chat/conversation/leave_guard/chat_leave_guard_web.dart @@ -0,0 +1,27 @@ +import 'dart:js_interop'; + +import 'package:web/web.dart' as web; + +final Set _owners = {}; +bool _listening = false; + +/// Registers one `beforeunload` listener for the page and keeps it inert +/// unless some composer holds a prompt in flight. The browser then shows its +/// own "Leave site?" confirmation; the wording is the browser's. +void setChatLeaveGuard(Object owner, {required bool active}) { + if (active) { + _owners.add(owner); + } else { + _owners.remove(owner); + } + if (_listening || _owners.isEmpty) return; + _listening = true; + web.window.addEventListener('beforeunload', _onBeforeUnload.toJS); +} + +void _onBeforeUnload(web.Event event) { + if (_owners.isEmpty) return; + event.preventDefault(); + // Older engines still require a non-null returnValue to ask. + (event as web.BeforeUnloadEvent).returnValue = ''; +} diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index c8666708..ab8183c3 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -36,7 +36,8 @@ class ChatMessageView extends StatelessWidget { static final ChatAttachmentImages _inlineImages = ChatAttachmentImages(null); - /// The turn's settled permissions, independent of passive activity details. + /// Beneath the turn: an agent turn's settled permissions, or the delivery + /// line under the operator's own message. final List footer; @override @@ -103,27 +104,40 @@ class ChatMessageView extends StatelessWidget { : row; /// Attached images sit above the operator's bubble, as their own thumbnails; - /// an images-only turn draws no empty bubble. + /// an images-only turn draws no empty bubble. The footer (the delivery line) + /// sits under the bubble's trailing corner. Widget _userTurn(bool cupertino, List content, Widget body) { final thumbnails = [ for (final part in _partsOf(_userMessage)) if (_isFile(part) && chatPartIsThumbnail(part)) part, ]; - if (thumbnails.isEmpty) { + if (thumbnails.isEmpty && footer.isEmpty) { return ChatUserBubble(cupertino: cupertino, child: body); } return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: [ - ChatAttachmentGallery( - parts: thumbnails, - images: images ?? _inlineImages, - cupertino: cupertino, - ), - if (content.isNotEmpty) const SizedBox(height: 6), - if (content.isNotEmpty) + if (thumbnails.isNotEmpty) + ChatAttachmentGallery( + parts: thumbnails, + images: images ?? _inlineImages, + cupertino: cupertino, + ), + if (thumbnails.isNotEmpty && content.isNotEmpty) + const SizedBox(height: 6), + if (content.isNotEmpty || thumbnails.isEmpty) ChatUserBubble(cupertino: cupertino, child: body), + if (footer.isNotEmpty) ...[ + const SizedBox(height: 2), + Wrap( + key: const Key('chat-message-footer'), + spacing: 8, + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + children: footer, + ), + ], ], ); } diff --git a/app/test/features/chat/conversation/chat_composer_draft_test.dart b/app/test/features/chat/conversation/chat_composer_draft_test.dart index 99e6f07c..529fd9ee 100644 --- a/app/test/features/chat/conversation/chat_composer_draft_test.dart +++ b/app/test/features/chat/conversation/chat_composer_draft_test.dart @@ -26,6 +26,13 @@ class _DelayedDraftStore implements ChatDraftStore { writes.add(text); return true; } + + @override + Future> readUnsent(String sessionId) async => const []; + + @override + Future writeUnsent(String sessionId, List intents) async => + true; } void main() { diff --git a/app/test/features/chat/conversation/chat_composer_send_test.dart b/app/test/features/chat/conversation/chat_composer_send_test.dart index a7f6257f..ace29cfc 100644 --- a/app/test/features/chat/conversation/chat_composer_send_test.dart +++ b/app/test/features/chat/conversation/chat_composer_send_test.dart @@ -90,41 +90,47 @@ void main() { expect(controller.sending, isFalse); }); - test('a refused unchanged intent retries with the same identity', () async { - var fail = true; - gateway.prompt = (_, _) async { - if (fail) throw StateError('response lost'); - return const {}; - }; - await controller.setDraft(' keep me '); + test( + 'a refused intent is kept as Not sent and Retry reuses its identity', + () async { + var fail = true; + gateway.prompt = (_, _) async { + if (fail) throw StateError('response lost'); + return const {}; + }; + await controller.setDraft(' keep me '); - await controller.send(); - expect(controller.error, contains('response lost')); - expect(controller.draft, ' keep me '); - expect(await drafts.read('s'), ' keep me '); - expect(rejected.single, contains('response lost')); + await controller.send(); + expect(controller.error, contains('response lost')); + // The composer is free for the next message; the refused one is kept. + expect(controller.draft, ''); + expect(rejected.single, contains('response lost')); + expect(controller.deliveries.unsent.single.operationId, 'op/1'); + expect(drafts.unsentEntries['s'], hasLength(1)); - fail = false; - await controller.send(); - expect(gateway.promptBodies.map((body) => body['operation_id']), [ - 'op/1', - 'op/1', - ]); - expect(gateway.promptBodies.map((body) => body['native_message_id']), [ - 'msg_op1', - 'msg_op1', - ]); - expect(controller.draft, ''); - expect(controller.error, isNull); + fail = false; + expect(await controller.retry('op/1'), isTrue); + expect(gateway.promptBodies.map((body) => body['operation_id']), [ + 'op/1', + 'op/1', + ]); + expect(gateway.promptBodies.map((body) => body['native_message_id']), [ + 'msg_op1', + 'msg_op1', + ]); + expect(controller.error, isNull); + expect(controller.deliveries.unsent, isEmpty); + expect(drafts.unsentEntries, isEmpty); - fail = true; - await controller.setDraft('other'); - await controller.send(); - expect(gateway.promptBodies.last['operation_id'], 'op/2'); - expect(gateway.promptBodies.last['native_message_id'], 'msg_op2'); - }); + fail = true; + await controller.setDraft('other'); + await controller.send(); + expect(gateway.promptBodies.last['operation_id'], 'op/2'); + expect(gateway.promptBodies.last['native_message_id'], 'msg_op2'); + }, + ); - test('a refusal keeps newer typing instead of restoring the draft', () async { + test('a refusal keeps newer typing and the refused message apart', () async { final reply = Completer>(); gateway.prompt = (_, _) => reply.future; await controller.setDraft('original'); @@ -140,8 +146,13 @@ void main() { expect(await drafts.read('s'), 'newer'); expect(controller.error, contains('refused')); expect(rejected.single, contains('refused')); - // The optimistic turn still carries the intent that was refused. - expect(optimistic.single.text, 'original'); + expect(controller.deliveries.unsent.single.text, 'original'); + + // Edit puts the refused text after the newer typing and forgets it. + await controller.edit('op/1'); + expect(controller.draft, 'newer\noriginal'); + expect(controller.deliveries.unsent, isEmpty); + expect(drafts.unsentEntries, isEmpty); }); test( diff --git a/app/test/features/chat/conversation/chat_delivery_test.dart b/app/test/features/chat/conversation/chat_delivery_test.dart new file mode 100644 index 00000000..43d4a19a --- /dev/null +++ b/app/test/features/chat/conversation/chat_delivery_test.dart @@ -0,0 +1,247 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +/// A thread gateway whose prompt replies the test settles one by one. +class _Gateway extends FakeChatGateway { + final prompts = >[]; + final promptBodies = []; + List messages = []; + + _Gateway() { + history = (_) async => chatPage(messages); + } + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_prompt') { + promptBodies.add(fields['chat_prompt'] as JsonMap); + final reply = Completer(); + prompts.add(reply); + return reply.future; + } + return super.call(type, fields); + } +} + +Future _pump(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(); +} + +/// Hosts one thread; [generation] changes the key so a second call simulates +/// a page reload: a fresh thread and composer over the same device store. +Future _host( + WidgetTester tester, + _Gateway gateway, + MemoryChatDraftStore drafts, { + bool cupertino = false, + int generation = 0, +}) async { + var sequence = 0; + final thread = ChatThreadView( + key: ValueKey(generation), + gateway: gateway, + sessionId: 's', + onBack: () {}, + drafts: drafts, + newOperationId: () => 'op-$generation-${++sequence}', + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: thread)) + : MaterialApp(home: Scaffold(body: thread)), + ); + await _pump(tester); +} + +Future _send(WidgetTester tester, String text) async { + await tester.enterText(find.byKey(const Key('chat-composer-field')), text); + await tester.pump(); + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await _pump(tester); +} + +Finder _state(String name) => find.byKey(Key('chat-delivery-$name')); + +void main() { + for (final cupertino in [false, true]) { + testWidgets('send shows Sending… then Sent ($cupertino)', (tester) async { + final gateway = _Gateway(); + addTearDown(gateway.close); + await _host( + tester, + gateway, + MemoryChatDraftStore(), + cupertino: cupertino, + ); + + await _send(tester, 'Hello'); + expect(_state('sending'), findsOneWidget); + expect(find.text('Sending…'), findsOneWidget); + + gateway.prompts.single.complete({}); + await _pump(tester); + expect(_state('sending'), findsNothing); + expect(_state('sent'), findsOneWidget); + + // Only the newest accepted message keeps its quiet check. + await _send(tester, 'Again'); + gateway.prompts.last.complete({}); + await _pump(tester); + expect(_state('sent'), findsOneWidget); + }); + + testWidgets('a queued reply shows Queued until the turn moves on ' + '($cupertino)', (tester) async { + final gateway = _Gateway(); + addTearDown(gateway.close); + await _host( + tester, + gateway, + MemoryChatDraftStore(), + cupertino: cupertino, + ); + + await _send(tester, 'Later please'); + gateway.prompts.single.complete({'chat_queued': true}); + await _pump(tester); + expect(_state('queued'), findsOneWidget); + expect(find.text('Queued'), findsOneWidget); + + gateway.emitEvent(chatStepFrame('running')); + await _pump(tester); + expect(_state('queued'), findsNothing); + expect(_state('sent'), findsOneWidget); + }); + + testWidgets('a refusal shows Not sent and Retry reuses the operation id ' + '($cupertino)', (tester) async { + final gateway = _Gateway(); + addTearDown(gateway.close); + final drafts = MemoryChatDraftStore(); + await _host(tester, gateway, drafts, cupertino: cupertino); + + await _send(tester, 'Please refuse'); + gateway.prompts.single.completeError(StateError('refused')); + await _pump(tester); + expect(_state('failed'), findsOneWidget); + expect(find.text('Not sent'), findsOneWidget); + expect(find.text('Please refuse'), findsOneWidget); + expect(drafts.unsentEntries['s'], hasLength(1)); + + await tester.tap(find.byKey(const Key('chat-delivery-retry'))); + await _pump(tester); + expect(_state('sending'), findsOneWidget); + expect(_state('failed'), findsNothing); + expect(gateway.promptBodies.map((body) => body['operation_id']), [ + 'op-0-1', + 'op-0-1', + ]); + + gateway.prompts.last.complete({}); + await _pump(tester); + expect(_state('sent'), findsOneWidget); + expect(find.text('Please refuse'), findsOneWidget); + expect(drafts.unsentEntries, isEmpty); + }); + } + + testWidgets('a message in flight at reload comes back as Not sent with ' + 'Retry and Edit', (tester) async { + final gateway = _Gateway(); + addTearDown(gateway.close); + final drafts = MemoryChatDraftStore(); + await _host(tester, gateway, drafts); + + await _send(tester, 'Did this arrive?'); + expect(_state('sending'), findsOneWidget); + // The draft is gone from the composer but the message is on the device. + expect(drafts.entries, isEmpty); + expect(drafts.unsentEntries['s'], hasLength(1)); + + // Reload: a new thread and composer; the old request never answers. + await _host(tester, gateway, drafts, generation: 1); + expect(_state('failed'), findsOneWidget); + expect(find.text('Did this arrive?'), findsOneWidget); + expect(find.byKey(const Key('chat-delivery-edit')), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-delivery-retry'))); + await _pump(tester); + expect(gateway.promptBodies.last['operation_id'], 'op-0-1'); + expect(gateway.promptBodies.last['native_message_id'], 'msg_op01'); + gateway.prompts.last.complete({}); + await _pump(tester); + expect(_state('sent'), findsOneWidget); + expect(drafts.unsentEntries, isEmpty); + }); + + testWidgets('Edit puts a reloaded unsent message back in the composer', ( + tester, + ) async { + final gateway = _Gateway(); + addTearDown(gateway.close); + final drafts = MemoryChatDraftStore( + unsent: { + 's': [ + { + 'session_id': 's', + 'text': 'Fix the typo', + 'operation_id': 'op-old', + 'native_message_id': 'msg_opold', + }, + ], + }, + ); + await _host(tester, gateway, drafts); + expect(_state('failed'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-delivery-edit'))); + await _pump(tester); + expect(_state('failed'), findsNothing); + final field = tester.widget(find.byType(EditableText)); + expect(field.controller.text, 'Fix the typo'); + expect(drafts.unsentEntries, isEmpty); + expect(gateway.promptBodies, isEmpty); + }); + + testWidgets('a stored message the history already records is cleared as ' + 'sent', (tester) async { + final gateway = _Gateway() + ..messages = [ + { + 'id': 'msg_opold', + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'Already there'}, + ], + }, + ]; + addTearDown(gateway.close); + final drafts = MemoryChatDraftStore( + unsent: { + 's': [ + { + 'session_id': 's', + 'text': 'Already there', + 'operation_id': 'op-old', + 'native_message_id': 'msg_opold', + }, + ], + }, + ); + await _host(tester, gateway, drafts); + + expect(_state('failed'), findsNothing); + expect(find.text('Already there'), findsOneWidget); + expect(drafts.unsentEntries, isEmpty); + }); +} diff --git a/app/tool/chat_composer_probe_entry.dart b/app/tool/chat_composer_probe_entry.dart index 4172d078..93360aca 100644 --- a/app/tool/chat_composer_probe_entry.dart +++ b/app/tool/chat_composer_probe_entry.dart @@ -95,6 +95,10 @@ class _ProbeGateway implements ApiGateway { if (text.toLowerCase().contains('refuse')) { throw StateError('The fixture refused this prompt.'); } + // `hold`: the reply never arrives, so the message stays Sending…. + if (text.toLowerCase().contains('hold')) { + return Completer().future; + } final queued = text.toLowerCase().contains('queued'); Timer(const Duration(milliseconds: 150), _running); await Future.delayed(const Duration(milliseconds: 450)); @@ -197,6 +201,11 @@ const _probeStyle = String.fromEnvironment( /// Browser overrides: `?platform=cupertino|material`, `?theme=dark|light`, /// `?long=1`, `?paras=1` (a chunked multi-paragraph reply), `?tasks=`, `?mode=0` (no permission mode recorded) and /// `?model=0` (a backend without models). +/// +/// Delivery states: `?send=` types and sends that text once the thread +/// has loaded (`hold` never replies, `queued` queues, `refuse` is refused), and +/// `?unsent=1` opens with a message a previous visit sent but never saw +/// accepted, as after a page reload mid-request. Map get _query => Uri.base.queryParameters; int get _probeTasks => int.tryParse(_query['tasks'] ?? '') ?? 0; @@ -219,9 +228,28 @@ void main() { }, }, onBack: () {}, - drafts: MemoryChatDraftStore(), + drafts: MemoryChatDraftStore( + drafts: {'probe-composer': ?_query['send']}, + unsent: { + if (_query['unsent'] == '1') + 'probe-composer': [ + { + 'session_id': 'probe-composer', + 'text': 'Did this one reach the server before the reload?', + 'operation_id': 'probe-op-reloaded', + 'native_message_id': 'msg_probeopreloaded', + }, + ], + }, + ), newOperationId: gateway.nextOperation, ); + if (_query['send'] != null) { + Timer( + const Duration(milliseconds: 1200), + () => _press('chat-composer-primary'), + ); + } if (cupertino) { runApp( CupertinoApp( @@ -243,3 +271,20 @@ void main() { ), ); } + +/// Presses the native button carrying [key], as a tap would; the probe has no +/// pointer in a headless screenshot. +void _press(String key) { + void visit(Element element) { + final widget = element.widget; + if (widget.key == Key(key)) { + if (widget is CupertinoButton) widget.onPressed?.call(); + if (widget is ButtonStyleButton) widget.onPressed?.call(); + if (widget is IconButton) widget.onPressed?.call(); + return; + } + element.visitChildren(visit); + } + + WidgetsBinding.instance.rootElement?.visitChildren(visit); +}