Show injected Claude input as agent reports and notices, not operator bubbles

Claude Code records subagent/peer reports, task notifications, reminders and
skill bodies as user-role entries. Classify them server-side (history and live
stream) by origin/isMeta/queued_command mode: reports become kind agent_report,
task notifications kind notice, harness meta is hidden, and the mid-turn
wrapper is unwrapped to the operator's text. The app draws a collapsed Agent
report card and a one-line system notice on the agent's side.
This commit is contained in:
2026-11-02 16:44:07 +00:00
parent d78cbe3f66
commit 07d4740d0c
15 changed files with 1208 additions and 16 deletions
@@ -373,7 +373,8 @@ class ChatThreadController extends ChangeNotifier {
_running = next['running'] == true;
if (!_running) {
_liveAssistantMessageId = null;
} else if (const ['text', 'reasoning', 'tool'].contains(body['kind'])) {
} else if (const ['text', 'reasoning', 'tool'].contains(body['kind']) &&
chatInjectedKind({'kind': body['message_kind']}) == null) {
_liveAssistantMessageId = body['message_id'] as String?;
}
if (body['kind'] == 'step' &&
@@ -16,6 +16,7 @@ import '../ui/sessions/chat_adaptive.dart';
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 'chat_background_tasks.dart';
import 'chat_command_actions.dart';
import 'chat_composer_bar.dart';
@@ -1160,6 +1161,10 @@ class _ChatThreadViewState extends State<ChatThreadView> {
if (kind == 'activity') {
return _ChatActivityLine(row: row, onDismiss: onDismissCompaction);
}
if (kind == 'agent_report') {
return ChatAgentReportCard(row: row, textBuilder: chatMarkdownText);
}
if (kind == 'system_notice') return ChatSystemNoticeLine(row: row);
if (kind == 'permission' || kind == 'question') {
return ChatTranscriptCard(
row: row,
@@ -70,6 +70,11 @@ JsonMap refreshCachedChatHistory(
/// the latest record and that record's lifecycle state. Several updates of one
/// compaction are therefore one line, never one line per update.
///
/// A message the server marks with a `kind` is content the harness delivered,
/// 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]).
///
/// [trailing] rows are conversation cards (permission requests and questions),
/// not messages. They keep the server's order after the transcript, the way the
/// web renders approvals and forms at the end of the conversation.
@@ -124,6 +129,18 @@ List<JsonMap> transcriptRows(
}
for (final message in messages) {
final injected = chatInjectedKind(message);
if (injected != null) {
flush();
rows.add({
'kind': injected == chatKindAgentReport
? 'agent_report'
: 'system_notice',
'key': message['id'],
'message': message,
});
continue;
}
if (message['role'] == 'assistant') {
final id = '${message['id'] ?? ''}'.trim();
key ??= id;
@@ -149,10 +166,14 @@ List<JsonMap> transcriptRows(
// Prefer the assistant identity that actually streamed: a queued follow-up
// can be later in the transcript while this same reply is still arriving.
// Before a first delta, do not reopen an older reply behind a new user turn.
final answers = [
for (final message in messages)
if (chatInjectedKind(message) == null) message,
];
final streamingId =
liveMessageId ??
(messages.isNotEmpty && messages.last['role'] == 'assistant'
? '${messages.last['id'] ?? ''}'
(answers.isNotEmpty && answers.last['role'] == 'assistant'
? '${answers.last['id'] ?? ''}'
: null);
var hasStreamingRow = false;
if (running && streamingId != null) {
@@ -180,6 +201,19 @@ List<JsonMap> transcriptRows(
return rows;
}
/// `ChatMessage.Kind` of a report another agent delivered into the session.
const String chatKindAgentReport = 'agent_report';
/// `ChatMessage.Kind` of a one-line harness notice (a background task ended).
const String chatKindNotice = 'notice';
/// The injected-content kind the server recorded on [message], or null for an
/// ordinary turn. An unknown future kind keeps the message's own role.
String? chatInjectedKind(JsonMap message) {
final kind = '${message['kind'] ?? ''}';
return kind == chatKindAgentReport || kind == chatKindNotice ? kind : null;
}
/// Whether [part] is a recorded activity record rather than answer content.
///
/// Both spellings occur: `compaction` is the native lifecycle record and
@@ -307,6 +341,9 @@ JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
final incoming = frame['part'];
if (incoming is! Map || incoming['id'] == null) return thread;
final messageId = frame['message_id'];
// An agent report or notice the harness delivered: drawn on its own, and
// never evidence that the agent's turn is running.
final injected = chatInjectedKind({'kind': frame['message_kind']});
var index = messages.indexWhere(
(m) => m['id'] == messageId && m['role'] == 'assistant',
);
@@ -315,6 +352,7 @@ JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
'id': messageId,
'session_id': frame['session_id'],
'role': 'assistant',
'kind': ?injected,
'parts': <JsonMap>[],
});
index = messages.length - 1;
@@ -331,7 +369,12 @@ JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
final delta = frame['delta'];
if (delta is! String || delta.isEmpty) return thread;
if (partIndex < 0) {
parts.add({'type': kind, 'id': incoming['id'], 'text': delta});
parts.add({
'type': kind,
'id': incoming['id'],
'text': delta,
if (incoming['name'] is String) 'name': incoming['name'],
});
} else {
parts[partIndex] = {
...parts[partIndex],
@@ -354,6 +397,9 @@ JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
parts[partIndex] = merged;
}
messages[index] = {...message, 'parts': parts};
if (chatInjectedKind(message) != null) {
return {...thread, 'messages': messages};
}
return {...thread, 'messages': messages, 'running': true};
}
if (kind == 'step' && frame['step'] is Map) {
@@ -0,0 +1,244 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_message_bubble.dart';
import 'chat_message_view.dart';
/// Content the harness delivered into the session, drawn on the agent's side:
/// an `agent_report` row (a delegated agent's report) and a `system_notice`
/// row (a one-line harness notice such as a background task finishing). Neither
/// is the operator's turn, so neither uses the operator's bubble.
/// The text and sender a row's message recorded.
({String text, String sender}) _content(JsonMap row) {
final message = row['message'];
final parts = message is Map ? message['parts'] : null;
final buffer = StringBuffer();
var sender = '';
if (parts is List) {
for (final part in parts) {
if (part is! Map || part['type'] != 'text') continue;
final text = '${part['text'] ?? ''}';
if (text.trim().isEmpty) continue;
if (buffer.isNotEmpty) buffer.write('\n\n');
buffer.write(text);
final name = '${part['name'] ?? ''}'.trim();
if (sender.isEmpty && name.isNotEmpty) sender = name;
}
}
return (text: buffer.toString().trim(), sender: sender);
}
/// The report's first line, with markdown markers removed, as its summary.
String chatAgentReportSummary(String text) {
for (final raw in text.split('\n')) {
final line = raw
.trim()
.replaceFirst(RegExp(r'^(#{1,6}\s+|[-*+]\s+|>\s*)'), '')
.replaceAll('**', '')
.trim();
if (line.isNotEmpty) return line;
}
return '';
}
/// A delegated agent's report: collapsed to its first line, expanded to the
/// whole report rendered as markdown.
class ChatAgentReportCard extends StatefulWidget {
const ChatAgentReportCard({super.key, required this.row, this.textBuilder});
final JsonMap row;
final ChatMessageTextBuilder? textBuilder;
@override
State<ChatAgentReportCard> createState() => _ChatAgentReportCardState();
}
class _ChatAgentReportCardState extends State<ChatAgentReportCard> {
bool _expanded = false;
void _toggle() => setState(() => _expanded = !_expanded);
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final content = _content(widget.row);
final title = content.sender.isEmpty
? 'Agent report'
: 'Agent report · ${content.sender}';
final summary = chatAgentReportSummary(content.text);
final secondary = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final header = Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsetsDirectional.only(end: 12, top: 2),
child: Icon(
cupertino ? CupertinoIcons.person_crop_rectangle : Icons.assignment,
color: secondary,
),
),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: cupertino
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
fontWeight: FontWeight.w600,
)
: Theme.of(context).textTheme.titleSmall,
),
if (summary.isNotEmpty)
Text(
summary,
maxLines: _expanded ? null : 1,
overflow: _expanded ? null : TextOverflow.ellipsis,
style:
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium)
?.copyWith(color: secondary),
),
],
),
),
Icon(
cupertino
? (_expanded
? CupertinoIcons.chevron_up
: CupertinoIcons.chevron_down)
: (_expanded ? Icons.expand_less : Icons.expand_more),
color: secondary,
),
],
);
final toggle = Semantics(
container: true,
button: true,
expanded: _expanded,
label: title,
value: summary,
onTap: _toggle,
child: ExcludeSemantics(
child: cupertino
? CupertinoButton(
padding: const EdgeInsets.all(12),
onPressed: _toggle,
child: DefaultTextStyle.merge(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: header,
),
)
: InkWell(
onTap: _toggle,
child: Padding(
padding: const EdgeInsets.all(12),
child: header,
),
),
),
);
final body = _expanded
? Padding(
padding: const EdgeInsetsDirectional.fromSTEB(12, 0, 12, 12),
child: DefaultTextStyle.merge(
style: chatMessageTextStyle(context, cupertino),
child:
widget.textBuilder?.call(context, content.text) ??
SelectableText(content.text),
),
)
: null;
final column = Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [toggle, ?body],
);
return Semantics(
container: true,
explicitChildNodes: true,
label: 'Agent report',
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 720),
child: cupertino
? DecoratedBox(
decoration: BoxDecoration(
color: CupertinoColors.secondarySystemGroupedBackground
.resolveFrom(context),
border: Border.all(
color: CupertinoColors.separator.resolveFrom(context),
),
borderRadius: const BorderRadius.all(Radius.circular(12)),
),
child: column,
)
: Card.outlined(
margin: EdgeInsets.zero,
clipBehavior: Clip.antiAlias,
child: column,
),
),
),
),
);
}
}
/// A one-line harness notice in the agent's column, in the secondary style.
class ChatSystemNoticeLine extends StatelessWidget {
const ChatSystemNoticeLine({super.key, required this.row});
final JsonMap row;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final text = _content(row).text;
if (text.isEmpty) return const SizedBox.shrink();
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final style =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(color: color);
return Semantics(
container: true,
label: 'System notice',
value: text,
child: ExcludeSemantics(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: Icon(
cupertino ? CupertinoIcons.info_circle : Icons.info_outline,
size: style?.fontSize == null ? 16 : style!.fontSize! * 1.2,
color: color,
),
),
Expanded(child: Text(text, style: style)),
],
),
),
),
);
}
}
@@ -0,0 +1,260 @@
import 'dart:async';
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/domain/chat_transcript.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 'chat_thread_fixtures.dart';
/// Content the harness delivered (agent reports, task notices) carries the
/// server's message kind; it is drawn on the agent's side and never as the
/// operator's bubble, and it does not disturb the operator's delivery line.
const _report =
'## Segmented bar report\n\n- first finding\n - nested detail\n\n'
'The **whole** report.';
JsonMap _reportMessage() => {
'id': 'agent-report-1',
'role': 'assistant',
'kind': 'agent_report',
'parts': [
{
'type': 'text',
'id': 'agent-report-1#text#0',
'text': _report,
'name': 'general-purpose',
},
],
};
JsonMap _noticeMessage() => {
'id': 'task-notice-toolu_1-completed',
'role': 'assistant',
'kind': 'notice',
'parts': [
{
'type': 'text',
'text': 'Background task finished: Background command "Build" completed',
},
],
};
class _Gateway extends FakeChatGateway {
final prompts = <Completer<JsonMap>>[];
List<JsonMap> messages = [];
_Gateway() {
history = (_) async => chatPage(messages);
}
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_prompt') {
final reply = Completer<JsonMap>();
prompts.add(reply);
return reply.future;
}
return super.call(type, fields);
}
}
Future<void> _pump(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
await tester.pump();
}
Future<void> _host(
WidgetTester tester,
_Gateway gateway, {
bool cupertino = false,
}) async {
var sequence = 0;
final thread = ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
drafts: MemoryChatDraftStore(),
newOperationId: () => 'op-${++sequence}',
);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: thread))
: MaterialApp(home: Scaffold(body: thread)),
);
await _pump(tester);
}
void main() {
test('transcriptRows gives injected kinds their own rows', () {
final rows = transcriptRows([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'hi'},
],
),
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'id': 'a1#text#0', 'text': 'answer'},
],
),
_reportMessage(),
_noticeMessage(),
chatMessage(
'a2',
'assistant',
parts: [
{'type': 'text', 'id': 'a2#text#0', 'text': 'next'},
],
),
]);
expect(rows.map((row) => row['kind']), [
'user',
'assistant',
'agent_report',
'system_notice',
'assistant',
]);
expect(rows[1]['messageIds'], ['a1']);
expect(rows[4]['messageIds'], ['a2']);
});
test('a live report frame keeps its kind and does not start a turn', () {
final thread = applyChatEvent(
{'sessionId': 's', 'messages': <JsonMap>[]},
{
'session_id': 's',
'message_id': 'agent-report-1',
'message_kind': 'agent_report',
'kind': 'text',
'part': {'id': 'agent-report-1#text#0', 'name': 'general-purpose'},
'delta': _report,
},
);
final message = (thread['messages'] as List).single as Map;
expect(message['kind'], 'agent_report');
expect(message['role'], 'assistant');
expect((message['parts'] as List).single['name'], 'general-purpose');
expect(thread['running'], isNot(true));
});
test('the summary is the first line without markdown markers', () {
expect(chatAgentReportSummary(_report), 'Segmented bar report');
expect(chatAgentReportSummary('\n- **Done**: all\n'), 'Done: all');
});
for (final cupertino in [false, true]) {
testWidgets('a report is a collapsed card on the agent side, a notice is '
'one line, a prompt stays a bubble ($cupertino)', (tester) async {
tester.view.physicalSize = const Size(1000, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final gateway = _Gateway()
..messages = [
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'Please delegate this'},
],
),
_reportMessage(),
_noticeMessage(),
];
addTearDown(gateway.close);
await _host(tester, gateway, cupertino: cupertino);
final prompt = find.text('Please delegate this');
expect(prompt, findsOneWidget);
expect(
find.ancestor(of: prompt, matching: find.byType(ChatUserBubble)),
findsOneWidget,
);
final card = find.byType(ChatAgentReportCard);
expect(card, findsOneWidget);
expect(find.text('Agent report · general-purpose'), findsOneWidget);
expect(find.text('Segmented bar report'), findsOneWidget);
// Collapsed: the rest of the report is not laid out yet.
expect(find.textContaining('nested detail'), findsNothing);
expect(
find.ancestor(of: card, matching: find.byType(ChatUserBubble)),
findsNothing,
);
// The card starts on the agent's (leading) side; the prompt ends on
// the operator's (trailing) side.
final width = tester.getSize(find.byType(ChatThreadView)).width;
expect(tester.getTopLeft(card).dx, lessThan(width * 0.2));
expect(
tester.getTopRight(find.byType(ChatUserBubble)).dx,
greaterThan(width * 0.8),
);
final notice = find.text(
'Background task finished: Background command "Build" completed',
);
expect(notice, findsOneWidget);
expect(
find.ancestor(of: notice, matching: find.byType(ChatUserBubble)),
findsNothing,
);
expect(find.bySemanticsLabel('System notice'), findsOneWidget);
await tester.tap(find.text('Agent report · general-purpose'));
await _pump(tester);
expect(find.textContaining('nested detail'), findsOneWidget);
expect(find.textContaining('first finding'), findsOneWidget);
// Markdown is rendered, not shown raw.
expect(find.textContaining('## Segmented'), findsNothing);
expect(find.textContaining('**whole**'), findsNothing);
});
testWidgets('a live report leaves the prompt\'s delivery line alone '
'($cupertino)', (tester) async {
final gateway = _Gateway();
addTearDown(gateway.close);
await _host(tester, gateway, cupertino: cupertino);
await tester.enterText(
find.byKey(const Key('chat-composer-field')),
'Hello',
);
await tester.pump();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await _pump(tester);
gateway.prompts.single.complete({});
await _pump(tester);
expect(find.byKey(const Key('chat-delivery-sent')), findsOneWidget);
gateway.emitEvent({
'session_id': 's',
'message_id': 'agent-report-1',
'message_kind': 'agent_report',
'kind': 'text',
'part': {'id': 'agent-report-1#text#0', 'name': 'general-purpose'},
'delta': _report,
});
await _pump(tester);
expect(find.byType(ChatAgentReportCard), findsOneWidget);
expect(find.byKey(const Key('chat-delivery-sent')), findsOneWidget);
expect(
find.ancestor(
of: find.text('Hello'),
matching: find.byType(ChatUserBubble),
),
findsOneWidget,
);
});
}
}