Files
pipelines/app/lib/features/chat/conversation/chat_composer_controller.dart
T
alan 4bc99f490b 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.
2026-10-31 19:54:48 +00:00

352 lines
11 KiB
Dart

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<JsonMap>? _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<void> _writes = Future<void>.value();
bool _disposed = false;
/// 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.
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<void> 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<void> setDraft(String text) {
if (_disposed || text == _draft) return Future<void>.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 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 text = _draft.trim();
if (text.isEmpty) return false;
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);
// 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;
_queued = reply['chat_queued'] == true;
_forgetStored(intent.operationId);
deliveries.accepted(intent, queued: _queued);
onAccepted?.call(intent, _queued);
_settle(null);
return true;
} catch (error) {
if (_disposed) return false;
final message = '$error';
deliveries.failed(intent);
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;
}
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 {
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;
deliveries.admitQueued();
_notify();
}
String _nextOperationId() =>
newOperationId?.call() ??
'native-chat-${DateTime.now().microsecondsSinceEpoch}-${_operationSeq++}';
Future<void> _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();
}
}