Merge branch 'chat-reasoning-chip'

This commit is contained in:
2026-10-24 18:30:20 +01:00
11 changed files with 646 additions and 165 deletions
@@ -7,7 +7,7 @@ import '../../../../core/api_gateway.dart';
import '../sessions/chat_adaptive.dart'; import '../sessions/chat_adaptive.dart';
import '../../domain/chat_tool_calls.dart'; import '../../domain/chat_tool_calls.dart';
import 'chat_tool_calls_view.dart'; import 'chat_tool_calls_view.dart';
import 'chat_reasoning_disclosure.dart'; import 'chat_reasoning_chip.dart';
import 'native_disclosure.dart'; import 'native_disclosure.dart';
/// Builds an assistant text part; the default keeps the server's text exactly. /// Builds an assistant text part; the default keeps the server's text exactly.
@@ -26,8 +26,8 @@ class ChatMessageView extends StatelessWidget {
final JsonMap row; final JsonMap row;
final ChatMessageTextBuilder? textBuilder; final ChatMessageTextBuilder? textBuilder;
/// More of an agent turn's summary chips, after its tools chip (the turn's /// More of an agent turn's summary chips, after its reasoning and tools chips
/// settled permission requests). /// (the turn's settled permission requests).
final List<Widget> footer; final List<Widget> footer;
@override @override
@@ -198,7 +198,9 @@ class ChatMessageView extends StatelessWidget {
return widgets; return widgets;
} }
/// Reasoning stays in the transcript so an open body follows live deltas. /// 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.
Widget _agentTurn(BuildContext context, List<Widget> content, Widget bubble) { Widget _agentTurn(BuildContext context, List<Widget> content, Widget bubble) {
final parts = _partsOf(row); final parts = _partsOf(row);
final reasoning = [ final reasoning = [
@@ -213,6 +215,12 @@ class ChatMessageView extends StatelessWidget {
]; ];
final model = '${row['model'] ?? ''}'.trim(); final model = '${row['model'] ?? ''}'.trim();
final footer = <Widget>[ 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), if (tools.isNotEmpty) ChatToolCallsChip(calls: tools),
...this.footer, ...this.footer,
if (model.isNotEmpty) if (model.isNotEmpty)
@@ -230,15 +238,9 @@ class ChatMessageView extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (content.isNotEmpty) bubble, if (content.isNotEmpty) bubble,
if (reasoning.isNotEmpty) if (footer.isNotEmpty)
ChatReasoningDisclosure(
key: const Key('chat-turn-reasoning'),
steps: reasoning,
streaming: row['streaming'] == true,
trailing: footer,
),
if (reasoning.isEmpty && footer.isNotEmpty)
Wrap( Wrap(
key: const Key('chat-message-footer'),
spacing: 8, spacing: 8,
crossAxisAlignment: WrapCrossAlignment.center, crossAxisAlignment: WrapCrossAlignment.center,
children: footer, children: footer,
@@ -337,6 +339,21 @@ class ChatMessageView extends StatelessWidget {
SelectableText(const JsonEncoder.withIndent(' ').convert(part)); 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) { List<JsonMap> _partsOf(Map<dynamic, dynamic> source) {
final parts = source['parts']; final parts = source['parts'];
if (parts is! List) return const []; if (parts is! List) return const [];
@@ -0,0 +1,195 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_turn_chip.dart';
/// `Reasoning` / `Reasoning · N steps`.
String chatReasoningLabel(int steps) =>
steps == 1 ? 'Reasoning' : 'Reasoning · $steps steps';
/// A turn's reasoning as the first chip of its footer, the same pattern as its
/// tools and permissions: it spins while the turn streams and opens a native
/// sheet with every step. Only reasoning the backend supplied is shown.
///
/// The open sheet follows live deltas: this state owns the steps the sheet
/// listens to and updates them on every rebuild of the turn.
class ChatReasoningChip extends StatefulWidget {
const ChatReasoningChip({
super.key,
required this.steps,
required this.streaming,
});
final List<String> steps;
final bool streaming;
@override
State<ChatReasoningChip> createState() => _ChatReasoningChipState();
}
typedef _Reasoning = ({List<String> steps, bool streaming});
class _ChatReasoningChipState extends State<ChatReasoningChip> {
late final _live = _LiveReasoning((
steps: widget.steps,
streaming: widget.streaming,
));
@override
void didUpdateWidget(ChatReasoningChip oldWidget) {
super.didUpdateWidget(oldWidget);
final current = _live.value;
if (widget.streaming == current.streaming &&
listEquals(widget.steps, current.steps)) {
return;
}
// The sheet lives in another route, outside this subtree, so it may only
// be marked dirty once this build is over; the next frame shows the delta.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_live.value = (steps: widget.steps, streaming: widget.streaming);
});
}
@override
void dispose() {
_live.release();
super.dispose();
}
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final label = chatReasoningLabel(widget.steps.length);
return ChatTurnChip(
chipKey: const Key('chat-reasoning-chip'),
leading: widget.streaming
? _spinner(cupertino)
: Icon(
cupertino ? CupertinoIcons.lightbulb : Icons.lightbulb_outline,
size: 14,
color: color,
),
label: label,
color: color,
semanticsLabel: '$label, expand for details',
sheet: ValueListenableBuilder<_Reasoning>(
valueListenable: _live,
builder: (context, reasoning, _) => _ReasoningSheet(
steps: reasoning.steps,
streaming: reasoning.streaming,
),
),
);
}
}
Widget _spinner(bool cupertino) => cupertino
? const CupertinoActivityIndicator(radius: 7)
: const SizedBox.square(
dimension: 12,
child: CircularProgressIndicator(strokeWidth: 2),
);
/// The steps an open sheet listens to. The turn can leave the tree while its
/// sheet is still open (its row scrolled away or replaced), so the notifier is
/// disposed only once its owner released it and no sheet listens any more.
class _LiveReasoning extends ValueNotifier<_Reasoning> {
_LiveReasoning(super.value);
bool _released = false;
bool _disposed = false;
void release() {
_released = true;
_disposeIfUnused();
}
@override
void removeListener(VoidCallback listener) {
super.removeListener(listener);
_disposeIfUnused();
}
void _disposeIfUnused() {
if (!_released || _disposed || hasListeners) return;
_disposed = true;
dispose();
}
}
class _ReasoningSheet extends StatelessWidget {
const _ReasoningSheet({required this.steps, required this.streaming});
final List<String> steps;
final bool streaming;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
final secondary = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
return DefaultTextStyle.merge(
style: style,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: ListView(
key: const Key('chat-reasoning-sheet'),
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
Flexible(
child: Text(
chatReasoningLabel(steps.length),
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
if (streaming) ...[
const SizedBox(width: 8),
_spinner(cupertino),
],
],
),
),
for (final (index, step) in steps.indexed)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (steps.length > 1)
Text(
'STEP ${index + 1}',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: secondary,
),
),
SelectableText(step),
],
),
),
],
),
),
);
}
}
@@ -1,101 +0,0 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../sessions/chat_adaptive.dart';
/// Only reasoning actually supplied by the backend. Keeping its body in the
/// transcript (rather than a modal snapshot) lets an open disclosure rebuild
/// with every delta, even while answer text is also arriving.
class ChatReasoningDisclosure extends StatefulWidget {
const ChatReasoningDisclosure({
super.key,
required this.steps,
required this.streaming,
this.trailing = const [],
});
final List<String> steps;
final bool streaming;
final List<Widget> trailing;
@override
State<ChatReasoningDisclosure> createState() =>
_ChatReasoningDisclosureState();
}
class _ChatReasoningDisclosureState extends State<ChatReasoningDisclosure> {
late bool _expanded = widget.streaming;
void _toggle() => setState(() => _expanded = !_expanded);
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final label = widget.steps.length == 1
? 'Reasoning'
: 'Reasoning · ${widget.steps.length} steps';
final control = Semantics(
key: const Key('chat-reasoning-toggle'),
button: true,
expanded: _expanded,
label: label,
onTap: _toggle,
excludeSemantics: true,
child: cupertino
? CupertinoButton(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
minimumSize: Size.zero,
onPressed: _toggle,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: Text(label)),
Icon(
_expanded
? CupertinoIcons.chevron_up
: CupertinoIcons.chevron_down,
size: 14,
),
],
),
)
: TextButton(
onPressed: _toggle,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: Text(label)),
Icon(
_expanded ? Icons.expand_less : Icons.expand_more,
size: 14,
),
],
),
),
);
return DefaultTextStyle.merge(
style: cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium,
child: Column(
key: const Key('chat-reasoning-disclosure'),
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Wrap(
key: const Key('chat-message-footer'),
spacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [control, ...widget.trailing],
),
if (_expanded)
for (final (index, step) in widget.steps.indexed)
Padding(
padding: EdgeInsets.only(top: index == 0 ? 0 : 12, bottom: 8),
child: SelectableText(step),
),
],
),
);
}
}
+25
View File
@@ -0,0 +1,25 @@
# Chat reasoning chip
User request: reasoning expanded differently from tools; make it the same as tools.
- Reasoning is now `ChatReasoningChip` (`lib/features/chat/ui/transcript/chat_reasoning_chip.dart`),
built on the shared `ChatTurnChip`: lightbulb icon, `Reasoning` / `Reasoning · N steps`,
chevron, accessible name `... , expand for details`. It opens the same native sheet
(Material bottom sheet / Cupertino popup) listing every step as plain selectable text
(`STEP n` headings when there are several), as the old inline disclosure did (no markdown).
- Footer order: reasoning, tools, permissions, model label (`chat-message-footer` Wrap).
The inline disclosure (`chat_reasoning_disclosure.dart`) is removed; this supersedes the
inline layout in `per-message-reasoning-footer.md`.
- The chip spins while the turn streams and reasoning is its newest part; once an answer
or tool call follows, it shows its icon (a running tool spins its own chip).
- An open sheet follows live deltas: the chip state owns a notifier the sheet listens to,
updated after each rebuild of the turn (one frame later, since the sheet is another route).
If the row leaves the tree, the open sheet keeps its last steps and closes cleanly.
- Behaviour change: a newly streaming reply no longer shows its reasoning inline without a
tap; the operator opens the chip (a modal must not pop up by itself).
Evidence: full `flutter test` passes (1,865), `flutter analyze` clean. Browser probe
`tool/chat_message_probe.{dart,mjs}` now also has a live turn whose step grows every 0.5 s;
both hosts passed, including OCR that the open sheet's tick advanced (Material 36 -> 42,
Cupertino 38 -> 45). Captures: `build/reasoning-chip-{material,cupertino}/`.
No device verification.
@@ -112,7 +112,7 @@ void main() {
}); });
for (final cupertino in [false, true]) { for (final cupertino in [false, true]) {
testWidgets('reasoning first arriving after a queued follow-up opens live ' testWidgets('reasoning first arriving after a queued follow-up stays live '
'($cupertino)', (tester) async { '($cupertino)', (tester) async {
gateway.prompt = (_, _) async => {'chat_queued': true}; gateway.prompt = (_, _) async => {'chat_queued': true};
await tester.pumpWidget( await tester.pumpWidget(
@@ -145,7 +145,17 @@ void main() {
'part': {'id': 'live-reasoning-0', 'type': 'reasoning'}, 'part': {'id': 'live-reasoning-0', 'type': 'reasoning'},
'delta': 'Provided reasoning after the follow-up', 'delta': 'Provided reasoning after the follow-up',
}); });
await tester.pumpAndSettle(); // The reasoning chip spins while its step is the newest part, so the
// frames are pumped rather than settled.
Future<void> frames() async {
for (var frame = 0; frame < 8; frame++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
await frames();
await tester.tap(find.text('Reasoning'));
await frames();
expect( expect(
find.text('Provided reasoning after the follow-up'), find.text('Provided reasoning after the follow-up'),
findsOneWidget, findsOneWidget,
@@ -24,9 +24,31 @@ Widget _host(Widget child, bool cupertino) => cupertino
home: Scaffold(body: child), 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
/// entrance or exit instead.
Future<void> _settle(WidgetTester tester) async {
for (var frame = 0; frame < 8; frame++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
final _sheet = find.byKey(const Key('chat-reasoning-sheet'));
Finder _inSheet(String text) =>
find.descendant(of: _sheet, matching: find.text(text));
Future<void> _dismiss(WidgetTester tester) async {
await tester.tapAt(const Offset(10, 10));
await _settle(tester);
expect(_sheet, findsNothing);
}
void main() { void main() {
for (final cupertino in [false, true]) { for (final cupertino in [false, true]) {
testWidgets('reasoning arriving after text opens live ($cupertino)', ( final host = cupertino ? 'Cupertino' : 'Material';
testWidgets('reasoning arriving after text is a spinning chip ($host)', (
tester, tester,
) async { ) async {
final gateway = FakeChatGateway(); final gateway = FakeChatGateway();
@@ -42,14 +64,39 @@ void main() {
gateway.emitEvent(_delta('text', 'Answer first')); gateway.emitEvent(_delta('text', 'Answer first'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Reasoning'), findsNothing); expect(find.text('Reasoning'), findsNothing);
gateway.emitEvent(_delta('reasoning', 'Only supplied reasoning')); gateway.emitEvent(_delta('reasoning', 'Only supplied reasoning'));
await tester.pumpAndSettle(); await _settle(tester);
expect(find.text('Only supplied reasoning'), findsOneWidget); // 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); 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,
);
await tester.tap(find.text('Reasoning'));
await _settle(tester);
expect(_inSheet('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);
}); });
testWidgets('live reasoning survives text, collapse, paging and resync ' testWidgets('an open reasoning sheet follows live deltas, paging and '
'(${cupertino ? 'Cupertino' : 'Material'})', (tester) async { 'resync ($host)', (tester) async {
final gateway = FakeChatGateway(); final gateway = FakeChatGateway();
addTearDown(gateway.close); addTearDown(gateway.close);
gateway.history = (_) async => gateway.history = (_) async =>
@@ -63,34 +110,41 @@ void main() {
await tester.pumpAndSettle(); await tester.pumpAndSettle();
gateway.emitEvent(_delta('reasoning', 'Provided thought')); gateway.emitEvent(_delta('reasoning', 'Provided thought'));
await tester.pumpAndSettle(); await _settle(tester);
// No opening tap required for a newly streaming reply.
expect(find.text('Provided thought'), findsOneWidget);
final rowElement = tester.element(find.byType(ChatMessageView)); final rowElement = tester.element(find.byType(ChatMessageView));
await tester.tap(find.text('Reasoning'));
await _settle(tester);
expect(_inSheet('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('text', 'Answer'));
gateway.emitEvent(_delta('reasoning', ' continues')); gateway.emitEvent(_delta('reasoning', ' continues'));
await tester.pumpAndSettle(); await _settle(tester);
expect(find.text('Provided thought continues'), findsOneWidget); expect(_inSheet('Provided thought continues'), findsOneWidget);
expect(find.text('Answer'), findsOneWidget); expect(find.text('Answer'), findsOneWidget);
expect(tester.element(find.byType(ChatMessageView)), same(rowElement)); expect(tester.element(find.byType(ChatMessageView)), same(rowElement));
gateway.emitEvent(_delta('reasoning', ' live'));
await _settle(tester);
expect(_inSheet('Provided thought continues live'), findsOneWidget);
await _dismiss(tester);
await tester.tap(find.text('Reasoning')); // A closed sheet draws nothing; reopening shows the newest text.
await tester.pumpAndSettle(); gateway.emitEvent(_delta('reasoning', ' while closed'));
gateway.emitEvent(_delta('reasoning', ' while collapsed'));
gateway.emitEvent(_delta('text', ' continues')); gateway.emitEvent(_delta('text', ' continues'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.textContaining('while collapsed'), findsNothing); expect(find.textContaining('while closed'), findsNothing);
expect(find.text('Answer continues'), findsOneWidget); expect(find.text('Answer continues'), findsOneWidget);
await tester.tap(find.text('Reasoning')); await tester.tap(find.text('Reasoning'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect( expect(
find.text('Provided thought continues while collapsed'), _inSheet('Provided thought continues live while closed'),
findsOneWidget, findsOneWidget,
); );
await _dismiss(tester);
// Prepending another assistant message folds into the same turn without // Prepending another assistant message folds into the same turn without
// replacing the row or closing the already-open reasoning disclosure. // replacing the row; the chip counts both steps.
gateway.history = (_) async => chatPage([ gateway.history = (_) async => chatPage([
chatMessage( chatMessage(
'older', 'older',
@@ -106,20 +160,18 @@ void main() {
]); ]);
await tester.tap(find.text('Load older')); await tester.tap(find.text('Load older'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Older provided thought'), findsOneWidget); expect(find.text('Reasoning · 2 steps'), findsOneWidget);
expect(
find.text('Provided thought continues while collapsed'),
findsOneWidget,
);
expect(tester.element(find.byType(ChatMessageView)), same(rowElement)); expect(tester.element(find.byType(ChatMessageView)), same(rowElement));
await tester.tap(find.text('Reasoning · 2 steps'));
gateway.emitEvent(chatStepFrame('ended'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(_inSheet('Older provided thought'), findsOneWidget);
expect( expect(
find.text('Provided thought continues while collapsed'), _inSheet('Provided thought continues live while closed'),
findsOneWidget, findsOneWidget,
); );
// A resync replaces the stored turn under the open sheet.
gateway.emitEvent(chatStepFrame('ended'));
gateway.history = (_) async => chatPage([ gateway.history = (_) async => chatPage([
chatMessage( chatMessage(
'a', 'a',
@@ -136,16 +188,14 @@ void main() {
]); ]);
gateway.emitEvent({'session_id': 's', 'kind': 'resync'}); gateway.emitEvent({'session_id': 's', 'kind': 'resync'});
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Stored provided thought'), findsOneWidget); expect(_inSheet('Stored provided thought'), findsOneWidget);
expect(find.textContaining('while closed'), findsNothing);
expect(find.text('Stored answer'), findsOneWidget); expect(find.text('Stored answer'), findsOneWidget);
expect(find.textContaining('while collapsed'), findsNothing);
expect(tester.element(find.byType(ChatMessageView)), same(rowElement)); expect(tester.element(find.byType(ChatMessageView)), same(rowElement));
await tester.tap(find.text('Reasoning')); await _dismiss(tester);
await tester.pumpAndSettle();
expect(find.text('Stored provided thought'), findsNothing);
// A fresh history visit starts collapsed; missing reasoning is never // A fresh history visit draws the chip closed; missing reasoning is
// fabricated. Cupertino keeps only its native controls. // never fabricated. Cupertino keeps only its native controls.
await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpWidget( await tester.pumpWidget(
_host( _host(
@@ -157,7 +207,7 @@ void main() {
expect(find.text('Stored provided thought'), findsNothing); expect(find.text('Stored provided thought'), findsNothing);
await tester.tap(find.text('Reasoning')); await tester.tap(find.text('Reasoning'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Stored provided thought'), findsOneWidget); expect(_inSheet('Stored provided thought'), findsOneWidget);
if (cupertino) expect(find.byType(Material), findsNothing); if (cupertino) expect(find.byType(Material), findsNothing);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
}); });
@@ -168,8 +168,8 @@ void main() {
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
// The turn's reasoning is one disclosure below its answer; it counts the // The turn's reasoning is one footer chip below its answer; it counts
// steps of every message folded into the turn. // the steps of every message folded into the turn.
expect(find.text('Reasoning · 2 steps'), findsOneWidget); expect(find.text('Reasoning · 2 steps'), findsOneWidget);
await tester.tap(find.text('Load older')); await tester.tap(find.text('Load older'));
@@ -182,10 +182,18 @@ void main() {
'NEWEST folded reasoning body.', 'NEWEST folded reasoning body.',
'OLDEST folded reasoning body.', 'OLDEST folded reasoning body.',
]) { ]) {
expect(find.text(body), findsOneWidget, reason: body); expect(
find.descendant(
of: find.byKey(const Key('chat-reasoning-sheet')),
matching: find.text(body),
),
findsOneWidget,
reason: body,
);
} }
await tester.tap(find.text('Reasoning · 4 steps')); await tester.tapAt(const Offset(10, 10));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('OLDEST folded reasoning body.'), findsNothing);
expect( expect(
find.text('Load older'), find.text('Load older'),
keepsControl ? findsOneWidget : findsNothing, keepsControl ? findsOneWidget : findsNothing,
@@ -124,7 +124,7 @@ void main() {
expect(find.textContaining('"payload": 7'), findsNothing); expect(find.textContaining('"payload": 7'), findsNothing);
expect(find.text('plain future text'), findsOneWidget); expect(find.text('plain future text'), findsOneWidget);
// The answer keeps its own order; reasoning expands inline below it. // The answer keeps its own order; the footer chips sit below it.
double top(String text) => tester.getTopLeft(find.text(text)).dy; double top(String text) => tester.getTopLeft(find.text(text)).dy;
expect(top('First answer'), lessThan(top('Second answer'))); expect(top('First answer'), lessThan(top('Second answer')));
expect( expect(
@@ -134,13 +134,21 @@ void main() {
expect(top('Unrecognised part: future_part'), lessThan(top('1 tool'))); expect(top('Unrecognised part: future_part'), lessThan(top('1 tool')));
expect(top('Unrecognised part: future_part'), lessThan(top('Reasoning'))); expect(top('Unrecognised part: future_part'), lessThan(top('Reasoning')));
// Reasoning is a chip like the tools chip: it opens a native sheet.
await tester.ensureVisible(find.text('Reasoning')); await tester.ensureVisible(find.text('Reasoning'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.tap(find.text('Reasoning')); await tester.tap(find.text('Reasoning'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('private reasoning'), findsOneWidget); expect(
await tester.tap(find.text('Reasoning')); 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.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('private reasoning'), findsNothing);
// The chip opens the calls; a call opens to its formatted input. // The chip opens the calls; a call opens to its formatted input.
await tester.ensureVisible(find.text('1 tool')); await tester.ensureVisible(find.text('1 tool'));
@@ -267,11 +275,20 @@ void main() {
expect(reasoning.center.dy, closeTo(tools.center.dy, 2)); expect(reasoning.center.dy, closeTo(tools.center.dy, 2));
expect(reasoning.right, lessThan(tools.left)); expect(reasoning.right, lessThan(tools.left));
// The inline disclosure opens with every recorded step. // The sheet lists every recorded step, in order.
await tester.tap(find.text('Reasoning · 2 steps')); await tester.tap(find.text('Reasoning · 2 steps'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('first thought'), findsOneWidget); final sheet = find.byKey(const Key('chat-reasoning-sheet'));
expect(find.text('second thought'), findsOneWidget); 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);
}); });
} }
@@ -352,7 +369,7 @@ void main() {
expect(find.byType(SelectableText), findsNothing); expect(find.byType(SelectableText), findsNothing);
}); });
testWidgets('Cupertino disclosure expands with the native control', ( testWidgets('Cupertino reasoning and tool chips open native popups', (
tester, tester,
) async { ) async {
final row = _assistant([ final row = _assistant([
@@ -369,9 +386,11 @@ void main() {
expect(find.text('thought'), findsNothing); expect(find.text('thought'), findsNothing);
await tester.tap(find.text('Reasoning')); await tester.tap(find.text('Reasoning'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(CupertinoPopupSurface), findsOneWidget);
expect(find.text('thought'), findsOneWidget); expect(find.text('thought'), findsOneWidget);
await tester.tap(find.text('Reasoning')); await tester.tapAt(const Offset(10, 10));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('thought'), findsNothing);
await tester.tap(find.text('1 tool')); await tester.tap(find.text('1 tool'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
@@ -0,0 +1,158 @@
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/domain/chat_transcript.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart';
JsonMap _turn(List<JsonMap> parts, {String model = ''}) => transcriptRows([
{
'id': 'a1',
'role': 'assistant',
if (model.isNotEmpty) 'model': model,
'parts': parts,
},
]).single;
Widget _app(Widget body, bool cupertino) => cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: body))
: MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: body),
);
final _sheet = find.byKey(const Key('chat-reasoning-sheet'));
Finder _inSheet(String text) =>
find.descendant(of: _sheet, 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 '
'($host)', (tester) async {
tester.view.physicalSize = const Size(900, 600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
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,
),
);
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(
(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,
),
),
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);
});
testWidgets('an open sheet follows a rebuilt turn and outlives its row '
'($host)', (tester) async {
final row = ValueNotifier<JsonMap?>(
_turn([
{'type': 'reasoning', 'id': 'r1', 'text': 'first'},
]),
);
addTearDown(row.dispose);
await tester.pumpWidget(
_app(
ValueListenableBuilder<JsonMap?>(
valueListenable: row,
builder: (context, value, _) => ListView(
children: [
if (value != null)
ChatMessageView(key: const Key('turn'), row: value),
],
),
),
cupertino,
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Reasoning'));
await tester.pumpAndSettle();
expect(_inSheet('Reasoning'), findsOneWidget);
expect(_inSheet('first'), findsOneWidget);
row.value = _turn([
{'type': 'reasoning', 'id': 'r1', 'text': 'first, longer'},
{'type': 'text', 'text': 'Answer'},
{'type': 'reasoning', 'id': 'r2', 'text': 'second'},
]);
await tester.pumpAndSettle();
expect(_inSheet('Reasoning · 2 steps'), findsOneWidget);
expect(_inSheet('first, longer'), findsOneWidget);
expect(_inSheet('second'), findsOneWidget);
// The row leaves the transcript while the sheet is open: the sheet keeps
// its last steps and closes cleanly.
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(tester.takeException(), isNull);
});
}
}
+62 -6
View File
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -9,8 +11,9 @@ const _style = String.fromEnvironment(
defaultValue: 'material', defaultValue: 'material',
); );
/// Visible fixture for one user row and one folded assistant turn. The unknown /// Visible fixture for one user row, one folded assistant turn and one live
/// part and the tool body start collapsed so the browser probe has to open them. /// turn whose newest reasoning step grows every half second. The unknown part
/// and the tool body start collapsed so the browser probe has to open them.
void main() { void main() {
final rows = transcriptRows([ final rows = transcriptRows([
{ {
@@ -57,10 +60,7 @@ void main() {
], ],
}, },
]); ]);
final content = ListView( final content = _LiveTranscript(rows: rows);
padding: const EdgeInsets.all(16),
children: [for (final row in rows) ChatMessageView(row: row)],
);
if (_style == 'cupertino') { if (_style == 'cupertino') {
runApp( runApp(
CupertinoApp( CupertinoApp(
@@ -80,3 +80,59 @@ void main() {
), ),
); );
} }
/// The fixture rows plus a streaming turn, rebuilt on each tick the way the
/// thread repaints a live delta.
class _LiveTranscript extends StatefulWidget {
const _LiveTranscript({required this.rows});
final List<Map<String, dynamic>> rows;
@override
State<_LiveTranscript> createState() => _LiveTranscriptState();
}
class _LiveTranscriptState extends State<_LiveTranscript> {
int _tick = 0;
late final Timer _timer;
@override
void initState() {
super.initState();
_timer = Timer.periodic(
const Duration(milliseconds: 500),
(_) => setState(() => _tick++),
);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final live = {
...transcriptRows([
{
'id': 'probe-live',
'role': 'assistant',
'parts': [
{'type': 'reasoning', 'id': 'r1', 'text': 'Live step one settled.'},
{'type': 'text', 'id': 't1', 'text': 'Live answer so far.'},
{'type': 'reasoning', 'id': 'r2', 'text': 'Live tick $_tick.'},
],
},
]).single,
'streaming': true,
};
return ListView(
padding: const EdgeInsets.all(16),
children: [
for (final row in [...widget.rows, live])
ChatMessageView(key: ValueKey(row['key']), row: row),
],
);
}
}
+44
View File
@@ -376,6 +376,50 @@ try {
await assertOcr(openTool, text); await assertOcr(openTool, text);
} }
// Dismiss the tool sheet, then bring the live turn into view.
for (const type of ['mousePressed', 'mouseReleased']) {
await send('Input.dispatchMouseEvent', { type, x: 10, y: 10, button: 'left', clickCount: 1 }, session);
}
await delay(800);
await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 420, deltaX: 0, deltaY: 3000 }, session);
await delay(800);
const liveName = 'Reasoning · 2 steps, expand for details';
await requireNode(liveName);
const liveChip = await capture(`${style}-live-chip`);
await assertOcr(liveChip, 'Live answer so far');
await assertOcr(liveChip, 'Reasoning');
// The open sheet follows the live turn: its newest step keeps growing.
// A real pointer tap on the chip's own node (the smallest one carrying its
// name; its row group repeats the text).
const chipNode = (await nodes())
.filter((node) => node.label === liveName || node.text === liveName)
.sort((a, b) => a.w * a.h - b.w * b.h)[0];
for (const type of ['mousePressed', 'mouseReleased']) {
await send('Input.dispatchMouseEvent', {
type,
x: chipNode.x + chipNode.w / 2,
y: chipNode.y + chipNode.h / 2,
button: 'left',
clickCount: 1,
}, session);
}
await delay(800);
const tickOf = async (path) => {
const match = (await ocr(path)).match(/Live tick (\d+)/);
if (!match) throw new Error(`OCR of ${path} shows no live tick`);
return Number(match[1]);
};
const liveA = await capture(`${style}-live-sheet-a`);
await assertOcr(liveA, 'Live step one settled');
const first = await tickOf(liveA);
await delay(2000);
const liveB = await capture(`${style}-live-sheet-b`);
const second = await tickOf(liveB);
evidence.checks.push({ check: 'open reasoning sheet follows live deltas', first, second });
if (second <= first) {
throw new Error(`Open sheet did not follow live deltas: ${first} then ${second}`);
}
const report = JSON.stringify(evidence, null, 2); const report = JSON.stringify(evidence, null, 2);
await writeFile(join(out, `${style}-evidence.json`), report); await writeFile(join(out, `${style}-evidence.json`), report);
console.log(report); console.log(report);