Files
pipelines/app/lib/features/chat/domain/chat_transcript_rows.dart
T
alan 9be31b8ba0 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>
2026-11-22 18:24:02 +00:00

258 lines
8.7 KiB
Dart

import 'dart:collection';
import '../../../core/api_gateway.dart';
import 'chat_task_notices.dart';
import 'chat_transcript.dart';
/// 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.
///
/// Rows are values: nothing downstream changes a row in place, which is what
/// lets [ChatTranscriptRows] hand out the same rows again.
List<JsonMap> transcriptRows(
List<JsonMap> messages, {
List<JsonMap> trailing = const [],
bool running = false,
bool awaitingResponse = false,
String? liveMessageId,
}) => _finish(
[for (final segment in _segments(messages)) ..._segmentRows(segment)],
messages,
trailing: trailing,
running: running,
awaitingResponse: awaitingResponse,
liveMessageId: liveMessageId,
);
/// [transcriptRows] for a transcript that changes a little at a time.
///
/// The rows of a run of consecutive answer messages, or of one other message,
/// depend on those messages alone. Each run's rows are kept while the run holds
/// the identical message objects, so a streamed delta (which replaces only the
/// live message) rebuilds only the live turn, and a prepended history page
/// only the runs it touches. The result equals [transcriptRows] for the same
/// arguments; messages must not be changed in place once passed.
class ChatTranscriptRows {
/// The previous call's runs, by their first message.
Map<JsonMap, _Segment> _held = HashMap.identity();
List<JsonMap> rows(
List<JsonMap> messages, {
List<JsonMap> trailing = const [],
bool running = false,
bool awaitingResponse = false,
String? liveMessageId,
}) {
final next = HashMap<JsonMap, _Segment>.identity();
final rows = <JsonMap>[];
for (final messages in _segments(messages)) {
final held = _held[messages.first];
final segment = held != null && _sameMessages(held.messages, messages)
? held
: _Segment(messages, _segmentRows(messages));
next[messages.first] = segment;
rows.addAll(segment.rows);
}
_held = next;
return _finish(
rows,
messages,
trailing: trailing,
running: running,
awaitingResponse: awaitingResponse,
liveMessageId: liveMessageId,
);
}
static bool _sameMessages(List<JsonMap> a, List<JsonMap> b) {
if (a.length != b.length) return false;
for (var index = 0; index < a.length; index++) {
if (!identical(a[index], b[index])) return false;
}
return true;
}
}
class _Segment {
_Segment(this.messages, this.rows);
final List<JsonMap> messages;
final List<JsonMap> rows;
}
/// Whether [message] folds into an answer turn with its assistant neighbours.
bool _answerPart(JsonMap message) =>
chatInjectedKind(message) == null && message['role'] == 'assistant';
/// [messages] split into runs whose rows depend on the run alone: each maximal
/// run of answer messages, and every other message on its own.
List<List<JsonMap>> _segments(List<JsonMap> messages) {
final segments = <List<JsonMap>>[];
List<JsonMap>? answer;
for (final message in messages) {
if (_answerPart(message)) {
if (answer == null) segments.add(answer = []);
answer.add(message);
} else {
answer = null;
segments.add([message]);
}
}
return segments;
}
/// The rows of one run from [_segments].
List<JsonMap> _segmentRows(List<JsonMap> segment) {
final first = segment.first;
if (!_answerPart(first)) {
final injected = chatInjectedKind(first);
if (injected != null) {
return [
{
'kind': injected == chatKindAgentReport
? 'agent_report'
: 'system_notice',
'key': first['id'],
'message': first,
},
];
}
return [
{'kind': 'user', 'key': first['id'], 'message': first},
];
}
final rows = <JsonMap>[];
String? key;
String model = '';
final ids = <String>[];
final parts = <JsonMap>[];
final activity = <JsonMap>[];
String? activityKey;
int? createdAt;
for (final message in segment) {
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);
}
}
}
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 (parts.isNotEmpty || passive.isNotEmpty) {
rows.add({
'kind': 'assistant',
'key': key,
'messageIds': ids,
'parts': 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,
});
}
return rows;
}
/// The streaming mark, the response shell, task-notice grouping and the
/// trailing cards over the transcript's own [rows]. [rows] is not changed: a
/// marked row is a copy.
List<JsonMap> _finish(
List<JsonMap> rows,
List<JsonMap> messages, {
required List<JsonMap> trailing,
required bool running,
required bool awaitingResponse,
required String? liveMessageId,
}) {
// 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.
String? streamingId = liveMessageId;
if (streamingId == null) {
for (final message in messages.reversed) {
if (chatInjectedKind(message) != null) continue;
if (message['role'] == 'assistant') {
streamingId = '${message['id'] ?? ''}';
}
break;
}
}
var marked = rows;
var hasStreamingRow = false;
if (running && streamingId != null) {
for (var index = rows.length - 1; index >= 0; index--) {
final row = rows[index];
if (row['kind'] == 'assistant' &&
(row['messageIds'] as List).contains(streamingId)) {
marked = List<JsonMap>.of(rows);
marked[index] = {...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)) {
marked = [
...marked,
{
'kind': 'assistant',
'key': 'chat-pending-response',
'messageIds': <String>[],
'parts': <JsonMap>[],
'streaming': true,
},
];
}
// Consecutive background-task notices are one collapsed group.
return [...groupTaskNotices(marked), ...trailing];
}