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.
This commit is contained in:
2026-10-31 19:54:48 +00:00
parent 24956266d8
commit 4bc99f490b
15 changed files with 1133 additions and 177 deletions
@@ -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<JsonMap> attachments;
/// Mirrors the web's `nativeChatMessageId(operationId) || local-<operationId>`.
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<void> _writes = Future<void>.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<ChatComposerSend> _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<bool> send({List<JsonMap> 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<bool> 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<void> 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<void> loadUnsent() async {
if (_disposed) return;
List<Object?> 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<JsonMap> messages) {
if (_disposed) return;
final confirmed = deliveries.reconcile(messages);
if (confirmed.isEmpty) return;
_stored.removeWhere(confirmed.contains);
_persistUnsent();
}
Future<bool> _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<void> 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<JsonMap> a, List<JsonMap> 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<void> _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();
}