Keep chat activity stable in one live disclosure and distinguish unread attention

This commit is contained in:
2026-10-28 16:45:05 +00:00
parent e0317574de
commit 7027da4248
22 changed files with 968 additions and 301 deletions
@@ -88,22 +88,29 @@ List<JsonMap> transcriptRows(
final activity = <JsonMap>[];
String? activityKey;
void flush() {
if (activity.isNotEmpty) {
final latest = activity.last;
final compactions = activity
.where((p) => chatActivityKind(p) == 'compaction')
.toList();
final passive = activity
.where((p) => chatActivityKind(p) != 'compaction')
.toList();
if (compactions.isNotEmpty) {
final latest = compactions.last;
rows.add({
'kind': 'activity',
'key': activityKey == null ? '' : 'chat-activity-$activityKey',
'records': List<JsonMap>.of(activity),
'records': compactions,
'label': chatActivityLabel(latest),
'state': chatActivityState(latest).toLowerCase(),
});
}
if (key != null && parts.isNotEmpty) {
if (key != null && (parts.isNotEmpty || passive.isNotEmpty)) {
rows.add({
'kind': 'assistant',
'key': key,
'messageIds': List<String>.of(ids),
'parts': List<JsonMap>.of(parts),
if (passive.isNotEmpty) 'activityRecords': passive,
// The model that answered, as the server recorded it on the reply.
if (model.isNotEmpty) 'model': model,
});
@@ -0,0 +1,125 @@
import '../../../core/api_gateway.dart';
import 'chat_tool_calls.dart';
import 'chat_transcript.dart';
/// Presentation facts only: never infer a command or successful outcome from
/// answer prose, and never treat a still-running record as a completed command.
class ChatTurnActivityData {
ChatTurnActivityData(this.parts, {required this.streaming});
final List<JsonMap> parts;
final bool streaming;
List<JsonMap> get tools => parts.where(isChatToolPart).toList();
List<String> get reasoning => [
for (final p in parts)
if (p['type'] == 'reasoning' && '${p['text'] ?? ''}'.trim().isNotEmpty)
'${p['text']}',
];
List<JsonMap> get records => parts.where(chatActivityType).toList();
bool get hasDetails =>
tools.isNotEmpty || reasoning.isNotEmpty || records.isNotEmpty;
JsonMap? get active {
for (final tool in tools.reversed) {
if (chatToolRunning(tool)) return tool;
}
if (records.isNotEmpty) {
// Sequence updates can be distinct records; a completed newest record
// must not resurrect an older running phase.
final record = records.last;
if ([
'running',
'streaming',
'pending',
].contains(chatActivityState(record))) {
return record;
}
}
return null;
}
String get identity {
final p = active;
return p == null
? 'thinking'
: '${p['type']}:${p['id'] ?? p['name'] ?? p['kind'] ?? ''}';
}
DateTime? get started {
final p = active;
if (p == null) return null;
final state = p['state'];
final time = p['time'] ?? (state is Map ? state['time'] : null);
if (time is! Map) return null;
final value = time['ran'] ?? time['started'] ?? time['created'];
if (value is num && value > 0) {
return DateTime.fromMillisecondsSinceEpoch(value.toInt());
}
return value is String ? DateTime.tryParse(value) : null;
}
String get label {
if (streaming) {
final p = active;
if (p == null) {
for (final part in parts.reversed) {
if (part['type'] == 'text' &&
'${part['text'] ?? ''}'.trim().isNotEmpty) {
return 'Responding';
}
if (part['type'] == 'reasoning') return 'Thinking';
}
return 'Thinking';
}
if (!isChatToolPart(p)) {
return chatActivityLabel(p).replaceAll('…', '').trim();
}
final state = p['state'];
final title = state is Map ? '${state['title'] ?? ''}'.trim() : '';
return title.isNotEmpty
? title
: chatToolDetail(p) ??
(_command(p)
? 'Running a command'
: 'Running ${chatToolLabel(p)}');
}
final calls = tools;
if (calls.isEmpty) {
return records.isNotEmpty ? 'Activity details' : 'Reasoning';
}
final commands = calls.every(_command);
final failed = calls.where(chatToolFailed).length;
final unfinished = calls.any((p) {
final state = p['state'];
return chatToolRunning(p) ||
(state is Map &&
[
'stopped',
'interrupted',
'canceled',
'cancelled',
'pending',
].contains(state['status']));
});
final noun = commands
? (calls.length == 1 ? 'command' : 'commands')
: (calls.length == 1 ? 'tool' : 'tools');
final summary =
'${unfinished
? 'Stopped after'
: commands
? 'Ran'
: 'Used'} ${calls.length} $noun';
return failed == 0 ? summary : '$summary · $failed failed';
}
bool get failed => tools.any(chatToolFailed);
}
bool _command(JsonMap tool) => const [
'bash',
'shell',
'command',
'exec',
'execute',
'run_command',
].contains(chatToolLabel(tool).toLowerCase());
@@ -39,6 +39,8 @@ class ChatSessionsController extends ChangeNotifier {
bool _disposed = false;
int _generation = 0;
Future<void> _persistTail = Future<void>.value();
int _runningRevision = 0;
final Map<String, ({int revision, bool running})> _runningFrames = {};
StreamSubscription<JsonMap>? _frameSubscription;
String? activeSessionId;
@@ -61,6 +63,7 @@ class ChatSessionsController extends ChangeNotifier {
void _setRunning(String id, bool running) {
if (_disposed) return;
_runningFrames[id] = (revision: ++_runningRevision, running: running);
var changed = false;
_sessions = _sessions.map((session) {
if ('${session['id'] ?? ''}' != id || session['running'] == running) {
@@ -121,6 +124,7 @@ class ChatSessionsController extends ChangeNotifier {
void replaceRepository(ChatRepository next) {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
_runningFrames.clear();
_listenFrames();
refresh();
}
@@ -135,9 +139,17 @@ class ChatSessionsController extends ChangeNotifier {
// must not hide the list or delay the first request.
unawaited(_ensureLocal());
try {
final runningRevision = _runningRevision;
final sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = sessions;
_sessions = [
for (final row in sessions)
if ((_runningFrames['${row['id'] ?? ''}']?.revision ?? 0) >
runningRevision)
{...row, 'running': _runningFrames['${row['id'] ?? ''}']!.running}
else
row,
];
_seedLocal();
_loading = false;
_notify();
@@ -48,27 +48,17 @@ ChatSessionFrameEffect? chatSessionFrameEffect(JsonMap frame) {
} else if (kind == 'step') {
final step = event['step'];
if (step is Map) {
if (step['status'] == 'started' || step['status'] == 'streamed') {
if ([
'started',
'streamed',
'running',
'streaming',
].contains(step['status'])) {
running = true;
} else if (step['status'] == 'ended' && step['intermediate'] != true) {
running = false;
}
}
} else if (kind == 'compaction') {
final compaction = event['compaction'];
if (compaction is Map) {
if (compaction['status'] == 'running') running = true;
if (compaction['status'] == 'completed' ||
compaction['status'] == 'failed') {
running = false;
}
}
} else if (kind == 'shell') {
final shell = event['shell'];
if (shell is Map) {
if (shell['status'] == 'running') running = true;
if (shell['status'] == 'exited') running = false;
}
}
} else if (type == 'chat_permission') {
final permission = frame['chat_permission'];
@@ -82,7 +82,11 @@ class ChatSessionRowContent extends StatelessWidget {
children: [
if (status != null)
_StatusLabel(status: status!, style: statusStyle),
if (status == null && loading) _LoadingStatus(),
if (status == null && loading)
Semantics(
label: 'Chat is working',
child: const _LoadingStatus(),
),
for (final line in meta)
Text(
line,
@@ -123,6 +127,7 @@ class ChatSessionRowContent extends StatelessWidget {
}
class _LoadingStatus extends StatelessWidget {
const _LoadingStatus();
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
@@ -6,10 +6,8 @@ import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../sessions/chat_adaptive.dart';
import '../../domain/chat_tool_calls.dart';
import 'chat_tool_calls_view.dart';
import 'chat_reasoning_chip.dart';
import 'chat_turn_activity_view.dart';
import 'native_disclosure.dart';
import 'chat_response_pending.dart';
/// Builds an assistant text part; the default keeps the server's text exactly.
typedef ChatMessageTextBuilder = Widget Function(BuildContext, String);
@@ -27,8 +25,7 @@ class ChatMessageView extends StatelessWidget {
final JsonMap row;
final ChatMessageTextBuilder? textBuilder;
/// More of an agent turn's summary chips, after its reasoning and tools chips
/// (the turn's settled permission requests).
/// The turn's settled permissions, independent of passive activity details.
final List<Widget> footer;
@override
@@ -199,9 +196,8 @@ class ChatMessageView extends StatelessWidget {
return widgets;
}
/// The turn's footer: its reasoning, tools and permissions chips, then its
/// model. Each chip opens a native sheet; an open reasoning sheet follows
/// live deltas.
/// Stable activity precedes the answer; permission summaries and recorded
/// model remain beneath it. Pending interaction cards are rendered separately.
Widget _agentTurn(BuildContext context, List<Widget> content, Widget bubble) {
final parts = _partsOf(row);
final reasoning = [
@@ -216,13 +212,6 @@ class ChatMessageView extends StatelessWidget {
];
final model = '${row['model'] ?? ''}'.trim();
final footer = <Widget>[
if (reasoning.isNotEmpty)
ChatReasoningChip(
key: const Key('chat-turn-reasoning'),
steps: reasoning,
streaming: row['streaming'] == true && _reasoningIsNewest(parts),
),
if (tools.isNotEmpty) ChatToolCallsChip(calls: tools),
...this.footer,
if (model.isNotEmpty)
Text(
@@ -238,6 +227,20 @@ class ChatMessageView extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (row['streaming'] == true ||
reasoning.isNotEmpty ||
tools.isNotEmpty ||
(row['activityRecords'] as List? ?? const []).isNotEmpty)
ChatTurnActivityView(
key: const Key('chat-stable-turn-activity'),
parts: [
...parts,
...List<JsonMap>.from(
row['activityRecords'] as List? ?? const [],
),
],
streaming: row['streaming'] == true,
),
if (content.isNotEmpty) bubble,
if (footer.isNotEmpty)
Wrap(
@@ -266,9 +269,6 @@ class ChatMessageView extends StatelessWidget {
KeyedSubtree(key: _partKey(part, index, seen), child: widget),
);
}
if (widgets.isEmpty && row['streaming'] == true) {
widgets.add(const ChatResponsePending());
}
return widgets;
}
@@ -294,7 +294,7 @@ class ChatMessageView extends StatelessWidget {
if (!hasText) return type.isEmpty ? _unrecognised(part) : null;
return textBuilder?.call(context, text) ?? SelectableText(text);
}
// Reasoning and tool calls are drawn outside the bubble (_agentTurn).
// Reasoning and tools are retained in the turn's activity disclosure.
if (type == 'reasoning' || type == 'tool') return null;
if (type == 'file') {
if (_isFile(part)) return _attachment(context, part);
@@ -343,21 +343,6 @@ class ChatMessageView extends StatelessWidget {
SelectableText(const JsonEncoder.withIndent(' ').convert(part));
}
/// Whether the turn's newest drawn part is reasoning: while it streams, that
/// is the step still arriving. Once an answer or a tool call starts after it,
/// the reasoning chip stops spinning (a running tool spins its own chip).
bool _reasoningIsNewest(List<JsonMap> parts) {
for (final part in parts.reversed) {
final type = part['type'];
if (type == 'tool') return false;
if ((type == 'text' || type == 'reasoning') &&
'${part['text'] ?? ''}'.trim().isNotEmpty) {
return type == 'reasoning';
}
}
return false;
}
List<JsonMap> _partsOf(Map<dynamic, dynamic> source) {
final parts = source['parts'];
if (parts is! List) return const [];
@@ -85,7 +85,7 @@ class _ToolCallsSheet extends StatelessWidget {
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
for (final call in calls) _ToolCallRow(call: call),
for (final call in calls) ChatToolCallDetail(call: call),
],
),
),
@@ -95,8 +95,8 @@ class _ToolCallsSheet extends StatelessWidget {
/// One call: status glyph, name, its command/description and duration; it
/// opens to the formatted INPUT and OUTPUT (or ERROR).
class _ToolCallRow extends StatelessWidget {
const _ToolCallRow({required this.call});
class ChatToolCallDetail extends StatelessWidget {
const ChatToolCallDetail({super.key, required this.call});
final JsonMap call;
@@ -0,0 +1,47 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../domain/chat_turn_activity.dart';
import '../../domain/chat_activity_detail.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_tool_calls_view.dart';
import 'native_disclosure.dart';
class ChatTurnActivityDetails extends StatelessWidget {
const ChatTurnActivityDetails({super.key, required this.data});
final ChatTurnActivityData data;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return DefaultTextStyle.merge(
style: cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
if (!data.hasDetails) const Text('Waiting for activity details.'),
for (final (index, step) in data.reasoning.indexed)
NativeDisclosure(
label: 'Reasoning ${index + 1}',
childBuilder: (_) => SelectableText(step),
),
for (final tool in data.tools) ChatToolCallDetail(call: tool),
for (final record in data.records)
NativeDisclosure(
label: '${record['label'] ?? record['kind'] ?? 'Activity'}',
childBuilder: (_) {
final d = chatActivityDetail(record);
return SelectableText(
'Status: ${d.lifecycle}\nInput: ${d.input}\nOutput: ${d.output}\nError: ${d.error}\nDuration: ${d.duration}\nDiff: ${d.diff}',
);
},
),
],
),
);
}
}
@@ -0,0 +1,193 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_turn_activity.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_response_pending.dart';
import 'chat_turn_activity_details.dart';
/// A stable one-line turn status; only this small subtree ticks, never the
/// transcript. The same disclosure and live records survive tool transitions.
class ChatTurnActivityView extends StatefulWidget {
const ChatTurnActivityView({
super.key,
required this.parts,
required this.streaming,
});
final List<JsonMap> parts;
final bool streaming;
@override
State<ChatTurnActivityView> createState() => _ChatTurnActivityViewState();
}
class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
late final _live = ValueNotifier(_data);
ChatTurnActivityData get _data =>
ChatTurnActivityData(widget.parts, streaming: widget.streaming);
Timer? _timer;
final _clock = Stopwatch()..start();
Duration _observedAt = Duration.zero;
String? _identity;
TransitionRoute<void>? _modal;
@override
void initState() {
super.initState();
_sync();
}
void _sync() {
final data = _data;
if (_identity != data.identity) {
_identity = data.identity;
_observedAt = _clock.elapsed;
}
_timer?.cancel();
if (widget.streaming) {
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() {});
});
}
}
@override
void didUpdateWidget(ChatTurnActivityView oldWidget) {
super.didUpdateWidget(oldWidget);
_sync();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _live.value = _data;
});
}
void _open() {
if (_modal != null) return;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
Widget dialog(BuildContext dialogContext) {
final content = ValueListenableBuilder<ChatTurnActivityData>(
valueListenable: _live,
builder: (_, data, _) =>
SingleChildScrollView(child: ChatTurnActivityDetails(data: data)),
);
void close() => Navigator.of(dialogContext).pop();
return cupertino
? CupertinoAlertDialog(
title: const Text('Activity details'),
content: content,
actions: [
CupertinoDialogAction(
onPressed: close,
child: const Text('Done'),
),
],
)
: AlertDialog(
title: const Text('Activity details'),
scrollable: true,
content: content,
actions: [
TextButton(onPressed: close, child: const Text('Done')),
],
);
}
final TransitionRoute<void> route = cupertino
? CupertinoDialogRoute<void>(
context: context,
barrierDismissible: true,
builder: dialog,
)
: DialogRoute<void>(context: context, builder: dialog);
_modal = route;
Navigator.of(context, rootNavigator: true).push(route);
route.completed.then((_) {
if (_modal == route) _modal = null;
});
}
@override
void dispose() {
_timer?.cancel();
_clock.stop();
final route = _modal;
if (route != null) {
// Do not pop a different route the operator opened above our dialog.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (route.isActive) route.navigator?.removeRoute(route);
});
route.completed.then((_) => _live.dispose());
} else {
_live.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final data = _data;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final accent = cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary;
final color = data.failed && !widget.streaming
? (cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error)
: (cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant);
final started = data.started;
final duration = started == null
? _clock.elapsed - _observedAt
: DateTime.now().difference(started);
final seconds = duration.inSeconds.clamp(0, 2147483647);
final label = '${data.label}${widget.streaming ? ' ${seconds}s' : ''}';
final content = Row(
children: [
if (widget.streaming) ...[
ExcludeSemantics(
child: DefaultTextStyle.merge(
style: TextStyle(color: accent),
child: const ChatResponsePending(),
),
),
const SizedBox(width: 8),
],
Expanded(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color),
),
),
Icon(
cupertino ? CupertinoIcons.chevron_right : Icons.chevron_right,
color: color,
),
],
);
return Semantics(
button: true,
label: '$label, expand for details',
excludeSemantics: true,
onTap: _open,
child: cupertino
? CupertinoButton(
key: const Key('chat-turn-activity'),
padding: EdgeInsets.zero,
onPressed: _open,
child: content,
)
: TextButton(
key: const Key('chat-turn-activity'),
onPressed: _open,
child: content,
),
);
}
}
+63
View File
@@ -0,0 +1,63 @@
# Stable turn activity and chat attention
## Turn activity
- One stable native disclosure replaces separate reasoning/tool footer chips and
the empty pending-answer bubble. It sits above the answer from prompt acceptance
through completion, with a single-line current recorded tool title/description,
elapsed seconds, theme-accent animated dots and trailing disclosure arrow.
- Local animation/timer ticks rebuild only the status subtree. Reduced-motion
settings stop the dots. Current calls update the same widget; completed calls
never remain labelled running while the turn waits for its answer.
- Finished turns retain a compact summary such as `Ran 4 commands`, `Used 2
tools`, or `Reasoning`. Recorded failures/stopped calls are not represented as
successful completion. No command counts are inferred from assistant prose.
- The owned native dialog follows live records and reuses tool input/output/error
detail rendering. Reasoning remains expandable/selectable there. Disposal closes
only its owned route; pending permissions/questions remain separate/actionable.
- Ordinary passive activity records join the assistant turn; dedicated compaction
safety notices retain their existing lifecycle and dismissal behavior.
## Evidence so far
- Production-entry isolated browser probe `tool/chat_stable_activity_probe.mjs`
passed: current command/elapsed, unchanged row top/height through tool changes,
hidden reasoning, live open-detail updates, final four-command summary and answer.
Captures inspected at `build/stable-activity-{material,cupertino}`. The latter
name denotes the narrow probe configuration, not proof of Cupertino rendering:
the current production web theme intentionally uses Material controls.
- Full integrated suite: **1,984 tests passed**. Scoped analysis of chat source,
chat tests and registration passed with no issues. Whole-app analysis retains
one unrelated existing unnecessary-import info in artifact viewer tests.
- Regressions cover new summary/disclosure ordering, reasoning folding/paging,
queued follow-up identity, live modal updates, stable row height, pending
animation, compaction safety notices and independent permission controls.
## Chat-list attention
- Integrated `985cc355` plus manager fixes: actual unread assistant messages,
user messages from another client, returned visible tool content, and unresolved
forms/permissions mark New. Step/reasoning/activity/usage/metadata chatter does
not. Generic `updated_at` changes are not proof of unseen content.
- Native loading is shown while working with nothing unread. New takes precedence
even during a running turn; opening suppresses/acknowledges New. Timestamp-only
refresh cannot manufacture unread. Without actual content/action evidence, the
list cannot infer messages missed offline from its metadata-only listing.
- Only final turn-end clears live working state; a background shell exiting or
compaction completing cannot incorrectly clear it. List snapshots preserve
newer in-flight running frames, and delayed preference reads respect opens.
- Production browser probe `tool/chat_attention_probe.mjs` passed and captures
inspected at `build/chat-attention-release`: loading-only, New for a message
during work, then acknowledged by opening. Native host tests passed as well.
## Publication
- Existing installer used for web and APK, with no executing pipeline runs,
backend/auth change, shared-service restart, real-chat mutation or device use.
- Rollback of installed/public artifacts:
`~/.local/share/pipelines/backups/stable-chat-activity-20261028-162341/`.
- Website live; public rollback `build/web-before-stable-activity-1793205830/`.
Full authenticated JS downloads on HTTPS 8443/8096 match SHA256:
`5895b2f091a9a5ce876ad03a9971740e0e98340c31f3ea59f8f19a42159fa2dc`.
- APK build underway. Installer builds contain all functional source changes;
the only subsequent source edit encloses a return in braces to satisfy lint.
@@ -203,8 +203,8 @@ void main() {
'cursor': '',
});
expect(find.text('The stored reply stays readable.'), findsOneWidget);
expect(find.text('Reasoning'), findsOneWidget);
expect(find.text('1 tool'), findsOneWidget);
expect(find.text('Ran 1 command'), findsOneWidget);
expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget);
expect(find.text('Kept behind a native disclosure.'), findsNothing);
// The shell bar stays over the list and rail; the open chat has its
@@ -123,10 +123,11 @@ void main() {
expect(rows.map((row) => row['kind']), ['activity', 'assistant']);
final activity = rows.first;
expect(activity['records'], hasLength(3));
expect(activity['records'], hasLength(2));
expect(activity['label'], 'Context compacted');
expect(activity['state'], 'completed');
expect((rows.last['parts'] as List).single['text'], 'answer');
expect(rows.last['activityRecords'], hasLength(1));
});
test('a sequence can span consecutive assistant messages', () {
@@ -143,8 +144,8 @@ void main() {
]),
]);
expect(_activityRows(rows), hasLength(1));
expect(_activityRows(rows).single['label'], 'Thought');
expect(_activityRows(rows), isEmpty);
expect(rows.single['activityRecords'], hasLength(2));
});
test('separate turns keep separate lines', () {
@@ -243,9 +244,8 @@ void main() {
group('expanded detail', () {
final recorded = <JsonMap>[
{
'type': 'activity',
'type': 'compaction',
'id': 'e1',
'kind': 'tool',
'state': 'completed',
'label': 'Ran a tool',
'input': {'command': 'ls'},
@@ -138,6 +138,8 @@ void main() {
await tester.pump();
await tester.tap(find.byKey(const Key('chat-composer-primary')));
await tester.pumpAndSettle();
final activity = find.byKey(const Key('chat-stable-turn-activity'));
final activityElement = tester.element(activity);
gateway.emitEvent({
'session_id': 's',
'message_id': 'live',
@@ -145,8 +147,8 @@ void main() {
'part': {'id': 'live-reasoning-0', 'type': 'reasoning'},
'delta': 'Provided reasoning after the follow-up',
});
// The reasoning chip spins while its step is the newest part, so the
// frames are pumped rather than settled.
// The combined activity control remains keyed to the live turn while
// the queued follow-up is a separate user row.
Future<void> frames() async {
for (var frame = 0; frame < 8; frame++) {
await tester.pump(const Duration(milliseconds: 100));
@@ -154,7 +156,11 @@ void main() {
}
await frames();
await tester.tap(find.text('Reasoning'));
expect(tester.element(activity), same(activityElement));
expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-turn-activity')));
await frames();
await tester.tap(find.text('Reasoning 1'));
await frames();
expect(
find.text('Provided reasoning after the follow-up'),
@@ -24,8 +24,8 @@ Widget _host(Widget child, bool cupertino) => cupertino
home: Scaffold(body: child),
);
/// A streaming reasoning chip spins for as long as reasoning is the newest
/// part, so pumpAndSettle would never return; this lets a sheet finish its
/// The streaming activity control animates, so pumpAndSettle would never
/// return; this lets its dialog finish its
/// entrance or exit instead.
Future<void> _settle(WidgetTester tester) async {
for (var frame = 0; frame < 8; frame++) {
@@ -33,69 +33,63 @@ Future<void> _settle(WidgetTester tester) async {
}
}
final _sheet = find.byKey(const Key('chat-reasoning-sheet'));
final _activity = find.byKey(const Key('chat-turn-activity'));
final _dialog = find.text('Activity details');
Finder _inSheet(String text) =>
find.descendant(of: _sheet, matching: find.text(text));
Finder _inDialog(String text) => find.text(text);
Future<void> _dismiss(WidgetTester tester) async {
await tester.tapAt(const Offset(10, 10));
await _settle(tester);
expect(_sheet, findsNothing);
expect(_dialog, findsNothing);
}
void main() {
for (final cupertino in [false, true]) {
final host = cupertino ? 'Cupertino' : 'Material';
testWidgets('reasoning arriving after text is a spinning chip ($host)', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
_host(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
cupertino,
),
);
await tester.pumpAndSettle();
gateway.emitEvent(_delta('text', 'Answer first'));
await tester.pumpAndSettle();
expect(find.text('Reasoning'), findsNothing);
testWidgets(
'reasoning arriving after text keeps one streaming activity control ($host)',
(tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
_host(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
cupertino,
),
);
await tester.pumpAndSettle();
gateway.emitEvent(_delta('text', 'Answer first'));
await tester.pumpAndSettle();
expect(find.text('Reasoning'), findsNothing);
gateway.emitEvent(_delta('reasoning', 'Only supplied reasoning'));
await _settle(tester);
// A chip in the footer like the tools chip, not an inline body.
expect(find.text('Only supplied reasoning'), findsNothing);
expect(find.text('Answer first'), findsOneWidget);
final chip = find.byKey(const Key('chat-reasoning-chip'));
final spinner = find.descendant(
of: chip,
matching: find.byType(
cupertino ? CupertinoActivityIndicator : CircularProgressIndicator,
),
);
expect(spinner, findsOneWidget);
expect(
find.bySemanticsLabel('Reasoning, expand for details'),
findsOneWidget,
);
gateway.emitEvent(_delta('reasoning', 'Only supplied reasoning'));
await _settle(tester);
// Reasoning is private until the operator opens the combined activity.
expect(find.text('Only supplied reasoning'), findsNothing);
expect(find.text('Answer first'), findsOneWidget);
expect(_activity, findsOneWidget);
expect(find.textContaining('Thinking'), findsOneWidget);
expect(find.byKey(const Key('chat-reasoning-chip')), findsNothing);
await tester.tap(find.text('Reasoning'));
await _settle(tester);
expect(_inSheet('Only supplied reasoning'), findsOneWidget);
await _dismiss(tester);
await tester.tap(_activity);
await _settle(tester);
await tester.tap(find.text('Reasoning 1'));
await _settle(tester);
expect(_inDialog('Only supplied reasoning'), findsOneWidget);
await _dismiss(tester);
// The step ends: the chip settles to its icon.
gateway.emitEvent(chatStepFrame('ended'));
await tester.pumpAndSettle();
expect(spinner, findsNothing);
expect(tester.takeException(), isNull);
});
// The step ends: the chip settles to its icon.
gateway.emitEvent(chatStepFrame('ended'));
await tester.pumpAndSettle();
expect(_activity, findsOneWidget);
expect(tester.takeException(), isNull);
},
);
testWidgets('an open reasoning sheet follows live deltas, paging and '
testWidgets('an open activity dialog follows live deltas, paging and '
'resync ($host)', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
@@ -112,21 +106,23 @@ void main() {
gateway.emitEvent(_delta('reasoning', 'Provided thought'));
await _settle(tester);
final rowElement = tester.element(find.byType(ChatMessageView));
await tester.tap(find.text('Reasoning'));
await tester.tap(_activity);
await _settle(tester);
expect(_inSheet('Provided thought'), findsOneWidget);
await tester.tap(find.text('Reasoning 1'));
await _settle(tester);
expect(_inDialog('Provided thought'), findsOneWidget);
// The open sheet repaints with each delta while the answer streams too;
// the row and its chip are the same elements throughout.
gateway.emitEvent(_delta('text', 'Answer'));
gateway.emitEvent(_delta('reasoning', ' continues'));
await _settle(tester);
expect(_inSheet('Provided thought continues'), findsOneWidget);
expect(_inDialog('Provided thought continues'), findsOneWidget);
expect(find.text('Answer'), findsOneWidget);
expect(tester.element(find.byType(ChatMessageView)), same(rowElement));
gateway.emitEvent(_delta('reasoning', ' live'));
await _settle(tester);
expect(_inSheet('Provided thought continues live'), findsOneWidget);
expect(_inDialog('Provided thought continues live'), findsOneWidget);
await _dismiss(tester);
// A closed sheet draws nothing; reopening shows the newest text.
@@ -135,16 +131,19 @@ void main() {
await tester.pumpAndSettle();
expect(find.textContaining('while closed'), findsNothing);
expect(find.text('Answer continues'), findsOneWidget);
await tester.tap(find.text('Reasoning'));
await tester.tap(_activity);
await tester.pumpAndSettle();
expect(find.text('Reasoning 1'), findsOneWidget);
await tester.tap(find.text('Reasoning 1'));
await tester.pumpAndSettle();
expect(
_inSheet('Provided thought continues live while closed'),
_inDialog('Provided thought continues live while closed'),
findsOneWidget,
);
await _dismiss(tester);
// Prepending another assistant message folds into the same turn without
// replacing the row; the chip counts both steps.
// replacing the row; the one activity control keeps both steps.
gateway.history = (_) async => chatPage([
chatMessage(
'older',
@@ -160,13 +159,19 @@ void main() {
]);
await tester.tap(find.text('Load older'));
await tester.pumpAndSettle();
expect(find.text('Reasoning · 2 steps'), findsOneWidget);
expect(_activity, findsOneWidget);
expect(tester.element(find.byType(ChatMessageView)), same(rowElement));
await tester.tap(find.text('Reasoning · 2 steps'));
await tester.tap(_activity);
await tester.pumpAndSettle();
expect(_inSheet('Older provided thought'), findsOneWidget);
expect(find.text('Reasoning 1'), findsOneWidget);
expect(find.text('Reasoning 2'), findsOneWidget);
await tester.tap(find.text('Reasoning 1'));
await tester.pumpAndSettle();
await tester.tap(find.text('Reasoning 2'));
await tester.pumpAndSettle();
expect(_inDialog('Older provided thought'), findsOneWidget);
expect(
_inSheet('Provided thought continues live while closed'),
_inDialog('Provided thought continues live while closed'),
findsOneWidget,
);
@@ -188,7 +193,7 @@ void main() {
]);
gateway.emitEvent({'session_id': 's', 'kind': 'resync'});
await tester.pumpAndSettle();
expect(_inSheet('Stored provided thought'), findsOneWidget);
expect(_inDialog('Stored provided thought'), findsOneWidget);
expect(find.textContaining('while closed'), findsNothing);
expect(find.text('Stored answer'), findsOneWidget);
expect(tester.element(find.byType(ChatMessageView)), same(rowElement));
@@ -205,9 +210,11 @@ void main() {
);
await tester.pumpAndSettle();
expect(find.text('Stored provided thought'), findsNothing);
await tester.tap(find.text('Reasoning'));
await tester.tap(_activity);
await tester.pumpAndSettle();
expect(_inSheet('Stored provided thought'), findsOneWidget);
await tester.tap(find.text('Reasoning 1'));
await tester.pumpAndSettle();
expect(_inDialog('Stored provided thought'), findsOneWidget);
if (cupertino) expect(find.byType(Material), findsNothing);
expect(tester.takeException(), isNull);
});
@@ -115,7 +115,7 @@ void main() {
});
await tester.pumpAndSettle();
expect(find.text('1 tool'), findsOneWidget);
expect(find.text('Ran 1 command'), findsOneWidget);
expect(find.text('1 permission'), findsOneWidget);
expect(find.text('Rejected'), findsNothing);
@@ -78,7 +78,7 @@ void main() {
await _send(tester);
expect(find.byType(ChatResponsePending), findsOneWidget);
expect(
find.bySemanticsLabel('Assistant is responding'),
find.bySemanticsLabel(RegExp(r'Thinking.*expand for details')),
findsOneWidget,
);
expect(find.byType(ChatMessageView), findsNWidgets(2));
@@ -131,20 +131,25 @@ void main() {
});
await _pump(tester);
expect(find.byType(ChatResponsePending), findsOneWidget);
expect(find.text('1 tool'), findsOneWidget);
expect(find.textContaining('Thinking'), findsOneWidget);
expect(find.byType(ChatMessageView), findsNWidgets(2));
expect(
tester.getTopLeft(find.byType(ChatResponsePending)).dy,
lessThan(tester.getTopLeft(find.text('1 tool')).dy),
find.descendant(
of: find.byKey(const Key('chat-turn-activity')),
matching: find.byType(ChatResponsePending),
),
findsOneWidget,
);
gateway.emitEvent(chatTextFrame('Here is the answer.'));
await _pump(tester);
expect(find.byType(ChatResponsePending), findsNothing);
expect(find.byType(ChatResponsePending), findsOneWidget);
expect(find.text('Here is the answer.'), findsOneWidget);
expect(find.text('1 tool'), findsOneWidget);
expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget);
gateway.emitEvent(chatStepFrame('ended'));
await tester.pumpAndSettle();
expect(find.byType(ChatResponsePending), findsNothing);
expect(find.text('Used 1 tool'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
},
);
@@ -168,30 +168,40 @@ void main() {
);
await tester.pumpAndSettle();
// The turn's reasoning is one footer chip below its answer; it counts
// the steps of every message folded into the turn.
expect(find.text('Reasoning · 2 steps'), findsOneWidget);
// The folded turn has one stable activity control, not one chip per
// category. Its summary stays generic when only reasoning is known.
expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget);
expect(find.text('Reasoning'), findsOneWidget);
await tester.tap(find.text('Load older'));
await tester.pumpAndSettle();
expect(find.text('Reasoning · 4 steps'), findsOneWidget);
await tester.tap(find.text('Reasoning · 4 steps'));
expect(find.text('Reasoning'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-turn-activity')));
await tester.pumpAndSettle();
for (var index = 1; index <= 4; index++) {
final disclosure = find.text('Reasoning $index');
if (tester.any(disclosure)) {
await tester.tap(disclosure);
await tester.pumpAndSettle();
}
}
for (final body in [
'NEWEST folded reasoning body.',
'OLDEST folded reasoning body.',
]) {
expect(
find.descendant(
of: find.byKey(const Key('chat-reasoning-sheet')),
of: cupertino
? find.byType(CupertinoAlertDialog)
: find.byType(AlertDialog),
matching: find.text(body),
),
findsOneWidget,
reason: body,
);
}
await tester.tapAt(const Offset(10, 10));
await tester.tap(find.text('Done'));
await tester.pumpAndSettle();
expect(find.text('OLDEST folded reasoning body.'), findsNothing);
expect(
@@ -0,0 +1,40 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/ui/sessions/session_attention.dart';
void main() {
test('only final turn end clears working; a background shell cannot', () {
for (final status in ['started', 'streamed', 'running', 'streaming']) {
final effect = chatSessionFrameEffect({
'type': 'chat_event',
'chat_event': {
'session_id': 's',
'kind': 'step',
'step': {'status': status},
},
});
expect(effect!.running, isTrue);
expect(effect.attention, isFalse);
}
for (final kind in ['shell', 'compaction']) {
final effect = chatSessionFrameEffect({
'type': 'chat_event',
'chat_event': {
'session_id': 's',
'kind': kind,
kind: {'status': kind == 'shell' ? 'exited' : 'completed'},
},
});
expect(effect!.running, isNull);
expect(effect.attention, isFalse);
}
final intermediate = chatSessionFrameEffect({
'type': 'chat_event',
'chat_event': {
'session_id': 's',
'kind': 'step',
'step': {'status': 'ended', 'intermediate': true},
},
});
expect(intermediate!.running, isNull);
});
}
@@ -124,39 +124,31 @@ void main() {
expect(find.textContaining('"payload": 7'), findsNothing);
expect(find.text('plain future text'), findsOneWidget);
// The answer keeps its own order; the footer chips sit below it.
// Answer content stays ordered, while reasoning and tools share one
// stable activity control before the transcript body.
double top(String text) => tester.getTopLeft(find.text(text)).dy;
expect(top('First answer'), lessThan(top('Second answer')));
expect(
top('Second answer'),
lessThan(top('Unrecognised part: future_part')),
);
expect(top('Unrecognised part: future_part'), lessThan(top('1 tool')));
expect(top('Unrecognised part: future_part'), lessThan(top('Reasoning')));
final activity = find.byKey(const Key('chat-turn-activity'));
expect(activity, findsOneWidget);
expect(find.text('Ran 1 command'), findsOneWidget);
expect(top('Ran 1 command'), lessThan(top('First answer')));
// Reasoning is a chip like the tools chip: it opens a native sheet.
await tester.ensureVisible(find.text('Reasoning'));
// The combined activity control opens the recorded reasoning and tool.
await tester.ensureVisible(activity);
await tester.pumpAndSettle();
await tester.tap(find.text('Reasoning'));
await tester.tap(activity);
await tester.pumpAndSettle();
expect(
find.descendant(
of: find.byKey(const Key('chat-reasoning-sheet')),
matching: find.text('private reasoning'),
),
findsOneWidget,
);
await tester.tapAt(const Offset(10, 10));
await tester.tap(find.text('Reasoning 1'));
await tester.pumpAndSettle();
expect(find.text('private reasoning'), findsNothing);
// The chip opens the calls; a call opens to its formatted input.
await tester.ensureVisible(find.text('1 tool'));
await tester.tap(find.text('1 tool'));
expect(find.text('private reasoning'), findsOneWidget);
final tool = find.textContaining('shell · ls');
await tester.ensureVisible(tool);
await tester.tap(tool);
await tester.pumpAndSettle();
await tester.tap(find.text('shell · ls'));
await tester.pumpAndSettle();
expect(find.text('INPUT'), findsOneWidget);
expect(find.textContaining('"command": "ls"'), findsOneWidget);
await tester.tapAt(const Offset(10, 10));
await tester.pumpAndSettle();
@@ -170,7 +162,7 @@ void main() {
for (final cupertino in [false, true]) {
testWidgets(
'each message keeps its reasoning beside its own tools ($cupertino)',
'each message keeps its combined activity with its own turn ($cupertino)',
(tester) async {
_phone(tester);
final first = _assistant([
@@ -209,40 +201,35 @@ void main() {
);
await tester.pumpAndSettle();
for (final (key, count) in [
('message-first', '1 tool'),
('message-second', '2 tools'),
('message-first', 'Used 1 tool'),
('message-second', 'Used 2 tools'),
]) {
final message = find.byKey(Key(key));
final reasoning = find.descendant(
final activity = find.descendant(
of: message,
matching: find.text('Reasoning'),
);
final tools = find.descendant(
of: message,
matching: find.text(count),
matching: find.byKey(const Key('chat-turn-activity')),
);
expect(activity, findsOneWidget);
expect(
tester.getRect(reasoning).right,
lessThan(tester.getRect(tools).left),
);
expect(
tester.getRect(reasoning).center.dy,
closeTo(tester.getRect(tools).center.dy, 2),
find.descendant(of: activity, matching: find.text(count)),
findsOneWidget,
);
}
await tester.tap(
find.descendant(
of: find.byKey(const Key('message-first')),
matching: find.text('Reasoning'),
matching: find.byKey(const Key('chat-turn-activity')),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Reasoning 1'));
await tester.pumpAndSettle();
expect(find.text('First reasoning'), findsOneWidget);
expect(find.text('Second reasoning'), findsNothing);
},
);
testWidgets('reasoning sits immediately left of the tools count '
testWidgets('reasoning and tools are in one activity control '
'(${cupertino ? 'cupertino' : 'material'})', (tester) async {
// The test font draws every glyph as a full square, so the chips need
// more room than real text does on a phone.
@@ -266,29 +253,27 @@ void main() {
);
await tester.pumpAndSettle();
final reasoning = tester.getRect(find.text('Reasoning · 2 steps'));
final tools = tester.getRect(find.text('1 tool'));
final activity = find.byKey(const Key('chat-turn-activity'));
expect(activity, findsOneWidget);
expect(
reasoning.top,
greaterThan(tester.getRect(find.text('The answer')).bottom),
tester.getTopLeft(activity).dy,
lessThan(tester.getRect(find.text('The answer')).top),
);
expect(reasoning.center.dy, closeTo(tools.center.dy, 2));
expect(reasoning.right, lessThan(tools.left));
expect(find.text('Ran 1 command'), findsOneWidget);
// The sheet lists every recorded step, in order.
await tester.tap(find.text('Reasoning · 2 steps'));
await tester.tap(activity);
await tester.pumpAndSettle();
final sheet = find.byKey(const Key('chat-reasoning-sheet'));
Finder inSheet(String text) =>
find.descendant(of: sheet, matching: find.text(text));
expect(inSheet('first thought'), findsOneWidget);
expect(inSheet('second thought'), findsOneWidget);
expect(
tester.getTopLeft(inSheet('first thought')).dy,
lessThan(tester.getTopLeft(inSheet('second thought')).dy),
);
expect(inSheet('STEP 1'), findsOneWidget);
expect(inSheet('STEP 2'), findsOneWidget);
expect(find.text('Reasoning 1'), findsOneWidget);
expect(find.text('Reasoning 2'), findsOneWidget);
await tester.tap(find.text('Reasoning 1'));
await tester.pumpAndSettle();
final secondStep = find.text('Reasoning 2');
await tester.ensureVisible(secondStep);
await tester.tap(secondStep);
await tester.pumpAndSettle();
expect(find.text('first thought'), findsOneWidget);
expect(find.text('second thought'), findsOneWidget);
});
}
@@ -369,7 +354,7 @@ void main() {
expect(find.byType(SelectableText), findsNothing);
});
testWidgets('Cupertino reasoning and tool chips open native popups', (
testWidgets('Cupertino combined activity opens a native dialog', (
tester,
) async {
final row = _assistant([
@@ -384,16 +369,13 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('thought'), findsNothing);
await tester.tap(find.text('Reasoning'));
await tester.tap(find.byKey(const Key('chat-turn-activity')));
await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.text('Activity details'), findsOneWidget);
await tester.tap(find.text('Reasoning 1'));
await tester.pumpAndSettle();
expect(find.byType(CupertinoPopupSurface), findsOneWidget);
expect(find.text('thought'), findsOneWidget);
await tester.tapAt(const Offset(10, 10));
await tester.pumpAndSettle();
expect(find.text('thought'), findsNothing);
await tester.tap(find.text('1 tool'));
await tester.pumpAndSettle();
await tester.tap(find.text('read · failed'));
await tester.pumpAndSettle();
expect(find.text('ERROR'), findsOneWidget);
@@ -5,14 +5,14 @@ import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart';
JsonMap _turn(List<JsonMap> parts, {String model = ''}) => transcriptRows([
JsonMap _turn(List<JsonMap> parts, {bool streaming = false}) => transcriptRows([
{
'id': 'a1',
'role': 'assistant',
if (model.isNotEmpty) 'model': model,
'parts': parts,
if (streaming) 'streaming': true,
},
]).single;
], running: streaming).single;
Widget _app(Widget body, bool cupertino) => cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: body))
@@ -21,91 +21,60 @@ Widget _app(Widget body, bool cupertino) => cupertino
home: Scaffold(body: body),
);
final _sheet = find.byKey(const Key('chat-reasoning-sheet'));
final _activity = find.byKey(const Key('chat-turn-activity'));
final _dialog = find.text('Activity details');
Finder _inSheet(String text) =>
find.descendant(of: _sheet, matching: find.text(text));
Finder _inDialog(String text) => find.descendant(
of: find.byType(CupertinoAlertDialog).evaluate().isNotEmpty
? find.byType(CupertinoAlertDialog)
: find.byType(AlertDialog),
matching: find.text(text),
);
void main() {
for (final cupertino in [false, true]) {
final host = cupertino ? 'Cupertino' : 'Material';
testWidgets('the footer reads reasoning, tools, permissions, model '
testWidgets('one stable activity control combines reasoning and tools '
'($host)', (tester) async {
tester.view.physicalSize = const Size(900, 600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final row = _turn([
{'type': 'reasoning', 'id': 'r1', 'text': 'thought'},
{
'type': 'tool',
'name': 'read',
'state': {
'status': 'completed',
'input': {'path': '/tmp/a'},
},
},
]);
await tester.pumpWidget(
_app(
ListView(
children: [
ChatMessageView(
row: _turn([
{'type': 'text', 'text': 'Answer'},
{'type': 'reasoning', 'text': 'thought'},
{
'type': 'tool',
'name': 'read',
'state': {'status': 'completed'},
},
], model: 'model-x'),
footer: const [Text('permissions')],
),
],
),
cupertino,
),
_app(ListView(children: [ChatMessageView(row: row)]), cupertino),
);
await tester.pumpAndSettle();
// The test font draws every glyph as a full square, so the row may wrap;
// each item then follows the previous one in reading order.
final rects = [
for (final text in ['Reasoning', '1 tool', 'permissions', 'model-x'])
tester.getRect(find.text(text)),
];
for (var index = 1; index < rects.length; index++) {
final before = rects[index - 1];
final after = rects[index];
final sameLine = (after.center.dy - before.center.dy).abs() < 3;
expect(
sameLine ? after.left > before.right : after.top >= before.bottom,
isTrue,
reason: 'footer item $index follows item ${index - 1}',
);
}
expect(_activity, findsOneWidget);
expect(find.byKey(const Key('chat-reasoning-chip')), findsNothing);
expect(find.byKey(const Key('chat-tool-chip')), findsNothing);
expect(find.text('Used 1 tool'), findsOneWidget);
expect(
(rects[1].center.dy - rects[0].center.dy).abs(),
lessThan(3),
reason: 'reasoning and tools share a line',
);
// Same native chip as the tools: an icon and a chevron, one button node.
final chip = find.byKey(const Key('chat-reasoning-chip'));
expect(
find.descendant(
of: chip,
matching: find.byIcon(
cupertino ? CupertinoIcons.lightbulb : Icons.lightbulb_outline,
),
),
find.bySemanticsLabel('Used 1 tool, expand for details'),
findsOneWidget,
);
expect(
find.descendant(
of: chip,
matching: find.byIcon(
cupertino ? CupertinoIcons.chevron_up : Icons.expand_less,
),
),
findsOneWidget,
);
final semantics = tester.getSemantics(
find.bySemanticsLabel('Reasoning, expand for details'),
);
expect(semantics.flagsCollection.isButton, isTrue);
if (cupertino) expect(find.byType(Material), findsNothing);
await tester.tap(_activity);
await tester.pumpAndSettle();
expect(_dialog, findsOneWidget);
expect(_inDialog('Reasoning 1'), findsOneWidget);
expect(_inDialog('thought'), findsNothing);
await tester.tap(_inDialog('Reasoning 1'));
await tester.pumpAndSettle();
expect(_inDialog('thought'), findsOneWidget);
expect(find.textContaining('read'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('an open sheet follows a rebuilt turn and outlives its row '
testWidgets('the activity dialog tracks rebuilt parts and closes with Done '
'($host)', (tester) async {
final row = ValueNotifier<JsonMap?>(
_turn([
@@ -117,7 +86,7 @@ void main() {
_app(
ValueListenableBuilder<JsonMap?>(
valueListenable: row,
builder: (context, value, _) => ListView(
builder: (_, value, _) => ListView(
children: [
if (value != null)
ChatMessageView(key: const Key('turn'), row: value),
@@ -128,30 +97,91 @@ void main() {
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Reasoning'));
await tester.tap(_activity);
await tester.pumpAndSettle();
expect(_inSheet('Reasoning'), findsOneWidget);
expect(_inSheet('first'), findsOneWidget);
expect(_inDialog('first'), findsNothing);
await tester.tap(_inDialog('Reasoning 1'));
await tester.pumpAndSettle();
expect(_inDialog('first'), findsOneWidget);
row.value = _turn([
{'type': 'reasoning', 'id': 'r1', 'text': 'first, longer'},
{'type': 'text', 'text': 'Answer'},
{'type': 'reasoning', 'id': 'r1', 'text': 'first updated'},
{'type': 'reasoning', 'id': 'r2', 'text': 'second'},
{
'type': 'tool',
'name': 'read',
'state': {'status': 'completed'},
},
]);
await tester.pumpAndSettle();
expect(_inSheet('Reasoning · 2 steps'), findsOneWidget);
expect(_inSheet('first, longer'), findsOneWidget);
expect(_inSheet('second'), findsOneWidget);
expect(_inDialog('first updated'), findsOneWidget);
expect(_inDialog('Reasoning 2'), findsOneWidget);
expect(_inDialog('read'), findsOneWidget);
// The row leaves the transcript while the sheet is open: the sheet keeps
// its last steps and closes cleanly.
final done = find.text('Done');
await tester.tap(done);
await tester.pumpAndSettle();
expect(_dialog, findsNothing);
await tester.tap(_activity);
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(_dialog, findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('a streaming turn keeps a generic activity control until tool '
'activity is recorded ($host)', (tester) async {
final row = _turn([
{'type': 'reasoning', 'id': 'r1', 'text': 'secret reasoning'},
], streaming: true);
await tester.pumpWidget(
_app(ListView(children: [ChatMessageView(row: row)]), cupertino),
);
await tester.pump(const Duration(milliseconds: 50));
expect(_activity, findsOneWidget);
expect(find.textContaining('Thinking'), findsOneWidget);
expect(find.text('secret reasoning'), findsNothing);
final activityElement = tester.element(_activity);
final height = tester.getSize(_activity).height;
await tester.pump(const Duration(seconds: 2));
expect(tester.element(_activity), same(activityElement));
expect(tester.getSize(_activity).height, height);
expect(tester.takeException(), isNull);
});
testWidgets('removing the owning turn closes its activity dialog ($host)', (
tester,
) async {
final row = ValueNotifier<JsonMap?>(
_turn([
{'type': 'reasoning', 'id': 'r1', 'text': 'owned detail'},
]),
);
addTearDown(row.dispose);
await tester.pumpWidget(
_app(
ValueListenableBuilder<JsonMap?>(
valueListenable: row,
builder: (_, value, _) => ListView(
children: [
if (value != null)
ChatMessageView(key: const Key('turn'), row: value),
],
),
),
cupertino,
),
);
await tester.pumpAndSettle();
await tester.tap(_activity);
await tester.pumpAndSettle();
expect(_dialog, findsOneWidget);
row.value = null;
await tester.pumpAndSettle();
expect(find.byKey(const Key('turn')), findsNothing);
expect(_inSheet('second'), findsOneWidget);
await tester.tapAt(const Offset(10, 10));
await tester.pumpAndSettle();
expect(_sheet, findsNothing);
expect(_dialog, findsNothing);
expect(tester.takeException(), isNull);
});
}
+55
View File
@@ -0,0 +1,55 @@
// Background-list attention is driven by content, not activity timestamps.
import assert from 'node:assert/strict';
import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
import { once } from 'node:events';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { startFixture } from './runs_probe_server.mjs';
import { launchChrome, waitForPort, waitForPage, connect } from './pipelines_probe_cdp_lib.mjs';
import { axNodes, enableSemantics, waitFor, capture, clickAt } from './pipelines_probe_cdp_input.mjs';
const output=resolve(process.argv[3]??'build/chat-attention-browser');
await mkdir(output,{recursive:true});
const fixture=await startFixture({root:resolve(process.argv[2]),chatMessages:[]});
const profile=await mkdtemp(join(tmpdir(),'chat-attention-'));
const chrome=launchChrome('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',profile,'about:blank');
const log={checks:[],captures:[]};let c;
const names=async()=>(await axNodes(c)).map(n=>n.name?.value??'');
const isNew=async()=>(await names()).some(n=>n.includes('Probe conversation')&&/\bNew\b/.test(n));
const working=async()=>(await names()).some(n=>n.includes('Chat is working'));
const emit=async body=>{assert.ok((await fetch(fixture.url+'/fixture/chat-event',{method:'POST',body:JSON.stringify(body)})).ok);};
try {
c=await connect((await waitForPage(await waitForPort(join(profile,'DevToolsActivePort')))).webSocketDebuggerUrl);
await c.send('Page.enable');
await c.send('Emulation.setDeviceMetricsOverride',{width:1280,height:900,deviceScaleFactor:1,mobile:false});
await c.send('Page.navigate',{url:fixture.url+'/chat'});
assert.ok(await waitFor(()=>c.evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),30000));
await enableSemantics(c);
assert.ok(await waitFor(async()=>(await names()).some(n=>n.includes('Probe conversation')),15000));
assert.ok(!await isNew());
await emit({kind:'step',step:{status:'running',turn_id:'attention'}});
assert.ok(await waitFor(working,10000));
await emit({kind:'reasoning',message_id:'attention-answer',part:{type:'reasoning',id:'r'},delta:'Background thinking is not unread.'});
await emit({kind:'shell',shell:{id:'background',status:'exited'}});
assert.ok(!await isNew());
assert.ok(await working(),'background shell exit cannot clear active turn');
await capture(c,output,log,'01-working-not-new');
await emit({kind:'step',step:{status:'ended',turn_id:'attention'}});
assert.ok(await waitFor(async()=>!await working(),10000));
assert.ok(!await isNew(),'completion without content is not unread');
log.checks.push('working indicator for activity-only events, no New on reasoning/shell/turn completion');
await emit({kind:'step',step:{status:'running',turn_id:'attention-two'}});
await emit({kind:'text',message_id:'attention-answer',part:{type:'text',id:'answer'},delta:'A new assistant message to read.'});
assert.ok(await waitFor(isNew,10000));
assert.ok(!await working(),'unread content takes precedence over loading');
await capture(c,output,log,'02-new-message');
const row=(await axNodes(c)).find(n=>n.name?.value?.startsWith('Claude harness')&&n.name.value.includes('Probe conversation')&&n.backendDOMNodeId);
assert.ok(row);
const {model}=await c.send('DOM.getBoxModel',{backendNodeId:row.backendDOMNodeId});
await clickAt(c,model.content[0]+30,model.content[1]+10);
assert.ok(await waitFor(async()=>!await isNew(),10000));
await capture(c,output,log,'03-opened-clears-new');
log.checks.push('actual unread message shows New even while running; opening acknowledges it');
console.log(JSON.stringify(log,null,2));
} catch(error){if(c){await capture(c,output,log,'failure');await writeFile(join(output,'failure-ax.json'),JSON.stringify(await axNodes(c),null,2));}throw error;}
finally{await writeFile(join(output,'result.json'),JSON.stringify(log,null,2));c?.close();const exited=once(chrome,'exit');chrome.kill();await exited;await fixture.close();}
+105
View File
@@ -0,0 +1,105 @@
// Production chat turn, driven only by isolated loopback tool/reasoning frames.
import assert from 'node:assert/strict';
import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
import { once } from 'node:events';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { startFixture } from './runs_probe_server.mjs';
import { launchChrome, waitForPort, waitForPage, connect, sleep } from './pipelines_probe_cdp_lib.mjs';
import { axNodes, enableSemantics, waitFor, capture, click, clickAt } from './pipelines_probe_cdp_input.mjs';
const platform = process.env.PROBE_PLATFORM ?? 'material';
const width = Number(process.env.PROBE_WIDTH ?? 1280);
const output = resolve(process.argv[3] ?? `build/stable-activity-${platform}`);
await mkdir(output, { recursive: true });
const fixture = await startFixture({ root: resolve(process.argv[2]), chatMessages: [] });
const profile = await mkdtemp(join(tmpdir(), 'stable-activity-'));
const chrome = launchChrome('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', profile, 'about:blank');
const log = { platform, width, checks: [], captures: [] };
let c;
const nodes = () => axNodes(c);
const names = async () => (await nodes()).flatMap(n => [n.name?.value ?? '', n.value?.value ?? '']);
const emit = async event => {
const response = await fetch(fixture.url + '/fixture/chat-event', { method: 'POST', body: JSON.stringify(event) });
assert.ok(response.ok);
};
async function status(title) {
return waitFor(async () => (await nodes()).find(n => n.role?.value === 'button' &&
n.name?.value?.includes(title) && n.backendDOMNodeId), 10000);
}
async function box(node) {
assert.ok(node, 'activity disclosure is accessible');
const { model } = await c.send('DOM.getBoxModel', { backendNodeId: node.backendDOMNodeId });
const [x,y,,,right,bottom] = model.content;
return { x, y, width:right-x, height:bottom-y };
}
async function tap(node) {
const b = await box(node); await clickAt(c, b.x+b.width/2, b.y+b.height/2);
}
const call = (id, description, state = 'running') => ({ kind:'tool', message_id:'fixture-answer', part:{
type:'tool', id, name:'bash', time:{created:Date.now()-9000, ran:Date.now()-9000,
...(state === 'completed' ? {completed:Date.now()} : {})},
state:{status:state, input:{description, command:'echo isolated-fixture'},
...(state === 'completed' ? {content:[{type:'text',text:'Fixture command output '+id}]} : {})},
} });
try {
c = await connect((await waitForPage(await waitForPort(join(profile,'DevToolsActivePort')))).webSocketDebuggerUrl);
await c.send('Page.enable');
if (platform === 'material') await c.send('Emulation.setUserAgentOverride', {
userAgent:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36',platform:'Win32',
});
else await c.send('Emulation.setUserAgentOverride', {
userAgent:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36',platform:'MacIntel',
});
await c.send('Emulation.setDeviceMetricsOverride',{width,height:900,deviceScaleFactor:1,mobile:false});
await c.send('Page.navigate',{url:fixture.url+'/chat/ses_probechat'});
assert.ok(await waitFor(()=>c.evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"),30000));
await enableSemantics(c);
const composer = await waitFor(async()=>(await nodes()).find(n=>n.role?.value==='textbox'&&n.backendDOMNodeId),15000);
await tap(composer);
await c.send('Input.insertText',{text:'Run the isolated activity fixture.'});
await click(c,'Send');
await emit({kind:'step',step:{status:'running',turn_id:'stable-turn'}});
await emit({kind:'reasoning',message_id:'fixture-answer',part:{type:'reasoning',id:'r'},delta:'Private fixture reasoning retained in details.'});
await emit(call('one','Checking fixture configuration'));
const first = await status('Checking fixture configuration');
const before = await box(first);
assert.ok(!(await names()).some(n=>n==='Private fixture reasoning retained in details.'),'reasoning hidden until disclosure');
await capture(c,output,log,'01-one-line-running');
await sleep(1200);
const timed = await status('Checking fixture configuration');
assert.ok(/\d+s/.test(timed.name.value),'elapsed seconds visible');
assert.equal((await box(timed)).height,before.height,'timer does not resize the row');
await emit(call('one','Checking fixture configuration','completed'));
await emit(call('two','Running fixture verification'));
const second = await status('Running fixture verification');
const after = await box(second);
assert.equal(after.height,before.height,'new actions retain one-row height');
assert.equal(after.y,before.y,'tool transitions do not move the activity row');
log.checks.push('one stable line with recorded current action and localized elapsed clock; reasoning hidden');
await tap(second);
assert.ok(await waitFor(async()=>(await names()).some(n=>n.includes('Checking fixture configuration')),10000));
await capture(c,output,log,'02-live-details');
await emit(call('two','Running fixture verification','completed'));
await emit(call('three','Checking fixture dependencies'));
assert.ok(await waitFor(async()=>(await names()).some(n=>n.includes('Checking fixture dependencies')),10000),'open details update live');
await c.send('Input.dispatchKeyEvent',{type:'keyDown',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
await c.send('Input.dispatchKeyEvent',{type:'keyUp',key:'Escape',code:'Escape',windowsVirtualKeyCode:27});
await sleep(300);
log.checks.push('disclosure opens recorded details and follows new tools while open');
await emit(call('three','Checking fixture dependencies','completed'));
await emit(call('four','Final fixture command','completed'));
await emit({kind:'text',message_id:'fixture-answer',part:{type:'text',id:'final'},delta:'The verified fixture answer stays readable.'});
await emit({kind:'step',step:{status:'ended',turn_id:'stable-turn'}});
assert.ok(await status('Ran 4 commands'),'finished compact command count');
assert.ok((await names()).includes('The verified fixture answer stays readable.'));
await capture(c,output,log,'03-finished-summary');
log.checks.push('finished turn stops loading and retains Ran 4 commands plus its answer');
console.log(JSON.stringify(log,null,2));
} catch(error) {
if(c){await capture(c,output,log,'failure');await writeFile(join(output,'failure-ax.json'),JSON.stringify(await nodes(),null,2));}
throw error;
} finally {
await writeFile(join(output,'result.json'),JSON.stringify(log,null,2));
c?.close();const exited=once(chrome,'exit');chrome.kill();await exited;await fixture.close();
}