From 03983cfd1ffc34e803fecdd09f41fadb7f29f49e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 17:28:47 +0000 Subject: [PATCH] Detached chat: read the chat again once its machine connects, and follow the main window's look A detached chat window read the chat list once, before any saved machine had connected, and never again; its pane also did not rebuild when the runtime adopted a row. Without the row the header showed a bare "Chat" with no folder or model, the window was named by the session id, and the chat's colour (bar tint, focus ring, prompt bar) was missing. The window now re-reads the list on each connection change and rebuilds on the runtime, as the Chat destination does. It also re-reads the stored design and font on the browser's storage event and on coming to the front, so a Settings change in the main window follows. Co-Authored-By: Claude Opus 5.5 --- .../application/detached/detached_app.dart | 7 + .../application/detached/detached_chat.dart | 25 ++- .../detached/detached_platform.dart | 5 + .../detached/detached_platform_web.dart | 16 ++ .../detached/detached_preferences.dart | 64 ++++++++ app/lib/ui/theme/app_font_controller.dart | 10 +- .../detached/detached_chat_header_test.dart | 142 ++++++++++++++++++ .../detached/detached_fixtures.dart | 23 ++- .../detached/detached_preferences_test.dart | 67 +++++++++ app/tool/search_selection_probe_entry.dart | 8 + 10 files changed, 356 insertions(+), 11 deletions(-) create mode 100644 app/lib/application/detached/detached_preferences.dart create mode 100644 app/test/application/detached/detached_chat_header_test.dart create mode 100644 app/test/application/detached/detached_preferences_test.dart diff --git a/app/lib/application/detached/detached_app.dart b/app/lib/application/detached/detached_app.dart index 46927fa1..7dd3126d 100644 --- a/app/lib/application/detached/detached_app.dart +++ b/app/lib/application/detached/detached_app.dart @@ -22,6 +22,7 @@ import '../server_endpoint.dart'; import 'detached_chat.dart'; import 'detached_diff.dart'; import 'detached_platform.dart'; +import 'detached_preferences.dart'; import 'detached_route.dart'; import 'detached_terminal.dart'; import 'detached_window_body.dart'; @@ -72,6 +73,10 @@ class _DetachedWindowAppState extends State { final _ready = ValueNotifier(false); final _sync = ValueNotifier(0); AppTerminals? _terminals; + // The design and font follow the main window's Settings. + late final _preferences = DetachedPreferencesFollower( + changes: _platform.preferencesChanged, + ); late final DetachedWindowControls _controls = DetachedWindowControls( ready: _ready, sync: _sync, @@ -108,6 +113,7 @@ class _DetachedWindowAppState extends State { layout: TerminalLayout.instance, ); } + _preferences.start(); unawaited(_session.start()); } @@ -116,6 +122,7 @@ class _DetachedWindowAppState extends State { _session.removeListener(_connectionChanged); widget.chatPool?.removeListener(_connectionChanged); _terminals?.dispose(); + _preferences.dispose(); _session.dispose(); _title.dispose(); _ready.dispose(); diff --git a/app/lib/application/detached/detached_chat.dart b/app/lib/application/detached/detached_chat.dart index 2bc3dfaa..37e63326 100644 --- a/app/lib/application/detached/detached_chat.dart +++ b/app/lib/application/detached/detached_chat.dart @@ -52,6 +52,7 @@ class _DetachedChatState extends State { _runtime.sessions.addListener(_rowsChanged); _runtime.addSessionReplacedListener(_replacedElsewhere); widget.window.ready.addListener(_rowsChanged); + widget.window.sync.addListener(_reconnected); _rowsChanged(); _runtime.composerFocus.request(_sessionId); _retitle(); @@ -67,11 +68,16 @@ class _DetachedChatState extends State { oldWidget.window.ready.removeListener(_rowsChanged); widget.window.ready.addListener(_rowsChanged); } + if (oldWidget.window.sync != widget.window.sync) { + oldWidget.window.sync.removeListener(_reconnected); + widget.window.sync.addListener(_reconnected); + } } @override void dispose() { widget.window.ready.removeListener(_rowsChanged); + widget.window.sync.removeListener(_reconnected); _runtime.removeListener(_retitle); _runtime.sessions.removeListener(_rowsChanged); _runtime.removeSessionReplacedListener(_replacedElsewhere); @@ -83,7 +89,7 @@ class _DetachedChatState extends State { void _retitle() => widget.window.setTitle(_runtime.titleFor(_sessionId)); /// The pane's title, model and mode come from the session list, read once - /// connected (and again on every reconnect, see [build]). + /// connected (and again on every reconnect, see [_reconnected]). void _rowsChanged() { if (!widget.window.ready.value) return; final sessions = _runtime.sessions; @@ -99,6 +105,15 @@ class _DetachedChatState extends State { }); } + /// A machine connected (or the connection was replaced): the list is read + /// again, as the Chat list does on a new sync token. A window opened before + /// its machine connects has no row yet (the first read finds no machine), + /// and without it the header has no title, folder or model and the chat + /// none of its colour. + void _reconnected() { + if (widget.window.ready.value) unawaited(_runtime.sessions.refresh()); + } + /// `/new` here, or on another device: the window follows the new session. void _follow(String previousId, JsonMap session, String notice) { final id = '${session['id'] ?? ''}'; @@ -119,7 +134,13 @@ class _DetachedChatState extends State { @override Widget build(BuildContext context) => ListenableBuilder( - listenable: Listenable.merge([widget.window.ready, widget.window.sync]), + // The runtime too, as the Chat destination rebuilds on it: the row it + // adopts (title, folder, model, colour) reaches the header only then. + listenable: Listenable.merge([ + widget.window.ready, + widget.window.sync, + _runtime, + ]), builder: (context, _) { if (!widget.window.ready.value) return const DetachedConnecting(); final sessionId = _sessionId; diff --git a/app/lib/application/detached/detached_platform.dart b/app/lib/application/detached/detached_platform.dart index 496ae568..1124bd33 100644 --- a/app/lib/application/detached/detached_platform.dart +++ b/app/lib/application/detached/detached_platform.dart @@ -55,6 +55,11 @@ abstract class DetachedPlatform { /// Messages the detached windows send to this (main) window. Stream get messages; + /// Raised when another window of this app changed the device's stored + /// preferences (the browser's `storage` event); none on a desktop, whose + /// windows are separate processes. + Stream get preferencesChanged => const Stream.empty(); + /// Keeps [json] for the window that will ask for [token]. Future put(String token, String json); diff --git a/app/lib/application/detached/detached_platform_web.dart b/app/lib/application/detached/detached_platform_web.dart index 6b0fd169..ec42cdae 100644 --- a/app/lib/application/detached/detached_platform_web.dart +++ b/app/lib/application/detached/detached_platform_web.dart @@ -87,6 +87,22 @@ class WebDetachedPlatform extends DetachedPlatform { return controller.stream; } + /// `shared_preferences` keeps its values under this prefix in + /// `localStorage`; another window's write raises `storage` here. + @override + Stream get preferencesChanged { + late final StreamController controller; + final listener = ((web.StorageEvent event) { + final key = event.key; + if (key == null || key.startsWith('flutter.')) controller.add(null); + }).toJS; + controller = StreamController( + onListen: () => web.window.addEventListener('storage', listener), + onCancel: () => web.window.removeEventListener('storage', listener), + ); + return controller.stream; + } + static String _key(String token) => 'pipelines.detached.$token'; @override diff --git a/app/lib/application/detached/detached_preferences.dart b/app/lib/application/detached/detached_preferences.dart new file mode 100644 index 00000000..01a83418 --- /dev/null +++ b/app/lib/application/detached/detached_preferences.dart @@ -0,0 +1,64 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../ui/theme/app_design_controller.dart'; +import '../../ui/theme/app_font_controller.dart'; + +/// Keeps a detached window's look in step with the main window's. +/// +/// Both read the design and the font from the device's preferences at +/// launch, but each window is its own app instance: a choice made later in +/// the main window's Settings reaches this one only when it reads them +/// again. It does so on [changes] (the browser's `storage` event, which +/// another window of the origin raises as it writes) and whenever the window +/// comes back to the front (a desktop process has no such event). +class DetachedPreferencesFollower with WidgetsBindingObserver { + DetachedPreferencesFollower({ + required this._changes, + AppDesignController? designs, + AppFontController? fonts, + Future Function()? reload, + }) : _designs = designs ?? AppDesignController.instance, + _fonts = fonts ?? AppFontController.instance, + _reload = reload ?? _reloadSharedPreferences; + + final Stream _changes; + final AppDesignController _designs; + final AppFontController _fonts; + final Future Function() _reload; + StreamSubscription? _subscription; + + void start() { + WidgetsBinding.instance.addObserver(this); + _subscription = _changes.listen((_) => unawaited(follow())); + } + + void dispose() { + WidgetsBinding.instance.removeObserver(this); + unawaited(_subscription?.cancel()); + _subscription = null; + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) unawaited(follow()); + } + + /// Reads the stored design and font again and applies any change. + Future follow() async { + await _reload(); + await Future.wait([_designs.restore(), _fonts.restore()]); + } + + /// The preferences are cached per app instance; another window's writes + /// show only after a reload. + static Future _reloadSharedPreferences() async { + try { + await (await SharedPreferences.getInstance()).reload(); + } catch (_) { + // An unreadable store keeps the look this window has. + } + } +} diff --git a/app/lib/ui/theme/app_font_controller.dart b/app/lib/ui/theme/app_font_controller.dart index f4d290b3..ce4d45d8 100644 --- a/app/lib/ui/theme/app_font_controller.dart +++ b/app/lib/ui/theme/app_font_controller.dart @@ -82,12 +82,18 @@ class AppFontController extends ChangeNotifier { /// Reads the stored choice and starts loading it. With [wait], returns once /// it is applied or after [wait], whichever is first; a slower load still /// applies when it finishes. + /// + /// Read again later (a detached window following the main window's + /// choice), a stored system font returns the theme to it; an id this + /// device cannot resolve keeps the current font. Future restore({Duration? wait}) async { final id = await _store.load(); - if (id == null || id == AppFont.system.id) return; + if (id == null) return; final font = await _resolve(id); - if (font == AppFont.system || font == _selected) return; + if (font == _selected) return; + if (font == AppFont.system && id != AppFont.system.id) return; _selected = font; + _loadFailed = null; notifyListeners(); final applying = _apply(font); if (wait == null) return applying; diff --git a/app/test/application/detached/detached_chat_header_test.dart b/app/test/application/detached/detached_chat_header_test.dart new file mode 100644 index 00000000..3b1cf716 --- /dev/null +++ b/app/test/application/detached/detached_chat_header_test.dart @@ -0,0 +1,142 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/detached/detached_app.dart'; +import 'package:pipelines_app/application/detached/detached_chat.dart'; +import 'package:pipelines_app/application/detached/detached_route.dart'; +import 'package:pipelines_app/application/detached/detached_window_body.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_bar_tint.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_header.dart'; +import 'package:pipelines_app/features/terminal/terminal_layout.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_controller.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../core/transport/pipelines_client_test.dart' show FakeChannel; +import '../chat_registration_test.dart' show webServer; +import 'detached_fixtures.dart'; + +Future _run(WidgetTester tester, ChatServer server, Duration d) async { + for (var t = 0; t < d.inMilliseconds; t += 16) { + server.answer(); + await tester.pump(const Duration(milliseconds: 16)); + } + server.answer(); +} + +ChatThreadHeader _header(WidgetTester tester) => tester + .widget(find.byKey(const Key('chat-thread-header'))); + +void main() { + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + void sized(WidgetTester tester) { + tester.view.physicalSize = const Size(1200, 860); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + addTearDown(() => TerminalLayout.instance.persist = true); + } + + testWidgets('a chat opened before its machine connects is read again on ' + 'connect: the header names it and wears its colour', (tester) async { + sized(tester); + final channel = FakeChannel()..readyCompleter.complete(); + final server = ChatServer(channel) + ..listsChats = false + ..colors['a'] = 'teal'; + final client = PipelinesClient(channelFactory: (_) => channel); + await client.connect(Uri.parse('ws://fixture/connect')); + final ready = ValueNotifier(true); + final sync = ValueNotifier(0); + final titles = []; + addTearDown(ready.dispose); + addTearDown(sync.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: DetachedChat( + sessionId: 'a', + gateway: client, + window: DetachedWindowControls( + ready: ready, + sync: sync, + setTitle: titles.add, + close: () {}, + bringBackItem: (_, _, _, _) {}, + ), + ), + ), + ), + ); + await _run(tester, server, const Duration(milliseconds: 600)); + // The first list found no machine: no row, so no name and no colour. + expect(_header(tester).title, isEmpty); + expect(_header(tester).chatColor, isNull); + expect(titles.last, 'a'); + + // The machine connects: the pool's revision (the window's sync) moves. + server.listsChats = true; + sync.value = 1; + await _run(tester, server, const Duration(milliseconds: 600)); + expect(_header(tester).title, 'Chat a'); + expect(_header(tester).folder, 'demo'); + expect(_header(tester).chatColor, 'teal'); + expect(find.byKey(const Key('chat-bar-tint')), findsOneWidget); + expect(titles.last, 'Chat a'); + + // A rename and a new colour from the main window (or another device) + // arrive live. + channel.incoming.add( + jsonEncode({ + 'type': 'chat_session_changed', + 'chat_session': {'id': 'a', 'title': 'Renamed', 'color': 'blue'}, + }), + ); + await _run(tester, server, const Duration(milliseconds: 300)); + expect(_header(tester).chatColor, 'blue'); + expect(_header(tester).title, 'Renamed'); + expect(titles.last, 'Renamed'); + await tester.pumpWidget(const SizedBox.shrink()); + client.dispose(); + }); + + testWidgets('the detached window uses the main window\'s design and the ' + 'chat\'s colour', (tester) async { + sized(tester); + final designs = AppDesignController.instance; + final before = designs.design; + await designs.select(AppDesign.terminal); + addTearDown(() => designs.select(before)); + final channel = FakeChannel()..readyCompleter.complete(); + final server = ChatServer(channel)..colors['a'] = 'amber'; + await tester.pumpWidget( + DetachedWindowApp( + route: DetachedRoute.chat('a')!, + server: webServer(), + client: PipelinesClient(channelFactory: (_) => channel), + platform: FakeDetachedPlatform(), + ), + ); + await _run(tester, server, const Duration(milliseconds: 900)); + final app = tester.widget(find.byType(MaterialApp)); + final terminal = AppDesign.terminal.light(); + expect(app.theme!.colorScheme, terminal.colorScheme); + expect( + app.theme!.textTheme.bodyMedium?.fontFamily, + terminal.textTheme.bodyMedium?.fontFamily, + ); + expect(app.title, 'Chat a · Pipelines'); + final header = _header(tester); + expect(header.title, 'Chat a'); + expect(header.chatColor, 'amber'); + final context = tester.element(find.byKey(const Key('chat-thread-header'))); + final tint = tester + .widget(find.byKey(const Key('chat-bar-tint'))) + .tint; + expect(tint, chatBarTintOf(context, 'amber')); + }); +} diff --git a/app/test/application/detached/detached_fixtures.dart b/app/test/application/detached/detached_fixtures.dart index ae35ac26..5a6fb2ba 100644 --- a/app/test/application/detached/detached_fixtures.dart +++ b/app/test/application/detached/detached_fixtures.dart @@ -107,6 +107,13 @@ class ChatServer { final FakeChannel channel; final _answered = {}; final requests = >[]; + + /// False answers the chat list with no rows, as a pool whose machines + /// have not connected yet does. + bool listsChats = true; + + /// Each chat's shared colour, by id. + final colors = {}; List _entries; int _revision = 1; @@ -135,13 +142,15 @@ class ChatServer { 'id': id, 'type': type, 'chat_sessions': [ - for (final s in const ['a', 'b', 'c']) - { - 'id': s, - 'title': 'Chat $s', - 'directory': '/workspace/demo', - 'updated_at': '2026-11-12T10:00:00Z', - }, + if (listsChats) + for (final s in const ['a', 'b', 'c']) + { + 'id': s, + 'title': 'Chat $s', + 'directory': '/workspace/demo', + 'updated_at': '2026-11-12T10:00:00Z', + 'color': ?colors[s], + }, ], }; case 'chat_messages': diff --git a/app/test/application/detached/detached_preferences_test.dart b/app/test/application/detached/detached_preferences_test.dart new file mode 100644 index 00000000..e3119427 --- /dev/null +++ b/app/test/application/detached/detached_preferences_test.dart @@ -0,0 +1,67 @@ +import 'dart:async'; +import 'dart:ui'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/detached/detached_preferences.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_controller.dart'; +import 'package:pipelines_app/ui/theme/app_font.dart'; +import 'package:pipelines_app/ui/theme/app_font_controller.dart'; +import 'package:pipelines_app/ui/theme/app_font_store.dart'; + +void main() { + testWidgets('the design and font chosen in the main window follow into a ' + 'detached window, on a storage event and on coming to the front', ( + tester, + ) async { + final designStore = MemoryAppDesignStore(); + final fontStore = MemoryAppFontStore(); + final designs = AppDesignController(store: designStore); + final fonts = AppFontController(store: fontStore, loader: (_, _) async {}); + final changes = StreamController.broadcast(); + var reloads = 0; + final follower = DetachedPreferencesFollower( + changes: changes.stream, + designs: designs, + fonts: fonts, + reload: () async => reloads++, + )..start(); + addTearDown(() { + follower.dispose(); + unawaited(changes.close()); + }); + + // Another window stores the Terminal design and a font. + designStore.id = AppDesign.terminal.id; + fontStore.id = AppFont.inter.id; + changes.add(null); + await tester.pumpAndSettle(); + expect(reloads, 1); + expect(designs.design, AppDesign.terminal); + expect(fonts.selected, AppFont.inter); + expect(fonts.family, AppFont.inter.family); + + // Back to the defaults, seen when this window comes to the front. + designStore.id = AppDesign.standard.id; + fontStore.id = AppFont.system.id; + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pumpAndSettle(); + expect(reloads, 2); + expect(designs.design, AppDesign.standard); + expect(fonts.selected, AppFont.system); + expect(fonts.family, isNull); + // Following never writes the choice back. + expect(designStore.id, AppDesign.standard.id); + }); + + test('a font id this device cannot resolve keeps the current font', () async { + final store = MemoryAppFontStore(AppFont.inter.id); + final fonts = AppFontController(store: store, loader: (_, _) async {}); + await fonts.restore(); + expect(fonts.selected, AppFont.inter); + store.id = 'custom-unknown'; + await fonts.restore(); + expect(fonts.selected, AppFont.inter); + }); +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 2b19f3ec..4ca65ac2 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -975,6 +975,8 @@ class _FixtureSink implements WebSocketSink { /// `?speech=fake` reads replies aloud with a scripted engine, one word per /// `?speechStep=` ms (tool/probe_speech_fixture.dart); /// `?design=terminal` chooses that app design (Settings → Design); +/// `?poolDelay=` (with `?federated=1`) connects each machine that +/// much later, as a real server does (a detached chat window's first list); /// `?theme=dark` / `?theme=light` pins the platform brightness the app's /// `ThemeMode.system` follows (omitted: the browser's color scheme). /// @@ -1077,6 +1079,12 @@ Future main() async { ? ChatServerPool( machines, connect: (machine) async { + // `poolDelay=`: each machine connects that much later, as a + // real server does, so the first chat list finds none connected. + final delay = int.tryParse(params['poolDelay'] ?? '') ?? 0; + if (delay > 0) { + await Future.delayed(Duration(milliseconds: delay)); + } final client = PipelinesClient( channelFactory: (_) => _FixtureChannel( hostname: machine.id == 'mac' ? 'tank' : 'linux-box',