From 1a9fc749998bc9e1fba47f5c426906935fc19fbf Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 2 Nov 2026 16:37:35 +0000 Subject: [PATCH] Show the chat mode control as soon as the session names its mode A created chat's reply carried no mode, and the chat destination kept the first row it opened for the whole visit, ignoring later list re-reads, so the mode control only appeared after closing and reopening the chat. The server now names the mode on a created row, and the destination adopts each listed row that a re-read changed (excluding the live running flag), so the open conversation follows new, refreshed and other-device mode changes in place. --- app/lib/features/chat/screen.dart | 48 ++- .../features/chat/chat_screen_mode_test.dart | 289 ++++++++++++++++++ internal/server/chat_manager.go | 4 +- internal/server/chat_modes_test.go | 14 + 4 files changed, 345 insertions(+), 10 deletions(-) create mode 100644 app/test/features/chat/chat_screen_mode_test.dart diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 559b4b4f..42da11fe 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -9,6 +9,7 @@ import 'package:flutter/material.dart'; import '../../core/api_gateway.dart'; import 'conversation/chat_models.dart'; +import 'conversation/chat_row_widgets.dart'; import 'conversation/chat_scroll.dart'; import 'conversation/chat_thread_view.dart'; import 'conversation/chat_transcript_cache.dart'; @@ -64,6 +65,10 @@ class _ChatScreenState extends State { /// (a deep link) resolves the same row without a second list request. final Map _openedSessions = {}; + /// Each row as the list last reported it (without its live `running`), so + /// [_adoptRows] adopts only what a re-read changed. + final Map _listedRows = {}; + /// Model switches the server accepted after a row was opened. The row that /// opened the conversation may still carry the pre-switch model, so these win /// for the rest of this visit, including when the same chat is reopened. @@ -132,18 +137,40 @@ class _ChatScreenState extends State { unawaited(_sessions.refresh()); } - /// Adopts the list's loaded rows for the routed session: a deep link opens - /// the conversation before any row has been tapped, and the header's title - /// and model control come from that row. Called after a frame, never during + /// Adopts the list's loaded rows for the routed session and for every row + /// this visit has opened. A deep link opens the conversation before any row + /// has been tapped, and a created or long-open row can predate facts the + /// list has since read (its mode, a mode another device chose, a title). + /// The header's title, model and mode controls come from that row, so the + /// open conversation follows each re-read instead of waiting to be reopened. + /// Only a listed row that changed since the list last reported it is + /// adopted, so an unchanged (or still loading) listing never reverts a mode + /// or model this visit has just accepted. Fields only the opened row carries + /// (a create's instruction status) are kept. The list's live `running` flag + /// is ignored: the conversation tracks its own turn, and following it would + /// rebuild the open thread at every turn. Called after a frame, never during /// the list's own build. void _adoptRows(List rows) { - final id = _selected; - if (id == null || _openedSessions.containsKey(id)) return; + if (!mounted) return; + final selected = _selected; + final next = {}; for (final row in rows) { - if ('${row['id'] ?? ''}' != id) continue; - setState(() => _openedSessions[id] = row); - return; + final id = '${row['id'] ?? ''}'; + if (id.isEmpty) continue; + final listed = {...row}..remove('running'); + final previous = _listedRows[id]; + _listedRows[id] = listed; + final opened = _openedSessions[id]; + if (opened == null && id != selected) continue; + if (opened != null && chatJsonEquals(previous, listed)) continue; + final adopted = {...?opened, ...listed}; + if (opened != null && opened.containsKey('running')) { + adopted['running'] = opened['running']; + } + if (!chatJsonEquals(opened, adopted)) next[id] = adopted; } + if (next.isEmpty) return; + setState(() => _openedSessions.addAll(next)); } void _modelChanged(String id, ChatModelSelection applied) { @@ -152,13 +179,16 @@ class _ChatScreenState extends State { } /// An accepted mode switch updates the opened row, so reopening the chat in - /// this visit shows it before the list re-reads. + /// this visit shows it before the list re-reads. The list then re-reads, so + /// a listing already in flight from before the switch is superseded rather + /// than adopted over the accepted mode. void _modeChanged(String id, String mode, String name) { final row = _openedSessions[id]; if (!mounted || row == null) return; setState( () => _openedSessions[id] = {...row, 'mode': mode, 'mode_name': name}, ); + unawaited(_sessions.refresh()); } /// The row to open for [id], with an accepted model folded in. diff --git a/app/test/features/chat/chat_screen_mode_test.dart b/app/test/features/chat/chat_screen_mode_test.dart new file mode 100644 index 00000000..2b0e272a --- /dev/null +++ b/app/test/features/chat/chat_screen_mode_test.dart @@ -0,0 +1,289 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_mode_control.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; + +/// A chat destination gateway whose listing can change between reads, as it +/// does when the server learns a row's mode after the row was first opened. +class _ModeScreenGateway implements ApiGateway { + final calls = <({String type, JsonMap fields})>[]; + + List sessions = [ + _claude('s', 'Wire chat', mode: 'default', name: 'Ask for permission'), + ]; + + /// The `chat_session` a create replies with. + JsonMap created = _claude('n1', 'New chat'); + + /// Holds list reads while set, so a test can look before the re-read lands. + Completer? listGate; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add((type: type, fields: fields)); + switch (type) { + case 'chat_sessions': + final rows = [...sessions]; + await listGate?.future; + return {'chat_sessions': rows}; + case 'chat_create': + return {'chat_session': created}; + case 'chat_messages': + return { + 'chat_history': { + 'messages': const [], + 'next_cursor': '', + 'has_more': false, + }, + }; + } + return {}; + } +} + +JsonMap _claude( + String id, + String title, { + String mode = '', + String name = '', +}) => { + 'id': id, + 'title': title, + 'backend': 'claude', + 'directory': '/w', + if (mode.isNotEmpty) 'mode': mode, + if (name.isNotEmpty) 'mode_name': name, +}; + +/// `/new` is typed on a desktop keyboard, where Enter sends. +final _desktop = TargetPlatformVariant.only(TargetPlatform.linux); + +final _modeControl = find.byKey(const Key('chat-mode')); + +Widget _app( + _ModeScreenGateway gateway, { + required TargetPlatform platform, + String? initialSessionId, + int syncToken = 0, +}) => MaterialApp( + theme: ThemeData(platform: platform), + home: Scaffold( + body: ChatScreen( + gateway: gateway, + initialSessionId: initialSessionId, + syncToken: syncToken, + ), + ), +); + +Future _pump( + WidgetTester tester, + _ModeScreenGateway gateway, { + required TargetPlatform platform, + Size size = const Size(390, 844), + String? initialSessionId, +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + _app(gateway, platform: platform, initialSessionId: initialSessionId), + ); + await tester.pumpAndSettle(); +} + +/// The mode the drawn control names, or null when the bar has none. A +/// Cupertino phone bar draws only the shield, so read the control itself. +String? _shown(WidgetTester tester) { + if (_modeControl.evaluate().isEmpty) return null; + final control = find.byType(ChatModeControl); + expect(control, findsOneWidget); + return tester.widget(control).modeName; +} + +void main() { + for (final platform in [TargetPlatform.android, TargetPlatform.iOS]) { + final style = platform == TargetPlatform.iOS ? 'Cupertino' : 'Material'; + + testWidgets( + '$style: an existing chat opened from the list shows its mode', + (tester) async { + final gateway = _ModeScreenGateway(); + await _pump(tester, gateway, platform: platform); + + await tester.tap(find.byKey(const Key('chat-row-s'))); + await tester.pumpAndSettle(); + + expect(_shown(tester), 'Ask for permission'); + }, + ); + + testWidgets( + '$style: a mode the list learns after the chat opened appears in place', + (tester) async { + final gateway = _ModeScreenGateway() + ..sessions = [_claude('s', 'Wire chat')]; + await _pump(tester, gateway, platform: platform); + await tester.tap(find.byKey(const Key('chat-row-s'))); + await tester.pumpAndSettle(); + expect(_shown(tester), isNull); + + // A reconnect re-reads the list; the open chat follows that row + // without being closed and opened again. + gateway.sessions = [ + _claude( + 's', + 'Wire chat', + mode: 'default', + name: 'Ask for permission', + ), + ]; + await tester.pumpWidget( + _app(gateway, platform: platform, syncToken: 1), + ); + await tester.pumpAndSettle(); + expect(_shown(tester), 'Ask for permission'); + + // Another device chose Auto; the next re-read keeps the bar in sync. + gateway.sessions = [ + _claude('s', 'Wire chat', mode: 'auto', name: 'Auto'), + ]; + await tester.pumpWidget( + _app(gateway, platform: platform, syncToken: 2), + ); + await tester.pumpAndSettle(); + expect(_shown(tester), 'Auto'); + }, + ); + + testWidgets('$style: a routed chat shows its mode once the list loads', ( + tester, + ) async { + final gateway = _ModeScreenGateway(); + await _pump(tester, gateway, platform: platform, initialSessionId: 's'); + + expect(_shown(tester), 'Ask for permission'); + }); + + testWidgets('$style: switching chats shows each chat its own mode', ( + tester, + ) async { + final gateway = _ModeScreenGateway() + ..sessions = [ + _claude( + 's', + 'Wire chat', + mode: 'default', + name: 'Ask for permission', + ), + _claude('t', 'Other chat', mode: 'auto', name: 'Auto'), + {'id': 'u', 'title': 'Plain chat', 'backend': 'opencode'}, + ]; + // Wide: the list stays beside the open chat, so a row swaps it. + await _pump( + tester, + gateway, + platform: platform, + size: const Size(1400, 900), + ); + + await tester.tap(find.byKey(const Key('chat-row-s'))); + await tester.pumpAndSettle(); + expect(_shown(tester), 'Ask for permission'); + + await tester.tap(find.byKey(const Key('chat-row-t'))); + await tester.pumpAndSettle(); + expect(_shown(tester), 'Auto'); + + await tester.tap(find.byKey(const Key('chat-row-u'))); + await tester.pumpAndSettle(); + expect(_shown(tester), isNull); + + await tester.tap(find.byKey(const Key('chat-row-s'))); + await tester.pumpAndSettle(); + expect(_shown(tester), 'Ask for permission'); + }); + } + + Future runNew(WidgetTester tester) async { + await tester.enterText( + find.byKey(const Key('chat-composer-field')), + '/new', + ); + await tester.pump(); + // The first Enter may complete the palette row; the second runs it. + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + final field = tester.widget( + find.descendant( + of: find.byKey(const Key('chat-composer-field')), + matching: find.byType(EditableText), + ), + ); + if (field.controller.text.isNotEmpty) { + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + } + await tester.pumpAndSettle(); + } + + testWidgets( + 'a created chat whose reply names its mode shows it before the list re-reads', + (tester) async { + final gateway = _ModeScreenGateway() + ..created = _claude('n1', 'New chat', mode: 'plan', name: 'Plan'); + await _pump( + tester, + gateway, + platform: TargetPlatform.linux, + size: const Size(1400, 900), + ); + await tester.tap(find.byKey(const Key('chat-row-s'))); + await tester.pumpAndSettle(); + gateway.listGate = Completer(); + await runNew(tester); + + expect(find.text('New chat'), findsWidgets); + expect(_shown(tester), 'Plan'); + gateway.listGate!.complete(); + await tester.pumpAndSettle(); + }, + variant: _desktop, + ); + + testWidgets( + 'a created chat whose reply lacks its mode shows it when the list re-reads', + (tester) async { + final gateway = _ModeScreenGateway(); + await _pump( + tester, + gateway, + platform: TargetPlatform.linux, + size: const Size(1400, 900), + ); + await tester.tap(find.byKey(const Key('chat-row-s'))); + await tester.pumpAndSettle(); + gateway + ..listGate = Completer() + ..sessions = [ + _claude('n1', 'New chat', mode: 'plan', name: 'Plan'), + ...gateway.sessions, + ]; + await runNew(tester); + // The row is open on the create reply, which names no mode. + expect(find.text('New chat'), findsWidgets); + expect(_shown(tester), isNull); + + gateway.listGate!.complete(); + await tester.pumpAndSettle(); + expect(_shown(tester), 'Plan'); + }, + variant: _desktop, + ); +} diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index 923d6c6f..1b19fa78 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -293,7 +293,9 @@ func (m *chatManager) CreateBackend(ctx context.Context, title, directory, backe m.mu.Lock() m.cache[session.ID] = backend m.mu.Unlock() - return session, nil + // The created row names its mode like a listed one, so the opened chat + // shows the mode control at once rather than after the list re-reads. + return m.withMode(ctx, session), nil } func (m *chatManager) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) { diff --git a/internal/server/chat_modes_test.go b/internal/server/chat_modes_test.go index 242fa73c..4b8c7bad 100644 --- a/internal/server/chat_modes_test.go +++ b/internal/server/chat_modes_test.go @@ -100,3 +100,17 @@ func TestChatModeIsStoredAppliedAndSurvivesRestart(t *testing.T) { t.Fatalf("stored mode not re-applied before turns: %v", fake.applied) } } + +// A created chat names its mode like a listed row, so the client shows the +// mode control without re-reading the list. +func TestCreatedChatNamesItsMode(t *testing.T) { + fake := &modedChat{fakeChat: scriptedChat()} + manager := &chatManager{claude: fake, cache: map[string]string{}} + session, err := manager.CreateBackend(context.Background(), "chat", "/fixture", "claude") + if err != nil { + t.Fatal(err) + } + if session.Mode != "default" || session.ModeName != "Ask" { + t.Fatalf("created session names %q/%q, want the harness default", session.Mode, session.ModeName) + } +}