Files
pipelines/app/lib/features/chat/domain/chat_shown_items.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

174 lines
6.2 KiB
Dart

import '../../../core/api_gateway.dart';
import 'chat_transcript.dart';
/// Entries a chat's model showed the operator through the Pipelines tools
/// (`show_file`, `show_image`, `show_html`, `show_diff`, `notify`).
///
/// The server keeps them per chat, outside the harness transcript: the
/// `chat_subscribe` reply carries the retained list (oldest first) and a
/// pushed `chat_shown` frame carries each new or updated item. Items are keyed
/// by `id`; a later copy replaces the held one in place.
/// The recorded kinds.
const chatShownKinds = {'file', 'image', 'html', 'diff', 'notify'};
/// The transcript row kind an item is drawn as.
const String chatShownRowKind = 'shown';
/// The items of a `chat_shown` body for [sessionId], or null when the body is
/// absent, malformed or for another chat. Items of unknown kind or without an
/// id are dropped rather than drawn as something they are not.
List<JsonMap>? chatShownItemsOf(Object? body, String sessionId) {
if (body is! Map || '${body['session_id'] ?? ''}' != sessionId) return null;
final items = body['items'];
if (items is! List) return const [];
return [
for (final item in items.whereType<Map>())
if ('${item['id'] ?? ''}'.isNotEmpty &&
chatShownKinds.contains(item['kind']))
Map<String, dynamic>.from(item),
];
}
/// [held] with [incoming] merged by id: a known item is replaced where it is,
/// a new one is appended. [replace] adopts [incoming] as the whole list (the
/// subscribe reply is the server's complete retained set).
List<JsonMap> mergeChatShownItems(
List<JsonMap> held,
List<JsonMap> incoming, {
bool replace = false,
}) {
if (replace) return List<JsonMap>.unmodifiable(incoming);
final byId = {for (final item in incoming) '${item['id']}': item};
final merged = [
for (final item in held) byId.remove('${item['id']}') ?? item,
...byId.values,
];
return List<JsonMap>.unmodifiable(merged);
}
/// The tool names a harness reports for the Pipelines tools: Claude Code
/// `mcp__pipelines__show_file`, OpenCode `pipelines_show_file`, Codex
/// `pipelines/show_file`.
final RegExp _pipelinesTool = RegExp(
r'^(?:mcp__pipelines__|pipelines_|pipelines/)'
r'(?:show_file|show_image|show_html|show_diff|notify)$',
);
/// Whether [part] is a call of a Pipelines tool whose result the transcript
/// draws as its own entry. A failed call stays a normal tool row: its error is
/// the only record of what went wrong.
bool chatPipelinesToolRepresented(JsonMap part) {
if ('${part['type'] ?? ''}' != 'tool') return false;
if (!_pipelinesTool.hasMatch('${part['name'] ?? ''}'.trim())) return false;
final state = part['state'];
return !(state is Map && '${state['status'] ?? ''}' == 'error');
}
int? _createdAt(JsonMap value) => chatMessageCreatedAt(value);
/// A transcript row's recorded time, or null for a row without one.
int? _rowTime(JsonMap row) {
final own = _createdAt(row);
if (own != null) return own;
final message = row['message'];
if (message is! Map) return null;
return _createdAt(
message is JsonMap ? message : Map<String, dynamic>.from(message),
);
}
// Derived per input object. Rows and items are values that are never changed
// in place (see [transcriptRows]), so an unchanged turn keeps one derived row
// object across builds instead of an equal copy per build.
final Expando<List<JsonMap>> _withoutTools = Expando('chat row without tools');
final Expando<JsonMap> _shownRows = Expando('chat shown row');
/// [row] without its represented Pipelines tool calls: the row itself when it
/// has none, nothing when they were all it held.
List<JsonMap> _withoutToolCalls(JsonMap row) {
final parts = row['parts'];
if (row['kind'] != 'assistant' || parts is! List) return [row];
final kept = [
for (final part in parts.whereType<Map>())
if (!chatPipelinesToolRepresented(
part is JsonMap ? part : Map<String, dynamic>.from(part),
))
part,
];
if (kept.length == parts.length) return [row];
if (kept.isNotEmpty ||
row['streaming'] == true ||
row['activityRecords'] != null) {
return [
{...row, 'parts': kept},
];
}
return const [];
}
/// [rows] (from [transcriptRows]) with the Pipelines tool calls removed from
/// answer turns and each shown item placed by its time.
///
/// An item goes before the first timed row recorded after it, else after the
/// last timed row (so it never follows the pending cards or the response
/// shell that come after the transcript). While older history pages remain
/// ([hasMore]), an item older than the oldest loaded row stays out until that
/// page loads, so it is never drawn above messages that precede it.
List<JsonMap> withChatShownItems(
List<JsonMap> rows,
List<JsonMap> items, {
required bool hasMore,
}) {
final out = <JsonMap>[
for (final row in rows) ...(_withoutTools[row] ??= _withoutToolCalls(row)),
];
if (items.isEmpty) return out;
final timed = [
for (final item in items)
if (_createdAt(item) != null) item,
]..sort((a, b) => _createdAt(a)!.compareTo(_createdAt(b)!));
final times = [for (final row in out) _rowTime(row)];
int? oldest;
var lastTimed = -1;
for (var index = 0; index < out.length; index++) {
final time = times[index];
if (time == null) continue;
oldest ??= time;
lastTimed = index;
}
final result = <JsonMap>[];
var next = 0;
JsonMap rowOf(JsonMap item) => _shownRows[item] ??= {
'kind': chatShownRowKind,
'key': 'chat-shown-${item['id']}',
'messageIds': ['shown:${item['id']}'],
'item': item,
};
if (hasMore) {
while (next < timed.length &&
(oldest == null || _createdAt(timed[next])! < oldest)) {
next++;
}
}
for (var index = 0; index < out.length; index++) {
final time = times[index];
if (time != null) {
while (next < timed.length && _createdAt(timed[next])! < time) {
result.add(rowOf(timed[next++]));
}
}
result.add(out[index]);
if (index == lastTimed) {
while (next < timed.length) {
result.add(rowOf(timed[next++]));
}
}
}
// A transcript with no timed row yet: the items lead.
if (lastTimed < 0) {
return [for (; next < timed.length; next++) rowOf(timed[next]), ...result];
}
return result;
}