From 1a9db0206c1a28402a9e15ce8231539b3813a4ae Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 3 Nov 2026 12:44:57 +0000 Subject: [PATCH] Chat: group consecutive background-task notices into one collapsed chip Two or more consecutive Claude Code task notices fold into one task_notices row: a chip 'N background tasks' (tinted when one failed) that opens a sheet with one compact row per task (outcome icon, summary, outcome word), like the tools and permissions chips. A lone notice stays one line. The server also treats Claude Code's [SYSTEM NOTIFICATION] banner as harness text, so a bannered notification without an origin is still a notice, never the operator's turn. The chat fixture gains ?tasks=N. --- .../chat/conversation/chat_thread_view.dart | 2 + .../chat/domain/chat_task_notices.dart | 108 ++++++++++++ .../features/chat/domain/chat_transcript.dart | 7 +- .../transcript/chat_task_notices_group.dart | 161 ++++++++++++++++++ .../chat_task_notices_group_test.dart | 151 ++++++++++++++++ .../chat/domain/chat_task_notices_test.dart | 117 +++++++++++++ app/tool/capture/README.md | 2 +- app/tool/perf/chat_scroll_fixture.dart | 31 +++- internal/claude/injected.go | 3 + internal/claude/injected_test.go | 14 ++ 10 files changed, 591 insertions(+), 5 deletions(-) create mode 100644 app/lib/features/chat/domain/chat_task_notices.dart create mode 100644 app/lib/features/chat/ui/transcript/chat_task_notices_group.dart create mode 100644 app/test/features/chat/conversation/chat_task_notices_group_test.dart create mode 100644 app/test/features/chat/domain/chat_task_notices_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 07491e6f..a1e5617f 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -19,6 +19,7 @@ import '../ui/sessions/session_actions.dart'; import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_message_view.dart'; import '../ui/transcript/chat_injected_rows.dart'; +import '../ui/transcript/chat_task_notices_group.dart'; import '../../artifacts/actions/artifact_file_bridge.dart'; import '../domain/chat_session_handoff.dart'; import 'chat_account_usage_section.dart'; @@ -1246,6 +1247,7 @@ class _ChatThreadViewState extends State { return ChatAgentReportCard(row: row, textBuilder: chatMarkdownText); } if (kind == 'system_notice') return ChatSystemNoticeLine(row: row); + if (kind == 'task_notices') return ChatTaskNoticesGroup(row: row); if (kind == 'permission' || kind == 'question') { return ChatTranscriptCard( row: row, diff --git a/app/lib/features/chat/domain/chat_task_notices.dart b/app/lib/features/chat/domain/chat_task_notices.dart new file mode 100644 index 00000000..b131cbf3 --- /dev/null +++ b/app/lib/features/chat/domain/chat_task_notices.dart @@ -0,0 +1,108 @@ +import '../../../core/api_gateway.dart'; + +/// Background-task notices: the one-line `notice` messages the server records +/// when a harness reports that a background task ended (Claude Code's task +/// notifications). The server writes them as +/// `Background task [: ]`. + +/// How a background task ended, as its notice reports it. +enum ChatTaskOutcome { finished, failed, stopped } + +/// One background task's notice: its outcome and the harness's summary. +class ChatTaskNotice { + const ChatTaskNotice({ + required this.id, + required this.outcome, + required this.summary, + }); + + final String id; + final ChatTaskOutcome outcome; + + /// The harness's summary (may be blank when it recorded none). + final String summary; +} + +final _taskNoticeLine = RegExp( + r'^Background task (finished|failed|stopped)(?::\s*([\s\S]*))?$', +); + +/// The notice text of [message], its text parts joined. +String _noticeText(JsonMap message) { + final parts = message['parts']; + if (parts is! List) return ''; + return [ + for (final part in parts) + if (part is Map && part['type'] == 'text') '${part['text'] ?? ''}'.trim(), + ].where((text) => text.isNotEmpty).join(' '); +} + +/// The background task [message] reports, or null for any other message +/// (another notice, an ordinary turn, a report). +ChatTaskNotice? chatTaskNotice(JsonMap message) { + if (message['kind'] != 'notice') return null; + final match = _taskNoticeLine.firstMatch(_noticeText(message)); + if (match == null) return null; + return ChatTaskNotice( + id: '${message['id'] ?? ''}', + outcome: ChatTaskOutcome.values.byName(match.group(1)!), + summary: (match.group(2) ?? '').trim(), + ); +} + +/// The task notice a `system_notice` row carries, or null. +ChatTaskNotice? _rowNotice(JsonMap row) { + if (row['kind'] != 'system_notice') return null; + final message = row['message']; + return message is Map + ? chatTaskNotice(Map.from(message)) + : null; +} + +/// Folds each run of two or more consecutive background-task notice rows into +/// one `task_notices` row, the way a turn's tool calls fold into one chip. +/// +/// The group keeps the first notice's key and lists every notice's id in +/// `messageIds`, so the row keeps its place when a later notice joins it, and +/// its `messages` in transcript order. A lone +/// notice, and any other notice, stays its own `system_notice` line. +List groupTaskNotices(List rows) { + final result = []; + final run = []; + void close() { + if (run.length == 1) { + result.add(run.single); + } else if (run.isNotEmpty) { + result.add({ + 'kind': 'task_notices', + 'key': run.first['key'], + // Every grouped message's id, so the row keeps one widget identity as + // notices join it at either end (see ChatRowKeys). + 'messageIds': [for (final row in run) '${row['key'] ?? ''}'], + 'messages': [for (final row in run) row['message']], + }); + } + run.clear(); + } + + for (final row in rows) { + if (_rowNotice(row) != null) { + run.add(row); + continue; + } + close(); + result.add(row); + } + close(); + return result; +} + +/// The notices a `task_notices` row groups, in transcript order. +List chatTaskNoticesOf(JsonMap row) => [ + for (final message in (row['messages'] as List? ?? const [])) + if (message is Map) ?chatTaskNotice(Map.from(message)), +]; + +/// `1 background task` / `N background tasks`. +String chatTaskNoticesLabel(int count) => + count == 1 ? '1 background task' : '$count background tasks'; diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart index 51b04aed..678d73fc 100644 --- a/app/lib/features/chat/domain/chat_transcript.dart +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -1,4 +1,5 @@ import '../../../core/api_gateway.dart'; +import 'chat_task_notices.dart'; /// Merge chronological history pages by message id. Incoming authoritative /// copies replace held copies without changing their order; cursor is opaque. @@ -74,6 +75,8 @@ JsonMap refreshCachedChatHistory( /// 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 @@ -197,8 +200,8 @@ List transcriptRows( 'streaming': true, }); } - rows.addAll(trailing); - return rows; + // Consecutive background-task notices are one collapsed group. + return [...groupTaskNotices(rows), ...trailing]; } /// `ChatMessage.Kind` of a report another agent delivered into the session. diff --git a/app/lib/features/chat/ui/transcript/chat_task_notices_group.dart b/app/lib/features/chat/ui/transcript/chat_task_notices_group.dart new file mode 100644 index 00000000..3f2886aa --- /dev/null +++ b/app/lib/features/chat/ui/transcript/chat_task_notices_group.dart @@ -0,0 +1,161 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../domain/chat_task_notices.dart'; +import '../sessions/chat_adaptive.dart'; +import 'chat_turn_chip.dart'; + +/// A run of background-task notices as one quiet chip on the agent's side, +/// like a turn's tools and permissions chips: `N background tasks`, tinted +/// when one failed. It opens a sheet with one compact row per task. +class ChatTaskNoticesGroup extends StatelessWidget { + const ChatTaskNoticesGroup({super.key, required this.row}); + + /// A `task_notices` row (see [groupTaskNotices]). + final JsonMap row; + + @override + Widget build(BuildContext context) { + final notices = chatTaskNoticesOf(row); + if (notices.isEmpty) return const SizedBox.shrink(); + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final failed = notices + .where((n) => n.outcome == ChatTaskOutcome.failed) + .length; + final color = failed > 0 + ? _errorColor(context, cupertino) + : _secondaryColor(context, cupertino); + final label = chatTaskNoticesLabel(notices.length); + final shown = failed > 0 ? '$label · $failed failed' : label; + return Align( + alignment: AlignmentDirectional.centerStart, + child: ChatTurnChip( + chipKey: const Key('chat-task-notices-chip'), + leading: Icon( + cupertino ? CupertinoIcons.square_stack_3d_up : Icons.task_alt, + size: 14, + color: color, + ), + label: shown, + color: color, + semanticsLabel: '$shown ended, expand for details', + sheet: _TaskNoticesSheet(notices: notices, title: label), + ), + ); + } +} + +Color _secondaryColor(BuildContext context, bool cupertino) => cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + +Color _errorColor(BuildContext context, bool cupertino) => cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error; + +String _outcomeLabel(ChatTaskOutcome outcome) => switch (outcome) { + ChatTaskOutcome.finished => 'Finished', + ChatTaskOutcome.failed => 'Failed', + ChatTaskOutcome.stopped => 'Stopped', +}; + +class _TaskNoticesSheet extends StatelessWidget { + const _TaskNoticesSheet({required this.notices, required this.title}); + + final List notices; + final String title; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final style = cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyMedium; + return DefaultTextStyle.merge( + style: style, + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.8, + ), + child: ListView( + key: const Key('chat-task-notices-sheet'), + shrinkWrap: true, + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + children: [ + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + title, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ), + for (final notice in notices) _TaskNoticeRow(notice: notice), + ], + ), + ), + ); + } +} + +/// One task: its outcome icon, the harness's summary and the outcome word. +class _TaskNoticeRow extends StatelessWidget { + const _TaskNoticeRow({required this.notice}); + + final ChatTaskNotice notice; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final secondary = _secondaryColor(context, cupertino); + final outcome = _outcomeLabel(notice.outcome); + final (icon, color) = switch (notice.outcome) { + ChatTaskOutcome.finished => ( + cupertino + ? CupertinoIcons.checkmark_circle + : Icons.check_circle_outline, + secondary, + ), + ChatTaskOutcome.failed => ( + cupertino ? CupertinoIcons.xmark_circle : Icons.error_outline, + _errorColor(context, cupertino), + ), + ChatTaskOutcome.stopped => ( + cupertino ? CupertinoIcons.stop_circle : Icons.stop_circle_outlined, + secondary, + ), + }; + final summary = notice.summary.isEmpty + ? 'Background task ${outcome.toLowerCase()}' + : notice.summary; + return Semantics( + container: true, + label: '$outcome: $summary', + child: ExcludeSemantics( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsetsDirectional.only(end: 8, top: 2), + child: Icon(icon, size: 16, color: color), + ), + Expanded(child: Text(summary)), + Padding( + padding: const EdgeInsetsDirectional.only(start: 8), + child: Text( + outcome, + style: TextStyle(color: color, fontSize: 13), + ), + ), + ], + ), + ), + ), + ); + } +} 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 new file mode 100644 index 00000000..65b5bee9 --- /dev/null +++ b/app/test/features/chat/conversation/chat_task_notices_group_test.dart @@ -0,0 +1,151 @@ +import 'package:flutter/cupertino.dart'; +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_injected_rows.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_bubble.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_task_notices_group.dart'; + +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. + +JsonMap _notice(String id, String text) => { + 'id': id, + 'role': 'assistant', + 'kind': 'notice', + 'parts': [ + {'type': 'text', 'id': '$id#text#0', 'text': text}, + ], +}; + +final _messages = [ + chatMessage( + 'u1', + 'user', + parts: [ + {'type': 'text', 'text': 'Build everything'}, + ], + ), + _notice( + 'task-notice-t1-completed', + 'Background task finished: Background command "Build the app" ' + 'completed (exit code 0)', + ), + _notice( + 'task-notice-t2-failed', + 'Background task failed: Background command "Run the tests" failed ' + '(exit code 1)', + ), + _notice( + 'task-notice-t3-completed', + 'Background task finished: Agent "Review the diff" finished', + ), +]; + +Future _pump(WidgetTester tester) async { + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(); +} + +Future _host( + WidgetTester tester, + List messages, { + bool cupertino = false, +}) 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); + final thread = ChatThreadView( + gateway: gateway, + sessionId: 's', + onBack: () {}, + drafts: MemoryChatDraftStore(), + newOperationId: () => 'op', + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: thread)) + : MaterialApp(home: Scaffold(body: thread)), + ); + await _pump(tester); + return gateway; +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets('consecutive task notices are one chip that opens to each ' + 'task ($cupertino)', (tester) async { + await _host(tester, _messages, cupertino: cupertino); + + expect(find.byType(ChatTaskNoticesGroup), findsOneWidget); + expect(find.byType(ChatSystemNoticeLine), findsNothing); + final chip = find.byKey(const Key('chat-task-notices-chip')); + expect(chip, findsOneWidget); + expect(find.text('3 background tasks · 1 failed'), findsOneWidget); + expect( + find.ancestor(of: chip, matching: find.byType(ChatUserBubble)), + findsNothing, + ); + // Only the operator's prompt is a bubble, on the trailing side; the + // group starts on the agent's side. + expect(find.byType(ChatUserBubble), findsOneWidget); + final width = tester.getSize(find.byType(ChatThreadView)).width; + expect(tester.getTopLeft(chip).dx, lessThan(width * 0.2)); + // Collapsed: no summary is laid out yet. + expect(find.textContaining('Build the app'), findsNothing); + + await tester.tap(chip); + await tester.pumpAndSettle(); + final sheet = find.byKey(const Key('chat-task-notices-sheet')); + expect(sheet, findsOneWidget); + for (final summary in [ + 'Background command "Build the app" completed (exit code 0)', + 'Background command "Run the tests" failed (exit code 1)', + 'Agent "Review the diff" finished', + ]) { + expect( + find.descendant(of: sheet, matching: find.text(summary)), + findsOneWidget, + ); + } + expect( + find.descendant(of: sheet, matching: find.text('Finished')), + findsNWidgets(2), + ); + expect( + find.descendant(of: sheet, matching: find.text('Failed')), + findsOneWidget, + ); + }); + } + + 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()); + expect(find.byType(ChatSystemNoticeLine), findsOneWidget); + expect(find.byType(ChatTaskNoticesGroup), findsNothing); + + gateway.emitEvent({ + 'session_id': 's', + 'message_id': 'task-notice-t2-failed', + 'message_kind': 'notice', + 'kind': 'text', + 'part': {'id': 'task-notice-t2-failed#text#0'}, + 'delta': + 'Background task failed: Background command "Run the tests" ' + 'failed (exit code 1)', + }); + await _pump(tester); + 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_task_notices_test.dart b/app/test/features/chat/domain/chat_task_notices_test.dart new file mode 100644 index 00000000..4a2d7728 --- /dev/null +++ b/app/test/features/chat/domain/chat_task_notices_test.dart @@ -0,0 +1,117 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/domain/chat_task_notices.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; + +/// The server records each Claude Code task notification as a `notice` +/// message `Background task : `. +JsonMap _notice(String id, String text, {String kind = 'notice'}) => { + 'id': id, + 'role': 'assistant', + 'kind': kind, + 'parts': [ + {'type': 'text', 'id': '$id#text#0', 'text': text}, + ], +}; + +JsonMap _turn(String id, String role) => { + 'id': id, + 'role': role, + 'parts': [ + {'type': 'text', 'id': '$id#text#0', 'text': 'text of $id'}, + ], +}; + +void main() { + test('a task notice reads its outcome and summary', () { + final done = chatTaskNotice( + _notice( + 'n1', + 'Background task finished: Background command "Build" completed ' + '(exit code 0)', + ), + )!; + expect(done.id, 'n1'); + expect(done.outcome, ChatTaskOutcome.finished); + expect(done.summary, 'Background command "Build" completed (exit code 0)'); + expect( + chatTaskNotice(_notice('n2', 'Background task failed: x'))!.outcome, + ChatTaskOutcome.failed, + ); + final stopped = chatTaskNotice(_notice('n3', 'Background task stopped'))!; + expect(stopped.outcome, ChatTaskOutcome.stopped); + expect(stopped.summary, isEmpty); + // Other notices, and the same words in an ordinary message, are not tasks. + expect(chatTaskNotice(_notice('n4', 'Context compacted')), isNull); + expect( + chatTaskNotice(_notice('n5', 'Background task finished: x', kind: '')), + isNull, + ); + }); + + test('consecutive task notices fold into one group in order', () { + final rows = transcriptRows([ + _turn('u1', 'user'), + _turn('a1', 'assistant'), + _notice('n1', 'Background task finished: one'), + _notice('n2', 'Background task failed: two'), + _notice('n3', 'Background task stopped: three'), + _turn('a2', 'assistant'), + _notice('n4', 'Background task finished: lone'), + _turn('u2', 'user'), + _notice('n5', 'Background task finished: five'), + _notice('n6', 'Background task finished: six'), + ]); + expect(rows.map((row) => row['kind']), [ + 'user', + 'assistant', + 'task_notices', + 'assistant', + 'system_notice', + 'user', + 'task_notices', + ]); + final group = rows[2]; + expect(group['key'], 'n1'); + expect(group['messageIds'], ['n1', 'n2', 'n3']); + final notices = chatTaskNoticesOf(group); + expect(notices.map((n) => n.summary), ['one', 'two', 'three']); + expect(notices.map((n) => n.outcome), [ + ChatTaskOutcome.finished, + ChatTaskOutcome.failed, + ChatTaskOutcome.stopped, + ]); + expect(rows[4]['key'], 'n4'); + expect(chatTaskNoticesOf(rows[6]).map((n) => n.id), ['n5', 'n6']); + }); + + test('a non-task notice breaks a run and stays its own line', () { + final rows = groupTaskNotices([ + { + 'kind': 'system_notice', + 'key': 'n1', + 'message': _notice('n1', 'Background task finished: one'), + }, + { + 'kind': 'system_notice', + 'key': 'x', + 'message': _notice('x', 'Something else'), + }, + { + 'kind': 'system_notice', + 'key': 'n2', + 'message': _notice('n2', 'Background task finished: two'), + }, + ]); + expect(rows.map((row) => row['kind']), [ + 'system_notice', + 'system_notice', + 'system_notice', + ]); + }); + + test('the label counts tasks', () { + expect(chatTaskNoticesLabel(1), '1 background task'); + expect(chatTaskNoticesLabel(3), '3 background tasks'); + }); +} diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 64c0f63e..9deccbef 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -116,7 +116,7 @@ Look at every PNG you cite. A capture that exits 0 is not a review. Check a chat scroll: the full-app fixture exposes `chatScrollMetrics()` (the open transcript's `{pixels, min, max, viewport}` as JSON; `tool/perf/chat_scroll_probe.dart`), and `?chats=N` with `?msgs=`, `?rich=1`, -`?older=1` and `?live=N` (`tool/perf/chat_scroll_fixture.dart`) shapes the +`?older=1`, `?live=N` and `?tasks=N` (`tool/perf/chat_scroll_fixture.dart`) shape the transcripts. `tool/capture/examples/chat-wheel-scroll.json` wheels over each content kind and expects the offset to move: diff --git a/app/tool/perf/chat_scroll_fixture.dart b/app/tool/perf/chat_scroll_fixture.dart index 2acdc3ec..3ef9d76a 100644 --- a/app/tool/perf/chat_scroll_fixture.dart +++ b/app/tool/perf/chat_scroll_fixture.dart @@ -9,7 +9,9 @@ // `?older=1` the first page reports more history; Load older adds 20 // earlier messages; // `?live=N` 3 s after a chat subscribes, N text deltas stream into a -// new reply, one every 60 ms. +// 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). import 'dart:async'; import 'package:pipelines_app/core/api_gateway.dart'; @@ -21,6 +23,28 @@ void configureChatScrollFixture(Map params) => _params = params; bool get _rich => _params['rich'] == '1'; bool get _older => _params['older'] == '1'; int get _live => int.tryParse(_params['live'] ?? '') ?? 0; +int get _tasks => int.tryParse(_params['tasks'] ?? '') ?? 0; + +/// Background task [i]'s notice, as the server records a Claude Code task +/// notification. +JsonMap _taskNotice(String chat, int i) { + final failed = i % 3 == 2; + final summary = i.isEven + ? 'Background command "Build step $i" ' + '${failed ? 'failed (exit code 1)' : 'completed (exit code 0)'}' + : 'Agent "Review part $i" ${failed ? 'failed' : 'finished'}'; + return { + 'id': '$chat-task-$i', + 'role': 'assistant', + 'kind': 'notice', + 'parts': [ + { + 'type': 'text', + 'text': 'Background task ${failed ? 'failed' : 'finished'}: $summary', + }, + ], + }; +} /// The message count for chat [index] (`perf-chat-`). int chatScrollMessageCount(int index) { @@ -115,7 +139,10 @@ JsonMap chatScrollHistory(String sessionId, int index, String cursor) { }; } return { - 'messages': [for (var i = 0; i < count; i++) _message(sessionId, i)], + 'messages': [ + for (var i = 0; i < count; i++) _message(sessionId, i), + for (var i = 0; i < _tasks; i++) _taskNotice(sessionId, i), + ], 'next_cursor': _older ? 'older' : '', 'has_more': _older, }; diff --git a/internal/claude/injected.go b/internal/claude/injected.go index 69c5998f..9e466a07 100644 --- a/internal/claude/injected.go +++ b/internal/claude/injected.go @@ -80,6 +80,9 @@ var harnessPrefixes = []string{ "Caveat: The messages below were generated by the user while running local commands.", "[Request interrupted by user", "Base directory for this skill:", + // The banner Claude Code puts before a background-task event it delivers + // as user-role text (current CLIs; older ones sent the bare block). + "[SYSTEM NOTIFICATION - NOT USER INPUT]", } // classifyInjected decides how a user-role text is shown. origin and meta are diff --git a/internal/claude/injected_test.go b/internal/claude/injected_test.go index 08fa13f8..6311c1df 100644 --- a/internal/claude/injected_test.go +++ b/internal/claude/injected_test.go @@ -26,6 +26,10 @@ const taskNotification = "\nb1\n/tmp/b1.output\ncompleted\n" + "Background command \"Build the app\" completed (exit code 0)\n" +// systemNotificationBanner is the preamble Claude Code records before a task +// notification it delivers as a user line. +const systemNotificationBanner = "[SYSTEM NOTIFICATION - NOT USER INPUT]\nThis is an automated background-task event, NOT a message from the user.\n\n" + const midTurnWrapped = "\nThe user sent a new message while you were working:\nship it now\n\n" + "This is how Claude Code surfaces messages the user sends mid-turn. Address the message above as you continue this turn.\n" @@ -162,6 +166,16 @@ func TestClassifyKeepsOperatorTextAndHidesHarness(t *testing.T) { t.Fatalf("classify %q: %+v", c.text, item) } } + // Current CLIs open a task notification with a banner; without an origin + // object the text shape alone must still make it a notice, never the + // operator's turn, and the banner alone is hidden. + bannered := classifyInjected(systemNotificationBanner+taskNotification, injectedOrigin{}, false) + if bannered.class != classNotice || bannered.id != "task-notice-toolu_bg1-completed" { + t.Fatalf("bannered task notice: %+v", bannered) + } + if bare := classifyInjected(systemNotificationBanner+"nothing else", injectedOrigin{}, false); bare.class != classHidden { + t.Fatalf("bare banner: %+v", bare) + } failed := classifyInjected(strings.Replace(taskNotification, "completed", "failed", 1), injectedOrigin{}, false) if failed.class != classNotice || !strings.HasPrefix(failed.text, "Background task failed: ") { t.Fatalf("failed task notice: %+v", failed)