Files
pipelines/app/lib/features/chat/domain/chat_activity_groups.dart
T
alan 22866ec0ce Chat: fold activity-only rows between messages into one summary line
Tool-only turns, thinking-only turns and background-task notices that sit
between two content rows become one collapsible activity_group row, e.g.
"Ran 7 commands · used 9 tools · 8 background tasks finished · 1 failed",
the failure count in the error colour and never ellipsized. Expanding it
shows the folded rows as they render on their own. A run's task notices
fold into one chip at the newest notice; a notice whose id recurs later is
counted only at its latest position.

Grouping is a pure domain step (groupChatActivity) applied last in the
thread view's row pipeline; group rows list every member id so ChatRowKeys
keeps their identity, unchanged runs return the identical group object, and
the transcript anchor accepts a group's agent-turn ids. The scroll fixture
gains ?bgwork=1 for the shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:58:25 +00:00

272 lines
9.6 KiB
Dart

import '../../../core/api_gateway.dart';
import '../shell/chat_shell_history.dart';
import 'chat_task_notices.dart';
import 'chat_tool_calls.dart';
import 'chat_turn_activity.dart';
/// The row kind of a run of activity-only rows folded into one summary line.
const String chatActivityGroupKind = 'activity_group';
/// Whether [row] carries activity only: an agent turn with nothing but tool
/// calls, reasoning or recorded activity (no answer text, file or unknown part,
/// and no footer chip), or a background-task notice. Such rows say that work
/// happened, not what the agent said, so a run of them reads as one line.
///
/// A streaming turn is never activity-only: its live status stays its own row.
bool chatActivityOnlyRow(JsonMap row) {
switch (row['kind']) {
case 'task_notices':
return true;
case 'system_notice':
return _noticeMessage(row) != null;
case 'assistant':
break;
default:
return false;
}
if (row['streaming'] == true || row['turnDiff'] != null) return false;
for (final field in ['permissions', 'questions', chatShellHistoryField]) {
final value = row[field];
if (value is List && value.isNotEmpty) return false;
}
for (final part in row['parts'] as List? ?? const []) {
if (part is! Map) return false;
final type = '${part['type'] ?? ''}';
if (type == 'tool' || type == 'reasoning') continue;
if (type == 'text' && '${part['text'] ?? ''}'.trim().isEmpty) continue;
return false;
}
return true;
}
/// Folds every run of consecutive activity-only rows (see
/// [chatActivityOnlyRow]) between two content rows into one
/// [chatActivityGroupKind] row, so the agent's own messages are not buried
/// under one line per tool turn and one per background-task notice.
///
/// The group lists its member rows in `rows`, as they render on their own.
/// A run's task notices fold into one member at the newest notice's place (a
/// `task_notices` row, or the lone notice), so the background-task chip shows
/// once per run; a notice whose message id recurs later in the transcript is
/// counted only at its latest position. A run of a single agent turn stays that
/// row. The group's `messageIds` lists every member's ids, so [ChatRowKeys]
/// keeps one widget identity as the run grows, and an unchanged run yields the
/// identical group object.
List<JsonMap> groupChatActivity(List<JsonMap> rows) {
final stale = _staleNotices(rows);
final result = <JsonMap>[];
final run = <JsonMap>[];
void close() {
if (run.isEmpty) return;
final members = _members(run, stale);
if (members.length == 1 && members.single['kind'] == 'assistant') {
result.add(members.single);
} else if (members.isNotEmpty) {
result.add(_group(members));
}
run.clear();
}
for (final row in rows) {
if (chatActivityOnlyRow(row)) {
run.add(row);
} else {
close();
result.add(row);
}
}
close();
return result;
}
/// The notice messages a notice row carries, in transcript order.
List<JsonMap> _rowNotices(JsonMap row) {
if (row['kind'] == 'system_notice') {
final message = _noticeMessage(row);
return message == null ? const [] : [message];
}
if (row['kind'] != 'task_notices') return const [];
return [
for (final message in row['messages'] as List? ?? const [])
if (message is Map<String, dynamic> && chatTaskNotice(message) != null)
message,
];
}
JsonMap? _noticeMessage(JsonMap row) {
final message = row['message'];
if (message is! Map<String, dynamic>) return null;
return chatTaskNotice(message) == null ? null : message;
}
/// Notice messages whose id appears again later: only the latest counts.
Set<JsonMap> _staleNotices(List<JsonMap> rows) {
final seen = <String>{};
final stale = Set<JsonMap>.identity();
for (final row in rows.reversed) {
for (final message in _rowNotices(row).reversed) {
final id = '${message['id'] ?? ''}'.trim();
if (id.isNotEmpty && !seen.add(id)) stale.add(message);
}
}
return stale;
}
/// [run]'s members: its agent turns in order, with its current notices as one
/// member where the newest of them was.
List<JsonMap> _members(List<JsonMap> run, Set<JsonMap> stale) {
final members = <JsonMap>[];
final notices = <JsonMap>[];
final sources = <JsonMap>{};
var at = -1;
for (final row in run) {
final rowNotices = _rowNotices(row);
if (rowNotices.isEmpty && row['kind'] == 'assistant') {
members.add(row);
continue;
}
for (final message in rowNotices) {
if (stale.contains(message)) continue;
notices.add(message);
sources.add(row);
at = members.length;
}
}
if (notices.isEmpty) return members;
return members..insert(at, _noticeMember(notices, sources));
}
/// One member for [notices]: the row that already holds exactly them, a lone
/// notice line, or a `task_notices` row (the same object while they hold).
JsonMap _noticeMember(List<JsonMap> notices, Set<JsonMap> sources) {
if (sources.length == 1) {
final source = sources.single;
if (_identical(_rowNotices(source), notices)) return source;
}
if (notices.length == 1) {
final message = notices.single;
return {'kind': 'system_notice', 'key': message['id'], 'message': message};
}
final held = _noticeRows[notices.first];
if (held != null && _identical(held.notices, notices)) return held.row;
final row = <String, dynamic>{
'kind': 'task_notices',
'key': notices.first['id'],
'messageIds': [for (final message in notices) '${message['id'] ?? ''}'],
'messages': notices,
};
_noticeRows[notices.first] = (notices: List.of(notices), row: row);
return row;
}
final Expando<({List<JsonMap> notices, JsonMap row})> _noticeRows = Expando(
'chat activity notices',
);
final Expando<({List<JsonMap> members, JsonMap group})> _groups = Expando(
'chat activity group',
);
bool _identical(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;
}
JsonMap _group(List<JsonMap> members) {
final held = _groups[members.first];
if (held != null && _identical(held.members, members)) return held.group;
var commands = 0, tools = 0, failed = 0, tasks = 0;
var tasksEnded = false, thinking = false;
for (final member in members) {
for (final message in _rowNotices(member)) {
final notice = chatTaskNotice(message)!;
tasks++;
if (notice.outcome == ChatTaskOutcome.failed) failed++;
if (notice.outcome != ChatTaskOutcome.finished) tasksEnded = true;
}
if (member['kind'] != 'assistant') continue;
final parts = [
for (final part in member['parts'] as List? ?? const [])
if (part is Map) Map<String, dynamic>.from(part),
];
final calls = parts.where(isChatToolPart).toList();
// Summed the way each turn's own line words it: a turn of commands only
// says "Ran N commands", any other turn "Used N tools".
if (calls.isNotEmpty && calls.every(chatToolIsCommand)) {
commands += calls.length;
} else {
tools += calls.length;
}
failed += calls.where(chatToolFailed).length;
if (parts.any((part) => part['type'] == 'reasoning')) thinking = true;
}
final first = members.first;
final group = <String, dynamic>{
'kind': chatActivityGroupKind,
'key': 'chat-activity-group-${first['key'] ?? ''}',
'messageIds': [for (final member in members) ..._memberIds(member)],
'rows': members,
'commands': commands,
'tools': tools,
'tasks': tasks,
'tasksEnded': tasksEnded,
'failed': failed,
'thinking': thinking,
};
_groups[first] = (members: List.of(members), group: group);
return group;
}
List<String> _memberIds(JsonMap row) {
final listed = row['messageIds'];
if (listed is List) return [for (final id in listed) '$id'];
final key = '${row['key'] ?? ''}'.trim();
return key.isEmpty ? const [] : [key];
}
/// The member rows a group row folds, in transcript order.
List<JsonMap> chatActivityGroupRows(JsonMap row) => [
for (final member in row['rows'] as List? ?? const [])
if (member is Map<String, dynamic>) member,
];
/// The agent-turn message ids a group holds (what a scroll anchor may name).
List<String> chatActivityGroupTurnIds(JsonMap row) => [
for (final member in chatActivityGroupRows(row))
if (member['kind'] == 'assistant') ..._memberIds(member),
];
/// One piece of a group's summary; [failed] pieces draw in the error colour.
typedef ChatActivitySegment = ({String text, bool failed});
/// A group's summary, e.g. `Ran 7 commands`, `used 9 tools`,
/// `3 background tasks finished`, `1 failed`.
List<ChatActivitySegment> chatActivityGroupSegments(JsonMap row) {
int count(String field) => (row[field] as num?)?.toInt() ?? 0;
String plural(int n, String one) => n == 1 ? '1 $one' : '$n ${one}s';
final commands = count('commands'), tools = count('tools');
final tasks = count('tasks'), failed = count('failed');
final texts = [
if (commands > 0) 'ran ${plural(commands, 'command')}',
if (tools > 0) 'used ${plural(tools, 'tool')}',
if (tasks > 0)
'${plural(tasks, 'background task')} '
'${row['tasksEnded'] == true ? 'ended' : 'finished'}',
];
if (texts.isEmpty) {
texts.add(row['thinking'] == true ? 'reasoning' : 'activity');
}
texts[0] = texts[0][0].toUpperCase() + texts[0].substring(1);
return [
for (final text in texts) (text: text, failed: false),
if (failed > 0) (text: '$failed failed', failed: true),
];
}
/// The summary as one line: its segments joined by ` · `.
String chatActivityGroupLabel(JsonMap row) =>
chatActivityGroupSegments(row).map((segment) => segment.text).join(' · ');