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>
This commit is contained in:
2026-11-30 15:46:54 +00:00
parent 2cdd524ecc
commit aeefe67631
4 changed files with 266 additions and 3 deletions
@@ -5,6 +5,7 @@ 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';
@@ -61,6 +62,7 @@ class ChatThreadController extends ChangeNotifier {
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();
@@ -280,10 +282,20 @@ class ChatThreadController extends ChangeNotifier {
}
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)) return;
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>()
@@ -297,15 +309,25 @@ class ChatThreadController extends ChangeNotifier {
_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.
_applyPage(mergeChatHistory({'messages': _messages}, page));
// 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.
@@ -416,6 +438,8 @@ class ChatThreadController extends ChangeNotifier {
);
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;
@@ -163,6 +163,9 @@ class ChatRepository {
'nextCursor': '${page['next_cursor'] ?? ''}',
'hasMore': page['has_more'] == true,
'turnDiffs': ?turnDiffs,
// A streaming reply's text so far (see chat_live_frames.dart).
if (page['live_seq'] is int) 'liveSeq': page['live_seq'],
if (page['live_parts'] is List) 'liveParts': page['live_parts'],
};
}
return {
@@ -0,0 +1,84 @@
import '../../../core/api_gateway.dart';
import 'chat_transcript.dart';
/// Joins a history read with the live reply that streams during it.
///
/// A harness that numbers its text and reasoning deltas (`seq`) puts a
/// streaming block's text so far into the newest history page, under the
/// block's live part id, and reports the last delta the page includes
/// (`liveSeq`) and which parts it added (`liveParts`). Without this a client
/// that read history mid-reply (opening the chat, a reconnect, a resync) only
/// ever got the deltas after its read, and the reply's first part was missing.
///
/// [ChatLiveFrames] records the numbered frames that arrive while a read is in
/// flight and, once the page is applied, folds back the ones the page does not
/// include. It also drops a frame already included in a page, which can still
/// be on its way when the page arrives.
class ChatLiveFrames {
final List<List<JsonMap>> _reads = [];
int _included = 0;
/// Starts recording for one read; pass the result to [settle].
List<JsonMap> beginRead() {
final frames = <JsonMap>[];
_reads.add(frames);
return frames;
}
/// Stops recording for a read that will not be applied.
void abandon(List<JsonMap> frames) => _reads.remove(frames);
/// Whether [frame] should be folded into the held transcript, recording it
/// for every read in flight. A frame with no number is always folded.
bool admit(JsonMap frame) {
final seq = frame['seq'];
if (seq is! int) return true;
if (seq <= _included) return false;
_included = seq;
for (final read in _reads) {
read.add(frame);
}
return true;
}
/// [messages] after applying [page]: frames recorded during the read that
/// the page does not include are folded onto the page's copies. [replaced]
/// says whether a message's held copy was replaced by the page (frames for a
/// held copy that was kept are already in it).
List<JsonMap> settle(
List<JsonMap> frames,
JsonMap page,
List<JsonMap> messages, {
required bool Function(Object? messageId) replaced,
}) {
_reads.remove(frames);
final liveSeq = page['liveSeq'];
if (liveSeq is! int) return messages;
if (liveSeq > _included) _included = liveSeq;
final live = {...(page['liveParts'] as List? ?? const [])};
final pageParts = <Object?, Set<Object?>>{};
for (final message in (page['messages'] as List? ?? const [])) {
if (message is! Map) continue;
pageParts[message['id']] = {
for (final part in (message['parts'] as List? ?? const []))
if (part is Map) part['id'],
};
}
var thread = <String, dynamic>{'messages': messages};
for (final frame in frames) {
final seq = frame['seq'];
if (seq is! int || seq <= liveSeq) continue;
final messageId = frame['message_id'];
if (!replaced(messageId)) continue;
final part = frame['part'];
final partId = part is Map ? part['id'] : null;
final held = pageParts[messageId];
// A part the page holds whole (not as live text) is already complete.
if (held != null && held.contains(partId) && !live.contains(partId)) {
continue;
}
thread = applyChatEvent(thread, frame);
}
return chatMessageList(thread['messages']);
}
}