Re-derive only the live turn's transcript rows per streamed delta

ChatTranscriptRows keeps each message run's rows while the run holds the
identical message objects; applyChatEvent and the controller keep untouched
messages' identity. Shown-item filtering, task-notice groups and row-key ids
are held per row object, and the view reads message ids once per list.
Tests check the incremental path equals a full derivation across streaming,
appends, shown items, cards, turn diffs and prepended pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 18:24:02 +00:00
parent 58c72538d5
commit 9be31b8ba0
9 changed files with 698 additions and 199 deletions
+13 -157
View File
@@ -1,5 +1,6 @@
import '../../../core/api_gateway.dart';
import 'chat_task_notices.dart';
export 'chat_transcript_rows.dart';
/// Merge chronological history pages by message id. Incoming authoritative
/// copies replace held copies without changing their order; cursor is opaque.
@@ -56,158 +57,6 @@ JsonMap refreshCachedChatHistory(
return mergeChatHistory({'messages': live}, page, older: true);
}
/// Consecutive assistant messages form one answer turn. All part fields (also
/// future/unknown protocol types) are preserved in original order.
///
/// `key` is the turn's first assistant message id, which is only a display
/// anchor: paging an older assistant message into the turn changes it, so widget
/// identity uses `messageIds`. That list carries every message the folded turn
/// currently holds so the view can keep the same row element while the turn
/// grows at either end.
///
/// A recorded activity sequence is not an answer bubble. Parts whose `type` is
/// `activity` or `compaction` are lifted out of the turn and collapse into one
/// `activity` row before it, carrying the recorded records, the web wording for
/// the latest record and that record's lifecycle state. Several updates of one
/// compaction are therefore one line, never one line per update.
///
/// A message the server marks with a `kind` is content the harness delivered,
/// not a turn: an `agent_report` becomes its own `agent_report` row and a
/// `notice` its own `system_notice` row, on the agent's side, never folded into
/// an answer and never drawn as the operator's bubble (see [chatInjectedKind]).
/// Two or more consecutive background-task notices fold into one
/// `task_notices` row (see [groupTaskNotices]).
///
/// [trailing] rows are conversation cards (permission requests and questions),
/// not messages. They keep the server's order after the transcript, the way the
/// web renders approvals and forms at the end of the conversation.
List<JsonMap> transcriptRows(
List<JsonMap> messages, {
List<JsonMap> trailing = const [],
bool running = false,
bool awaitingResponse = false,
String? liveMessageId,
}) {
final rows = <JsonMap>[];
String? key;
String model = '';
final ids = <String>[];
final parts = <JsonMap>[];
final activity = <JsonMap>[];
String? activityKey;
int? createdAt;
void flush() {
final compactions = activity
.where((p) => chatActivityKind(p) == 'compaction')
.toList();
final passive = activity
.where((p) => chatActivityKind(p) != 'compaction')
.toList();
if (compactions.isNotEmpty) {
final latest = compactions.last;
rows.add({
'kind': 'activity',
'key': activityKey == null ? '' : 'chat-activity-$activityKey',
'records': compactions,
'label': chatActivityLabel(latest),
'state': chatActivityState(latest).toLowerCase(),
});
}
if (key != null && (parts.isNotEmpty || passive.isNotEmpty)) {
rows.add({
'kind': 'assistant',
'key': key,
'messageIds': List<String>.of(ids),
'parts': List<JsonMap>.of(parts),
if (passive.isNotEmpty) 'activityRecords': passive,
// The model that answered, as the server recorded it on the reply.
if (model.isNotEmpty) 'model': model,
'created_at': ?createdAt,
});
}
key = null;
model = '';
ids.clear();
parts.clear();
activity.clear();
activityKey = null;
createdAt = null;
}
for (final message in messages) {
final injected = chatInjectedKind(message);
if (injected != null) {
flush();
rows.add({
'kind': injected == chatKindAgentReport
? 'agent_report'
: 'system_notice',
'key': message['id'],
'message': message,
});
continue;
}
if (message['role'] == 'assistant') {
final id = '${message['id'] ?? ''}'.trim();
key ??= id;
createdAt ??= chatMessageCreatedAt(message);
final recorded = '${message['model'] ?? ''}'.trim();
if (recorded.isNotEmpty) model = recorded;
if (id.isNotEmpty) ids.add(id);
for (final part in (message['parts'] as List? ?? const [])) {
if (part is! Map) continue;
final record = Map<String, dynamic>.from(part);
if (chatActivityType(record)) {
activityKey ??= id.isEmpty ? null : id;
activity.add(record);
} else {
parts.add(record);
}
}
} else {
flush();
rows.add({'kind': 'user', 'key': message['id'], 'message': message});
}
}
flush();
// Prefer the assistant identity that actually streamed: a queued follow-up
// can be later in the transcript while this same reply is still arriving.
// Before a first delta, do not reopen an older reply behind a new user turn.
final answers = [
for (final message in messages)
if (chatInjectedKind(message) == null) message,
];
final streamingId =
liveMessageId ??
(answers.isNotEmpty && answers.last['role'] == 'assistant'
? '${answers.last['id'] ?? ''}'
: null);
var hasStreamingRow = false;
if (running && streamingId != null) {
for (final row in rows.reversed) {
if (row['kind'] == 'assistant' &&
(row['messageIds'] as List).contains(streamingId)) {
row['streaming'] = true;
hasStreamingRow = true;
break;
}
}
}
// Display-only response shell: never inserted into stored message history.
// A queued follow-up does not create a second shell beside the active reply.
if (!hasStreamingRow && (running || awaitingResponse)) {
rows.add({
'kind': 'assistant',
'key': 'chat-pending-response',
'messageIds': <String>[],
'parts': <JsonMap>[],
'streaming': true,
});
}
// Consecutive background-task notices are one collapsed group.
return [...groupTaskNotices(rows), ...trailing];
}
/// The protocol records creation in epoch milliseconds. Invalid values do not
/// acquire an invented display time.
int? chatMessageCreatedAt(JsonMap message) {
@@ -312,6 +161,14 @@ List<JsonMap> reconcileChatUser(List<JsonMap> messages, JsonMap remote) {
return result;
}
/// The messages of a decoded `messages` value. A message that already is a
/// [JsonMap] is kept as the same object (messages are never changed in place);
/// any other map is converted.
List<JsonMap> chatMessageList(Object? messages) => [
for (final message in (messages as List? ?? const []).whereType<Map>())
message is JsonMap ? message : Map<String, dynamic>.from(message),
];
/// Fold a live chat frame into an immutable thread snapshot. Text and reasoning
/// deltas append by part id, tool snapshots merge without dropping prior fields,
/// and step frames update turn activity. Frames for another session are ignored.
@@ -322,10 +179,9 @@ JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
session != frame['session_id']) {
return thread;
}
final messages = (thread['messages'] as List? ?? const [])
.whereType<Map>()
.map((m) => Map<String, dynamic>.from(m))
.toList();
// Untouched messages keep their identity, so derived rows held for them
// (see ChatTranscriptRows) are reused; a changed message is a new map.
final messages = chatMessageList(thread['messages']);
final kind = frame['kind'];
if (kind == 'user') {
final part = frame['part'];