diff --git a/app/lib/application/open_in_chat.dart b/app/lib/application/open_in_chat.dart index b6f3000c..28fb49da 100644 --- a/app/lib/application/open_in_chat.dart +++ b/app/lib/application/open_in_chat.dart @@ -4,6 +4,7 @@ import '../core/api_gateway.dart'; import '../features/chat/chat_runtime.dart'; import '../features/chat/ui/sessions/chat_create_fields.dart'; import '../features/settings/settings_store.dart'; +import 'open_in_chat_preferences.dart'; typedef OpenInChat = Future Function(BuildContext context); @@ -42,8 +43,15 @@ Future openReferenceInChat({ // Match the New chat dialog: prefer OpenCode when it is available, but // use the first server-advertised harness on installations where it is // not. Do not invent a backend when the catalog cannot be read. - final backends = await runtime.sessions.repository.backends(); - final backend = backends.contains('opencode') ? 'opencode' : backends.first; + final repository = runtime.sessions.repository; + final backends = await repository.backends(); + final chosen = await OpenInChatPreferences.load(repository.gateway); + // The harness chosen in Settings → Open in chat, when the server offers it. + final backend = backends.contains(chosen.harness) + ? chosen.harness + : backends.contains('opencode') + ? 'opencode' + : backends.first; final session = await runtime.sessions.createOrThrow( title: title, directory: directory.trim().isEmpty ? chatHomeDirectory : directory, @@ -53,8 +61,26 @@ Future openReferenceInChat({ ); final id = '${session['id'] ?? ''}'; if (id.isEmpty) throw StateError('The new chat has no id.'); + if (chosen.hasModel && backend == chosen.harness) { + try { + await repository.selectModel(id, chosen.provider, chosen.model); + } catch (error) { + // The chat still opens on the harness default; say why. + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Opened with the default model: ${chosen.model} is not ' + 'available ($error).', + ), + ), + ); + } + } + } runtime.opened[id] = session; runtime.pendingDrafts[id] = draft; + runtime.openedForWork.add(id); selectChat(id); runtime.composerFocus.request(id); } catch (error) { diff --git a/app/lib/application/open_in_chat_preferences.dart b/app/lib/application/open_in_chat_preferences.dart new file mode 100644 index 00000000..54e87167 --- /dev/null +++ b/app/lib/application/open_in_chat_preferences.dart @@ -0,0 +1,43 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import '../core/api_gateway.dart'; +import '../core/servers/server_scope.dart'; + +const openInChatPreferenceKey = 'pipelines.openInChat.v1'; + +/// The harness and model Open in chat starts its chats with, per server and +/// device. Empty fields mean the default: the New chat dialog's harness and +/// the harness's own default model. +class OpenInChatPreferences { + const OpenInChatPreferences({ + this.harness = '', + this.provider = '', + this.model = '', + }); + + final String harness; + final String provider; + final String model; + + bool get hasModel => provider.isNotEmpty && model.isNotEmpty; + + static String _key(ApiGateway gateway) => scopedServerKey( + openInChatPreferenceKey, + serverStorageScope(serverIdentity(gateway)), + ); + + static Future load(ApiGateway gateway) async { + final values = + (await SharedPreferences.getInstance()).getStringList(_key(gateway)) ?? + const []; + String at(int index) => index < values.length ? values[index].trim() : ''; + return OpenInChatPreferences(harness: at(0), provider: at(1), model: at(2)); + } + + Future save(ApiGateway gateway) async => + (await SharedPreferences.getInstance()).setStringList(_key(gateway), [ + harness, + provider, + model, + ]); +} diff --git a/app/lib/features/chat/chat_runtime.dart b/app/lib/features/chat/chat_runtime.dart index 8b8585f2..c40d8822 100644 --- a/app/lib/features/chat/chat_runtime.dart +++ b/app/lib/features/chat/chat_runtime.dart @@ -100,6 +100,12 @@ class ChatRuntime extends ChangeNotifier { /// consumed by the first composer for that session. final Map pendingDrafts = {}; + /// Chats an external action (Open in chat) opened for the operator to work + /// in: the chat screen shows each beside the active chat rather than in + /// its place, makes it active and puts the keyboard in its composer once + /// it is on screen. + final Set openedForWork = {}; + /// Each row as the list last reported it (without its live `running`), so /// [adoptRows] adopts only what a re-read changed. final Map _listed = {}; diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index e97d2b37..1e7495cd 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -354,6 +354,34 @@ class _ChatScreenState extends State widget.onBack?.call(); } + /// Opens the chat the route names. A chat opened for work from elsewhere + /// (Open in chat) goes beside the active chat on a wide layout instead of + /// replacing it, and takes the keyboard once its composer is built. + void _openRouted(String id) { + if (!_runtime.openedForWork.remove(id)) { + _workspace.open(id); + return; + } + final beside = + !_page.open && + showsListBesideDetail(context) && + _workspace.paneCount > 0 && + !_workspace.holdsSession(id); + if (beside) { + _workspace.splitActive(id, ChatSplitAxis.horizontal); + } else { + _workspace.open(id); + } + _composerFocus.request(id); + // The composer may be built a frame later (a new pane, a switched tab); + // ask again then so the request is never lost to the switch. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _workspace.activePane?.sessionId == id) { + _composerFocus.request(id); + } + }); + } + /// On a phone the open chat is a real page above the main screen. final DetailPageHost _page = DetailPageHost(); @@ -379,7 +407,7 @@ class _ChatScreenState extends State if (id != null && id.isNotEmpty) { _workspaceVisible = true; _publishedWorkspaceSession = id; - _workspace.open(id); + _openRouted(id); } else if (widget.onSessionSelected != null) { _workspaceVisible = false; } diff --git a/app/lib/features/settings/settings_open_in_chat_section.dart b/app/lib/features/settings/settings_open_in_chat_section.dart new file mode 100644 index 00000000..1270c72c --- /dev/null +++ b/app/lib/features/settings/settings_open_in_chat_section.dart @@ -0,0 +1,186 @@ +import 'package:flutter/material.dart'; + +import '../../application/open_in_chat_preferences.dart'; +import '../../core/api_gateway.dart'; +import '../chat/data/chat_repository.dart'; +import 'settings_group.dart'; + +/// The harness and model Open in chat (a run's or pipeline's More menu) +/// starts its chats with. The server lists models only for an existing chat, +/// so a harness's models come from its most recent chat; with none, only the +/// harness default is offered. +class SettingsOpenInChatSection extends StatefulWidget { + const SettingsOpenInChatSection({super.key, required this.gateway}); + + final ApiGateway gateway; + + @override + State createState() => + _SettingsOpenInChatSectionState(); +} + +class _SettingsOpenInChatSectionState extends State { + late final ChatRepository _chats = ChatRepository(widget.gateway); + OpenInChatPreferences _chosen = const OpenInChatPreferences(); + List? _harnesses; + List _models = const []; + bool _loadingModels = false; + String? _error; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + final chosen = await OpenInChatPreferences.load(widget.gateway); + final harnesses = await _chats.backends(); + if (!mounted) return; + setState(() { + _chosen = chosen; + _harnesses = harnesses; + }); + await _loadModels(chosen.harness); + } catch (error) { + if (mounted) setState(() => _error = '$error'); + } + } + + /// The models of [harness]'s most recent chat, or none. + Future _loadModels(String harness) async { + setState(() { + _models = const []; + _loadingModels = harness.isNotEmpty; + }); + if (harness.isEmpty) return; + try { + final sessions = await _chats.sessions(); + final latest = + sessions.where((session) => session['backend'] == harness).toList() + ..sort( + (a, b) => '${b['updated_at'] ?? ''}'.compareTo( + '${a['updated_at'] ?? ''}', + ), + ); + final models = latest.isEmpty + ? const [] + : await _chats.models('${latest.first['id']}'); + if (mounted && _chosen.harness == harness) { + setState(() { + _models = models; + _loadingModels = false; + }); + } + } catch (_) { + if (mounted) setState(() => _loadingModels = false); + } + } + + Future _save(OpenInChatPreferences next) async { + setState(() => _chosen = next); + await next.save(widget.gateway); + } + + @override + Widget build(BuildContext context) { + final harnesses = _harnesses; + final error = _error; + return SettingsGroup( + title: 'Open in chat', + footer: Text( + 'Used when a run or pipeline is opened in a new chat. Models come ' + "from this harness's most recent chat.", + ), + children: [ + if (error != null) + ListTile( + leading: const Icon(Icons.error_outline), + title: const Text('Could not load the harnesses'), + subtitle: Text(error), + trailing: TextButton( + onPressed: () { + setState(() => _error = null); + _load(); + }, + child: const Text('Retry'), + ), + ) + else if (harnesses == null) + const ListTile( + leading: SizedBox.square( + dimension: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), + title: Text('Loading harnesses…'), + ) + else ...[ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 8), + child: DropdownMenu( + key: const Key('open-in-chat-harness'), + expandedInsets: EdgeInsets.zero, + label: const Text('Harness'), + initialSelection: harnesses.contains(_chosen.harness) + ? _chosen.harness + : '', + dropdownMenuEntries: [ + const DropdownMenuEntry(value: '', label: 'Default'), + for (final harness in harnesses) + DropdownMenuEntry(value: harness, label: harness), + ], + onSelected: (harness) async { + final value = harness ?? ''; + if (value == _chosen.harness) return; + await _save(OpenInChatPreferences(harness: value)); + await _loadModels(value); + }, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 12), + child: DropdownMenu( + key: ValueKey('open-in-chat-model-${_chosen.harness}'), + expandedInsets: EdgeInsets.zero, + enabled: _chosen.harness.isNotEmpty && !_loadingModels, + label: Text(_loadingModels ? 'Loading models…' : 'Model'), + initialSelection: _chosen.hasModel + ? '${_chosen.provider}/${_chosen.model}' + : '', + dropdownMenuEntries: [ + const DropdownMenuEntry(value: '', label: 'Harness default'), + if (_chosen.hasModel && + !_models.any( + (m) => + '${m['provider']}/${m['id']}' == + '${_chosen.provider}/${_chosen.model}', + )) + DropdownMenuEntry( + value: '${_chosen.provider}/${_chosen.model}', + label: _chosen.model, + ), + for (final model in _models) + DropdownMenuEntry( + value: '${model['provider']}/${model['id']}', + label: '${model['name'] ?? model['id']}', + ), + ], + onSelected: (value) { + final picked = value ?? ''; + final slash = picked.indexOf('/'); + _save( + OpenInChatPreferences( + harness: _chosen.harness, + provider: slash < 0 ? '' : picked.substring(0, slash), + model: slash < 0 ? '' : picked.substring(slash + 1), + ), + ); + }, + ), + ), + ], + ], + ); + } +} diff --git a/app/lib/features/settings/settings_page_sections.dart b/app/lib/features/settings/settings_page_sections.dart index 1551b1cf..b6402923 100644 --- a/app/lib/features/settings/settings_page_sections.dart +++ b/app/lib/features/settings/settings_page_sections.dart @@ -106,6 +106,13 @@ extension _SettingsPageSections on _SettingsScreenState { workspaceField: _workspaceField, ), ), + SettingsSection( + id: 'open-in-chat', + title: 'Open in chat', + keywords: 'open in chat run pipeline harness model default new chat', + lazy: true, + builder: (_) => SettingsOpenInChatSection(gateway: widget.client), + ), if (widget.notifications case final notifications?) SettingsSection( id: 'notifications', diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart index 0a126c6f..55fd5e30 100644 --- a/app/lib/features/settings/settings_screen.dart +++ b/app/lib/features/settings/settings_screen.dart @@ -43,6 +43,7 @@ import 'settings_row.dart'; import 'settings_read_aloud_section.dart'; import '../chat/speech/speech_controller.dart'; +import 'settings_open_in_chat_section.dart'; part 'settings_page_sections.dart'; /// The Settings destination: one searchable page of grouped Material sections. diff --git a/app/test/application/open_in_chat_test.dart b/app/test/application/open_in_chat_test.dart index 79469ae0..14f7c624 100644 --- a/app/test/application/open_in_chat_test.dart +++ b/app/test/application/open_in_chat_test.dart @@ -1,8 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/application/open_in_chat.dart'; +import 'package:pipelines_app/application/open_in_chat_preferences.dart'; import 'package:pipelines_app/features/chat/chat_runtime.dart'; import 'package:pipelines_app/features/chat/ui/sessions/chat_create_fields.dart'; import 'package:pipelines_app/features/pipelines/pipeline_models.dart'; @@ -18,6 +20,75 @@ import '../features/pipelines/fixtures.dart'; import '../features/pipelines/test_helpers.dart'; void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + testWidgets('the harness and model chosen in Settings start the chat', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({}); + final gateway = FakeChatGateway() + ..backendsHandler = () async => const { + 'chat_backends': ['opencode', 'claude'], + }; + await const OpenInChatPreferences( + harness: 'claude', + provider: 'anthropic', + model: 'claude-opus-5-5', + ).save(gateway); + final runtime = ChatRuntime(gateway: gateway); + + await tester.pumpWidget(const MaterialApp(home: Scaffold())); + await openReferenceInChat( + context: tester.element(find.byType(Scaffold)), + runtime: runtime, + selectChat: (_) {}, + directory: '/work/run', + title: 'Run #42: Build', + draft: 'About Pipelines run #42.', + ); + + final create = gateway.lastFields('chat_create')!['chat_create'] as Map; + expect(create['backend'], 'claude'); + final model = gateway.lastFields('chat_model')!['chat_model'] as Map; + expect(model['session_id'], 'created'); + expect(model['provider'], 'anthropic'); + expect(model['model'], 'claude-opus-5-5'); + // Opened for work: beside the active chat, with the keyboard in it. + expect(runtime.openedForWork, contains('created')); + runtime.dispose(); + }); + + testWidgets('a harness the server no longer offers falls back to the ' + 'default, without the saved model', (tester) async { + SharedPreferences.setMockInitialValues({}); + final gateway = FakeChatGateway() + ..backendsHandler = () async => const { + 'chat_backends': ['opencode', 'codex'], + }; + await const OpenInChatPreferences( + harness: 'claude', + provider: 'anthropic', + model: 'claude-opus-5-5', + ).save(gateway); + final runtime = ChatRuntime(gateway: gateway); + + await tester.pumpWidget(const MaterialApp(home: Scaffold())); + await openReferenceInChat( + context: tester.element(find.byType(Scaffold)), + runtime: runtime, + selectChat: (_) {}, + directory: '/work/run', + title: 'Run #42: Build', + draft: 'About Pipelines run #42.', + ); + + final create = gateway.lastFields('chat_create')!['chat_create'] as Map; + // The default harness (OpenCode) is the request's default: not claude. + expect(create['backend'], anyOf(isNull, 'opencode')); + expect(gateway.lastFields('chat_model'), isNull); + runtime.dispose(); + }); + test('a run summary names its pipeline in name', () { final draft = runChatReference({ 'id': 7, diff --git a/app/test/features/chat/chat_open_for_work_test.dart b/app/test/features/chat/chat_open_for_work_test.dart new file mode 100644 index 00000000..35b67b5a --- /dev/null +++ b/app/test/features/chat/chat_open_for_work_test.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'new']) + {'id': id, 'title': 'Chat $id', 'directory': '/home/$id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +ChatWorkspaceController _workspace(WidgetTester tester) => tester + .widget(find.byType(ChatWorkspace, skipOffstage: false)) + .controller; + +void main() { + testWidgets('a chat opened for work goes beside the active chat, becomes ' + 'active and takes the keyboard', (tester) async { + final layout = ChatWorkspaceController()..open('a'); + SharedPreferences.setMockInitialValues({ + chatWorkspacePreferenceKey: layout.snapshot()!.encode(), + }); + tester.view.physicalSize = const Size(1600, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage([]); + addTearDown(gateway.close); + final runtime = ChatRuntime(gateway: gateway); + addTearDown(runtime.dispose); + + Widget screen(String? routed) => MaterialApp( + home: Scaffold( + body: ChatScreen( + gateway: gateway, + runtime: runtime, + persistWorkspace: true, + initialSessionId: routed, + onSessionSelected: (_) {}, + onBack: () {}, + ), + ), + ); + + await tester.pumpWidget(screen('a')); + await tester.pumpAndSettle(); + expect(_workspace(tester).panes.map((p) => p.sessionId), ['a']); + + runtime.openedForWork.add('new'); + await tester.pumpWidget(screen('new')); + await tester.pumpAndSettle(); + + final workspace = _workspace(tester); + expect(workspace.panes.map((p) => p.sessionId), ['a', 'new']); + expect(workspace.activePane?.sessionId, 'new'); + expect(runtime.openedForWork, isEmpty); + final composer = tester + .widgetList( + find.descendant( + of: find.byKey(const ValueKey('chat-composer-new')), + matching: find.byType(EditableText), + ), + ) + .first; + expect(composer.focusNode.hasFocus, isTrue); + }); + + testWidgets('an ordinary routed chat still opens in the active pane', ( + tester, + ) async { + final layout = ChatWorkspaceController()..open('a'); + SharedPreferences.setMockInitialValues({ + chatWorkspacePreferenceKey: layout.snapshot()!.encode(), + }); + tester.view.physicalSize = const Size(1600, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage([]); + addTearDown(gateway.close); + final runtime = ChatRuntime(gateway: gateway); + addTearDown(runtime.dispose); + Widget screen(String? routed) => MaterialApp( + home: Scaffold( + body: ChatScreen( + gateway: gateway, + runtime: runtime, + persistWorkspace: true, + initialSessionId: routed, + onSessionSelected: (_) {}, + onBack: () {}, + ), + ), + ); + await tester.pumpWidget(screen('a')); + await tester.pumpAndSettle(); + await tester.pumpWidget(screen('b')); + await tester.pumpAndSettle(); + expect(_workspace(tester).panes.map((p) => p.sessionId), ['b']); + }); +} diff --git a/app/test/features/settings/settings_open_in_chat_section_test.dart b/app/test/features/settings/settings_open_in_chat_section_test.dart new file mode 100644 index 00000000..6994048f --- /dev/null +++ b/app/test/features/settings/settings_open_in_chat_section_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/application/open_in_chat_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/settings/settings_open_in_chat_section.dart'; + +import '../chat/ui/sessions/fake_chat_gateway.dart'; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) async { + switch (type) { + case 'chat_backends': + return { + 'chat_backends': ['opencode', 'claude'], + }; + case 'chat_sessions': + return { + 'chat_sessions': [ + {'id': 'old', 'backend': 'claude', 'updated_at': '2026-01-01'}, + {'id': 'new', 'backend': 'claude', 'updated_at': '2026-02-01'}, + ], + }; + case 'chat_models': + final session = (fields['chat_query'] as Map)['session_id']; + return { + 'chat_models': [ + { + 'id': 'claude-opus-5-5', + 'provider': 'anthropic', + 'name': 'Opus from $session', + }, + ], + }; + } + return super.call(type, fields); + } +} + +void main() { + testWidgets('choosing a harness and model saves them for Open in chat', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({}); + final gateway = _Gateway(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SettingsOpenInChatSection(gateway: gateway), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Open in chat'), findsOneWidget); + + await tester.tap(find.byKey(const Key('open-in-chat-harness'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('claude').last); + await tester.pumpAndSettle(); + expect((await OpenInChatPreferences.load(gateway)).harness, 'claude'); + + // Models come from the harness's most recent chat. + await tester.tap(find.byKey(const ValueKey('open-in-chat-model-claude'))); + await tester.pumpAndSettle(); + expect(find.text('Opus from new'), findsWidgets); + await tester.tap(find.text('Opus from new').last); + await tester.pumpAndSettle(); + final saved = await OpenInChatPreferences.load(gateway); + expect(saved.provider, 'anthropic'); + expect(saved.model, 'claude-opus-5-5'); + }); +}