Files
pipelines/app/lib/features/chat/conversation/chat_thread_controller.dart
T
alan aeefe67631 Chat: a reply that streams during a history read is shown whole
The thread controller records numbered (seq) deltas that arrive while the
newest page is read and folds back those the page does not include, onto its
live parts or parts it lacks; a delta the page already included is not added
again when it arrives late. The page's order now leads when a reply streamed
during the initial read, so the reply stays below its prompt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:46:54 +00:00

580 lines
20 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import '../domain/chat_account_usage.dart';
import '../domain/chat_live_frames.dart';
import '../domain/chat_sessions.dart';
import '../domain/chat_shown_items.dart';
import '../domain/chat_transcript.dart';
import '../domain/chat_turn_diffs.dart';
import 'chat_server_queue.dart';
import 'chat_thread_cards.dart';
import 'chat_transcript_cache.dart';
/// One open conversation's transcript and live turn state.
///
/// The controller attaches to exactly one session: it subscribes that session
/// with `chat_subscribe`, then reads the newest history page. Pushed frames for
/// any other session are ignored, a superseded or disposed read never lands, and
/// a reconnect/resync replaces the held turn with the newest authoritative page
/// instead of merging stale state. The server detaches subscriptions when the
/// socket closes, so disposal only cancels the local stream (there is no
/// `chat_unsubscribe`).
///
/// Approval requests and question forms are recorded cards rather than
/// messages; [ChatThreadCards] owns their frames, answers and send gates.
///
/// A [cached] transcript from an earlier visit is shown at once instead of a
/// loading state, but it is only a starting point: [load] still subscribes and
/// reads, and the newest page replaces every cached message no live frame has
/// changed since (see [refreshCachedChatHistory]).
class ChatThreadController extends ChangeNotifier {
ChatThreadController(
this.gateway,
this.sessionId, {
ChatTranscriptSnapshot? cached,
}) {
if (cached != null) {
_messages = cached.messages;
_cursor = cached.cursor;
_hasMore = cached.hasMore;
_loaded = true;
_untouchedCached = {
for (final message in cached.messages)
if (message['id'] != null) message['id'] as Object,
};
}
_subscription = gateway.frames.listen(_onFrame);
}
final ApiGateway gateway;
final String sessionId;
late final ChatRepository _repository = ChatRepository(gateway);
late final ChatThreadCards _cards = ChatThreadCards(
repository: _repository,
sessionId: sessionId,
notify: _notify,
isAlive: () => !_disposed,
);
StreamSubscription<JsonMap>? _subscription;
final _transcriptChanges = ChangeNotifier();
final ChatServerQueue _queue = ChatServerQueue();
final ChatLiveFrames _live = ChatLiveFrames();
/// The per-turn change summaries the transcript's change chips show.
final ChatTurnDiffs turnDiffs = ChatTurnDiffs();
/// Fetches one turn's recorded changes through this chat's own gateway.
Future<JsonMap> turnDiff(String turnId) =>
_repository.turnDiff(sessionId, turnId);
/// Told about every queue body the server sends (the subscribe reply's and
/// each `chat_queue` frame), so delivery states follow the server.
void Function(JsonMap queue)? onQueue;
List<JsonMap> _messages = const [];
List<JsonMap> _shown = const [];
bool _running = false;
bool _loaded = false;
bool _loading = false;
bool _hasMore = false;
String _cursor = '';
String _nativeTurnId = '';
String? _liveAssistantMessageId;
String? _awaitingResponseOperation;
JsonMap? _usage;
ChatAccountUsage? _accountUsage;
String? _error;
bool _subscribed = false;
String? _subscriptionError;
bool _disposed = false;
int _generation = 0;
bool _resyncing = false;
bool _resyncAgain = false;
/// Ids of cached messages that no frame or read has confirmed yet; null once
/// a read replaced the cached transcript, or when there was none.
Set<Object>? _untouchedCached;
/// True while the held transcript came from a successful read on the current
/// connection; a socket gap clears it until the repair's read succeeds.
bool _authoritative = false;
/// Whether this visit opened on a cached transcript that no read has
/// replaced yet.
bool get showingCached => _untouchedCached != null;
/// The transcript to keep for a later visit, or null when the held one is
/// not backed by a successful read on the current connection.
ChatTranscriptSnapshot? get snapshot => _authoritative
? ChatTranscriptSnapshot(
messages: _messages,
cursor: _cursor,
hasMore: _hasMore,
)
: null;
List<JsonMap> get messages => _messages;
/// What the model showed through the Pipelines tools ([chatShownItemsOf]),
/// as the server retains it, oldest first.
List<JsonMap> get shown => _shown;
/// The prompts the server still holds for this session, in delivery order.
List<JsonMap> get queuedPrompts => _queue.prompts;
/// The queued prompts not already drawn in the transcript (this device's
/// own optimistic bubble and another device's echo are drawn in place).
/// They follow the transcript, since none has reached the harness yet.
List<JsonMap> get queuedOutsideTranscript => [
for (final prompt in _queue.prompts)
if (!_messages.any(
(message) => message['operation_id'] == prompt['operation_id'],
))
prompt,
];
/// Whether [operationId] is still waiting in the server's queue.
bool isQueued(String operationId) => _queue.holds(operationId);
/// Removes one queued prompt on the server. A refusal (it was already sent)
/// is thrown to the caller; the queue itself only changes from the reply.
Future<void> unqueue(String operationId) async {
final reply = await _repository.unqueue(sessionId, operationId);
if (_disposed) return;
_applyQueue(reply['chat_queue']);
}
/// Usage-only snapshots refresh Info, not the expensive transcript tree.
Listenable get transcriptChanges => _transcriptChanges;
bool get running => _running;
bool get awaitingResponse => _awaitingResponseOperation != null;
String? get liveAssistantMessageId => _liveAssistantMessageId;
bool get loaded => _loaded;
bool get loading => _loading;
bool get hasMore => _hasMore;
/// The server's opaque older-page cursor. Never interpreted, only passed back.
String get cursor => _cursor;
/// The latest recorded usage snapshot, or null before the harness reports.
/// Unknown fields stay null, so a viewer can distinguish them from zero.
JsonMap? get usage => _usage;
/// The harness account's latest reported quota, or null while unknown. It
/// is account state: a frame without one keeps the last known value.
ChatAccountUsage? get accountUsage => _accountUsage;
/// Adopts the quota of the Claude account the operator just switched to
/// (see ChatAccountUsage.switchedAt), which ends a limit the previous
/// account had reached.
void accountSwitched(ChatAccountUsage usage) {
_accountUsage = usage;
_notify(transcript: false);
}
String? get error => _error;
bool get subscribed => _subscribed;
String? get subscriptionError => _subscriptionError;
/// Every retained permission request, settled or still open, in server order.
List<JsonMap> get permissionFrames => _cards.permissions;
/// Every retained question form, including answered and expired ones.
List<JsonMap> get questionForms => _cards.forms;
String permissionAnswerFor(String requestId) => _cards.answerFor(requestId);
String? permissionErrorFor(String requestId) =>
_cards.permissionErrorFor(requestId);
String? questionErrorFor(String formId) => _cards.formErrorFor(formId);
/// Answer one pending approval through the card collaborator.
Future<void> replyPermission(String requestId, String decision) =>
_cards.replyPermission(requestId, decision);
/// Answer or close a pending question through the card collaborator.
Future<void> answerQuestion(
String formId,
Map<String, dynamic> answers,
String action,
) => _cards.answerQuestion(formId, answers, action);
/// Subscribes this session, then loads its newest history page.
Future<void> load() async {
if (_disposed) return;
final token = ++_generation;
_loading = true;
_error = null;
_notify();
await _attach();
if (!_owned(token)) return;
await _readNewest(token, replaceHeldTurn: false);
}
/// Reads the next older page. Only offered while the server says `has_more`;
/// the cursor is the server's own `next_cursor`, passed back verbatim.
Future<void> loadOlder() async {
if (_disposed || _loading || !_hasMore) return;
final token = ++_generation;
_loading = true;
_error = null;
_notify();
try {
final page = await _repository.history(
sessionId,
cursor: _cursor,
limit: 200,
);
if (!_owned(token)) return;
turnDiffs.apply(page['turnDiffs'], sessionId);
final merged = mergeChatHistory(
{'messages': _messages},
page,
older: true,
);
_applyPage(merged);
} catch (error) {
if (!_owned(token)) return;
_loading = false;
_error = '$error';
}
_notify();
}
/// The reconnect/resync repair: settle the held turn, re-attach the session,
/// then replace the conversation with the newest authoritative page. Activity
/// replayed while re-attaching (a running step) is fresh native state
/// and survives the replacement. A resync frame also lands here.
Future<void> resync() async {
if (_disposed) return;
if (_resyncing) {
_resyncAgain = true;
return;
}
_resyncing = true;
do {
_resyncAgain = false;
await _resyncOnce();
} while (_resyncAgain && !_disposed);
_resyncing = false;
}
Future<void> _resyncOnce() async {
final token = ++_generation;
_loading = true;
// A socket drop removed the frames feeding the turn, so no held turn may
// keep claiming to run until the re-subscribe proves otherwise.
_running = false;
_nativeTurnId = '';
_liveAssistantMessageId = null;
_awaitingResponseOperation = null;
_authoritative = false;
_notify();
await _attach(force: true);
if (!_owned(token)) return;
await _readNewest(token, replaceHeldTurn: true);
}
Future<void> _readNewest(int token, {required bool replaceHeldTurn}) async {
// Deltas of a reply streaming during the read: the page holds the reply
// up to its own point, and those after it are folded back on top.
final frames = _live.beginRead();
try {
final page = await _repository.history(sessionId, limit: 200);
if (!_owned(token)) {
_live.abandon(frames);
return;
}
turnDiffs.apply(page['turnDiffs'], sessionId);
final inPage = {
for (final message in (page['messages'] as List? ?? const []))
if (message is Map) message['id'],
};
if (replaceHeldTurn) {
_messages = (page['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
.toList();
_cursor = '${page['nextCursor'] ?? ''}';
_hasMore = page['hasMore'] == true;
} else if (_untouchedCached case final untouched?) {
// The cached transcript was a placeholder: the page decides what it
// still holds, and live arrivals since reopening are kept after it.
_applyPage(refreshCachedChatHistory(_messages, page, untouched));
} else {
// A live frame may have arrived while the page was loading; merge it
// over the held transcript instead of replacing it. The page's order
// leads: a reply that streamed during the read stays below its prompt.
_applyPage(
mergeChatHistory({'messages': _messages}, page, older: true),
);
}
_messages = _live.settle(
frames,
page,
_messages,
replaced: (id) => replaceHeldTurn || inPage.contains(id),
);
_untouchedCached = null;
_authoritative = true;
_loaded = true;
_loading = false;
_error = null;
} catch (error) {
_live.abandon(frames);
if (!_owned(token)) return;
// A refused read is not an empty successful history: the reason stays
// visible and the held transcript is kept.
_loaded = true;
_loading = false;
_error = '$error';
}
_notify();
}
/// Attaches the session stream once per connection. A refusal leaves history
/// usable (the live stream is simply not attached) and is retried on resync.
Future<void> _attach({bool force = false}) async {
if (_disposed || (_subscribed && !force)) return;
try {
final reply = await _repository.subscribe(sessionId);
if (_disposed) return;
_subscribed = true;
_subscriptionError = null;
_applyQueue(reply['chat_queue']);
_applyShown(reply['chat_shown'], replace: true);
} catch (error) {
// History stays usable, but the UI must report that live updates failed.
if (_disposed) return;
_subscribed = false;
_subscriptionError = '$error';
}
}
/// Adopts the server's queue. A prompt the server removed or could not
/// deliver leaves the transcript: it never reached the harness.
void _applyQueue(Object? body) {
if (!_queue.apply(sessionId, body)) return;
final frame = Map<String, dynamic>.from(body as Map);
for (final key in const ['removed', 'failed']) {
final operation = '${frame[key] ?? ''}';
if (operation.isEmpty) continue;
_messages = [
for (final message in _messages)
if (message['operation_id'] != operation) message,
];
if (_awaitingResponseOperation == operation) {
_awaitingResponseOperation = null;
}
}
onQueue?.call(frame);
_notify();
}
/// Adopts the subscribe reply's retained list, or one pushed item.
void _applyShown(Object? body, {bool replace = false}) {
final items = chatShownItemsOf(body, sessionId);
if (items == null) return;
_shown = mergeChatShownItems(_shown, items, replace: replace);
_notify();
}
void _onFrame(JsonMap envelope) {
if (_disposed) return;
if (envelope['type'] == 'chat_shown') {
_applyShown(envelope['chat_shown']);
return;
}
if (envelope['type'] == 'chat_queue') {
_applyQueue(envelope['chat_queue']);
return;
}
if (envelope['type'] == 'chat_turn_diffs') {
if (turnDiffs.apply(envelope['chat_turn_diffs'], sessionId)) _notify();
return;
}
if (envelope['type'] == 'chat_permission') {
final permission = envelope['chat_permission'];
if (permission is! Map) return;
final frame = Map<String, dynamic>.from(permission);
if ('${frame['session_id'] ?? ''}' != sessionId) return;
_cards.foldPermission(frame);
return;
}
final body = _eventBody(envelope);
if (body == null || body['session_id'] != sessionId) return;
if (body['kind'] == 'resync') {
unawaited(resync());
return;
}
if (body['kind'] == 'usage') {
// Usage replaces the last snapshot and never adds a message, runs a turn
// or admits a queued prompt. An unusable snapshot keeps the previous
// recorded values instead of replacing them with fabricated zeros.
final raw = body['usage'];
final account = chatAccountUsage(raw is Map ? raw['account'] : null);
if (account != null) _accountUsage = account;
final usage = chatUsageSnapshot(raw);
if (usage == null || !_reportedUsage(usage)) {
if (account != null) _notify(transcript: false);
return;
}
_usage = usage;
_notify(transcript: false);
return;
}
if (body['kind'] == 'form') {
final form = body['form'];
if (form is! Map) return;
_cards.foldForm(
Map<String, dynamic>.from(form),
raisedIn: _answeringMessageId(),
);
return;
}
// A delta a history page already included is not added again.
if (!_live.admit(body)) return;
final current = _thread;
final next = applyChatEvent(current, body);
if (identical(next, current)) return;
// A frame for a cached message is fresh state the next read must not drop.
final changed = body['message_id'];
if (changed != null) _untouchedCached?.remove(changed);
_messages = chatMessageList(next['messages']);
_running = next['running'] == true;
if (!_running) {
_liveAssistantMessageId = null;
} else if (const ['text', 'reasoning', 'tool'].contains(body['kind']) &&
chatInjectedKind({'kind': body['message_kind']}) == null) {
_liveAssistantMessageId = body['message_id'] as String?;
}
if (body['kind'] == 'step' &&
(body['step'] as Map?)?['status'] == 'ended' &&
(body['step'] as Map?)?['intermediate'] != true) {
_awaitingResponseOperation = null;
}
_nativeTurnId = '${next['nativeTurnId'] ?? ''}';
_notify();
}
/// Whether a normalized snapshot names a scope or carries a recorded fact.
/// A window of zero reports no usable limit, and a rate basis alone reports
/// no number at all, so neither counts as a fact on its own.
bool _reportedUsage(JsonMap usage) {
if ('${usage['scope'] ?? ''}'.isNotEmpty) return true;
if (usage['context_window'] is int &&
(usage['context_window'] as int) > 0) {
return true;
}
return const [
'total_tokens',
'context_tokens',
'cost_usd',
'output_tokens_per_second',
].any((key) => usage[key] != null);
}
/// The agent message a question frame arrives during: the streamed reply,
/// else the last answer when it is the agent's. A question raised before the
/// reply starts names none rather than an older turn.
String? _answeringMessageId() {
final live = _liveAssistantMessageId;
if (live != null && live.isNotEmpty) return live;
for (final message in _messages.reversed) {
if (chatInjectedKind(message) != null) continue;
if (message['role'] != 'assistant') return null;
final id = '${message['id'] ?? ''}'.trim();
return id.isEmpty ? null : id;
}
return null;
}
/// The pushed envelope body, or null for another message type. The server
/// wraps `chat_event` in the typed envelope; domain code never sees the
/// transport fields.
JsonMap? _eventBody(JsonMap envelope) {
if (envelope['type'] != 'chat_event') return null;
final body = envelope['chat_event'];
if (body is! Map) return null;
return Map<String, dynamic>.from(body);
}
JsonMap get _thread => {
'sessionId': sessionId,
'messages': _messages,
'running': _running,
'nativeTurnId': _nativeTurnId,
};
void _applyPage(JsonMap page) {
_messages = (page['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
.toList();
_cursor = '${page['nextCursor'] ?? ''}';
_hasMore = page['hasMore'] == true;
_loaded = true;
_loading = false;
}
bool _owned(int token) => !_disposed && token == _generation;
/// Puts a sent turn into the transcript where it was sent, as the web does:
/// after everything held so far and before any reply frame that follows. It
/// carries the id the harness will persist, so the live echo is ignored and
/// the history copy replaces it in place instead of moving it.
void insertLocal(JsonMap message) {
if (_disposed) return;
if (!_running) {
_awaitingResponseOperation ??= message['operation_id'] as String?;
}
_messages = [..._messages, message];
_notify();
}
/// Removes a sent turn the server refused.
void removeLocal(String operationId) {
if (_disposed) return;
if (_awaitingResponseOperation == operationId) {
_awaitingResponseOperation = null;
}
final next = [
for (final message in _messages)
if (message['operation_id'] != operationId) message,
];
if (next.length == _messages.length) return;
_messages = next;
_notify();
}
/// An accepted queued prompt waits behind another turn, not its own reply.
void promptAccepted(String operationId, {required bool queued}) {
if (_disposed || !queued || _awaitingResponseOperation != operationId) {
return;
}
_awaitingResponseOperation = null;
_notify();
}
void _notify({bool transcript = true}) {
if (_disposed) return;
notifyListeners();
if (transcript && !_disposed) _transcriptChanges.notifyListeners();
}
@override
void dispose() {
_disposed = true;
_transcriptChanges.dispose();
_generation++;
unawaited(_subscription?.cancel());
super.dispose();
}
}