diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 9e6a70cc..2fde91b5 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -587,7 +587,11 @@ class _ChatThreadViewState extends State { permissionErrorFor: _controller.permissionErrorFor, formErrorFor: _controller.questionErrorFor, ); - final allRows = transcriptRows(messages, trailing: cards); + final allRows = transcriptRows( + messages, + trailing: cards, + running: _controller.running && !_reconnecting && !_staleTranscript, + ); // A transcript held from before a socket gap may still say a compaction is // running even when the repair's read is refused. That running state is // stale, so no compaction notice is derived from it until a fresh read or diff --git a/app/lib/features/chat/domain/chat_transcript.dart b/app/lib/features/chat/domain/chat_transcript.dart index bbe0ce06..9977237f 100644 --- a/app/lib/features/chat/domain/chat_transcript.dart +++ b/app/lib/features/chat/domain/chat_transcript.dart @@ -53,6 +53,7 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) { List transcriptRows( List messages, { List trailing = const [], + bool running = false, }) { final rows = []; String? key; @@ -113,6 +114,19 @@ List transcriptRows( } } flush(); + // Only the newest assistant turn can be live. A running step before the + // first assistant delta must not reopen reasoning from an earlier reply. + if (running && messages.isNotEmpty && messages.last['role'] == 'assistant') { + for (final row in rows.reversed) { + if (row['kind'] == 'assistant' && + (row['messageIds'] as List).contains( + '${messages.last['id'] ?? ''}', + )) { + row['streaming'] = true; + break; + } + } + } rows.addAll(trailing); return rows; } diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index 294f411f..dfbc1c16 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -7,6 +7,7 @@ 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_disclosure.dart'; import 'native_disclosure.dart'; /// Builds an assistant text part; the default keeps the server's text exactly. @@ -188,8 +189,7 @@ class ChatMessageView extends StatelessWidget { return widgets; } - /// The agent turn: the answer in the bubble, then one row with its reasoning - /// and tool-call chips, each opening its own sheet. + /// Reasoning stays in the transcript so an open body follows live deltas. Widget _agentTurn(BuildContext context, List content, Widget bubble) { final parts = _partsOf(row); final reasoning = [ @@ -208,13 +208,17 @@ class ChatMessageView extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (content.isNotEmpty) bubble, - // Reasoning and tool calls share one quiet row below the answer. - if (reasoning.isNotEmpty || tools.isNotEmpty || model.isNotEmpty) + if (reasoning.isNotEmpty) + ChatReasoningDisclosure( + key: const Key('chat-turn-reasoning'), + steps: reasoning, + streaming: row['streaming'] == true, + ), + if (tools.isNotEmpty || model.isNotEmpty) Wrap( spacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: [ - if (reasoning.isNotEmpty) ChatReasoningChip(steps: reasoning), if (tools.isNotEmpty) ChatToolCallsChip(calls: tools), // Which model answered, quietly, after the chips. if (model.isNotEmpty) diff --git a/app/lib/features/chat/ui/transcript/chat_reasoning_disclosure.dart b/app/lib/features/chat/ui/transcript/chat_reasoning_disclosure.dart new file mode 100644 index 00000000..38048320 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/chat_reasoning_disclosure.dart @@ -0,0 +1,53 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../sessions/chat_adaptive.dart'; +import 'native_disclosure.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 StatelessWidget { + const ChatReasoningDisclosure({ + super.key, + required this.steps, + required this.streaming, + }); + + final List steps; + final bool streaming; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final label = steps.length == 1 + ? 'Reasoning' + : 'Reasoning · ${steps.length} steps'; + final disclosure = NativeDisclosure( + key: const Key('chat-reasoning-disclosure'), + label: label, + initiallyExpanded: streaming, + childBuilder: (_) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final (index, step) in steps.indexed) + Padding( + padding: EdgeInsets.only(top: index == 0 ? 0 : 12, bottom: 8), + child: SelectableText(step), + ), + ], + ), + ); + // Material's native ExpansionTile needs a surface; Cupertino must not + // acquire a Material dependency just to show its own disclosure button. + return DefaultTextStyle.merge( + style: cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyMedium, + child: cupertino + ? disclosure + : Material(color: Colors.transparent, child: disclosure), + ); + } +} diff --git a/app/lib/features/chat/ui/transcript/chat_tool_calls_view.dart b/app/lib/features/chat/ui/transcript/chat_tool_calls_view.dart index c2a9e31e..97971a4d 100644 --- a/app/lib/features/chat/ui/transcript/chat_tool_calls_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_tool_calls_view.dart @@ -54,39 +54,7 @@ class ChatToolCallsChip extends StatelessWidget { } } -/// A turn's reasoning as a chip beside its tool chip, the same way: `Reasoning` -/// or `Reasoning · N steps`, opening a sheet with the steps. -class ChatReasoningChip extends StatelessWidget { - const ChatReasoningChip({super.key, required this.steps}); - - final List steps; - - @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 = steps.length == 1 - ? 'Reasoning' - : 'Reasoning · ${steps.length} steps'; - return _TurnChip( - chipKey: const Key('chat-reasoning-chip'), - leading: Icon( - cupertino ? CupertinoIcons.lightbulb : Icons.lightbulb_outline, - size: 14, - color: color, - ), - label: label, - color: color, - semanticsLabel: '$label, expand for details', - sheet: _ReasoningSheet(label: label, steps: steps), - ); - } -} - -/// The quiet chip shell both turn summaries share, and its native sheet. +/// The quiet tool chip shell and its native sheet. class _TurnChip extends StatelessWidget { const _TurnChip({ required this.chipKey, @@ -171,49 +139,6 @@ class _TurnChip extends StatelessWidget { } } -class _ReasoningSheet extends StatelessWidget { - const _ReasoningSheet({required this.label, required this.steps}); - - final String label; - final List steps; - - @override - Widget build(BuildContext context) { - final cupertino = - chatControlsStyleOf(context) == ChatControlsStyle.cupertino; - final style = cupertino - ? CupertinoTheme.of(context).textTheme.textStyle - : Theme.of(context).textTheme.bodyMedium; - return DefaultTextStyle.merge( - style: style, - child: ConstrainedBox( - constraints: BoxConstraints( - maxHeight: MediaQuery.sizeOf(context).height * 0.8, - ), - child: ListView( - key: const Key('chat-reasoning-sheet'), - shrinkWrap: true, - padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), - children: [ - Padding( - padding: const EdgeInsets.only(bottom: 8), - child: Text( - label, - style: const TextStyle(fontWeight: FontWeight.w600), - ), - ), - for (final (index, step) in steps.indexed) - Padding( - padding: EdgeInsets.only(top: index == 0 ? 0 : 12), - child: SelectableText(step), - ), - ], - ), - ), - ); - } -} - class _ToolCallsSheet extends StatelessWidget { const _ToolCallsSheet({required this.calls}); diff --git a/app/lib/features/chat/ui/transcript/native_disclosure.dart b/app/lib/features/chat/ui/transcript/native_disclosure.dart index 29ab9436..5e085500 100644 --- a/app/lib/features/chat/ui/transcript/native_disclosure.dart +++ b/app/lib/features/chat/ui/transcript/native_disclosure.dart @@ -3,7 +3,7 @@ import 'package:flutter/material.dart'; import '../sessions/chat_adaptive.dart'; -/// A collapsed block opened with the host's own disclosure control. +/// A block opened with the host's own disclosure control (collapsed by default). /// /// [childBuilder] runs only while the block is open, so a closed disclosure /// never encodes or lays out its body. @@ -12,17 +12,19 @@ class NativeDisclosure extends StatefulWidget { super.key, required this.label, required this.childBuilder, + this.initiallyExpanded = false, }); final String label; final WidgetBuilder childBuilder; + final bool initiallyExpanded; @override State createState() => _NativeDisclosureState(); } class _NativeDisclosureState extends State { - bool _expanded = false; + late bool _expanded = widget.initiallyExpanded; void _toggle() => setState(() => _expanded = !_expanded); @@ -31,6 +33,7 @@ class _NativeDisclosureState extends State { if (chatControlsStyleOf(context) != ChatControlsStyle.cupertino) { return ExpansionTile( title: Text(widget.label), + initiallyExpanded: widget.initiallyExpanded, maintainState: false, // A transcript block starts at the row edge, like its answer text; the // tile's own padding would indent it, and its body defaults to centred, diff --git a/app/test/features/chat/conversation/chat_live_reasoning_test.dart b/app/test/features/chat/conversation/chat_live_reasoning_test.dart new file mode 100644 index 00000000..e20c6529 --- /dev/null +++ b/app/test/features/chat/conversation/chat_live_reasoning_test.dart @@ -0,0 +1,165 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart'; + +import 'chat_thread_fixtures.dart'; + +// Matches the normalized OpenCode V2 protocol: text and reasoning each start +// at ordinal zero but have distinct stable IDs (ChatDeltaPartID in Go). +JsonMap _delta(String kind, String text) => { + 'session_id': 's', + 'message_id': 'a', + 'kind': kind, + 'part': {'id': 'a#$kind#0', 'type': kind}, + 'delta': text, +}; + +Widget _host(Widget child, bool cupertino) => cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: child)) + : MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: child), + ); + +void main() { + for (final cupertino in [false, true]) { + testWidgets('reasoning arriving after text opens live ($cupertino)', ( + 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 tester.pumpAndSettle(); + expect(find.text('Only supplied reasoning'), findsOneWidget); + expect(find.text('Answer first'), findsOneWidget); + }); + + testWidgets('live reasoning survives text, collapse, paging and resync ' + '(${cupertino ? 'Cupertino' : 'Material'})', (tester) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => + chatPage(const [], hasMore: true, cursor: 'old'); + await tester.pumpWidget( + _host( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + cupertino, + ), + ); + await tester.pumpAndSettle(); + + gateway.emitEvent(_delta('reasoning', 'Provided thought')); + await tester.pumpAndSettle(); + // No opening tap required for a newly streaming reply. + expect(find.text('Provided thought'), findsOneWidget); + final rowElement = tester.element(find.byType(ChatMessageView)); + + gateway.emitEvent(_delta('text', 'Answer')); + gateway.emitEvent(_delta('reasoning', ' continues')); + await tester.pumpAndSettle(); + expect(find.text('Provided thought continues'), findsOneWidget); + expect(find.text('Answer'), findsOneWidget); + expect(tester.element(find.byType(ChatMessageView)), same(rowElement)); + + await tester.tap(find.text('Reasoning')); + await tester.pumpAndSettle(); + gateway.emitEvent(_delta('reasoning', ' while collapsed')); + gateway.emitEvent(_delta('text', ' continues')); + await tester.pumpAndSettle(); + expect(find.textContaining('while collapsed'), findsNothing); + expect(find.text('Answer continues'), findsOneWidget); + await tester.tap(find.text('Reasoning')); + await tester.pumpAndSettle(); + expect( + find.text('Provided thought continues while collapsed'), + findsOneWidget, + ); + + // Prepending another assistant message folds into the same turn without + // replacing the row or closing the already-open reasoning disclosure. + gateway.history = (_) async => chatPage([ + chatMessage( + 'older', + 'assistant', + parts: [ + { + 'type': 'reasoning', + 'id': 'older-r', + 'text': 'Older provided thought', + }, + ], + ), + ]); + await tester.tap(find.text('Load older')); + await tester.pumpAndSettle(); + expect(find.text('Older provided thought'), findsOneWidget); + expect( + find.text('Provided thought continues while collapsed'), + findsOneWidget, + ); + expect(tester.element(find.byType(ChatMessageView)), same(rowElement)); + + gateway.emitEvent(chatStepFrame('ended')); + await tester.pumpAndSettle(); + expect( + find.text('Provided thought continues while collapsed'), + findsOneWidget, + ); + + gateway.history = (_) async => chatPage([ + chatMessage( + 'a', + 'assistant', + parts: [ + { + 'type': 'reasoning', + 'id': 'a#reasoning#0', + 'text': 'Stored provided thought', + }, + {'type': 'text', 'id': 'a#text#0', 'text': 'Stored answer'}, + ], + ), + ]); + gateway.emitEvent({'session_id': 's', 'kind': 'resync'}); + await tester.pumpAndSettle(); + expect(find.text('Stored provided thought'), findsOneWidget); + expect(find.text('Stored answer'), findsOneWidget); + expect(find.textContaining('while collapsed'), findsNothing); + expect(tester.element(find.byType(ChatMessageView)), same(rowElement)); + await tester.tap(find.text('Reasoning')); + await tester.pumpAndSettle(); + expect(find.text('Stored provided thought'), findsNothing); + + // A fresh history visit starts collapsed; missing reasoning is never + // fabricated. Cupertino keeps only its native controls. + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpWidget( + _host( + ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}), + cupertino, + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Stored provided thought'), findsNothing); + await tester.tap(find.text('Reasoning')); + await tester.pumpAndSettle(); + expect(find.text('Stored provided thought'), findsOneWidget); + if (cupertino) expect(find.byType(Material), findsNothing); + expect(tester.takeException(), isNull); + }); + } +} diff --git a/app/test/features/chat/conversation/chat_thread_view_test.dart b/app/test/features/chat/conversation/chat_thread_view_test.dart index 4f94c6e6..4cedecab 100644 --- a/app/test/features/chat/conversation/chat_thread_view_test.dart +++ b/app/test/features/chat/conversation/chat_thread_view_test.dart @@ -168,7 +168,7 @@ void main() { ); await tester.pumpAndSettle(); - // The turn's reasoning is one chip below its answer; it counts the + // The turn's reasoning is one disclosure below its answer; it counts the // steps of every message folded into the turn. expect(find.text('Reasoning · 2 steps'), findsOneWidget); @@ -184,9 +184,7 @@ void main() { ]) { expect(find.text(body), findsOneWidget, reason: body); } - Navigator.of( - tester.element(find.text('NEWEST folded reasoning body.')), - ).pop(); + await tester.tap(find.text('Reasoning · 4 steps')); await tester.pumpAndSettle(); expect( find.text('Load older'), diff --git a/app/test/features/chat/domain/chat_live_reasoning_test.dart b/app/test/features/chat/domain/chat_live_reasoning_test.dart new file mode 100644 index 00000000..50d77597 --- /dev/null +++ b/app/test/features/chat/domain/chat_live_reasoning_test.dart @@ -0,0 +1,70 @@ +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'; + +void main() { + test('only the newest assistant turn is marked streaming', () { + final messages = [ + { + 'id': 'old', + 'role': 'assistant', + 'parts': [ + {'type': 'reasoning', 'text': 'Stored thought'}, + ], + }, + {'id': 'user', 'role': 'user', 'parts': []}, + ]; + expect(transcriptRows(messages, running: true).first['streaming'], isNull); + final activityOnly = [ + ...messages, + { + 'id': 'activity-only', + 'role': 'assistant', + 'parts': [ + {'type': 'activity', 'kind': 'thinking', 'state': 'running'}, + ], + }, + ]; + expect( + transcriptRows(activityOnly, running: true).first['streaming'], + isNull, + ); + messages.add({ + 'id': 'new', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'text': 'Answer'}, + ], + }); + final rows = transcriptRows(messages, running: true); + expect(rows.first['streaming'], isNull); + expect(rows.last['streaming'], isTrue); + expect(transcriptRows(messages).last['streaming'], isNull); + }); + + test('same ordinal text and reasoning stay independent across deltas', () { + var thread = {'sessionId': 's', 'messages': []}; + for (final (kind, delta) in [ + ('text', 'Answer'), + ('reasoning', 'Provided thought'), + ('text', ' continued'), + ('reasoning', ' continued'), + ]) { + thread = applyChatEvent(thread, { + 'session_id': 's', + 'message_id': 'a', + 'kind': kind, + 'part': {'type': kind, 'id': 'a#$kind#0'}, + 'delta': delta, + }); + } + expect((thread['messages'] as List).single['parts'], [ + {'type': 'text', 'id': 'a#text#0', 'text': 'Answer continued'}, + { + 'type': 'reasoning', + 'id': 'a#reasoning#0', + 'text': 'Provided thought continued', + }, + ]); + }); +} diff --git a/app/test/features/chat/ui/transcript/chat_message_view_test.dart b/app/test/features/chat/ui/transcript/chat_message_view_test.dart index b47aec8d..17087ae5 100644 --- a/app/test/features/chat/ui/transcript/chat_message_view_test.dart +++ b/app/test/features/chat/ui/transcript/chat_message_view_test.dart @@ -124,8 +124,7 @@ void main() { expect(find.textContaining('"payload": 7'), findsNothing); expect(find.text('plain future text'), findsOneWidget); - // The answer keeps its own order in the bubble; reasoning and the tool - // calls are two chips in one row below it. + // The answer keeps its own order; reasoning expands inline below it. double top(String text) => tester.getTopLeft(find.text(text)).dy; expect(top('First answer'), lessThan(top('Second answer'))); expect( @@ -140,7 +139,7 @@ void main() { await tester.tap(find.text('Reasoning')); await tester.pumpAndSettle(); expect(find.text('private reasoning'), findsOneWidget); - await tester.tapAt(const Offset(10, 10)); + await tester.tap(find.text('Reasoning')); await tester.pumpAndSettle(); // The chip opens the calls; a call opens to its formatted input. @@ -162,7 +161,7 @@ void main() { }); for (final cupertino in [false, true]) { - testWidgets('reasoning and tool chips share one row below the answer ' + testWidgets('reasoning disclosure and tool chip follow the answer ' '(${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. @@ -192,10 +191,9 @@ void main() { reasoning.top, greaterThan(tester.getRect(find.text('The answer')).bottom), ); - expect(reasoning.center.dy, moreOrLessEquals(tools.center.dy)); - expect(reasoning.right, lessThan(tools.left)); + expect(reasoning.bottom, lessThan(tools.top)); - // Like the tool chip, it opens a sheet with every step. + // The inline disclosure opens with every recorded step. await tester.tap(find.text('Reasoning · 2 steps')); await tester.pumpAndSettle(); expect(find.text('first thought'), findsOneWidget); @@ -298,7 +296,7 @@ void main() { await tester.tap(find.text('Reasoning')); await tester.pumpAndSettle(); expect(find.text('thought'), findsOneWidget); - await tester.tapAt(const Offset(10, 10)); + await tester.tap(find.text('Reasoning')); await tester.pumpAndSettle(); await tester.tap(find.text('1 tool'));