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>
This commit is contained in:
2026-11-25 10:58:25 +00:00
parent 33874005c4
commit 22866ec0ce
10 changed files with 963 additions and 13 deletions
@@ -32,6 +32,8 @@ import '../ui/transcript/chat_transcript_selection.dart';
import '../ui/transcript/chat_injected_rows.dart';
import '../ui/transcript/shown/chat_shown_card.dart';
import '../ui/transcript/chat_task_notices_group.dart';
import '../ui/transcript/chat_activity_group_view.dart';
import '../domain/chat_activity_groups.dart';
import '../ui/transcript/chat_turn_diff_chip.dart';
import '../../artifacts/actions/artifact_file_bridge.dart';
import '../domain/chat_session_handoff.dart';
@@ -1183,12 +1185,17 @@ class _ChatThreadViewState extends State<ChatThreadView> {
final compactionNotice = _noticeOf(notices, ChatNoticeKind.compaction);
// The operator's own shell commands sit among the turns by start time;
// dismissed ones fold into a chip under the answer that followed them.
final rows = attachChatShellHistory(
withChatShellRunRows([
for (final row in allRows)
if (!_hiddenRunningCompaction(row)) row,
], _shellRuns.runs),
_shellRuns.dismissedRuns,
// A run of activity-only rows (tool turns, background-task notices)
// between two messages folds into one summary line last, once every
// chip has found its row.
final rows = groupChatActivity(
attachChatShellHistory(
withChatShellRunRows([
for (final row in allRows)
if (!_hiddenRunningCompaction(row)) row,
], _shellRuns.runs),
_shellRuns.dismissedRuns,
),
);
// Older pages prepend messages and a live frame can append one, so a
// folded assistant turn's first message id is not a stable identity.
@@ -1728,6 +1735,14 @@ class _ChatThreadViewState extends State<ChatThreadView> {
);
}
if (kind == 'task_notices') return ChatTaskNoticesGroup(row: row);
if (kind == chatActivityGroupKind) {
// Each folded row is built (and memoised) as it would be on its own.
return ChatActivityGroupView(
row: row,
memberBuilder: (member) =>
_transcriptRow(member, '$key/${member['key'] ?? ''}'),
);
}
if (kind == 'questions') return ChatQuestionsRow(row: row);
if (kind == 'permission' || kind == 'question') {
return ChatTranscriptCard(
@@ -1,4 +1,5 @@
import '../../../core/api_gateway.dart';
import '../domain/chat_activity_groups.dart';
/// Where an opened transcript is split into its older and newer halves.
///
@@ -49,10 +50,17 @@ int chatTranscriptAnchorIndex(List<JsonMap> rows, String? anchor) {
return -1;
}
/// The stored message ids of one user or assistant row. Cards, activity lines
/// and the pending-response shell carry none and can never be an anchor.
/// The stored message ids of one user or assistant row, or of the agent turns
/// an activity group folds. Cards, notices, activity lines and the
/// pending-response shell carry none and can never be an anchor.
List<String> _messageIds(JsonMap row) {
final kind = row['kind'];
if (kind == chatActivityGroupKind) {
return [
for (final id in chatActivityGroupTurnIds(row))
if (id.trim().isNotEmpty) id.trim(),
];
}
if (kind == 'assistant') {
final listed = row['messageIds'];
if (listed is! List) return const [];
@@ -0,0 +1,271 @@
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(' · ');
@@ -78,7 +78,7 @@ class ChatTurnActivityData {
return title.isNotEmpty
? title
: chatToolDetail(p) ??
(_command(p)
(chatToolIsCommand(p)
? 'Running a command'
: 'Running ${chatToolLabel(p)}');
}
@@ -86,7 +86,7 @@ class ChatTurnActivityData {
if (calls.isEmpty) {
return records.isNotEmpty ? 'Activity details' : 'Reasoning';
}
final commands = calls.every(_command);
final commands = calls.every(chatToolIsCommand);
final failed = calls.where(chatToolFailed).length;
final unfinished = calls.any((p) {
final state = p['state'];
@@ -115,7 +115,8 @@ class ChatTurnActivityData {
bool get failed => tools.any(chatToolFailed);
}
bool _command(JsonMap tool) => const [
/// Whether [tool] is a shell command (`Ran N commands`), not another tool.
bool chatToolIsCommand(JsonMap tool) => const [
'bash',
'shell',
'command',
@@ -0,0 +1,123 @@
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../../../ui/adaptive/platform.dart';
import '../../domain/chat_activity_groups.dart';
import 'chat_turn_activity_view.dart';
/// A run of activity-only rows (tool turns, background-task notices) as one
/// summary line, e.g. `Ran 7 commands · used 9 tools · 1 failed`, the failure
/// in the error colour. Activating it shows the folded rows beneath, each as
/// it renders on its own.
class ChatActivityGroupView extends StatefulWidget {
const ChatActivityGroupView({
super.key,
required this.row,
required this.memberBuilder,
});
/// A [chatActivityGroupKind] row (see [groupChatActivity]).
final JsonMap row;
/// Builds one folded row the way the transcript builds it on its own.
final Widget Function(JsonMap member) memberBuilder;
@override
State<ChatActivityGroupView> createState() => _ChatActivityGroupViewState();
}
class _ChatActivityGroupViewState extends State<ChatActivityGroupView> {
bool _expanded = false;
void _toggle() => setState(() => _expanded = !_expanded);
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final color = scheme.onSurfaceVariant;
final segments = chatActivityGroupSegments(widget.row);
final label = chatActivityGroupLabel(widget.row);
final counts = [
for (final segment in segments)
if (!segment.failed) segment,
];
final failures = [
for (final segment in segments)
if (segment.failed) segment,
];
// Desktop hover hugs the label; phones keep the full-width touch row, as
// a turn's own activity line does.
final compact = prefersCompactHitTargets(context);
final summary = ConstrainedBox(
constraints: const BoxConstraints(minHeight: 32),
child: Row(
mainAxisSize: compact ? MainAxisSize.min : MainAxisSize.max,
children: [
// The counts shrink first on a narrow window; the failure count
// stays whole, in the error colour.
Flexible(
child: Text(
[for (final segment in counts) segment.text].join(' · '),
key: const Key('chat-activity-group-label'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color),
),
),
for (final segment in failures)
Text(
' · ${segment.text}',
key: const Key('chat-activity-group-failed'),
maxLines: 1,
style: TextStyle(color: scheme.error),
),
const SizedBox(width: 4),
Icon(
_expanded ? Icons.expand_more : Icons.chevron_right,
color: color,
),
],
),
);
final button = TextButton(
key: const Key('chat-activity-group'),
style: TextButton.styleFrom(
minimumSize: const Size(0, 48),
padding: const EdgeInsets.all(chatAgentContentInset),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: AlignmentDirectional.centerStart,
),
onPressed: _toggle,
child: summary,
);
final members = chatActivityGroupRows(widget.row);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Semantics(
button: true,
expanded: _expanded,
label:
'$label, ${_expanded ? 'hide' : 'show'} '
'${members.length == 1 ? 'the activity' : 'all ${members.length} activity rows'}',
excludeSemantics: true,
onTap: _toggle,
child: Align(
alignment: AlignmentDirectional.centerStart,
widthFactor: 1,
child: button,
),
),
if (_expanded)
for (var index = 0; index < members.length; index++)
KeyedSubtree(
key: ValueKey<String>(
'chat-activity-member-${members[index]['key'] ?? index}',
),
child: widget.memberBuilder(members[index]),
),
],
);
}
}