From 45f5323c75b6763a899f4637ed2a4aa45c45503a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 13:18:05 +0000 Subject: [PATCH] Keep phone chat back on the list Treat server-synced open workspace snapshots as pane membership only so they do not show or retain a phone chat page. Add regression coverage for repeated system, button, and predictive Back cycles with tiled and floating entries. --- .../features/chat/chat_screen_workspace.dart | 13 +- app/notes/phone-back-server-sync.md | 73 ++++ .../chat_phone_back_server_sync_test.dart | 342 ++++++++++++++++++ .../chat/chat_open_workspace_sync_test.dart | 5 + 4 files changed, 423 insertions(+), 10 deletions(-) create mode 100644 app/notes/phone-back-server-sync.md create mode 100644 app/test/application/chat_phone_back_server_sync_test.dart diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 65cea8d2..af5e2229 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -229,19 +229,12 @@ mixin _ChatScreenWorkspace on State { .firstOrNull; if (pane != null) _workspace.activate(pane.id); } - if (_workspace.paneCount == 0 && _workspaceVisible) _back(); } finally { _applyingServerWorkspace = false; } - // The first snapshot shows the server's chats as a restored layout does; - // later ones never pull this device into a chat another one opened. - if (first && _workspace.paneCount > 0 && !_workspaceVisible) { - setState(() { - _usedWorkspace = true; - _workspaceVisible = true; - }); - _publishWorkspaceRoute(); - } + // A snapshot only changes pane membership. It never shows the workspace, + // pushes a chat route or changes the view: on a phone the list stays the + // list until the user opens a chat. if (keepInitial) _syncOpenWorkspace(); } diff --git a/app/notes/phone-back-server-sync.md b/app/notes/phone-back-server-sync.md new file mode 100644 index 00000000..3d62ff8a --- /dev/null +++ b/app/notes/phone-back-server-sync.md @@ -0,0 +1,73 @@ +# Phone Back after server-synced open chats + +## Cause +`_applyOpenWorkspace` (`lib/features/chat/chat_screen_workspace.dart`) showed the +workspace on the first server snapshot that held panes: it set +`_workspaceVisible = true`, marked the Chat destination used, and published +`/chat/`. On a phone the first Back then only cleared the route to the +chat again, so the route stayed `/chat/` and the list reported +`handlesBack=true` before any chat was tapped. + +## Change +- `_applyOpenWorkspace` only changes pane membership (windows, panes, floating + state, active pane for a deep link). It no longer shows the workspace, sets + `_usedWorkspace` or publishes a route. +- A server snapshot that removes the last pane while a chat is shown no longer + calls `_back()`. Review must-fix (`chat_screen_workspace.dart`, the + `paneCount == 0 && _workspaceVisible` check) removed: that call changed the + route and view from a snapshot. The chat page stays as it was; Back from it + still returns to the list on the first press. + +## Tests +- `test/application/chat_phone_back_server_sync_test.dart` (new): 412x915 phone, + server holds two tiled chats, or one tiled plus one floating. Opens a tiled + chat from its row and presses Back 20 times each via `handlePopRoute`, the + BackButton tap and a predictive back gesture. After each Back asserts route + `/chat`, no thread, list rows present (including the floating chat's row), + and `setFrameworkHandlesBack(false)`. Before the fix the run failed with the + route still `/chat/a` after the first Back (observed in several cases). + A floating chat's row raises its window rather than opening a page (existing + behaviour; `ChatWorkspaceController.open` returns early for floating chats), + so the cycle opens only tiled chats. +- Same file, new test: a server snapshot that removes the open chat while its + page is shown leaves route `/chat/a` unchanged; the first system Back then + returns to the list with its rows and `setFrameworkHandlesBack(false)`. It + fails when the removed `_back()` call is put back (checked). +- `test/features/chat/chat_open_workspace_sync_test.dart`: "rebinding to another + server disposes the old sync" depended on the first snapshot showing the + workspace on a wide layout. It now taps each server's chat row before + checking panes; its pane and write assertions are unchanged. + +## Results (focused, via tool/memwatch/full.sh) +- Two changed test files (chat_phone_back_server_sync, chat_open_workspace_sync): + 10 passed, 0 failed. +- Related files (chat_phone_back_server_sync, chat_registration, chat_wide_back, + chat_scroll_back, list_detail_consistency, chat_floating_pane, + chat_open_workspace_sync, chat_pane_move, chat_workspace_restore, + chat_open_workspace_controller, chat_open_workspace_gateway), after the + must-fix: 66 passed, 4 failed. The 4 failures are all in `test/application/chat_registration_test.dart` + and also fail with the fix reverted (same names): + - mobile Chats retap reopens the retained multi-pane workspace after tabs + - a folded workspace rejects paste while retained behind the list + - mobile Chats retap stays on list with no history or a removed chat + - Chats retap restores a boot deep link after folding and Back + These are pre-existing on this HEAD; they are phone chat-list tests, so they + cannot confirm this change's phone behaviour. Not investigated further. +- `tool/analyze.sh`: clean (run after the focused tests). +- `dart format --set-exit-if-changed` clean on the changed Dart files. + +## Affected states (not captured here; ui-review owns capture) +- Phone, Chat list after server sync with 2 tiled or 1 tiled + 1 floating: list + stays on screen; Back from a chat returns to it on the first press. +- Wide layout, server holds open chats and no local layout: the list shows + without the tiling until a chat is opened from its row. Previously the + server's panes appeared at once. Desktop behaviour change, see limitations. + +## Limitations +- Wide/desktop: a new device no longer shows the server's open chats beside + the list on first load; they stay retained and appear when a chat is opened. +- Server removes the open chat while its page is shown: the page stays with + route `/chat/` and no pane until the user presses Back. The snapshot no + longer changes the view, so this empty page is left for the user to dismiss. + Whether it should show differently (e.g. an empty state) is open for review. +- Not built or captured; no device run. diff --git a/app/test/application/chat_phone_back_server_sync_test.dart b/app/test/application/chat_phone_back_server_sync_test.dart new file mode 100644 index 00000000..16c97d0a --- /dev/null +++ b/app/test/application/chat_phone_back_server_sync_test.dart @@ -0,0 +1,342 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; +import 'chat_registration_test.dart' show webServer; + +/// Answers the requests the app sends with plausible replies, holding the +/// server's open-chat set in [_entries] like the real `chat_open_workspace`. +class _Server { + _Server(this.channel, {required List entries}) + : _entries = entries, + _revision = entries.isEmpty ? 0 : 5; + + final FakeChannel channel; + final _answered = {}; + final types = {}; + int _revision; + List _entries; + + /// Another device (or the server) changed the open-chat set: pushes it. + void change(List entries) { + _entries = entries; + _revision++; + channel.incoming.add( + jsonEncode({ + 'type': 'chat_open_workspace_changed', + 'chat_open_workspace': {'revision': _revision, 'entries': _entries}, + }), + ); + } + + void answer() { + for (final raw in channel.outgoing.toList()) { + final m = jsonDecode(raw as String) as Map; + final id = m['id']; + if (id == null || !_answered.add(id)) continue; + final type = '${m['type']}'; + types.add(type); + channel.incoming.add(jsonEncode(_reply(type, id, m))); + } + } + + Map _reply(String type, Object? id, Map m) { + switch (type) { + case 'chat_sessions': + return { + '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', + }, + ], + }; + case 'chat_shells': + return {'id': id, 'type': type, 'chat_shells': const []}; + case 'chat_shell_runs': + return {'id': id, 'type': type, 'chat_shell_runs': const []}; + case 'chat_automations': + return { + 'id': id, + 'type': type, + 'chat_automations': { + 'session_id': m['chat_query']?['session_id'], + 'provider': 'fixture', + 'status': 'unavailable', + }, + }; + case 'chat_messages': + return { + 'id': id, + 'type': 'chat_history', + 'chat_history': { + 'messages': [ + for (var i = 0; i < 4; i++) + { + 'id': 'm$i', + 'role': i.isEven ? 'user' : 'assistant', + 'parts': [ + {'type': 'text', 'text': 'Message $i'}, + ], + }, + ], + 'next_cursor': '', + 'has_more': false, + }, + }; + case 'chat_open_workspace': + final write = m['chat_open_workspace_request'] as Map?; + if (write != null) { + _revision++; + _entries = write['entries'] as List; + } + return { + 'id': id, + 'type': type, + 'chat_open_workspace': {'revision': _revision, 'entries': _entries}, + }; + default: + return {'id': id, 'type': type}; + } + } +} + +enum _BackVia { system, button, predictive } + +/// Pumps [d] in 16 ms steps while answering the app's requests. +Future _run(WidgetTester tester, _Server server, Duration d) async { + for (var t = 0; t < d.inMilliseconds; t += 16) { + server.answer(); + await tester.pump(const Duration(milliseconds: 16)); + } + server.answer(); +} + +Future _gesture(WidgetTester tester, String method, [double? progress]) => + tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/backgesture', + const StandardMethodCodec().encodeMethodCall( + MethodCall( + method, + progress == null + ? null + : { + 'touchOffset': [5 + 300 * progress, 400], + 'progress': progress, + 'swipeEdge': 0, + }, + ), + ), + (_) {}, + ); + +/// Presses Back from the open chat through [via] and waits for the list. +Future _back(WidgetTester tester, _Server server, _BackVia via) async { + switch (via) { + case _BackVia.system: + await tester.binding.handlePopRoute(); + case _BackVia.button: + expect(find.byType(BackButton), findsWidgets); + await tester.tap(find.byType(BackButton).last); + case _BackVia.predictive: + await _gesture(tester, 'startBackGesture', 0); + for (var p = 1; p <= 6; p++) { + await _gesture(tester, 'updateBackGestureProgress', p / 10); + await tester.pump(const Duration(milliseconds: 16)); + } + await _gesture(tester, 'commitBackGesture'); + } + await _run(tester, server, const Duration(milliseconds: 900)); +} + +void main() { + // The server holds two tiled chats, or one tiled and one floating chat. + // Phone Back from an open chat must return to the list on every press. + final layouts = >{ + 'two tiled': [ + {'session_id': 'a'}, + {'session_id': 'b'}, + ], + 'one tiled and one floating': [ + {'session_id': 'a'}, + {'session_id': 'c', 'floating': true}, + ], + }; + for (final layout in layouts.entries) { + for (final via in _BackVia.values) { + testWidgets('phone Back from a chat returns to the list 20 times ' + 'via ${via.name}, server holding ${layout.key}', (tester) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(412, 915); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + bool? handlesBack; + final exits = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'SystemNavigator.setFrameworkHandlesBack') { + handlesBack = call.arguments as bool; + } + if (call.method == 'SystemNavigator.pop') exits.add(call.method); + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = _Server(channel, entries: layout.value); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), + ); + addTearDown(provider.dispose); + await tester.pumpWidget( + PipelinesApp( + androidSupported: false, + server: webServer(), + client: client, + routeInformationProvider: provider, + ), + ); + tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.resumed, + ); + await _run(tester, server, const Duration(seconds: 2)); + + // The list alone: no chat is open, so it does not take Back. + expect(provider.value.uri.path, '/chat'); + expect(handlesBack, isFalse); + expect(find.text('Chat a'), findsWidgets); + expect(find.text('Chat b'), findsWidgets); + expect(find.text('Chat c'), findsWidgets); + + // Tiled chats are opened from their rows. A floating chat's row + // raises its window instead of opening a page, so it is only checked + // to stay listed. + const tiled = ['a', 'b']; + for (var i = 0; i < 20; i++) { + final chat = tiled[i % tiled.length]; + await tester.tap(find.text('Chat $chat').first); + await _run(tester, server, const Duration(milliseconds: 900)); + expect(provider.value.uri.path, '/chat/$chat', reason: 'cycle $i'); + expect( + find.byType(ChatThreadView), + findsWidgets, + reason: 'cycle $i open', + ); + + await _back(tester, server, via); + expect(provider.value.uri.path, '/chat', reason: 'back $i'); + expect(handlesBack, isFalse, reason: 'back $i'); + expect(find.byType(ChatThreadView), findsNothing, reason: 'back $i'); + expect(find.text('Chat a'), findsWidgets, reason: 'back $i'); + expect(find.text('Chat b'), findsWidgets, reason: 'back $i'); + expect(find.text('Chat c'), findsWidgets, reason: 'back $i'); + expect(tester.takeException(), isNull, reason: 'back $i'); + } + expect(exits, isEmpty); + expect(server.types, contains('chat_open_workspace')); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); + } + } + + testWidgets('a server snapshot that removes the open chat leaves the phone ' + 'view alone, and Back still returns to the list on the first press', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(412, 915); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + bool? handlesBack; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'SystemNavigator.setFrameworkHandlesBack') { + handlesBack = call.arguments as bool; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final server = _Server( + channel, + entries: const [ + {'session_id': 'a'}, + ], + ); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), + ); + addTearDown(provider.dispose); + await tester.pumpWidget( + PipelinesApp( + androidSupported: false, + server: webServer(), + client: client, + routeInformationProvider: provider, + ), + ); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await _run(tester, server, const Duration(seconds: 2)); + + // The server's chat alone does not open a page or take Back. + expect(provider.value.uri.path, '/chat'); + expect(handlesBack, isFalse); + expect(find.byType(ChatThreadView), findsNothing); + + await tester.tap(find.text('Chat a').first); + await _run(tester, server, const Duration(milliseconds: 900)); + expect(provider.value.uri.path, '/chat/a'); + + // The server drops the chat that is showing. The snapshot must not change + // the view, so the route and page stay as they were. + server.change(const []); + await _run(tester, server, const Duration(milliseconds: 900)); + expect(provider.value.uri.path, '/chat/a'); + expect(tester.takeException(), isNull); + + // The first Back still returns to the list, with its rows present. + await tester.binding.handlePopRoute(); + await _run(tester, server, const Duration(milliseconds: 900)); + expect(provider.value.uri.path, '/chat'); + expect(handlesBack, isFalse); + expect(find.text('Chat a'), findsWidgets); + expect(find.text('Chat b'), findsWidgets); + expect(tester.takeException(), isNull); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }); +} diff --git a/app/test/features/chat/chat_open_workspace_sync_test.dart b/app/test/features/chat/chat_open_workspace_sync_test.dart index 8b7c1379..7fab1a6e 100644 --- a/app/test/features/chat/chat_open_workspace_sync_test.dart +++ b/app/test/features/chat/chat_open_workspace_sync_test.dart @@ -182,8 +182,13 @@ void main() { final first = _server('server-a', revision: 1, open: ['a']); final second = _server('server-b', revision: 1, open: ['c']); await _mount(tester, first); + // A server snapshot only changes membership; the user opens the chat. + await tester.tap(find.text('Chat a').first); + await tester.pumpAndSettle(); expect(_open(tester), ['a']); await _mount(tester, second); + await tester.tap(find.text('Chat c').first); + await tester.pumpAndSettle(); expect(_open(tester), ['c']); // The old server's pushes no longer reach this screen.