From 22866ec0ce9af1fb1fb855ca09a059ca4806c91a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 25 Nov 2026 10:58:25 +0000 Subject: [PATCH] Chat: fold activity-only rows between messages into one summary line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../chat/conversation/chat_thread_view.dart | 27 +- .../conversation/chat_transcript_anchor.dart | 12 +- .../chat/domain/chat_activity_groups.dart | 271 +++++++++++++++ .../chat/domain/chat_turn_activity.dart | 7 +- .../transcript/chat_activity_group_view.dart | 123 +++++++ .../chat_activity_group_view_test.dart | 140 ++++++++ .../conversation/chat_injected_rows_test.dart | 6 + .../chat_task_notices_group_test.dart | 14 +- .../domain/chat_activity_groups_test.dart | 313 ++++++++++++++++++ app/tool/perf/chat_scroll_fixture.dart | 63 ++++ 10 files changed, 963 insertions(+), 13 deletions(-) create mode 100644 app/lib/features/chat/domain/chat_activity_groups.dart create mode 100644 app/lib/features/chat/ui/transcript/chat_activity_group_view.dart create mode 100644 app/test/features/chat/conversation/chat_activity_group_view_test.dart create mode 100644 app/test/features/chat/domain/chat_activity_groups_test.dart diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 191e2669..907f6310 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -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 { 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 { ); } 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( diff --git a/app/lib/features/chat/conversation/chat_transcript_anchor.dart b/app/lib/features/chat/conversation/chat_transcript_anchor.dart index 7be25b3a..d37674cd 100644 --- a/app/lib/features/chat/conversation/chat_transcript_anchor.dart +++ b/app/lib/features/chat/conversation/chat_transcript_anchor.dart @@ -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 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 _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 []; diff --git a/app/lib/features/chat/domain/chat_activity_groups.dart b/app/lib/features/chat/domain/chat_activity_groups.dart new file mode 100644 index 00000000..2ca91b2f --- /dev/null +++ b/app/lib/features/chat/domain/chat_activity_groups.dart @@ -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 groupChatActivity(List rows) { + final stale = _staleNotices(rows); + final result = []; + final run = []; + 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 _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 && chatTaskNotice(message) != null) + message, + ]; +} + +JsonMap? _noticeMessage(JsonMap row) { + final message = row['message']; + if (message is! Map) return null; + return chatTaskNotice(message) == null ? null : message; +} + +/// Notice messages whose id appears again later: only the latest counts. +Set _staleNotices(List rows) { + final seen = {}; + final stale = Set.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 _members(List run, Set stale) { + final members = []; + final notices = []; + final sources = {}; + 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 notices, Set 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 = { + '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 notices, JsonMap row})> _noticeRows = Expando( + 'chat activity notices', +); + +final Expando<({List members, JsonMap group})> _groups = Expando( + 'chat activity group', +); + +bool _identical(List a, List 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 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.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 = { + '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 _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 chatActivityGroupRows(JsonMap row) => [ + for (final member in row['rows'] as List? ?? const []) + if (member is Map) member, +]; + +/// The agent-turn message ids a group holds (what a scroll anchor may name). +List 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 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(' · '); diff --git a/app/lib/features/chat/domain/chat_turn_activity.dart b/app/lib/features/chat/domain/chat_turn_activity.dart index de1b881c..5d2b0b16 100644 --- a/app/lib/features/chat/domain/chat_turn_activity.dart +++ b/app/lib/features/chat/domain/chat_turn_activity.dart @@ -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', diff --git a/app/lib/features/chat/ui/transcript/chat_activity_group_view.dart b/app/lib/features/chat/ui/transcript/chat_activity_group_view.dart new file mode 100644 index 00000000..b08b3e17 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/chat_activity_group_view.dart @@ -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 createState() => _ChatActivityGroupViewState(); +} + +class _ChatActivityGroupViewState extends State { + 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( + 'chat-activity-member-${members[index]['key'] ?? index}', + ), + child: widget.memberBuilder(members[index]), + ), + ], + ); + } +} diff --git a/app/test/features/chat/conversation/chat_activity_group_view_test.dart b/app/test/features/chat/conversation/chat_activity_group_view_test.dart new file mode 100644 index 00000000..f38ef864 --- /dev/null +++ b/app/test/features/chat/conversation/chat_activity_group_view_test.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_activity_group_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_task_notices_group.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_turn_activity_view.dart'; + +import 'chat_thread_fixtures.dart'; + +/// Tool-only turns and background-task notices between two answers are one +/// summary line that opens to the rows as they render on their own. + +JsonMap _notice(String id) => { + 'id': id, + 'role': 'assistant', + 'kind': 'notice', + 'parts': [ + {'type': 'text', 'text': 'Background task finished: task $id'}, + ], +}; + +JsonMap _tool(String id, {bool failed = false}) => { + 'type': 'tool', + 'id': id, + 'name': 'bash', + 'state': {'status': failed ? 'error' : 'completed'}, +}; + +JsonMap _text(String text) => {'type': 'text', 'text': text}; + +final _messages = [ + chatMessage('u1', 'user', parts: [_text('Run the checks')]), + chatMessage('a1', 'assistant', parts: [_text('Starting them now.')]), + _notice('n1'), + chatMessage('w1', 'assistant', parts: [_tool('t1')]), + _notice('n2'), + _notice('n3'), + chatMessage( + 'w2', + 'assistant', + parts: [_tool('t2'), _tool('t3', failed: true)], + ), + _notice('n4'), + chatMessage('a2', 'assistant', parts: [_text('All done.')]), +]; + +Future _host(WidgetTester tester) async { + tester.view.physicalSize = const Size(1000, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = FakeChatGateway()..history = (_) async => chatPage(_messages); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ChatThreadView( + gateway: gateway, + sessionId: 's', + onBack: () {}, + drafts: MemoryChatDraftStore(), + newOperationId: () => 'op', + ), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(); +} + +void main() { + testWidgets('the activity summary expands to its rows and collapses again', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + await _host(tester); + + const label = 'Ran 3 commands · 4 background tasks finished · 1 failed'; + final summary = find.byKey(const Key('chat-activity-group')); + expect(find.byType(ChatActivityGroupView), findsOneWidget); + expect(summary, findsOneWidget); + expect( + find.text('Ran 3 commands · 4 background tasks finished'), + findsOneWidget, + ); + // The failure is drawn whole, in the error colour. + final failed = tester.widget( + find.byKey(const Key('chat-activity-group-failed')), + ); + expect(failed.data, ' · 1 failed'); + final context = tester.element(summary); + expect(failed.style?.color, Theme.of(context).colorScheme.error); + expect( + tester.getSemantics(summary), + matchesSemantics( + label: '$label, show all 3 activity rows', + isButton: true, + hasTapAction: true, + hasExpandedState: true, + isExpanded: false, + ), + ); + // Collapsed: neither the turns' own lines nor the notices are built; the + // answers on both sides still are. + expect(find.byType(ChatTurnActivityView), findsNothing); + expect(find.byType(ChatTaskNoticesGroup), findsNothing); + expect(find.text('Starting them now.'), findsOneWidget); + expect(find.text('All done.'), findsOneWidget); + + await tester.tap(summary); + await tester.pumpAndSettle(); + expect(find.text('Ran 1 command'), findsOneWidget); + expect(find.text('Ran 2 commands · 1 failed'), findsOneWidget); + // Every notice of the run is one chip, shown once at the newest notice. + expect(find.byType(ChatTaskNoticesGroup), findsOneWidget); + expect(find.text('4 background tasks'), findsOneWidget); + expect( + tester.getTopLeft(find.byType(ChatTaskNoticesGroup)).dy, + greaterThan(tester.getTopLeft(find.text('Ran 2 commands · 1 failed')).dy), + ); + expect( + tester.getSemantics(summary), + matchesSemantics( + label: '$label, hide all 3 activity rows', + isButton: true, + hasTapAction: true, + hasExpandedState: true, + isExpanded: true, + ), + ); + + await tester.tap(summary); + await tester.pumpAndSettle(); + expect(find.byType(ChatTurnActivityView), findsNothing); + expect(find.byType(ChatTaskNoticesGroup), findsNothing); + semantics.dispose(); + }); +} diff --git a/app/test/features/chat/conversation/chat_injected_rows_test.dart b/app/test/features/chat/conversation/chat_injected_rows_test.dart index 1e7918e2..79d5d1c8 100644 --- a/app/test/features/chat/conversation/chat_injected_rows_test.dart +++ b/app/test/features/chat/conversation/chat_injected_rows_test.dart @@ -191,6 +191,12 @@ void main() { greaterThan(width * 0.8), ); + // A task notice folds into the activity summary on the agent's side and + // shows as its own line once that is opened. + final summary = find.text('1 background task finished'); + expect(summary, findsOneWidget); + await tester.tap(summary); + await _pump(tester); final notice = find.text( 'Background task finished: Background command "Build" completed', ); diff --git a/app/test/features/chat/conversation/chat_task_notices_group_test.dart b/app/test/features/chat/conversation/chat_task_notices_group_test.dart index 71ba26d5..5b713c3f 100644 --- a/app/test/features/chat/conversation/chat_task_notices_group_test.dart +++ b/app/test/features/chat/conversation/chat_task_notices_group_test.dart @@ -10,8 +10,8 @@ import 'package:pipelines_app/features/chat/ui/transcript/chat_task_notices_grou import 'chat_thread_fixtures.dart'; /// Consecutive background-task notices are one collapsed chip on the agent's -/// side; it opens a sheet with one compact row per task. None of them is ever -/// the operator's bubble. +/// side, inside the activity summary they fold into; the chip opens a sheet +/// with one compact row per task. None of them is ever the operator's bubble. JsonMap _notice(String id, String text) => { 'id': id, @@ -73,11 +73,18 @@ Future _host( return gateway; } +/// Opens the activity summary the notices fold into. +Future _expand(WidgetTester tester, String label) async { + await tester.tap(find.text(label)); + await _pump(tester); +} + void main() { testWidgets('consecutive task notices are one chip that opens to each task', ( tester, ) async { await _host(tester, _messages); + await _expand(tester, '3 background tasks ended'); expect(find.byType(ChatTaskNoticesGroup), findsOneWidget); expect(find.byType(ChatSystemNoticeLine), findsNothing); @@ -122,6 +129,7 @@ void main() { testWidgets('a lone notice stays one line and a live second notice joins ' 'it into the group', (tester) async { final gateway = await _host(tester, _messages.take(2).toList()); + await _expand(tester, '1 background task finished'); expect(find.byType(ChatSystemNoticeLine), findsOneWidget); expect(find.byType(ChatTaskNoticesGroup), findsNothing); @@ -136,6 +144,8 @@ void main() { 'failed (exit code 1)', }); await _pump(tester); + // The summary keeps its place and open state as the notice joins it. + expect(find.text('2 background tasks ended'), findsOneWidget); expect(find.byType(ChatSystemNoticeLine), findsNothing); expect(find.text('2 background tasks · 1 failed'), findsOneWidget); expect(find.byType(ChatUserBubble), findsOneWidget); diff --git a/app/test/features/chat/domain/chat_activity_groups_test.dart b/app/test/features/chat/domain/chat_activity_groups_test.dart new file mode 100644 index 00000000..67a69fc5 --- /dev/null +++ b/app/test/features/chat/domain/chat_activity_groups_test.dart @@ -0,0 +1,313 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_row_keys.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_transcript_anchor.dart'; +import 'package:pipelines_app/features/chat/domain/chat_activity_groups.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript_rows.dart'; + +JsonMap _user(String id) => { + 'id': id, + 'role': 'user', + 'parts': [ + {'type': 'text', 'text': 'question $id'}, + ], +}; + +JsonMap _answer(String id, {List tools = const []}) => { + 'id': id, + 'role': 'assistant', + 'parts': [ + ...tools, + {'type': 'text', 'text': 'answer $id'}, + ], +}; + +JsonMap _tool(String id, String name, {bool failed = false}) => { + 'type': 'tool', + 'id': id, + 'name': name, + 'state': {'status': failed ? 'error' : 'completed'}, +}; + +JsonMap _work(String id, List parts) => { + 'id': id, + 'role': 'assistant', + 'parts': parts, +}; + +JsonMap _notice(String id, {String outcome = 'finished'}) => { + 'id': id, + 'role': 'assistant', + 'kind': 'notice', + 'parts': [ + {'type': 'text', 'text': 'Background task $outcome: task $id'}, + ], +}; + +List _rows(List messages) => + groupChatActivity(transcriptRows(messages)); + +List _kinds(List rows) => [ + for (final row in rows) '${row['kind']}', +]; + +/// The transcript the operator reported: two answers with tool-only turns and +/// background-task notices between them. +List _backgroundSession() => [ + _user('u1'), + _answer('a1'), + _notice('n1'), + _work('w1', [for (var i = 0; i < 9; i++) _tool('w1-$i', 'read')]), + _notice('n2'), + _notice('n3'), + _work('w2', [_tool('w2-0', 'bash')]), + _notice('n4'), + _work('w3', [ + for (var i = 0; i < 4; i++) _tool('w3-$i', 'bash', failed: i == 1), + ]), + _notice('n5'), + _work('w4', [ + {'type': 'reasoning', 'text': 'thinking'}, + ]), + _notice('n6'), + _answer('a2'), +]; + +void main() { + test('a run of activity rows between two answers is one summary row', () { + final rows = _rows(_backgroundSession()); + expect(_kinds(rows), [ + 'user', + 'assistant', + chatActivityGroupKind, + 'assistant', + ]); + final group = rows[2]; + expect( + chatActivityGroupLabel(group), + 'Ran 5 commands · used 9 tools · 6 background tasks finished · 1 failed', + ); + final segments = chatActivityGroupSegments(group); + expect(segments.last, (text: '1 failed', failed: true)); + expect(segments.where((s) => s.failed), hasLength(1)); + // The members render as before, with every notice folded into one chip + // at the newest notice's place, so the chip shows once. + final members = chatActivityGroupRows(group); + expect(_kinds(members), [ + 'assistant', + 'assistant', + 'assistant', + 'assistant', + 'task_notices', + ]); + expect(members.last['messageIds'], ['n1', 'n2', 'n3', 'n4', 'n5', 'n6']); + expect(group['messageIds'], [ + 'w1', + 'w2', + 'w3', + 'w4', + 'n1', + 'n2', + 'n3', + 'n4', + 'n5', + 'n6', + ]); + }); + + test('content rows bound runs and a single tool turn stays itself', () { + final rows = _rows([ + _user('u1'), + _answer('a1'), + _notice('n1'), + _answer('a2'), + _user('u2'), + _work('w1', [_tool('t', 'bash')]), + _user('u3'), + _work('w2', [_tool('t2', 'bash')]), + _work('w3', [ + {'type': 'text', 'text': ' '}, + ]), + ]); + // The lone notice is a summary, not a full-width line; the lone tool turn + // (folded with its blank neighbour into one turn) keeps its own row. + expect(_kinds(rows), [ + 'user', + 'assistant', + chatActivityGroupKind, + 'assistant', + 'user', + 'assistant', + 'user', + 'assistant', + ]); + expect(chatActivityGroupLabel(rows[2]), '1 background task finished'); + expect(chatActivityGroupRows(rows[2]).single['kind'], 'system_notice'); + }); + + test('a turn with answer text, a chip or a live stream is content', () { + final work = transcriptRows([ + _work('w1', [_tool('t', 'bash')]), + ]).single; + expect(chatActivityOnlyRow(work), isTrue); + expect(chatActivityOnlyRow({...work, 'streaming': true}), isFalse); + expect(chatActivityOnlyRow({...work, 'turnDiff': {}}), isFalse); + expect( + chatActivityOnlyRow({ + ...work, + 'shellHistory': ['r1'], + }), + isFalse, + ); + expect( + chatActivityOnlyRow({ + ...work, + 'questions': [{}], + }), + isFalse, + ); + final answer = transcriptRows([_answer('a1')]).single; + expect(chatActivityOnlyRow(answer), isFalse); + expect( + chatActivityOnlyRow({ + ...work, + 'parts': [ + {'type': 'file', 'name': 'a.png', 'uri': 'x'}, + ], + }), + isFalse, + ); + // The live turn stays its own row after the run before it. + final rows = groupChatActivity( + transcriptRows([ + _user('u1'), + _answer('a1'), + _notice('n1'), + _notice('n2'), + _work('w1', [_tool('t', 'bash')]), + ], running: true), + ); + expect(_kinds(rows), [ + 'user', + 'assistant', + chatActivityGroupKind, + 'assistant', + ]); + expect(rows.last['streaming'], isTrue); + }); + + test('failed and stopped tasks are carried into the summary', () { + final rows = _rows([ + _answer('a1'), + _notice('n1', outcome: 'failed'), + _notice('n2', outcome: 'stopped'), + _user('u1'), + ]); + expect( + chatActivityGroupLabel(rows[1]), + '2 background tasks ended · 1 failed', + ); + }); + + test('a repeated task notice counts once, at its latest position', () { + final rows = _rows([ + _answer('a1'), + _notice('n1'), + _work('w1', [_tool('t', 'bash')]), + _user('u1'), + _answer('a2'), + _notice('n1'), + _user('u2'), + ]); + // The earlier run keeps only its tool turn, which stays its own row; the + // task is counted where it was reported last. + expect(_kinds(rows), [ + 'assistant', + 'assistant', + 'user', + 'assistant', + chatActivityGroupKind, + 'user', + ]); + expect(rows[1]['key'], 'w1'); + expect(chatActivityGroupLabel(rows[4]), '1 background task finished'); + }); + + test('a repeated notice leaves only the later chip', () { + final rows = _rows([ + _answer('a1'), + _notice('n1'), + _notice('n2'), + _user('u1'), + _answer('a2'), + _notice('n1'), + _notice('n2'), + _user('u2'), + ]); + expect(_kinds(rows), [ + 'assistant', + 'user', + 'assistant', + chatActivityGroupKind, + 'user', + ]); + expect(chatActivityGroupLabel(rows[3]), '2 background tasks finished'); + }); + + test( + 'identity holds across a streamed delta and the key carries forward', + () { + final cache = ChatTranscriptRows(); + final history = _backgroundSession(); + final live = { + 'id': 'live', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': 'word'}, + ], + }; + final before = groupChatActivity( + cache.rows([...history, _user('u9'), live], running: true), + ); + final delta = { + ...live, + 'parts': [ + {'type': 'text', 'text': 'word word'}, + ], + }; + final after = groupChatActivity( + cache.rows([...history, _user('u9'), delta], running: true), + ); + expect(identical(before[2], after[2]), isTrue); + expect( + identical( + chatActivityGroupRows(before[2]).last, + chatActivityGroupRows(after[2]).last, + ), + isTrue, + ); + + // A tool turn that already had a row keeps its key when it joins a group. + final keys = ChatRowKeys(); + final single = _rows([ + _user('u1'), + _work('w1', [_tool('t', 'bash')]), + ]); + final firstKeys = keys.forRows(single); + final grown = _rows([ + _user('u1'), + _work('w1', [_tool('t', 'bash')]), + _notice('n1'), + ]); + expect(keys.forRows(grown)[1], firstKeys[1]); + }, + ); + + test('a group can anchor the transcript split by its agent turns', () { + final rows = _rows([..._backgroundSession(), _user('u2'), _answer('a3')]); + final anchor = chatTranscriptAnchor(rows); + expect(anchor, 'u2'); + expect(chatTranscriptAnchorIndex(rows, 'w3'), 2); + expect(chatTranscriptAnchorIndex(rows, 'n3'), -1); + }); +} diff --git a/app/tool/perf/chat_scroll_fixture.dart b/app/tool/perf/chat_scroll_fixture.dart index a49829c7..e3aa2df7 100644 --- a/app/tool/perf/chat_scroll_fixture.dart +++ b/app/tool/perf/chat_scroll_fixture.dart @@ -12,6 +12,9 @@ // new reply, one every 60 ms; // `?tasks=N` the history ends with N consecutive background-task notices // in the server's wording (every third one failed); +// `?bgwork=1` the history ends with an agent's background work between two +// answers: tool-only turns ("Used 9 tools", "Ran 1 command", +// one with a failed command) split by background-task notices; // `?links=1` answers and operator turns carry a markdown link, an // autolink, a bare URL and URLs inside code (never linkified). import 'dart:async'; @@ -31,6 +34,65 @@ bool get _links => _params['links'] == '1'; bool get _older => _params['older'] == '1'; int get _live => int.tryParse(_params['live'] ?? '') ?? 0; int get _tasks => int.tryParse(_params['tasks'] ?? '') ?? 0; +bool get _bgwork => _params['bgwork'] == '1'; + +/// `?bgwork=1`: a reply, then tool-only turns split by task notices, then a +/// closing reply, the shape a long background session records. +List _backgroundWork(String chat) { + var minute = 0; + int at() => DateTime.utc(2026, 11, 5, 10, minute++).millisecondsSinceEpoch; + JsonMap tool(String id, String name, {bool failed = false}) => { + 'type': 'tool', + 'id': id, + 'name': name, + 'state': {'status': failed ? 'error' : 'completed', 'title': name}, + }; + JsonMap turn(String id, List parts) => { + 'id': '$chat-bg-$id', + 'role': 'assistant', + 'created_at': at(), + 'parts': parts, + }; + JsonMap notice(String id, String summary) => { + ..._taskNotice(chat, 0), + 'id': '$chat-bg-task-$id', + 'created_at': at(), + 'parts': [ + {'type': 'text', 'text': 'Background task finished: $summary'}, + ], + }; + return [ + { + 'id': '$chat-bg-q', + 'role': 'user', + 'created_at': at(), + 'parts': [ + {'type': 'text', 'text': 'Run the checks in the background.'}, + ], + }, + turn('a0', [ + {'type': 'text', 'text': 'Starting the checks in the background.'}, + ]), + notice('1', 'Background command "Unit tests" completed (exit code 0)'), + turn('t1', [for (var i = 0; i < 9; i++) tool('t1-$i', 'read')]), + notice('2', 'Agent "Review part 1" finished'), + notice('3', 'Agent "Review part 2" finished'), + turn('t2', [tool('t2-0', 'bash')]), + notice('4', 'Background command "Lint" completed (exit code 0)'), + turn('t3', [tool('t3-0', 'bash')]), + notice('5', 'Background command "Build" completed (exit code 0)'), + notice('6', 'Background command "Docs" completed (exit code 0)'), + turn('t4', [ + for (var i = 0; i < 4; i++) tool('t4-$i', 'bash', failed: i == 2), + ]), + notice('7', 'Background command "Format" completed (exit code 0)'), + turn('t5', [tool('t5-0', 'bash')]), + notice('8', 'Background command "Smoke test" completed (exit code 0)'), + turn('a1', [ + {'type': 'text', 'text': 'All the background checks are done.'}, + ]), + ]; +} /// Background task [i]'s notice, as the server records a Claude Code task /// notification. @@ -168,6 +230,7 @@ JsonMap chatScrollHistory(String sessionId, int index, String cursor) { return { 'messages': [ for (var i = 0; i < count; i++) _message(sessionId, i), + if (_bgwork) ..._backgroundWork(sessionId), for (var i = 0; i < _tasks; i++) _taskNotice(sessionId, i), ], 'next_cursor': _older ? 'older' : '',