diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart new file mode 100644 index 00000000..6a183fda --- /dev/null +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -0,0 +1,116 @@ +part of 'screen.dart'; + +/// Pane layout, focus and route publication for one Chat destination visit. +mixin _ChatScreenWorkspace on State { + Map get _openedSessions; + ChatComposerFocusRequests get _composerFocus; + JsonMap? _rowFor(String id); + void _back(); + Widget _thread( + String selected, + VoidCallback onBack, { + ChatWorkspacePane? pane, + BuildContext? paneContext, + }); + + final ChatWorkspaceController _workspace = ChatWorkspaceController(); + final GlobalKey _workspaceKey = GlobalKey(); + bool _workspaceVisible = false; + bool _usedWorkspace = false; + String? _publishedWorkspaceSession; + String _workspaceSignature = ''; + + void _workspaceChanged() { + if (!mounted) return; + final signature = + '${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}'; + if (_workspaceSignature == signature) return; + _workspaceSignature = signature; + void update() { + if (!mounted) return; + final id = _workspace.activePane?.sessionId; + setState(() {}); + if (!_workspaceVisible || + id == null || + id == _publishedWorkspaceSession) { + return; + } + _publishedWorkspaceSession = id; + widget.onSessionSelected?.call(id); + } + + if (SchedulerBinding.instance.schedulerPhase == + SchedulerPhase.persistentCallbacks) { + WidgetsBinding.instance.addPostFrameCallback((_) => update()); + } else { + update(); + } + } + + void _split(JsonMap session, ChatSplitAxis axis) { + final id = '${session['id'] ?? ''}'; + if (id.isEmpty) return; + _openedSessions[id] = session; + _workspaceVisible = true; + _workspace.splitActive(id, axis); + _composerFocus.request(id); + } + + void _openBeside(JsonMap session) => + _split(session, ChatSplitAxis.horizontal); + void _openBelow(JsonMap session) => _split(session, ChatSplitAxis.vertical); + + void _closePane(String paneId) { + _workspace.close(paneId); + if (_workspace.paneCount == 0) _back(); + } + + void _pickPane(BuildContext context) => showChatPanePicker( + context, + panes: [ + for (final pane in _workspace.panes) + ( + id: pane.id, + title: '${_rowFor(pane.sessionId)?['title'] ?? pane.sessionId}', + ), + ], + activeId: _workspace.activePaneId, + onSelected: (id) { + _workspace.activate(id); + final session = _workspace.activePane?.sessionId; + if (session != null && chatSelectionFocusesComposer(const {})) { + _composerFocus.request(session); + } + }, + ); + + Widget _workspaceView() => ChatWorkspace( + key: _workspaceKey, + controller: _workspace, + shortcutsEnabled: _workspaceVisible, + singlePane: !showsListBesideDetail(context), + onFocusPane: (pane) => _composerFocus.request(pane.sessionId), + paneBuilder: (context, pane, active) => Semantics( + selected: active, + child: DecoratedBox( + position: DecorationPosition.foreground, + decoration: BoxDecoration( + border: Border.all( + color: _workspace.paneCount > 1 && active + ? (chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary) + : Colors.transparent, + ), + ), + child: DetailPane( + key: ValueKey('chat-pane-detail-${pane.id}'), + destination: AppDestination.chat, + implyBack: false, + builder: (context) => + _thread(pane.sessionId, _back, pane: pane, paneContext: context), + ), + ), + ), + ); +} diff --git a/app/lib/features/chat/conversation/chat_pane_picker.dart b/app/lib/features/chat/conversation/chat_pane_picker.dart new file mode 100644 index 00000000..07986a85 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_pane_picker.dart @@ -0,0 +1,54 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../ui/sessions/chat_adaptive.dart'; + +/// Selects a retained pane when the window cannot show every chat at once. +Future showChatPanePicker( + BuildContext context, { + required List<({String id, String title})> panes, + required String? activeId, + required ValueChanged onSelected, +}) async { + final String? selected; + if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { + selected = await showCupertinoModalPopup( + context: context, + builder: (context) => CupertinoActionSheet( + title: const Text('Open chats'), + actions: [ + for (final pane in panes) + CupertinoActionSheetAction( + isDefaultAction: pane.id == activeId, + onPressed: () => Navigator.pop(context, pane.id), + child: Text(pane.title), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ), + ); + } else { + selected = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('Open chats'), + children: [ + for (final pane in panes) + SimpleDialogOption( + onPressed: () => Navigator.pop(context, pane.id), + child: Row( + children: [ + Expanded(child: Text(pane.title)), + if (pane.id == activeId) const Icon(Icons.check), + ], + ), + ), + ], + ), + ); + } + if (selected != null && context.mounted) onSelected(selected); +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index bb904837..195f020b 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -90,6 +90,8 @@ class ChatThreadView extends StatefulWidget { this.fileBridge = const ArtifactFileBridge(), this.onColorSelected, this.onNextChat, + this.paneControls = const [], + this.showBackButton, }); final ApiGateway gateway; @@ -97,6 +99,8 @@ class ChatThreadView extends StatefulWidget { /// Opens the chat after this one in the list (wrapping to the first), from /// the bar's Next chat button; null when there is no other chat to open. final VoidCallback? onNextChat; + final List paneControls; + final bool? showBackButton; /// Sets the chat's shared colour (a palette name, null for none) from the /// information sheet; null leaves the sheet without the Colour choice. @@ -1154,9 +1158,11 @@ class _ChatThreadViewState extends State { /// the model and mode controls. Widget _header(BuildContext context, bool inShellBar) { final session = widget.session; - final canGoBack = inShellBar - ? ModalRoute.of(context)?.impliesAppBarDismissal ?? false - : true; + final canGoBack = + widget.showBackButton ?? + (inShellBar + ? ModalRoute.of(context)?.impliesAppBarDismissal ?? false + : true); final answeredBy = latestReplyModel(_controller.messages); return _chrome.widgetFor('header', answeredBy, [ widget, @@ -1191,13 +1197,16 @@ class _ChatThreadViewState extends State { showBack: canGoBack, // A pushed page keeps the platform's stock Back (pop this route); a // standalone conversation calls its owner. - onBack: inShellBar ? null : widget.onBack, + onBack: widget.showBackButton == true + ? widget.onBack + : (inShellBar ? null : widget.onBack), // Each control is its own action, so each pops in (and sinks) on its // own. Natural width while the bar has room; past the title's share // the model ellipsises, and the mode keeps its whole name until it // would take more than half the pill. A session without a mode draws // no mode control, so no empty pill is ever drawn. controls: [ + ...widget.paneControls, if (hasModel) ChatModelControl( key: ValueKey('chat-model-${widget.sessionId}'), diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index bd2e5b32..b7fab1f0 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -1,4 +1,5 @@ import '../../shell/destination.dart'; +import '../../shell/shell_bar.dart'; import '../../shell/detail_page.dart'; import '../../shell/empty_detail_pane.dart'; import '../../shell/list_detail.dart'; @@ -10,6 +11,9 @@ import 'package:flutter/scheduler.dart'; import '../../core/api_gateway.dart'; import 'conversation/chat_models.dart'; +import 'conversation/chat_pane_picker.dart'; +import 'workspace/chat_workspace.dart'; +import 'ui/sessions/chat_adaptive.dart'; import 'conversation/chat_row_widgets.dart'; import 'conversation/chat_scroll.dart'; import 'conversation/chat_thread_view.dart'; @@ -23,6 +27,8 @@ import 'ui/sessions/chat_sessions_body.dart'; import 'ui/sessions/chat_sessions_controller.dart'; import 'ui/sessions/chat_sessions_screen.dart'; +part 'chat_screen_workspace.dart'; + /// The Chat destination's list/detail switch. /// /// The route names the open session, so a row tap, a deep link and Back all @@ -57,7 +63,7 @@ class ChatScreen extends StatefulWidget { State createState() => _ChatScreenState(); } -class _ChatScreenState extends State { +class _ChatScreenState extends State with _ChatScreenWorkspace { /// The list's controller, shared with the mounted list screen. The list /// screen refreshes it on mount and swaps its repository when the socket is /// replaced; this destination lists created rows and re-reads after a @@ -69,6 +75,7 @@ class _ChatScreenState extends State { /// Rows this visit has opened, used for the native title and the recorded /// model facts. The mounted list also reports its loaded rows, so a routed id /// (a deep link) resolves the same row without a second list request. + @override final Map _openedSessions = {}; /// Each row as the list last reported it (without its live `running`), so @@ -98,6 +105,7 @@ class _ChatScreenState extends State { /// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer; choosing a /// chat does too where [chatSelectionFocusesComposer] allows. + @override final ChatComposerFocusRequests _composerFocus = ChatComposerFocusRequests(); /// The list's folded sections, kept here so Next chat counts the rows the @@ -111,6 +119,13 @@ class _ChatScreenState extends State { @override void initState() { super.initState(); + final initial = widget.initialSessionId; + if (initial != null && initial.isNotEmpty) { + _workspace.open(initial); + _workspaceVisible = true; + _publishedWorkspaceSession = initial; + } + _workspace.addListener(_workspaceChanged); // Seen from now on, so the press that chooses the first chat counts. LastPointerKind.instance; _sessions.addListener(_nextChanged); @@ -148,6 +163,10 @@ class _ChatScreenState extends State { } String? get _selected { + if (_workspaceVisible && _workspace.activePane != null) { + return _workspace.activePane!.sessionId; + } + if (!_workspaceVisible && _usedWorkspace) return null; final routed = widget.initialSessionId; if (routed != null && routed.isNotEmpty) return routed; return _standaloneSelection; @@ -172,10 +191,15 @@ class _ChatScreenState extends State { _composerFocus.cancel(); } _openedSessions[id] = session; + _workspaceVisible = true; + _workspace.open(id); if (_startNotice?.id != id) _startNotice = null; final select = widget.onSessionSelected; if (select != null) { - select(id); + if (_publishedWorkspaceSession != id) { + _publishedWorkspaceSession = id; + select(id); + } } else { setState(() => _standaloneSelection = id); } @@ -195,7 +219,10 @@ class _ChatScreenState extends State { /// Another device started a new session in a chat: only an open chat /// follows it; the list already swapped the row. void _replacedElsewhere(String previousId, JsonMap session) { - if (!mounted || _selected != previousId) return; + if (!mounted || + !_workspace.panes.any((pane) => pane.sessionId == previousId)) { + return; + } _followNewSession(previousId, session, chatNewSessionElsewhereNotice); } @@ -207,7 +234,9 @@ class _ChatScreenState extends State { final accepted = _acceptedModels[previousId]; if (accepted != null) _acceptedModels[id] = accepted; _startNotice = (id: id, notice: notice); - _open({...session}..remove('running')); + _openedSessions[id] = {...session}..remove('running'); + _workspace.replaceSession(previousId, id); + if (_workspace.paneCount == 0) _open(session); } /// `/rename` was accepted for [id]: the opened row follows the shared title @@ -222,8 +251,13 @@ class _ChatScreenState extends State { /// `/close` was accepted: the conversation leaves, back to the list, which /// re-reads the closed row. - void _closed() { - _back(); + void _closed(String sessionId) { + for (final pane + in _workspace.panes + .where((pane) => pane.sessionId == sessionId) + .toList()) { + _closePane(pane.id); + } unawaited(_sessions.refresh()); } @@ -282,6 +316,7 @@ class _ChatScreenState extends State { } /// The row to open for [id], with an accepted model folded in. + @override JsonMap? _rowFor(String id) { final row = _openedSessions[id]; final accepted = _acceptedModels[id]; @@ -294,7 +329,10 @@ class _ChatScreenState extends State { }; } + @override void _back() { + _workspaceVisible = false; + _publishedWorkspaceSession = null; _startNotice = null; _composerFocus.cancel(); final back = widget.onBack; @@ -311,6 +349,16 @@ class _ChatScreenState extends State { @override void didUpdateWidget(covariant ChatScreen oldWidget) { super.didUpdateWidget(oldWidget); + if (oldWidget.initialSessionId != widget.initialSessionId) { + final id = widget.initialSessionId; + if (id != null && id.isNotEmpty) { + _workspaceVisible = true; + _publishedWorkspaceSession = id; + _workspace.open(id); + } else if (widget.onSessionSelected != null) { + _workspaceVisible = false; + } + } // Transcripts read through another gateway belong to that server. if (oldWidget.gateway != widget.gateway) _transcripts.clear(); } @@ -318,13 +366,21 @@ class _ChatScreenState extends State { @override void dispose() { _page.dispose(); + _workspace.removeListener(_workspaceChanged); + _workspace.dispose(); _sessions.dispose(); _folds.dispose(); _composerFocus.dispose(); super.dispose(); } - Widget _thread(String selected, VoidCallback onBack) { + @override + Widget _thread( + String selected, + VoidCallback onBack, { + ChatWorkspacePane? pane, + BuildContext? paneContext, + }) { final row = _rowFor(selected); final start = _startNotice; final thread = ChatThreadView( @@ -344,9 +400,30 @@ class _ChatScreenState extends State { onModeChanged: (mode, name) => _modeChanged(selected, mode, name), onNewSession: _startedNewSession, onSessionRenamed: (title) => _renamed(selected, title), - onSessionClosed: _closed, + onSessionClosed: () => _closed(selected), onColorSelected: (color) => _sessions.setColor(selected, color), - onNextChat: _offeredNext ? () => _openNext(selected) : null, + onNextChat: _nextAfter(selected) != null + ? () => _openNext(selected) + : null, + showBackButton: pane == null ? null : !showsListBesideDetail(context), + paneControls: pane == null + ? const [] + : [ + if (_workspace.paneCount > 1) + ChatBarAction( + label: 'Open chats (${_workspace.paneCount})', + onPressed: () => _pickPane(paneContext ?? context), + materialIcon: Icons.view_quilt_outlined, + cupertinoIcon: CupertinoIcons.square_split_2x2, + ), + if (_workspace.paneCount > 1) + ChatBarAction( + label: 'Close pane', + onPressed: () => _closePane(pane.id), + materialIcon: Icons.close, + cupertinoIcon: CupertinoIcons.xmark, + ), + ], ); return ChatComposerFocusScope( sessionId: selected, @@ -363,9 +440,10 @@ class _ChatScreenState extends State { // window keeps the destination rail and the chat list beside the open // chat, which has no Back: another row, `/close` or a route change swaps it. final beside = showsListBesideDetail(context); + if (beside && selected != null) _usedWorkspace = true; _page.sync( context, - selected: selected != null && !beside, + selected: selected != null && !beside && !_usedWorkspace, destination: AppDestination.chat, onClosed: _back, builder: (context) => selected == null @@ -381,12 +459,49 @@ class _ChatScreenState extends State { controller: _sessions, folds: _folds, onOpen: _openBySelection, + onOpenBeside: beside ? _openBeside : null, + onOpenBelow: beside ? _openBelow : null, onShortcutOpen: _openByShortcut, onSessions: _adoptRows, activeSessionId: selected, - publishShellBar: true, + publishShellBar: beside || !_usedWorkspace || selected == null, ); - if (!beside) return list; + if (!beside) { + if (!_usedWorkspace) return list; + final media = MediaQuery.of(context); + final system = ShellSystemInsets.of(context); + return PopScope( + canPop: selected == null, + onPopInvokedWithResult: (didPop, _) { + if (!didPop && selected != null) _back(); + }, + child: ShellBar( + active: selected != null, + barless: true, + child: Stack( + fit: StackFit.expand, + children: [ + Offstage( + offstage: selected != null, + child: ExcludeFocus(excluding: selected != null, child: list), + ), + Offstage( + offstage: selected == null, + child: ExcludeFocus( + excluding: selected == null, + child: MediaQuery( + data: media.copyWith( + padding: media.padding.copyWith(top: system.top), + ), + child: _workspaceView(), + ), + ), + ), + ], + ), + ), + ); + } return ListDetailPanes( list: list, detailIdentity: selected, @@ -395,11 +510,9 @@ class _ChatScreenState extends State { destination: AppDestination.chat, message: 'Select a chat to open it here.', ) - : DetailPane( + : SizedBox.expand( key: const ValueKey('chat-detail-pane'), - destination: AppDestination.chat, - implyBack: false, - builder: (context) => _thread(selected, _back), + child: _workspaceView(), ), ); } diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart index acaa6f5d..f8ff621b 100644 --- a/app/lib/features/chat/workspace/chat_workspace.dart +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -21,11 +21,15 @@ class ChatWorkspace extends StatefulWidget { required this.paneBuilder, this.onFocusPane, this.shortcutsEnabled = true, + this.singlePane = false, }); final ChatWorkspaceController controller; final ChatWorkspacePaneBuilder paneBuilder; final bool shortcutsEnabled; + /// Keeps the retained layout while presenting only the active chat. + final bool singlePane; + /// Keyboard navigation only: the owner can focus the target composer. /// Pointer activation leaves text-selection and pointer focus alone. final ValueChanged? onFocusPane; @@ -109,6 +113,7 @@ class _ChatWorkspaceState extends State { if (root == null) return const SizedBox.shrink(); final geometry = ChatWorkspaceGeometry(root, constraints.biggest); _geometry = geometry; + final collapsed = widget.singlePane || geometry.collapsed; final panes = widget.controller.panes; final existing = panes.map((p) => p.id).toSet(); for (final id @@ -123,16 +128,15 @@ class _ChatWorkspaceState extends State { for (final pane in panes) Positioned.fromRect( key: ValueKey('chat-workspace-${pane.id}'), - rect: geometry.collapsed + rect: collapsed ? Offset.zero & constraints.biggest : geometry.panes[pane.id]!, child: Offstage( offstage: - geometry.collapsed && - pane.id != widget.controller.activePaneId, + collapsed && pane.id != widget.controller.activePaneId, child: ExcludeFocus( excluding: - geometry.collapsed && + collapsed && pane.id != widget.controller.activePaneId, child: FocusScope( node: _panes.putIfAbsent( @@ -160,7 +164,7 @@ class _ChatWorkspaceState extends State { ), ), ), - if (!geometry.collapsed) + if (!collapsed) for (final divider in geometry.dividers) Positioned.fromRect( key: ValueKey('chat-workspace-${divider.split.id}'), diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index d70c7c7f..811adc4e 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -209,6 +209,7 @@ class _AdaptiveShellState extends State { split: () => _bar.split(_selected), preferredWidth: () => _paneWidths.widthFor(_selected.name), bar: currentBar, + visible: () => !(_bar.specFor(_selected)?.barless ?? false), ); // The scaffolds below swap the system insets for their bars' // heights; panes beside a list read the real ones from here. @@ -393,6 +394,7 @@ class _ListPaneBar extends StatelessWidget required this.split, required this.preferredWidth, required this.bar, + required this.visible, }); final Listenable listenable; @@ -400,6 +402,7 @@ class _ListPaneBar extends StatelessWidget final bool Function() split; final double? Function() preferredWidth; final SegmentedBar Function() bar; + final bool Function() visible; @override Size get preferredSize => initial.preferredSize; @@ -411,11 +414,13 @@ class _ListPaneBar extends StatelessWidget @override Widget build(BuildContext context) => ListenableBuilder( listenable: listenable, - builder: (context, _) => ListPaneWidth( - split: split(), - preferredWidth: preferredWidth(), - alignment: AlignmentDirectional.topStart, - child: bar(), - ), + builder: (context, _) => !visible() + ? const SizedBox.shrink() + : ListPaneWidth( + split: split(), + preferredWidth: preferredWidth(), + alignment: AlignmentDirectional.topStart, + child: bar(), + ), ); } diff --git a/app/test/features/chat/chat_split_integration_test.dart b/app/test/features/chat/chat_split_integration_test.dart new file mode 100644 index 00000000..39ae2a90 --- /dev/null +++ b/app/test/features/chat/chat_split_integration_test.dart @@ -0,0 +1,263 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.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/screen.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_actions.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.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', 'c']) {'id': id, 'title': 'Chat $id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +Finder _thread(String id, {bool offstage = false}) => find.byWidgetPredicate( + (widget) => widget is ChatThreadView && widget.sessionId == id, + skipOffstage: !offstage, +); +Finder _input(String id, {bool offstage = false}) => find.descendant( + of: find.byKey(ValueKey('chat-composer-$id'), skipOffstage: !offstage), + matching: find.byType(EditableText, skipOffstage: !offstage), + skipOffstage: !offstage, +); +Widget _app(_Gateway gateway, {int sync = 0}) => MaterialApp( + home: Scaffold( + body: ChatScreen(gateway: gateway, syncToken: sync), + ), +); +Future<_Gateway> _setup(WidgetTester tester) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(1800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway() + ..history = (fields) async { + final id = (fields['chat_query'] as Map)['session_id']; + return chatPage([ + chatMessage( + '$id-history', + 'assistant', + parts: [ + {'type': 'text', 'text': 'History for $id'}, + ], + ), + ]); + }; + addTearDown(gateway.close); + await tester.pumpWidget(_app(gateway)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat a').first); + await tester.pumpAndSettle(); + return gateway; +} + +Future _split(WidgetTester tester, String id, String action) async { + await tester.tap( + find.byWidgetPredicate( + (widget) => widget is SessionActionsButton && widget.session['id'] == id, + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text(action)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets( + 'nested splits preserve drafts, resize, collapse and narrow restore', + (tester) async { + final gateway = await _setup(tester); + final stateA = tester.state(_thread('a')); + await tester.enterText(_input('a'), 'Draft A'); + await _split(tester, 'b', 'Open to the right'); + final stateB = tester.state(_thread('b')); + await tester.enterText(_input('b'), 'Draft B'); + await _split(tester, 'c', 'Open below'); + final workspace = tester.widget( + find.byType(ChatWorkspace), + ); + expect(workspace.controller.paneCount, 3); + expect(tester.state(_thread('a')), same(stateA)); + expect(tester.state(_thread('b')), same(stateB)); + expect( + tester.getCenter(_thread('a')).dx, + lessThan(tester.getCenter(_thread('b')).dx), + ); + expect( + tester.getCenter(_thread('b')).dy, + lessThan(tester.getCenter(_thread('c')).dy), + ); + final root = workspace.controller.root as ChatWorkspaceSplit; + final divider = find.byKey(ValueKey('chat-workspace-${root.id}')); + final width = tester.getSize(_thread('a')).width; + await tester.drag(divider, const Offset(80, 0)); + await tester.pumpAndSettle(); + expect(tester.getSize(_thread('a')).width, greaterThan(width)); + expect(tester.state(_thread('a')), same(stateA)); + tester.view.physicalSize = const Size(560, 1000); + await tester.pumpAndSettle(); + expect(_thread('c'), findsOneWidget); + expect(_thread('a'), findsNothing); + expect(_thread('b'), findsNothing); + tester.view.physicalSize = const Size(390, 844); + await tester.pumpAndSettle(); + expect(_thread('c'), findsOneWidget); + expect(_thread('a'), findsNothing); + expect(tester.state(_thread('a', offstage: true)), same(stateA)); + tester.view.physicalSize = const Size(1800, 1000); + await tester.pumpAndSettle(); + expect(tester.state(_thread('a')), same(stateA)); + expect( + tester.widget(_input('a')).controller.text, + 'Draft A', + ); + expect( + tester.widget(_input('b')).controller.text, + 'Draft B', + ); + await tester.tap( + find.descendant( + of: _thread('c'), + matching: find.byTooltip('Close pane'), + ), + ); + await tester.pumpAndSettle(); + expect(workspace.controller.paneCount, 2); + expect(_thread('c'), findsNothing); + expect(tester.state(_thread('b')), same(stateB)); + expect( + gateway.calls.where( + (call) => [ + 'chat_prompt', + 'chat_close', + 'chat_interrupt', + ].contains(call.type), + ), + isEmpty, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + testWidgets('pane keyboard focus, session-isolated streams and reconnects', ( + tester, + ) async { + final gateway = await _setup(tester); + await _split(tester, 'b', 'Open to the right'); + await tester.tap(_input('b')); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + expect( + tester.widget(_input('a')).focusNode.hasPrimaryFocus, + isTrue, + ); + gateway.emitEvent( + chatTextFrame('Alpha only', session: 'a', messageId: 'live-a'), + ); + gateway.emitEvent( + chatTextFrame('Beta only', session: 'b', messageId: 'live-b'), + ); + await tester.pumpAndSettle(); + expect( + find.descendant(of: _thread('a'), matching: find.text('Alpha only')), + findsOneWidget, + ); + expect( + find.descendant(of: _thread('b'), matching: find.text('Alpha only')), + findsNothing, + ); + expect( + find.descendant(of: _thread('b'), matching: find.text('Beta only')), + findsOneWidget, + ); + final states = [tester.state(_thread('a')), tester.state(_thread('b'))]; + final subscriptions = gateway.calls + .where((call) => call.type == 'chat_subscribe') + .length; + await tester.pumpWidget(_app(gateway, sync: 1)); + await tester.pumpAndSettle(); + expect(tester.state(_thread('a')), same(states[0])); + expect(tester.state(_thread('b')), same(states[1])); + expect( + gateway.calls.where((call) => call.type == 'chat_subscribe').length, + subscriptions + 2, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }); + testWidgets( + 'route focus and asynchronous new sessions affect the owning pane', + (tester) async { + final gateway = await _setup(tester); + final route = ValueNotifier('a'); + addTearDown(route.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ValueListenableBuilder( + valueListenable: route, + builder: (_, id, _) => ChatScreen( + gateway: gateway, + initialSessionId: id, + onSessionSelected: (id) => route.value = id, + onBack: () => route.value = null, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await _split(tester, 'b', 'Open to the right'); + await _split(tester, 'c', 'Open below'); + expect(route.value, 'c'); + final stateA = tester.state(_thread('a')); + final stateC = tester.state(_thread('c')); + final finishedNew = tester + .widget(_thread('b')) + .onNewSession!; + await tester.tap(_input('a')); + await tester.pumpAndSettle(); + expect(route.value, 'a'); + finishedNew('b', {'id': 'b-new', 'title': 'Fresh B'}, 'Started fresh'); + await tester.pumpAndSettle(); + expect(route.value, 'a'); + expect(_thread('b'), findsNothing); + expect(_thread('b-new'), findsOneWidget); + expect(tester.state(_thread('a')), same(stateA)); + expect(tester.state(_thread('c')), same(stateC)); + tester.view.physicalSize = const Size(560, 1000); + await tester.pumpAndSettle(); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(route.value, isNull); + expect(find.text('Chat a'), findsOneWidget); + expect( + gateway.calls.where( + (call) => ['chat_close', 'chat_interrupt'].contains(call.type), + ), + isEmpty, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); +} diff --git a/app/tool/capture/page.mjs b/app/tool/capture/page.mjs index 0f0af3b5..8cbe9d79 100644 --- a/app/tool/capture/page.mjs +++ b/app/tool/capture/page.mjs @@ -148,9 +148,9 @@ export function flutterPage(browser, log, { touch = false } = {}) { const key = parts.pop(); const bits = { Alt: 1, Control: 2, Meta: 4, Shift: 8 }; const modifiers = parts.reduce((m, p) => m | (bits[p] ?? 0), 0); - const codes = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8, ArrowDown: 40, ArrowUp: 38 }; + const codes = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8, ArrowDown: 40, ArrowUp: 38, ArrowLeft: 37, ArrowRight: 39, "/": 191 }; const digit = /^\d$/.test(key); - const code = digit ? `Digit${key}` : /^[a-z]$/i.test(key) ? `Key${key.toUpperCase()}` : key; + const code = key === '/' ? 'Slash' : digit ? `Digit${key}` : /^[a-z]$/i.test(key) ? `Key${key.toUpperCase()}` : key; const vk = codes[key] ?? (key.length === 1 ? key.toUpperCase().charCodeAt(0) : 0); const text = key === 'Enter' ? '\r' : key.length === 1 && !modifiers ? key : undefined; const base = { key, code, windowsVirtualKeyCode: vk, modifiers, text };