From 9408ec153175f09831b016df4e766efb34139824 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 7 Nov 2026 22:36:06 +0000 Subject: [PATCH] Restore mobile Chats workspace on tab retap --- app/lib/application/app_route.dart | 21 ++ app/lib/application/chat_destination.dart | 6 + app/lib/application/pipelines_app.dart | 24 ++ app/lib/features/chat/screen.dart | 23 ++ app/notes/chat-retap.md | 35 ++ app/test/application/app_route_test.dart | 29 ++ .../application/chat_registration_test.dart | 302 ++++++++++++++++++ 7 files changed, 440 insertions(+) create mode 100644 app/notes/chat-retap.md diff --git a/app/lib/application/app_route.dart b/app/lib/application/app_route.dart index 8b83c29a..730f7f51 100644 --- a/app/lib/application/app_route.dart +++ b/app/lib/application/app_route.dart @@ -176,6 +176,27 @@ class AppRoute { String toString() => path; } +/// Chooses what an already-selected Chats tab should show when it is tapped +/// again. A detail route is left alone; only the list can use the retained +/// workspace route, and an absent/invalid retained route stays at the list. +AppRoute? chatRouteForRetap( + AppRoute current, + AppRoute? retainedWorkspace, { + bool Function(String sessionId)? isValidSession, +}) { + if (current.kind != AppRouteKind.chat || current.chatSessionId != null) { + return current.kind == AppRouteKind.chat ? current : null; + } + final retained = retainedWorkspace; + return retained != null && + retained.kind == AppRouteKind.chat && + retained.chatSessionId != null && + retained.chatSessionId!.isNotEmpty && + (isValidSession == null || isValidSession(retained.chatSessionId!)) + ? retained + : null; +} + /// `AppRoute.run(3)` reads better than a constructor named after a field. class _RunRouteFactory { const _RunRouteFactory(); diff --git a/app/lib/application/chat_destination.dart b/app/lib/application/chat_destination.dart index bf0422a0..834dd62d 100644 --- a/app/lib/application/chat_destination.dart +++ b/app/lib/application/chat_destination.dart @@ -21,6 +21,8 @@ class ChatDestination extends StatelessWidget { this.initialSessionId, this.onSessionSelected, this.onBack, + this.onWorkspaceEmpty, + this.onAvailableSessionsChanged, }); final AppSession session; @@ -28,6 +30,8 @@ class ChatDestination extends StatelessWidget { final String? initialSessionId; final ValueChanged? onSessionSelected; final VoidCallback? onBack; + final VoidCallback? onWorkspaceEmpty; + final ValueChanged>? onAvailableSessionsChanged; @override Widget build(BuildContext context) => AnimatedBuilder( @@ -70,5 +74,7 @@ class ChatDestination extends StatelessWidget { syncToken: session.connectionEpoch, onSessionSelected: onSessionSelected, onBack: onBack, + onWorkspaceEmpty: onWorkspaceEmpty, + onAvailableSessionsChanged: onAvailableSessionsChanged, ); } diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index df666c97..746ab006 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -414,10 +414,23 @@ class _PipelinesAppState extends State /// The last route each tab showed, so switching tabs returns to where the /// operator left it; tapping the open tab again goes to its root. final Map _tabRoutes = {}; + AppRoute? _chatWorkspaceRoute; + Set? _availableChatSessionIds; void _selectDestination(AppDestination destination) { final current = _destinationOf(_delegate.shellRoute.kind); final last = _tabRoutes[destination]; + if (destination == AppDestination.chat && current == destination) { + final reopened = chatRouteForRetap( + _delegate.shellRoute, + _chatWorkspaceRoute, + isValidSession: (id) => + _availableChatSessionIds == null || + _availableChatSessionIds!.contains(id), + ); + _delegate.goTo(reopened ?? _routeOf(destination)); + return; + } _delegate.goTo( destination == current || last == null ? _routeOf(destination) : last, ); @@ -426,6 +439,9 @@ class _PipelinesAppState extends State void _routeChanged() { final shown = _delegate.shellRoute; _tabRoutes[_destinationOf(shown.kind)] = shown; + if (shown.kind == AppRouteKind.chat && shown.chatSessionId != null) { + _chatWorkspaceRoute = shown; + } final pending = _pendingRunSearch; if (!mounted || pending == null) return; final route = _delegate.shellRoute; @@ -562,6 +578,14 @@ class _PipelinesAppState extends State initialSessionId: chatRoute.chatSessionId, onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)), onBack: () => _delegate.goTo(AppRoute.chat), + onWorkspaceEmpty: () => _chatWorkspaceRoute = null, + onAvailableSessionsChanged: (ids) { + _availableChatSessionIds = ids; + final retained = _chatWorkspaceRoute?.chatSessionId; + if (retained != null && !ids.contains(retained)) { + _chatWorkspaceRoute = null; + } + }, ), // Search is the fourth tab; a result opens its destination. AppDestination.search: (_) => SearchDestination( diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 6520eeaf..c4ae03c0 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -59,6 +59,8 @@ class ChatScreen extends StatefulWidget { this.syncToken = 0, this.onSessionSelected, this.onBack, + this.onWorkspaceEmpty, + this.onAvailableSessionsChanged, this.persistWorkspace = false, }); @@ -74,6 +76,8 @@ class ChatScreen extends StatefulWidget { final ValueChanged? onSessionSelected; final VoidCallback? onBack; + final VoidCallback? onWorkspaceEmpty; + final ValueChanged>? onAvailableSessionsChanged; @override State createState() => _ChatScreenState(); @@ -157,6 +161,8 @@ class _ChatScreenState extends State // Seen from now on, so the press that chooses the first chat counts. LastPointerKind.instance; _sessions.addListener(_nextChanged); + _sessions.addListener(_availableSessionsChanged); + _availableSessionsChanged(); _folds.addListener(_nextChanged); } @@ -174,6 +180,15 @@ class _ChatScreenState extends State if (next != null) _openBySelection(next); } + void _availableSessionsChanged() { + if (!mounted || _sessions.loading) return; + widget.onAvailableSessionsChanged?.call({ + for (final row in _sessions.sessions) + if (row['closed_at'] == null && row['closed'] != true) + '${row['id'] ?? ''}', + }); + } + void _nextChanged() { if (!mounted) return; final id = _selected; @@ -307,6 +322,11 @@ class _ChatScreenState extends State /// the list's own build. void _adoptRows(List rows) { if (!mounted) return; + widget.onAvailableSessionsChanged?.call({ + for (final row in rows) + if (row['closed_at'] == null && row['closed'] != true) + '${row['id'] ?? ''}', + }); final selected = _selected; final retained = _workspace.panes.map((pane) => pane.sessionId).toSet(); final next = {}; @@ -367,6 +387,7 @@ class _ChatScreenState extends State _publishedWorkspaceSession = null; _startNotice = null; _composerFocus.cancel(); + if (_workspace.paneCount == 0) widget.onWorkspaceEmpty?.call(); final back = widget.onBack; if (back != null) { back(); @@ -408,6 +429,8 @@ class _ChatScreenState extends State _workspaceBinding?.dispose(); _workspace.removeListener(_workspaceChanged); _workspace.dispose(); + _sessions.removeListener(_nextChanged); + _sessions.removeListener(_availableSessionsChanged); _sessions.dispose(); _folds.dispose(); _composerFocus.dispose(); diff --git a/app/notes/chat-retap.md b/app/notes/chat-retap.md new file mode 100644 index 00000000..91040b6b --- /dev/null +++ b/app/notes/chat-retap.md @@ -0,0 +1,35 @@ +# Chats tab retap + +The selected Chats destination distinguishes its list from an open chat. After +Back, switching tabs, and returning to the Chats list, a second tap on the +already-selected Chats tab restores the retained workspace route. The mounted +`ChatScreen` workspace supplies existing panes, active pane, drafts/scroll +state, quick-switch ordering, and divider sizes. Tapping Chats while a chat is +already open is non-destructive, and closing the last pane clears retention. + +Retap validation is tied to the loaded chat-session controller. Retained IDs +that are no longer present or are closed remain on the list rather than being +resurrected; validity is unknown until the list has loaded, so an initial list +transition does not discard a valid retained workspace prematurely. + +Focused checks passed: +- `test/application/app_route_test.dart` +- `test/application/chat_registration_test.dart` (full PipelinesApp mobile tab-retap flow) +- `test/features/chat/chat_workspace_restore_test.dart` +- `test/features/chat/chat_list_detail_test.dart` +- `tool/analyze.sh` +- `flutter build web` + +Full-app fixture evidence at mobile width is in the shared artifact +`chat-retap-capture-v2/`: it captures opening a fixture chat from the list, +Back, Pipelines, Chats, then Chats again, with the restored conversation shown +at 560x1000. + +Manager follow-up adds real shell regressions for a resized mobile peek, +quickswitch pane ordering, a deliberately scrolled transcript, restored active +pane and both drafts, no-history retap, single-pane restore, and a session removed +from the loaded list. The restored UI reuses the existing workspace controller. +The session-list refresh test answers the cached thread's outstanding network +reads before refreshing, matching the client's serialized request protocol. +Focused follow-up: 18 tests passed (`/tmp/memwatch/out.0cayzm`); no new product +implementation changes were needed for these acceptance cases. diff --git a/app/test/application/app_route_test.dart b/app/test/application/app_route_test.dart index 124efeae..50cd0005 100644 --- a/app/test/application/app_route_test.dart +++ b/app/test/application/app_route_test.dart @@ -253,4 +253,33 @@ void main() { // Unknown deeper paths still resolve to the default list. expect(AppRoute.parse('/schedules/1'), AppRoute.pipelines); }); + + test('retapping Chats reopens only a retained workspace from its list', () { + final workspace = AppRoute.chatSession('active'); + expect(chatRouteForRetap(AppRoute.chat, workspace), workspace); + expect( + chatRouteForRetap( + AppRoute.chat, + workspace, + isValidSession: (id) => id == 'active', + ), + workspace, + ); + expect( + chatRouteForRetap( + AppRoute.chat, + workspace, + isValidSession: (id) => id == 'other', + ), + isNull, + ); + expect(chatRouteForRetap(AppRoute.chat, null), isNull); + expect(chatRouteForRetap(AppRoute.chat, AppRoute.chat), isNull); + }); + + test('retapping Chats while a chat is open does not return to the list', () { + final current = AppRoute.chatSession('active'); + expect(chatRouteForRetap(current, AppRoute.chatSession('older')), current); + expect(chatRouteForRetap(AppRoute.pipelines, current), isNull); + }); } diff --git a/app/test/application/chat_registration_test.dart b/app/test/application/chat_registration_test.dart index 24cfc30b..242107d3 100644 --- a/app/test/application/chat_registration_test.dart +++ b/app/test/application/chat_registration_test.dart @@ -3,11 +3,14 @@ import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; import 'package:pipelines_app/application/pipelines_app.dart'; import 'package:pipelines_app/application/server_endpoint.dart'; import 'package:pipelines_app/core/transport/pipelines_client.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_mobile_peek_divider.dart'; import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; @@ -154,6 +157,46 @@ Future replyHistory( await tester.pump(); } +Future replyChatSessions( + WidgetTester tester, + FakeChannel channel, + List ids, { + int index = 0, +}) async { + final request = await waitForRequest( + tester, + channel, + 'chat_sessions', + index: index, + ); + channel.incoming.add( + jsonEncode({ + 'id': request['id'], + 'type': 'chat_sessions', + 'chat_sessions': [ + for (final id in ids) {'id': id, 'title': 'Chat $id'}, + ], + }), + ); + await tester.pump(); +} + +Future replyChatHistory( + WidgetTester tester, + FakeChannel channel, { + required int subscribeIndex, + required int historyIndex, + String? text, +}) async { + await replySubscribe(tester, channel, index: subscribeIndex); + await replyHistory( + tester, + channel, + index: historyIndex, + text: text ?? 'History for chat ${subscribeIndex + 1}', + ); +} + void main() { for (final cupertino in [false, true]) { testWidgets( @@ -272,4 +315,263 @@ void main() { }, ); } + + testWidgets( + 'mobile Chats retap reopens the retained multi-pane workspace after tabs', + (tester) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(560, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), + ); + addTearDown(provider.dispose); + addTearDown(client.dispose); + + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: false, + routeInformationProvider: provider, + ), + ); + await tester.pump(); + await replyChatSessions(tester, channel, ['a', 'b']); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Chat a').first); + await tester.pump(); + await replyChatHistory( + tester, + channel, + subscribeIndex: 0, + historyIndex: 0, + ); + await tester.pumpAndSettle(); + await tester.enterText( + find.descendant( + of: find.byKey(const ValueKey('chat-composer-a')), + matching: find.byType(EditableText), + ), + 'Draft retained in pane a', + ); + + final addPane = find.byTooltip('Add chat pane').hitTestable(); + if (addPane.evaluate().isEmpty) { + await tester.tap(find.byTooltip('More actions').hitTestable().first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Add chat pane')); + } else { + await tester.tap(addPane); + } + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat b').last); + await tester.pump(); + await replyChatHistory( + tester, + channel, + subscribeIndex: 1, + historyIndex: 1, + text: List.generate(80, (i) => 'History line $i').join('\n\n'), + ); + await tester.pumpAndSettle(); + await tester.enterText( + find.descendant( + of: find.byKey(const ValueKey('chat-composer-b')), + matching: find.byType(EditableText), + ), + 'Draft retained in pane b', + ); + + expect( + tester + .widget( + find.descendant( + of: find.byKey(const ValueKey('chat-composer-b')), + matching: find.byType(EditableText), + ), + ) + .controller + .text, + 'Draft retained in pane b', + ); + + final workspace = tester.widget( + find.byType(ChatWorkspace), + ); + expect(workspace.controller.paneCount, 2); + expect(workspace.controller.activePane?.sessionId, 'b'); + expect(provider.value.uri.path, '/chat/b'); + final paneOrder = workspace.controller.panes + .map((p) => p.sessionId) + .toList(); + await tester.drag( + find.byType(ChatMobilePeekDivider), + const Offset(0, 60), + ); + await tester.pumpAndSettle(); + final peekFraction = workspace.controller.mobilePeekFraction; + expect(peekFraction, lessThan(.2)); + await tester.tap(find.bySemanticsLabel('Expand Chat a')); + await tester.pumpAndSettle(); + expect(workspace.controller.activePane?.sessionId, 'a'); + expect(workspace.controller.panes.map((p) => p.sessionId), paneOrder); + await tester.tap(find.bySemanticsLabel('Expand Chat b')); + await tester.pumpAndSettle(); + expect(workspace.controller.activePane?.sessionId, 'b'); + final transcript = find.byKey(const ValueKey('chat-thread-b')); + ScrollPosition historyPosition() => tester + .state( + find + .descendant(of: transcript, matching: find.byType(Scrollable)) + .first, + ) + .position; + final atEnd = historyPosition().pixels; + await tester.drag(transcript, const Offset(0, 250)); + await tester.pumpAndSettle(); + final historyOffset = historyPosition().pixels; + expect(historyOffset, isNot(closeTo(atEnd, 1))); + + await tester.tap(find.byTooltip('Back').hitTestable()); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat'); + expect(find.byType(ChatThreadView), findsNothing); + + await tester.tap(find.byKey(const ValueKey('shell.destination.runs'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('shell.destination.chat'))); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat'); + expect(find.byType(ChatThreadView), findsNothing); + + // The selected Chats destination is already showing its list: the + // second tap reuses the mounted workspace instead of opening a new one. + await tester.tap(find.byKey(const ValueKey('shell.destination.chat'))); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat/b'); + final restored = tester.widget(find.byType(ChatWorkspace)); + expect(restored.controller, same(workspace.controller)); + expect(restored.controller.paneCount, 2); + expect(restored.controller.activePane?.sessionId, 'b'); + expect(restored.controller.panes.map((p) => p.sessionId), paneOrder); + expect(restored.controller.mobilePeekFraction, peekFraction); + expect(historyPosition().pixels, closeTo(historyOffset, 1)); + expect(find.byType(ChatThreadView), findsNWidgets(2)); + expect( + tester + .widget( + find.descendant( + of: find.byKey(const ValueKey('chat-composer-b')), + matching: find.byType(EditableText), + ), + ) + .controller + .text, + 'Draft retained in pane b', + ); + expect( + find.descendant( + of: find.byKey( + const ValueKey('chat-composer-a'), + skipOffstage: false, + ), + matching: find.byType(EditableText, skipOffstage: false), + skipOffstage: false, + ), + findsOneWidget, + ); + expect( + tester + .widget( + find.descendant( + of: find.byKey( + const ValueKey('chat-composer-a'), + skipOffstage: false, + ), + matching: find.byType(EditableText, skipOffstage: false), + skipOffstage: false, + ), + ) + .controller + .text, + 'Draft retained in pane a', + ); + expect(tester.takeException(), isNull); + }, + ); + testWidgets( + 'mobile Chats retap stays on list with no history or a removed chat', + (tester) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(560, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), + ); + addTearDown(provider.dispose); + addTearDown(client.dispose); + await tester.pumpWidget( + PipelinesApp( + server: webServer(), + client: client, + cupertino: false, + routeInformationProvider: provider, + ), + ); + await tester.pump(); + await replyChatSessions(tester, channel, ['a']); + await tester.pumpAndSettle(); + final chatTab = find.byKey(const ValueKey('shell.destination.chat')); + await tester.tap(chatTab); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat'); + expect(find.byType(ChatThreadView), findsNothing); + await tester.tap(find.text('Chat a').first); + await tester.pump(); + await replyChatHistory( + tester, + channel, + subscribeIndex: 0, + historyIndex: 0, + ); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Back').hitTestable()); + await tester.pumpAndSettle(); + await tester.tap(chatTab); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat/a'); + expect(find.byType(ChatThreadView), findsOneWidget); + // The cached transcript renders immediately, but answer the restored + // thread's network read before refreshing the serialized session list. + await replyChatHistory( + tester, + channel, + subscribeIndex: 1, + historyIndex: 1, + ); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Back').hitTestable()); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-refresh')).hitTestable()); + await tester.pump(); + await replyChatSessions(tester, channel, [], index: 1); + await tester.pumpAndSettle(); + for (var attempt = 0; attempt < 2; attempt++) { + await tester.tap(chatTab); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat'); + expect(find.byType(ChatThreadView), findsNothing); + } + expect(tester.takeException(), isNull); + }, + ); }