Merge: background-task notices grouped in the chat

This commit is contained in:
2026-11-03 12:45:18 +00:00
10 changed files with 591 additions and 5 deletions
@@ -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';
@@ -1252,6 +1253,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
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,
@@ -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 <finished|failed|stopped>[: <summary>]`.
/// 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<String, dynamic>.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<JsonMap> groupTaskNotices(List<JsonMap> rows) {
final result = <JsonMap>[];
final run = <JsonMap>[];
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<ChatTaskNotice> chatTaskNoticesOf(JsonMap row) => [
for (final message in (row['messages'] as List? ?? const []))
if (message is Map) ?chatTaskNotice(Map<String, dynamic>.from(message)),
];
/// `1 background task` / `N background tasks`.
String chatTaskNoticesLabel(int count) =>
count == 1 ? '1 background task' : '$count background tasks';
@@ -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<JsonMap> 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.
@@ -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<ChatTaskNotice> 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),
),
),
],
),
),
),
);
}
}
@@ -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<void> _pump(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump();
}
Future<FakeChatGateway> _host(
WidgetTester tester,
List<JsonMap> 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);
});
}
@@ -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 <outcome>: <summary>`.
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');
});
}
+1 -1
View File
@@ -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:
+29 -2
View File
@@ -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<String, String> 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-<index>`).
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,
};
+3
View File
@@ -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
+14
View File
@@ -26,6 +26,10 @@ const taskNotification = "<task-notification>\n<task-id>b1</task-id>\n<tool-use-
"<output-file>/tmp/b1.output</output-file>\n<status>completed</status>\n" +
"<summary>Background command \"Build the app\" completed (exit code 0)</summary>\n</task-notification>"
// 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 = "<system-reminder>\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</system-reminder>"
@@ -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</status>", "failed</status>", 1), injectedOrigin{}, false)
if failed.class != classNotice || !strings.HasPrefix(failed.text, "Background task failed: ") {
t.Fatalf("failed task notice: %+v", failed)