diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 652ecb05..34e4f87f 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -15,6 +15,7 @@ import '../core/servers/server_scope.dart'; import '../core/transport/pipelines_client.dart'; import '../shell/adaptive_shell.dart'; import '../shell/destination.dart'; +import '../shell/shell_chat_actions_shortcut.dart'; import '../features/attention/notify/notification_controller.dart'; import '../features/attention/notify/notification_models.dart'; import '../features/attention/notify/chat_question_notices.dart'; @@ -55,6 +56,7 @@ import '../shell/windows/window_store.dart'; import 'app_terminals.dart'; import '../features/chat/chat_run_opener.dart'; import '../features/chat/chat_runtime.dart'; +import '../features/chat/data/chat_recency.dart'; import '../features/changes/windows/diff_windows.dart'; import '../features/chat/windows/chat_windows.dart'; import 'open_in_chat.dart'; @@ -359,7 +361,13 @@ class _PipelinesAppState extends State final chatScope = widget.chatPool != null ? 'all-saved-servers' : serverStorageScope(serverIdentity(chatGateway)); - _chatRuntime = ChatRuntime(gateway: chatGateway, serverKey: chatScope); + _chatRuntime = ChatRuntime( + gateway: chatGateway, + serverKey: chatScope, + recency: ChatRecency( + store: SharedPreferencesChatRecencyStore(serverScope: chatScope), + ), + ); _chatWindows = ChatWindows( manager: _windows, runtime: _chatRuntime, @@ -868,6 +876,19 @@ class _PipelinesAppState extends State if (!_chatRuntime.quickSwitch.toggle()) _focusOpenChatComposer(); } + /// Alt+N / Alt+J: the shell has shown Chat; once it has built (a first + /// visit mounts the chat screen), the chat screen acts. + void _chatAction(ShellChatAction action) { + final requests = switch (action) { + ShellChatAction.newChat => _chatRuntime.newChat, + ShellChatAction.nextAttention => _chatRuntime.nextAttention, + }; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) requests.toggle(); + }); + WidgetsBinding.instance.ensureVisualUpdate(); + } + void _selectDestination(AppDestination destination) { // Settings is shown from its own nav item and has no Back, so its route // (filed under the Pipelines tab) must not trap the Pipelines item: that @@ -1130,6 +1151,7 @@ class _PipelinesAppState extends State onDestinationReselected: _reselectDestination, onOpenChat: _focusOpenChatComposer, onChatQuickSwitch: _toggleChatQuickSwitch, + onChatAction: _chatAction, destinationBodies: { AppDestination.pipelines: (_) => FirstRunWalkthroughGate( store: _walkthroughStore, diff --git a/app/lib/features/chat/chat_runtime.dart b/app/lib/features/chat/chat_runtime.dart index 611e39ae..f828de14 100644 --- a/app/lib/features/chat/chat_runtime.dart +++ b/app/lib/features/chat/chat_runtime.dart @@ -13,6 +13,7 @@ import 'conversation/chat_transcript_cache.dart'; import 'conversation/chat_composer_controller.dart'; import 'conversation/chat_quick_switch_requests.dart'; import 'conversation/composer_focus_request.dart'; +import 'data/chat_recency.dart'; import 'data/chat_repository.dart'; import 'ui/sessions/chat_sessions_body.dart'; import 'ui/sessions/chat_sessions_controller.dart'; @@ -24,9 +25,13 @@ import 'ui/sessions/chat_sessions_controller.dart'; /// /// It notifies when a row a conversation is drawn from changes. class ChatRuntime extends ChangeNotifier { - ChatRuntime({required ApiGateway gateway, this.serverKey = ''}) - : _gateway = gateway, - sessions = ChatSessionsController(ChatRepository(gateway)) { + ChatRuntime({ + required ApiGateway gateway, + this.serverKey = '', + ChatRecency? recency, + }) : _gateway = gateway, + recency = recency ?? ChatRecency(), + sessions = ChatSessionsController(ChatRepository(gateway)) { sessions.onSessionReplaced = (previousId, session) { for (final listener in _replaced.toList()) { listener(previousId, session); @@ -132,6 +137,15 @@ class ChatRuntime extends ChangeNotifier { /// The Chat destination's quick switcher, toggled by Ctrl+K / Alt+K there. final ChatQuickSwitchRequests quickSwitch = ChatQuickSwitchRequests(); + /// New chat (Alt+N) and the next chat needing the operator (Alt+J), asked + /// of the mounted Chat destination. + final ChatQuickSwitchRequests newChat = ChatQuickSwitchRequests(); + final ChatQuickSwitchRequests nextAttention = ChatQuickSwitchRequests(); + + /// The chats this device used, most recent first (the quick switcher's + /// order with no query). + final ChatRecency recency; + /// Mounted composers are registered so external actions can append without /// sending. A selection made before a pane mounts is queued here. final Map composers = {}; diff --git a/app/lib/features/chat/chat_screen_attention.dart b/app/lib/features/chat/chat_screen_attention.dart new file mode 100644 index 00000000..1ef3edca --- /dev/null +++ b/app/lib/features/chat/chat_screen_attention.dart @@ -0,0 +1,54 @@ +part of 'screen.dart'; + +/// The Chat destination's app-wide chat shortcuts, run through +/// [ChatRuntime.newChat] and [ChatRuntime.nextAttention] (the shell shows +/// Chat first): Alt+N starts a new chat with the list's own create dialog, +/// and Alt+J opens the next chat needing the operator (waiting for an answer, +/// unread, or a failed action), cycling in list order. Neither acts while a +/// popup or dialog over the chat keeps the keyboard. +mixin _ChatScreenAttention on State, _ChatScreenWorkspace { + ChatRuntime get _runtime; + + void _bindAttention() { + _runtime.newChat.attach(_startNewChat); + _runtime.nextAttention.attach(_openNextAttention); + } + + void _unbindAttention() { + _runtime.newChat.detach(_startNewChat); + _runtime.nextAttention.detach(_openNextAttention); + } + + void _startNewChat() { + if (!mounted || !_chatOwnsKeyboard()) return; + final state = _sessionsKey.currentState; + if (state != null) unawaited(state.newChat()); + } + + void _openNextAttention() { + if (!mounted || !_chatOwnsKeyboard()) return; + final sessions = _runtime.sessions; + final current = _workspaceVisible ? _workspace.activePane?.sessionId : null; + final next = chatNextNeedingAttention( + sessions.sessions, + current, + (row) => chatNeedsAttention( + row, + unread: sessions.isUnseen(row), + failed: sessions.errorFor('${row['id'] ?? ''}') != null, + ), + ); + if (next != null) { + _openByShortcut(next); + return; + } + ScaffoldMessenger.maybeOf(context) + ?..hideCurrentSnackBar() + ..showSnackBar( + const SnackBar( + key: Key('chat-no-attention'), + content: Text('No other chat needs you.'), + ), + ); + } +} diff --git a/app/lib/features/chat/chat_screen_quick_switch.dart b/app/lib/features/chat/chat_screen_quick_switch.dart index adad1006..6940c3a9 100644 --- a/app/lib/features/chat/chat_screen_quick_switch.dart +++ b/app/lib/features/chat/chat_screen_quick_switch.dart @@ -1,16 +1,21 @@ part of 'screen.dart'; /// The quick switcher Ctrl+K / Alt+K (Cmd+K on a Mac) shows when pressed on -/// the Chat destination: the open chats to jump to, filtered as the operator -/// types (see [showChatQuickSwitch]). Pressing the shortcut again closes it. -/// A chosen chat opens as a keyboard choice from the list does: its pane is -/// reused when it is already open, and its composer takes the keyboard. +/// the Chat destination: the open chats to jump to, most recently used first +/// with the one used before the current chat selected, filtered as the +/// operator types (see [showChatQuickSwitch]). Pressing the shortcut again +/// closes it. A chosen chat opens as a keyboard choice from the list does: +/// its pane is reused when it is already open, and its composer takes the +/// keyboard. A closed chat a query found is reopened first. mixin _ChatScreenQuickSwitch on State, _ChatScreenWorkspace { ChatRuntime get _runtime; ModalRoute? _quickSwitchRoute; - void _bindQuickSwitch() => _runtime.quickSwitch.attach(_toggleQuickSwitch); + void _bindQuickSwitch() { + _runtime.quickSwitch.attach(_toggleQuickSwitch); + unawaited(_runtime.recency.load()); + } void _unbindQuickSwitch() { _runtime.quickSwitch.detach(_toggleQuickSwitch); @@ -24,6 +29,12 @@ mixin _ChatScreenQuickSwitch on State, _ChatScreenWorkspace { } } + @override + void _touchActiveChat() { + final id = _workspaceVisible ? _workspace.activePane?.sessionId : null; + if (id != null) _runtime.recency.touch(id); + } + void _toggleQuickSwitch() { final open = _quickSwitchRoute; if (open != null && open.isActive) { @@ -36,9 +47,11 @@ mixin _ChatScreenQuickSwitch on State, _ChatScreenWorkspace { final route = showChatQuickSwitch( context, sessions: _runtime.sessions, + recent: () => _runtime.recency.ids, + currentId: _workspaceVisible ? _workspace.activePane?.sessionId : null, serverName: _quickSwitchServerName, onSelected: (row) { - if (mounted) _openByShortcut(row); + if (mounted) unawaited(_openSwitched(row)); }, ); _quickSwitchRoute = route; @@ -47,6 +60,20 @@ mixin _ChatScreenQuickSwitch on State, _ChatScreenWorkspace { }); } + /// Opens a chosen chat, reopening it first when it was closed. A refused + /// reopen leaves it closed, with the list row showing the server's words. + Future _openSwitched(JsonMap row) async { + if (chatQuickSwitchIsClosed(row)) { + final id = '${row['id'] ?? ''}'; + await _runtime.sessions.reopen(id); + if (!mounted || _runtime.sessions.errorFor(id) != null) return; + row = {...row} + ..remove('closed_at') + ..remove('closed'); + } + if (mounted) _openByShortcut(row); + } + /// The machine a federated row is on, as the list names it. String? _quickSwitchServerName(JsonMap row) { final id = '${row['_server_id'] ?? ''}'; diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 36fb4e97..ea8d4415 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -365,6 +365,7 @@ mixin _ChatScreenWorkspace on State { if (_workspaceSignature == signature) return; _workspaceSignature = signature; _syncOpenWorkspace(); + _touchActiveChat(); void update() { if (!mounted) return; setState(() {}); @@ -379,6 +380,10 @@ mixin _ChatScreenWorkspace on State { } } + /// The active pane's chat, while shown, is the most recently used one (the + /// quick switcher's order). + void _touchActiveChat(); + void _publishWorkspaceRoute() { if (!mounted) return; final id = _workspace.activePane?.sessionId; diff --git a/app/lib/features/chat/conversation/chat_quick_switch_dialog.dart b/app/lib/features/chat/conversation/chat_quick_switch_dialog.dart index 73a317b0..306ffcc3 100644 --- a/app/lib/features/chat/conversation/chat_quick_switch_dialog.dart +++ b/app/lib/features/chat/conversation/chat_quick_switch_dialog.dart @@ -4,28 +4,39 @@ import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/app_popups.dart'; import '../domain/chat_quick_switch.dart'; +import '../domain/chat_quick_switch_order.dart'; import '../ui/sessions/chat_sessions_controller.dart'; import 'chat_quick_switch_keys.dart'; import 'chat_quick_switch_row.dart'; /// Shows the chat quick switcher over the Chat destination: a search field /// with the keyboard in it above the open chats ([chatQuickSwitchCandidates]), -/// narrowed and ranked as the operator types ([chatQuickSwitchMatches]). The -/// first match is selected; Ctrl+N / Ctrl+P and Down / Up move the selection, -/// wrapping, and Enter or a click chooses it. Esc closes it. +/// most recently used first ([recent]), narrowed and ranked as the operator +/// types ([chatQuickSwitchMatches]). With no query the chat used before +/// [currentId] is selected, so the shortcut and then Enter go back to it; +/// with one, the best match. A query also lists the closed chats it matches +/// under "Closed", after the open ones. Ctrl+N / Ctrl+P and Down / Up move +/// the selection, wrapping, and Enter or a click chooses it. Esc closes it. /// /// A centred dialog on a wide app, a full-width bottom sheet on a phone, on /// the root navigator either way. Returns the route so a second press of the -/// shortcut can close it; [onSelected] gets the chosen row once it closed. +/// shortcut can close it; [onSelected] gets the chosen row once it closed (a +/// closed row is still closed: the caller reopens it). ModalRoute showChatQuickSwitch( BuildContext context, { required ChatSessionsController sessions, required ValueChanged onSelected, String? Function(JsonMap session)? serverName, + List Function()? recent, + String? currentId, }) { final navigator = Navigator.of(context, rootNavigator: true); - Widget content(BuildContext context) => - ChatQuickSwitch(sessions: sessions, serverName: serverName); + Widget content(BuildContext context) => ChatQuickSwitch( + sessions: sessions, + serverName: serverName, + recent: recent?.call() ?? const [], + currentId: currentId, + ); final ModalRoute route = usesDesktopPopups(context) ? DialogRoute( context: context, @@ -76,11 +87,23 @@ void closeChatQuickSwitch(ModalRoute route) { /// The switcher's content: the field and the matching chats. class ChatQuickSwitch extends StatefulWidget { - const ChatQuickSwitch({super.key, required this.sessions, this.serverName}); + const ChatQuickSwitch({ + super.key, + required this.sessions, + this.serverName, + this.recent = const [], + this.currentId, + }); final ChatSessionsController sessions; final String? Function(JsonMap session)? serverName; + /// The chats used on this device, most recent first. + final List recent; + + /// The chat shown when the switcher opened, if any. + final String? currentId; + @override State createState() => _ChatQuickSwitchState(); } @@ -88,16 +111,52 @@ class ChatQuickSwitch extends StatefulWidget { class _ChatQuickSwitchState extends State { final _query = TextEditingController(); final _rowKeys = {}; - int _selected = 0; + + /// The row the operator moved to; null keeps the initial selection + /// ([chatQuickSwitchInitialSelection]). + int? _moved; List _shown = const []; + /// How many of [_shown] are open chats; the closed ones follow. + int _openCount = 0; + @override void dispose() { _query.dispose(); super.dispose(); } - void _queryChanged(String _) => setState(() => _selected = 0); + void _queryChanged(String _) => setState(() => _moved = null); + + int get _selected => + _moved ?? + chatQuickSwitchInitialSelection( + _shown, + currentId: widget.currentId, + emptyQuery: _query.text.trim().isEmpty, + ); + + /// The open matches, then (with a query) the closed ones. + void _match() { + final query = _query.text; + final open = chatQuickSwitchMatches( + chatQuickSwitchByRecency( + chatQuickSwitchCandidates(widget.sessions.sessions), + widget.recent, + ), + query, + serverName: widget.serverName, + ); + final closed = query.trim().isEmpty + ? const [] + : chatQuickSwitchMatches( + chatQuickSwitchClosed(widget.sessions.sessions), + query, + serverName: widget.serverName, + ); + _openCount = open.length; + _shown = [...open, ...closed]; + } /// Moves the selection [step] rows, wrapping, and scrolls it into view at /// the edge it moved towards. @@ -105,7 +164,7 @@ class _ChatQuickSwitchState extends State { if (_shown.isEmpty) return; final from = _selected.clamp(0, _shown.length - 1); final index = (from + step) % _shown.length; - setState(() => _selected = index); + setState(() => _moved = index); final id = '${_shown[index]['id'] ?? ''}'; final policy = step < 0 ? ScrollPositionAlignmentPolicy.keepVisibleAtStart @@ -154,11 +213,7 @@ class _ChatQuickSwitchState extends State { final list = ListenableBuilder( listenable: widget.sessions, builder: (context, _) { - _shown = chatQuickSwitchMatches( - chatQuickSwitchCandidates(widget.sessions.sessions), - _query.text, - serverName: widget.serverName, - ); + _match(); if (_shown.isEmpty) { return Padding( padding: const EdgeInsets.all(24), @@ -181,7 +236,9 @@ class _ChatQuickSwitchState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ - for (final (index, row) in _shown.indexed) + for (final (index, row) in _shown.indexed) ...[ + if (index == _openCount) + const ChatQuickSwitchSectionHeader(title: 'Closed'), ChatQuickSwitchRow( key: _rowKeys.putIfAbsent( '${row['id'] ?? ''}', @@ -190,8 +247,16 @@ class _ChatQuickSwitchState extends State { session: row, serverName: widget.serverName?.call(row), selected: index == selected, + closed: index >= _openCount, + markers: index >= _openCount + ? const [] + : chatQuickSwitchMarkers( + row, + unread: widget.sessions.isUnseen(row), + ), onTap: () => _choose(row), ), + ], ], ), ); diff --git a/app/lib/features/chat/conversation/chat_quick_switch_requests.dart b/app/lib/features/chat/conversation/chat_quick_switch_requests.dart index c0da63d8..2252d992 100644 --- a/app/lib/features/chat/conversation/chat_quick_switch_requests.dart +++ b/app/lib/features/chat/conversation/chat_quick_switch_requests.dart @@ -1,7 +1,9 @@ import 'package:flutter/foundation.dart'; -/// Where Ctrl+K / Alt+K pressed on the Chat destination goes: the mounted -/// chat screen attaches its quick switcher here, and the app toggles it. +/// Where an app-wide chat shortcut goes: Ctrl+K / Alt+K pressed on the Chat +/// destination (the quick switcher), Alt+N (New chat) and Alt+J (the next +/// chat needing the operator). The mounted chat screen attaches its action +/// here, and the app runs it. class ChatQuickSwitchRequests { VoidCallback? _toggle; diff --git a/app/lib/features/chat/conversation/chat_quick_switch_row.dart b/app/lib/features/chat/conversation/chat_quick_switch_row.dart index c8bd5232..3c32f132 100644 --- a/app/lib/features/chat/conversation/chat_quick_switch_row.dart +++ b/app/lib/features/chat/conversation/chat_quick_switch_row.dart @@ -2,14 +2,17 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_list_activity.dart'; +import '../domain/chat_quick_switch_order.dart'; import '../domain/chat_sessions.dart'; import '../ui/sessions/session_row_content.dart'; import '../ui/sessions/session_row_style.dart'; /// One chat in the quick switcher: the list's avatar (harness mark in the /// chat's colour, with its running or awaiting badge), the title, and the -/// folder with the machine it is on. The selected row takes the selection -/// fill; hover and click work as on any list tile. +/// folder with the machine it is on, then small [markers] (needs you, +/// working, unread) and the star. A [closed] chat (listed under "Closed", +/// reopened when chosen) shows no live state. The selected row takes the selection fill; hover +/// and click work as on any list tile. class ChatQuickSwitchRow extends StatelessWidget { const ChatQuickSwitchRow({ super.key, @@ -17,22 +20,31 @@ class ChatQuickSwitchRow extends StatelessWidget { required this.selected, required this.onTap, this.serverName, + this.markers = const [], + this.closed = false, }); final JsonMap session; final bool selected; final VoidCallback onTap; final String? serverName; + final List markers; + final bool closed; @override Widget build(BuildContext context) { final id = '${session['id'] ?? ''}'; final scheme = Theme.of(context).colorScheme; - final running = session['running'] == true; + final running = !closed && session['running'] == true; final subtitle = [ homeRelativePath('${session['directory'] ?? ''}'.trim()), ?serverName, ].where((part) => part.isNotEmpty).join(' · '); + final trailing = [ + for (final marker in markers) ChatQuickSwitchMarkerIcon(marker: marker), + if (session['starred'] == true) + Icon(Icons.star, color: scheme.primary, semanticLabel: 'Starred'), + ]; return ListTile( key: Key('chat-quick-switch-row-$id'), selected: selected, @@ -43,7 +55,7 @@ class ChatQuickSwitchRow extends StatelessWidget { session: session, running: running, backgroundTasks: running ? 0 : chatSessionBackgroundTasks(session), - awaitingOperator: chatSessionAwaitingOperator(session), + awaitingOperator: closed ? 0 : chatSessionAwaitingOperator(session), ), title: Text( chatSessionTitle(session), @@ -53,10 +65,70 @@ class ChatQuickSwitchRow extends StatelessWidget { subtitle: subtitle.isEmpty ? null : Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis), - trailing: session['starred'] == true - ? Icon(Icons.star, color: scheme.primary, semanticLabel: 'Starred') - : null, + trailing: trailing.isEmpty + ? null + : Row(mainAxisSize: MainAxisSize.min, spacing: 6, children: trailing), onTap: onTap, ); } } + +/// One row marker: a small icon in the state's colour, named by its tooltip +/// and to assistive technology. +class ChatQuickSwitchMarkerIcon extends StatelessWidget { + const ChatQuickSwitchMarkerIcon({super.key, required this.marker}); + + final ChatQuickSwitchMarker marker; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final (icon, color) = switch (marker) { + ChatQuickSwitchMarker.needsYou => ( + Icons.notifications_active, + scheme.error, + ), + ChatQuickSwitchMarker.working => ( + Icons.play_circle_outline, + scheme.onSurfaceVariant, + ), + ChatQuickSwitchMarker.unread => (Icons.circle, scheme.primary), + }; + return Tooltip( + message: marker.label, + child: Icon( + icon, + key: Key('chat-quick-switch-marker-${marker.name}'), + size: marker == ChatQuickSwitchMarker.unread ? 10 : 18, + color: color, + semanticLabel: marker.label, + ), + ); + } +} + +/// The heading over the switcher's closed chats. +class ChatQuickSwitchSectionHeader extends StatelessWidget { + const ChatQuickSwitchSectionHeader({super.key, required this.title}); + + final String title; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Container( + alignment: AlignmentDirectional.centerStart, + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Semantics( + header: true, + child: Text( + title, + key: const Key('chat-quick-switch-closed-header'), + style: theme.textTheme.labelLarge?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/data/chat_recency.dart b/app/lib/features/chat/data/chat_recency.dart new file mode 100644 index 00000000..d9d95441 --- /dev/null +++ b/app/lib/features/chat/data/chat_recency.dart @@ -0,0 +1,101 @@ +import 'dart:async'; + +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../../core/servers/server_scope.dart'; + +/// Where the chats' most-recently-used order is kept on this device. +abstract interface class ChatRecencyStore { + Future> read(); + + Future write(List ids); +} + +/// The chats this device used, most recent first, for the quick switcher's +/// order with no query. A chat counts as used when it is opened or its pane +/// takes focus ([touch]). The list is read once, lazily, and written back on +/// every change; a chat touched before the read finished stays in front. +class ChatRecency { + ChatRecency({ChatRecencyStore? store, this.limit = 200}) + : _store = store ?? MemoryChatRecencyStore(); + + final ChatRecencyStore _store; + + /// How many chats are remembered. + final int limit; + + List _ids = const []; + Future? _loading; + + /// The remembered chats, most recent first. + List get ids => _ids; + + /// Reads the stored order once; later calls return the same read. + Future load() => _loading ??= _read(); + + Future _read() async { + List stored; + try { + stored = await _store.read(); + } catch (_) { + stored = const []; + } + _ids = _merged(_ids, stored); + } + + /// [id] was opened or focused: it moves to the front. + void touch(String id) { + if (id.isEmpty || (_ids.isNotEmpty && _ids.first == id)) return; + _ids = _merged([id], _ids); + unawaited(load().then((_) => _write())); + } + + Future _write() async { + try { + await _store.write(_ids); + } catch (_) { + // The order is a convenience; the switcher still lists every chat. + } + } + + List _merged(List front, List rest) { + final seen = {}; + return [ + for (final id in [...front, ...rest]) + if (id.isNotEmpty && seen.add(id)) id, + ].take(limit).toList(growable: false); + } +} + +class SharedPreferencesChatRecencyStore implements ChatRecencyStore { + const SharedPreferencesChatRecencyStore({this.serverScope = ''}); + + final String serverScope; + + String get _key => scopedServerKey('pipelines.chat.recency.v1', serverScope); + + @override + Future> read() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getStringList(_key) ?? const []; + } + + @override + Future write(List ids) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setStringList(_key, ids); + } +} + +/// An in-memory store for tests and hosts without preferences. +class MemoryChatRecencyStore implements ChatRecencyStore { + MemoryChatRecencyStore([List? ids]) : ids = ids ?? []; + + List ids; + + @override + Future> read() async => List.of(ids); + + @override + Future write(List ids) async => this.ids = List.of(ids); +} diff --git a/app/lib/features/chat/domain/chat_attention_cycle.dart b/app/lib/features/chat/domain/chat_attention_cycle.dart new file mode 100644 index 00000000..e574810a --- /dev/null +++ b/app/lib/features/chat/domain/chat_attention_cycle.dart @@ -0,0 +1,40 @@ +import '../../../core/api_gateway.dart'; +import 'chat_list_activity.dart'; +import 'chat_sessions.dart'; + +/// Whether an open chat needs the operator: it waits on an approval or a +/// question, has replies not read yet ([unread]), or an action on it failed +/// ([failed]). +bool chatNeedsAttention( + JsonMap session, { + required bool unread, + required bool failed, +}) => chatSessionAwaitingOperator(session) > 0 || unread || failed; + +/// The chat Alt+J opens: the next open chat after [currentId], in the order +/// the list draws them (starred, then by directory; folded sections count), +/// that [needsAttention], wrapping around. With no current chat (or one not +/// among the open chats) the first such chat. Null when no other chat needs +/// the operator. +JsonMap? chatNextNeedingAttention( + List sessions, + String? currentId, + bool Function(JsonMap session) needsAttention, +) { + final open = chatSessionsInListOrder( + chatSessionSections( + sessions + .where((row) => row['closed_at'] == null && row['closed'] != true) + .toList(), + ), + isOpen: (_) => true, + ); + if (open.isEmpty) return null; + final at = open.indexWhere((row) => '${row['id'] ?? ''}' == currentId); + for (var step = 1; step <= open.length; step++) { + final row = open[(at + step) % open.length]; + if ('${row['id'] ?? ''}' == currentId) continue; + if (needsAttention(row)) return row; + } + return null; +} diff --git a/app/lib/features/chat/domain/chat_quick_switch_order.dart b/app/lib/features/chat/domain/chat_quick_switch_order.dart new file mode 100644 index 00000000..114ec611 --- /dev/null +++ b/app/lib/features/chat/domain/chat_quick_switch_order.dart @@ -0,0 +1,73 @@ +import '../../../core/api_gateway.dart'; +import 'chat_list_activity.dart'; + +/// [candidates] most recently used first: each chat in [recent] (most recent +/// first) by its place there, then the chats never used on this device in +/// [candidates]' own order. +List chatQuickSwitchByRecency( + List candidates, + List recent, +) { + final rank = {for (final (index, id) in recent.indexed) id: index}; + final indexed = candidates.indexed.toList() + ..sort((a, b) { + final ra = rank['${a.$2['id'] ?? ''}']; + final rb = rank['${b.$2['id'] ?? ''}']; + if (ra != null && rb != null) return ra - rb; + if (ra != null) return -1; + if (rb != null) return 1; + return a.$1 - b.$1; + }); + return [for (final (_, row) in indexed) row]; +} + +/// Whether [row] is a closed chat. +bool chatQuickSwitchIsClosed(JsonMap row) => + row['closed_at'] != null || row['closed'] == true; + +/// The closed chats the switcher offers under "Closed" once a query matches +/// them, most recently closed first. +List chatQuickSwitchClosed(List sessions) { + int closedAt(JsonMap row) { + final at = row['closed_at']; + return at is num ? at.toInt() : 0; + } + + return sessions.where(chatQuickSwitchIsClosed).toList() + ..sort((a, b) => closedAt(b) - closedAt(a)); +} + +/// The row the switcher selects first: with no query, the first chat that is +/// not [currentId] (the one used before it, so the shortcut and then Enter go +/// back there, as Alt+Tab does); with a query, the best match. +int chatQuickSwitchInitialSelection( + List shown, { + required String? currentId, + required bool emptyQuery, +}) { + if (!emptyQuery || currentId == null) return 0; + final index = shown.indexWhere((row) => '${row['id'] ?? ''}' != currentId); + return index < 0 ? 0 : index; +} + +/// What a switcher row marks about its chat, most urgent first. +enum ChatQuickSwitchMarker { + needsYou('Needs you'), + working('Working'), + unread('Unread'); + + const ChatQuickSwitchMarker(this.label); + + final String label; +} + +/// [session]'s markers: approvals or questions waiting on the operator, a +/// turn running, and replies not read yet ([unread], as the list reads it). +List chatQuickSwitchMarkers( + JsonMap session, { + required bool unread, +}) => [ + if (chatSessionAwaitingOperator(session) > 0) ChatQuickSwitchMarker.needsYou, + if (session['running'] == true) ChatQuickSwitchMarker.working, + if (unread) ChatQuickSwitchMarker.unread, +]; diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 7286deab..694632ee 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -50,7 +50,9 @@ import 'ui/sessions/chat_adaptive.dart'; import 'conversation/composer_focus_request.dart'; import 'conversation/composer_selection_focus.dart'; import 'domain/chat_commands.dart'; +import 'domain/chat_attention_cycle.dart'; import 'domain/chat_cycle.dart'; +import 'domain/chat_quick_switch_order.dart'; import '../terminal/terminal_scope.dart'; import 'domain/chat_colors.dart'; import 'ui/sessions/chat_color_palette.dart'; @@ -59,6 +61,7 @@ import 'ui/sessions/chat_sessions_controller.dart'; import 'ui/sessions/chat_sessions_screen.dart'; import '../../ui/input/keyboard_owner.dart'; +part 'chat_screen_attention.dart'; part 'chat_screen_float.dart'; part 'chat_screen_pane_menu.dart'; part 'chat_screen_keys.dart'; @@ -121,7 +124,8 @@ class _ChatScreenState extends State _ChatScreenKeys, _ChatScreenFloat, _ChatScreenPaneMenu, - _ChatScreenQuickSwitch { + _ChatScreenQuickSwitch, + _ChatScreenAttention { /// The chats' shared state: the list, opened rows, accepted models, /// transcript positions and caches (see [ChatRuntime]). @override @@ -161,11 +165,13 @@ class _ChatScreenState extends State _runtime.addSessionReplacedListener(_replacedElsewhere); _bindWindows(); _bindQuickSwitch(); + _bindAttention(); final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); _workspaceVisible = true; _publishedWorkspaceSession = initial; + _runtime.recency.touch(initial); } _workspace.addListener(_workspaceChanged); _bindWorkspacePersistence(); @@ -256,6 +262,7 @@ class _ChatScreenState extends State _openedSessions[id] = session; _workspaceVisible = true; _workspace.open(id); + _runtime.recency.touch(id); // A docked chat chosen while chat windows float over the workspace would // open behind them: hide the windows so the chosen chat is seen. final windows = widget.windows; @@ -465,6 +472,7 @@ class _ChatScreenState extends State _openWorkspace?.dispose(); _unbindWindows(); _unbindQuickSwitch(); + _unbindAttention(); _workspace.removeListener(_workspaceChanged); _workspace.dispose(); _sessions.removeListener(_nextChanged); diff --git a/app/lib/features/runs/ui/run_detail_tab_keys.dart b/app/lib/features/runs/ui/run_detail_tab_keys.dart new file mode 100644 index 00000000..90aac032 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_tab_keys.dart @@ -0,0 +1,40 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../../../ui/input/keyboard_owner.dart'; + +const _digits = [ + LogicalKeyboardKey.digit1, + LogicalKeyboardKey.digit2, + LogicalKeyboardKey.digit3, + LogicalKeyboardKey.digit4, + LogicalKeyboardKey.numpad1, + LogicalKeyboardKey.numpad2, + LogicalKeyboardKey.numpad3, + LogicalKeyboardKey.numpad4, +]; + +/// The 0-based run-detail tab a bare 1…4 key press names, or null. Any +/// modifier (Ctrl+1…9 opens a chat list item) or a repeat is not the key. +int? runDetailTabDigit(KeyEvent event, HardwareKeyboard keyboard) { + if (event is! KeyDownEvent || + keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isAltPressed || + keyboard.isShiftPressed) { + return null; + } + final index = _digits.indexOf(event.logicalKey); + return index < 0 ? null : index % 4; +} + +/// Whether a digit pressed now is meant for the run detail at [context]: it +/// is on screen (not in a hidden destination or tab), no dialog, menu or +/// visit page is over it, and nothing that takes typing (a text field, the +/// terminal) has the keyboard. +bool runDetailOwnsDigits(BuildContext context) { + if (!TickerMode.valuesOf(context).enabled) return false; + final route = ModalRoute.of(context); + if (route != null && !route.isCurrent) return false; + return !primaryFocusTakesTyping(); +} diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index b0e1ba27..71576333 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -7,6 +7,7 @@ import '../../../ui/motion/fade_through_stack.dart'; import 'dart:math' as math; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../graph/widgets/run_graph_view.dart'; @@ -19,6 +20,7 @@ import 'run_detail_content.dart'; import 'run_graph_preview.dart'; import 'run_detail_tab.dart'; import 'run_detail_tab_bodies.dart'; +import 'run_detail_tab_keys.dart'; import 'run_detail_tab_strip.dart'; import 'run_detail_timeline.dart'; import 'run_detail_visit.dart'; @@ -125,6 +127,19 @@ class _RunDetailTabsState extends State { void initState() { super.initState(); _applyInitialVisit(); + HardwareKeyboard.instance.addHandler(_tabDigitKey); + } + + /// A bare 1…4 outside text fields selects that tab of the shown ones. + bool _tabDigitKey(KeyEvent event) { + final index = runDetailTabDigit(event, HardwareKeyboard.instance); + if (index == null || !mounted || !runDetailOwnsDigits(context)) { + return false; + } + final tabs = _tabsFor(widget.run); + if (index >= tabs.length) return false; + if (_tab != tabs[index]) setState(() => _tab = tabs[index]); + return true; } @override @@ -141,6 +156,7 @@ class _RunDetailTabsState extends State { @override void dispose() { + HardwareKeyboard.instance.removeHandler(_tabDigitKey); _inputSection.dispose(); _outputSection.dispose(); _liveRun.dispose(); diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 9a7984a4..310a5fd3 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -4,6 +4,7 @@ import '../chat/workspace/chat_center_stage_controller.dart'; import '../chat/workspace/chat_float_shortcut.dart'; import '../terminal/terminal_shortcuts.dart'; import '../../shell/windows/window_shortcuts.dart'; +import '../../shell/shell_chat_actions_shortcut.dart'; import '../../shell/shell_chat_shortcut.dart'; import '../../shell/shell_cheatsheet_shortcut.dart'; import '../../shell/shell_runs_pipelines_shortcut.dart'; @@ -114,7 +115,21 @@ class KeyboardShortcutRegistry { action: 'Switch to another chat', keys: shellChatShortcutLabels(platform).join(', '), caveat: - 'On Chat: type to filter the open chats, Ctrl+N or Down and Ctrl+P or Up to move, Enter to open, Esc or the shortcut again to close.${web ? ' A browser tab keeps Ctrl+N (new window) for itself; use Down, or the installed app.' : ''}', + 'On Chat: the open chats, most recently used first, with the previous chat selected, so the shortcut then Enter goes back to it. Type to filter (matching closed chats are listed under Closed; Enter reopens one), Ctrl+N or Down and Ctrl+P or Up to move, Enter to open, Esc or the shortcut again to close.${web ? ' A browser tab keeps Ctrl+N (new window) for itself; use Down, or the installed app.' : ''}', + ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'New chat', + keys: shellChatActionLabel(ShellChatAction.newChat, platform), + caveat: + 'From any destination. In the terminal the key goes to the terminal.', + ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'Next chat needing you', + keys: shellChatActionLabel(ShellChatAction.nextAttention, platform), + caveat: + 'Opens the next chat waiting for you, with unread replies, or with a failed action, in list order; press again to cycle. In the terminal the key goes to the terminal.', ), KeyboardShortcutEntry( group: KeyboardShortcutGroup.chat, @@ -280,6 +295,13 @@ class KeyboardShortcutRegistry { caveat: 'Available when the Chat list is mounted; numbers select its visible item.', ), + const KeyboardShortcutEntry( + group: KeyboardShortcutGroup.lists, + action: 'Switch run detail tabs', + keys: '1, 2, 3, 4', + caveat: + 'In a run: Summary, Timeline, Artifacts, Changes, as the run offers them. Not while typing.', + ), const KeyboardShortcutEntry( group: KeyboardShortcutGroup.lists, action: 'Resize a list pane', diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index f5a2be80..8bef446f 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -12,6 +12,7 @@ import 'shell_navigation_bar.dart'; import 'shell_rail_scope.dart'; import 'list_pane_widths.dart'; import 'shell_bar.dart'; +import 'shell_chat_actions_shortcut.dart'; import 'shell_chat_shortcut.dart'; import 'shell_cheatsheet.dart'; import 'shell_cheatsheet_shortcut.dart'; @@ -33,6 +34,7 @@ class AdaptiveShell extends StatefulWidget { this.onSearch, this.onOpenChat, this.onChatQuickSwitch, + this.onChatAction, this.attentionCount = 0, this.runningRunCount, this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(), @@ -77,6 +79,11 @@ class AdaptiveShell extends StatefulWidget { /// the composer focus of [onOpenChat] there too. final VoidCallback? onChatQuickSwitch; + /// Runs after Alt+N or Alt+J (see [shellChatActionShortcut]) has shown the + /// Chat destination: the host starts a new chat or opens the next chat + /// needing the operator. Null leaves both chords unhandled. + final ValueChanged? onChatAction; + /// Runs needing the operator today, retained in the tab's accessible label. final int attentionCount; @@ -410,8 +417,20 @@ class _AdaptiveShellState extends State { } return true; } - // A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits). + // A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits, Alt+N, Alt+J). if (primaryFocusIsTypingSurface()) return false; + final chatAction = widget.onChatAction == null + ? null + : shellChatActionShortcut(event, keyboard); + if (chatAction != null) { + // A dialog or popup over the shell keeps its keys. + if (!_shellRouteHasKeyboard()) return false; + if (event is KeyDownEvent) { + if (_selected != AppDestination.chat) _select(AppDestination.chat); + widget.onChatAction!(chatAction); + } + return true; + } if (_selected == AppDestination.search && event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.escape && @@ -450,6 +469,16 @@ class _AdaptiveShellState extends State { widget.onOpenChat?.call(); } + /// Whether the keyboard is outside any dialog, sheet or menu (a page, such + /// as a phone's open chat, is fine). + bool _shellRouteHasKeyboard() { + final focusedContext = FocusManager.instance.primaryFocus?.context; + final focusedRoute = focusedContext == null + ? null + : ModalRoute.of(focusedContext); + return focusedRoute is! PopupRoute; + } + /// A popup or nested viewer owns Escape before the underlying Search tab. bool _searchEscape() { final route = ModalRoute.of(context); diff --git a/app/lib/shell/shell_chat_actions_shortcut.dart b/app/lib/shell/shell_chat_actions_shortcut.dart new file mode 100644 index 00000000..b3692be5 --- /dev/null +++ b/app/lib/shell/shell_chat_actions_shortcut.dart @@ -0,0 +1,56 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// The app-wide chat actions bound to a bare Alt chord (Option on a Mac). +enum ShellChatAction { + /// Alt+N: a new chat, with the Chat list's create dialog. + newChat, + + /// Alt+J: the next chat waiting for the operator, unread or failed. + nextAttention, +} + +/// The chat action [event] asks for, or null: Alt+N or Alt+J with no other +/// modifier. Option+N and Option+J yield a dead key or a symbol on a Mac, so +/// the key is matched by position as well. Repeats of a held chord match too, +/// so the caller can swallow them; only the first press acts. +/// +/// Neither chord is taken by Chromium, Firefox or Safari on Linux, Windows or +/// macOS, nor by the app's other shortcuts (Alt+K, Alt+T, Alt+Y, Alt+E, +/// Alt+`, Alt+/). The terminal keeps both for readline (Alt+N searches +/// history), so the caller leaves them to it while it has the keyboard. +ShellChatAction? shellChatActionShortcut( + KeyEvent event, + HardwareKeyboard keyboard, +) { + if (event is KeyUpEvent || + !keyboard.isAltPressed || + keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isShiftPressed) { + return null; + } + bool key(LogicalKeyboardKey logical, PhysicalKeyboardKey physical) => + event.logicalKey == logical || event.physicalKey == physical; + if (key(LogicalKeyboardKey.keyN, PhysicalKeyboardKey.keyN)) { + return ShellChatAction.newChat; + } + if (key(LogicalKeyboardKey.keyJ, PhysicalKeyboardKey.keyJ)) { + return ShellChatAction.nextAttention; + } + return null; +} + +/// [action]'s chord as it reads on [platform], for the help page. +String shellChatActionLabel( + ShellChatAction action, [ + TargetPlatform? platform, +]) { + final target = platform ?? defaultTargetPlatform; + final apple = target == TargetPlatform.macOS || target == TargetPlatform.iOS; + final letter = switch (action) { + ShellChatAction.newChat => 'N', + ShellChatAction.nextAttention => 'J', + }; + return '${apple ? 'Option' : 'Alt'}+$letter'; +} diff --git a/app/test/application/chat_quick_switch_shortcut_test.dart b/app/test/application/chat_quick_switch_shortcut_test.dart index 57482659..4ef9af04 100644 --- a/app/test/application/chat_quick_switch_shortcut_test.dart +++ b/app/test/application/chat_quick_switch_shortcut_test.dart @@ -13,7 +13,11 @@ import 'chat_registration_test.dart' final _field = find.byKey(const Key('chat-quick-switch-field')); -Future _replySessions(WidgetTester tester, FakeChannel channel) async { +Future _replySessions( + WidgetTester tester, + FakeChannel channel, { + bool awaiting = false, +}) async { final request = await waitForRequest(tester, channel, 'chat_sessions'); channel.incoming.add( jsonEncode({ @@ -22,7 +26,12 @@ Future _replySessions(WidgetTester tester, FakeChannel channel) async { 'chat_sessions': [ {'id': 's1', 'title': 'Wire chat', 'directory': '/workspace/demo'}, {'id': 's2', 'title': 'Second chat', 'directory': '/workspace/other'}, - {'id': 's3', 'title': 'Third chat', 'directory': '/workspace/demo'}, + { + 'id': 's3', + 'title': 'Third chat', + 'directory': '/workspace/demo', + if (awaiting) 'activity': {'awaiting_operator': 1, 'seq': 1}, + }, ], }), ); @@ -31,8 +40,9 @@ Future _replySessions(WidgetTester tester, FakeChannel channel) async { Future _mountOnChat( WidgetTester tester, - PlatformRouteInformationProvider provider, -) async { + PlatformRouteInformationProvider provider, { + bool awaiting = false, +}) async { tester.view.physicalSize = const Size(1200, 900); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); @@ -48,10 +58,15 @@ Future _mountOnChat( ), ); await tester.pump(); - await _replySessions(tester, channel); + await _replySessions(tester, channel, awaiting: awaiting); await replySubscribe(tester, channel); await replyHistory(tester, channel); - await tester.pumpAndSettle(); + // A chat waiting for the operator pulses its badge, so it never settles. + if (awaiting) { + await tester.pump(const Duration(seconds: 1)); + } else { + await tester.pumpAndSettle(); + } expect(find.byType(ChatThreadView), findsOneWidget); return channel; } @@ -149,6 +164,81 @@ void main() { await _teardown(tester); }); + testWidgets('the shortcut then Enter returns to the previous chat', ( + tester, + ) async { + final provider = _provider(); + final channel = await _mountOnChat(tester, provider); + await _chord(tester, LogicalKeyboardKey.controlLeft); + await tester.enterText(_field, 'second'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + await replySubscribe(tester, channel, index: 1); + await replyHistory(tester, channel, index: 1); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat/s2'); + + await _chord(tester, LogicalKeyboardKey.controlLeft); + // Most recent first: the open chat, then the one before it, selected. + final rows = tester + .widgetList( + find.byWidgetPredicate( + (w) => + w is ListTile && '${w.key}'.contains('chat-quick-switch-row'), + ), + ) + .toList(); + expect( + rows.map((tile) => '${tile.key}'.split('row-').last.split("'").first), + ['s2', 's1', 's3'], + ); + expect(rows[1].selected, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat/s1'); + await _teardown(tester); + }); + + testWidgets('Alt+J opens the next chat waiting for you', (tester) async { + final provider = _provider(); + final channel = await _mountOnChat(tester, provider, awaiting: true); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyJ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + await tester.pump(); + await replySubscribe(tester, channel, index: 1); + await replyHistory(tester, channel, index: 1); + await tester.pump(const Duration(seconds: 1)); + expect(provider.value.uri.path, '/chat/s3'); + + // Only the open chat needs you now: nothing else to go to. + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyJ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + await tester.pump(); + expect(provider.value.uri.path, '/chat/s3'); + expect(find.text('No other chat needs you.'), findsOneWidget); + await _teardown(tester); + }); + + testWidgets('Alt+N from Runs opens New chat', (tester) async { + await _mountOnChat(tester, _provider()); + await tester.tap(find.byKey(const ValueKey('shell.destination.runs'))); + await tester.pump(const Duration(milliseconds: 600)); + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyN); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + expect(find.byType(Dialog), findsOneWidget); + await _teardown(tester); + }); + testWidgets('elsewhere the shortcut still jumps to Chat', (tester) async { final provider = _provider(); await _mountOnChat(tester, provider); diff --git a/app/test/features/chat/conversation/chat_quick_switch_dialog_test.dart b/app/test/features/chat/conversation/chat_quick_switch_dialog_test.dart index 0bcdd428..1128f1ae 100644 --- a/app/test/features/chat/conversation/chat_quick_switch_dialog_test.dart +++ b/app/test/features/chat/conversation/chat_quick_switch_dialog_test.dart @@ -31,6 +31,8 @@ class _Switcher { Future<_Switcher> _open( WidgetTester tester, { Size size = const Size(900, 800), + List recent = const [], + String? currentId, }) async { tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; @@ -54,6 +56,8 @@ Future<_Switcher> _open( onPressed: () => switcher.route = showChatQuickSwitch( context, sessions: controller, + recent: () => recent, + currentId: currentId, onSelected: (row) => switcher.chosen.add('${row['id']}'), ), child: const Text('Open'), @@ -162,8 +166,20 @@ void main() { 'build', ); await tester.pump(); - // The closed chat titled "Closed build" is not offered. - expect(_shown(tester), ['one']); + // The closed chat titled "Closed build" follows under Closed. + expect(_shown(tester), ['one', 'gone']); + expect( + find.byKey(const Key('chat-quick-switch-closed-header')), + findsOneWidget, + ); + expect( + tester.getTopLeft(find.text('Closed')).dy, + lessThan( + tester + .getTopLeft(find.byKey(const Key('chat-quick-switch-row-gone'))) + .dy, + ), + ); await tester.enterText( find.byKey(const Key('chat-quick-switch-field')), 'zzz', @@ -213,6 +229,38 @@ void main() { await tester.pump(); }); + testWidgets( + 'no query: most recent first, the previous chat selected; Enter goes back', + (tester) async { + final switcher = await _open( + tester, + recent: ['three', 'two'], + currentId: 'three', + ); + expect(_shown(tester), ['three', 'two', 'one']); + expect(_selected(tester), 'two'); + await _key(tester, LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(switcher.chosen, ['two']); + }, + ); + + testWidgets('rows mark working, needs you and unread chats', (tester) async { + await _open(tester); + final two = find.byKey(const Key('chat-quick-switch-row-two')); + expect( + find.descendant( + of: two, + matching: find.byKey(const Key('chat-quick-switch-marker-working')), + ), + findsOneWidget, + ); + expect( + find.byKey(const Key('chat-quick-switch-marker-needsYou')), + findsNothing, + ); + }); + testWidgets('a phone shows it as a full-width bottom sheet', (tester) async { await _open(tester, size: const Size(400, 800)); expect(find.byType(Dialog), findsNothing); diff --git a/app/test/features/chat/data/chat_recency_test.dart b/app/test/features/chat/data/chat_recency_test.dart new file mode 100644 index 00000000..d0f3c970 --- /dev/null +++ b/app/test/features/chat/data/chat_recency_test.dart @@ -0,0 +1,44 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/data/chat_recency.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + test('touch moves a chat to the front and persists the order', () async { + final store = MemoryChatRecencyStore(['b', 'a']); + final recency = ChatRecency(store: store); + await recency.load(); + expect(recency.ids, ['b', 'a']); + recency.touch('a'); + recency.touch('c'); + expect(recency.ids, ['c', 'a', 'b']); + await Future.delayed(Duration.zero); + expect(store.ids, ['c', 'a', 'b']); + }); + + test('a chat touched before the read stays in front', () async { + final recency = ChatRecency(store: MemoryChatRecencyStore(['b', 'a'])); + recency.touch('a'); + await recency.load(); + expect(recency.ids, ['a', 'b']); + }); + + test('keeps at most the limit', () async { + final recency = ChatRecency(limit: 2); + for (final id in ['a', 'b', 'c']) { + recency.touch(id); + } + expect(recency.ids, ['c', 'b']); + }); + + test('shared preferences keep the order per server', () async { + SharedPreferences.setMockInitialValues({}); + const one = SharedPreferencesChatRecencyStore(serverScope: 'one'); + const two = SharedPreferencesChatRecencyStore(serverScope: 'two'); + await one.write(['x', 'y']); + expect(await one.read(), ['x', 'y']); + expect(await two.read(), isEmpty); + final reloaded = ChatRecency(store: one); + await reloaded.load(); + expect(reloaded.ids, ['x', 'y']); + }); +} diff --git a/app/test/features/chat/domain/chat_quick_switch_order_test.dart b/app/test/features/chat/domain/chat_quick_switch_order_test.dart new file mode 100644 index 00000000..c0866394 --- /dev/null +++ b/app/test/features/chat/domain/chat_quick_switch_order_test.dart @@ -0,0 +1,113 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/domain/chat_attention_cycle.dart'; +import 'package:pipelines_app/features/chat/domain/chat_quick_switch_order.dart'; + +List ids(List rows) => [ + for (final row in rows) '${row['id']}', +]; + +void main() { + final rows = [ + {'id': 'a', 'title': 'A'}, + {'id': 'b', 'title': 'B'}, + {'id': 'c', 'title': 'C'}, + {'id': 'd', 'title': 'D'}, + ]; + + test('recently used chats lead, the rest keep their order', () { + expect(ids(chatQuickSwitchByRecency(rows, ['c', 'x', 'a'])), [ + 'c', + 'a', + 'b', + 'd', + ]); + expect(ids(chatQuickSwitchByRecency(rows, const [])), ['a', 'b', 'c', 'd']); + }); + + test('no query selects the chat used before the current one', () { + final shown = chatQuickSwitchByRecency(rows, ['c', 'a']); + expect( + chatQuickSwitchInitialSelection(shown, currentId: 'c', emptyQuery: true), + 1, + ); + // Not showing a chat: the most recent one. + expect( + chatQuickSwitchInitialSelection(shown, currentId: null, emptyQuery: true), + 0, + ); + // A query selects the best match, even the current chat. + expect( + chatQuickSwitchInitialSelection(shown, currentId: 'c', emptyQuery: false), + 0, + ); + expect( + chatQuickSwitchInitialSelection( + [rows.first], + currentId: 'a', + emptyQuery: true, + ), + 0, + ); + }); + + test('closed chats, most recently closed first', () { + expect( + ids( + chatQuickSwitchClosed([ + ...rows, + {'id': 'old', 'closed_at': 1}, + {'id': 'new', 'closed_at': 9}, + {'id': 'flag', 'closed': true}, + ]), + ), + ['new', 'old', 'flag'], + ); + }); + + test('markers: needs you, working, unread', () { + expect( + chatQuickSwitchMarkers({ + 'awaiting_operator': 2, + 'running': true, + }, unread: true), + [ + ChatQuickSwitchMarker.needsYou, + ChatQuickSwitchMarker.working, + ChatQuickSwitchMarker.unread, + ], + ); + expect(chatQuickSwitchMarkers({'id': 'a'}, unread: false), isEmpty); + }); + + group('next chat needing attention', () { + final sessions = [ + {'id': 'a', 'title': 'A', 'directory': '/x'}, + {'id': 'b', 'title': 'B', 'directory': '/x', 'awaiting_operator': 1}, + {'id': 'c', 'title': 'C', 'directory': '/x'}, + {'id': 'd', 'title': 'D', 'directory': '/x'}, + {'id': 'e', 'title': 'E', 'closed_at': 3, 'awaiting_operator': 1}, + ]; + const unread = {'d'}; + const failed = {'a'}; + bool needs(JsonMap row) => chatNeedsAttention( + row, + unread: unread.contains(row['id']), + failed: failed.contains(row['id']), + ); + + test('cycles in list order, wrapping, skipping closed chats', () { + expect(chatNextNeedingAttention(sessions, 'a', needs)?['id'], 'b'); + expect(chatNextNeedingAttention(sessions, 'b', needs)?['id'], 'd'); + expect(chatNextNeedingAttention(sessions, 'd', needs)?['id'], 'a'); + expect(chatNextNeedingAttention(sessions, 'c', needs)?['id'], 'd'); + expect(chatNextNeedingAttention(sessions, null, needs)?['id'], 'a'); + }); + + test('null when only the current chat needs the operator', () { + bool onlyB(JsonMap row) => row['id'] == 'b'; + expect(chatNextNeedingAttention(sessions, 'b', onlyB), isNull); + expect(chatNextNeedingAttention(sessions, 'a', onlyB)?['id'], 'b'); + }); + }); +} diff --git a/app/test/features/runs/ui/run_detail_tab_keys_test.dart b/app/test/features/runs/ui/run_detail_tab_keys_test.dart new file mode 100644 index 00000000..9a0da857 --- /dev/null +++ b/app/test/features/runs/ui/run_detail_tab_keys_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; + +import 'run_detail_graph_support.dart'; + +int _current(WidgetTester tester) => tester + .widget( + find.descendant( + of: find.byKey(const Key('run-detail-tabs')), + matching: find.byType(FloatingDestinationBar), + ), + ) + .currentIndex; + +void main() { + testWidgets('bare 1-4 switch the run detail tabs', (tester) async { + await pumpRunDetail(tester, RunDetailTestPlatform.material); + expect(_current(tester), 0); + await tester.sendKeyEvent(LogicalKeyboardKey.digit2); + await tester.pump(); + expect(_current(tester), 1); + await tester.sendKeyEvent(LogicalKeyboardKey.numpad1); + await tester.pump(); + expect(_current(tester), 0); + }); + + testWidgets('a modifier or a focused text field keeps the digit', ( + tester, + ) async { + await pumpRunDetail(tester, RunDetailTestPlatform.material); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.digit2); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + expect(_current(tester), 0); + + // A text field over the detail (in an overlay of the same route) types. + final field = TextEditingController(); + addTearDown(field.dispose); + final overlay = OverlayEntry( + builder: (_) => Material( + child: TextField(key: const Key('probe-field'), controller: field), + ), + ); + Overlay.of( + tester.element(find.byKey(const Key('run-detail-tabs'))), + ).insert(overlay); + await tester.pump(); + await tester.tap(find.byKey(const Key('probe-field'))); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.digit2); + await tester.pump(); + expect(_current(tester), 0); + overlay.remove(); + }); + + testWidgets('a dialog over the run keeps the digits', (tester) async { + await pumpRunDetail(tester, RunDetailTestPlatform.material); + showDialog( + context: tester.element(find.byKey(const Key('run-detail-tabs'))), + builder: (_) => const AlertDialog(content: Text('Over')), + ); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.digit2); + await tester.pump(); + Navigator.of(tester.element(find.text('Over'))).pop(); + await tester.pumpAndSettle(); + expect(_current(tester), 0); + }); +} diff --git a/app/test/shell/shell_chat_actions_shortcut_test.dart b/app/test/shell/shell_chat_actions_shortcut_test.dart new file mode 100644 index 00000000..2468c609 --- /dev/null +++ b/app/test/shell/shell_chat_actions_shortcut_test.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/shell_chat_actions_shortcut.dart'; +import 'package:pipelines_app/ui/input/keyboard_owner.dart'; + +KeyDownEvent _down(PhysicalKeyboardKey physical, LogicalKeyboardKey logical) => + KeyDownEvent( + physicalKey: physical, + logicalKey: logical, + timeStamp: Duration.zero, + ); + +final _n = _down(PhysicalKeyboardKey.keyN, LogicalKeyboardKey.keyN); +final _j = _down(PhysicalKeyboardKey.keyJ, LogicalKeyboardKey.keyJ); + +Future _alt(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); +} + +void main() { + test('Alt+N is New chat and Alt+J the next chat needing you, alone', () { + ShellChatAction? chord(Set held, KeyEvent event) => + shellChatActionShortcut(event, _FakeKeyboard(held)); + const alt = LogicalKeyboardKey.altLeft; + expect(chord({alt}, _n), ShellChatAction.newChat); + expect(chord({alt}, _j), ShellChatAction.nextAttention); + expect(chord({}, _n), isNull); + expect(chord({alt, LogicalKeyboardKey.shiftLeft}, _n), isNull); + expect(chord({alt, LogicalKeyboardKey.controlLeft}, _j), isNull); + expect(chord({alt, LogicalKeyboardKey.metaLeft}, _j), isNull); + expect(chord({LogicalKeyboardKey.controlLeft}, _n), isNull); + // Option+N is a dead key (˜) on a Mac: matched by position. + final dead = _down( + PhysicalKeyboardKey.keyN, + const LogicalKeyboardKey(0x02dc), + ); + expect(chord({alt}, dead), ShellChatAction.newChat); + expect( + shellChatActionLabel(ShellChatAction.newChat, TargetPlatform.macOS), + 'Option+N', + ); + expect( + shellChatActionLabel(ShellChatAction.nextAttention, TargetPlatform.linux), + 'Alt+J', + ); + }); + + testWidgets('the chords show Chat and report the action; the terminal ' + 'keeps them', (tester) async { + final terminal = FocusNode(); + addTearDown(terminal.dispose); + final actions = []; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + onChatAction: actions.add, + destinationBodies: { + AppDestination.pipelines: (_) => TypingSurface( + child: Focus(focusNode: terminal, child: const Text('terminal')), + ), + AppDestination.chat: (_) => const Text('chat body'), + }, + ), + ), + ); + terminal.requestFocus(); + await tester.pump(); + await _alt(tester, LogicalKeyboardKey.keyN); + expect(actions, isEmpty); + expect(find.text('chat body'), findsNothing); + + terminal.unfocus(); + await tester.pump(); + await _alt(tester, LogicalKeyboardKey.keyJ); + expect(actions, [ShellChatAction.nextAttention]); + expect(find.text('chat body'), isOnstage); + await _alt(tester, LogicalKeyboardKey.keyN); + expect(actions, [ShellChatAction.nextAttention, ShellChatAction.newChat]); + }); + + testWidgets('a dialog keeps the chords', (tester) async { + final actions = []; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + onChatAction: actions.add, + destinationBodies: { + AppDestination.pipelines: (context) => TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => + const AlertDialog(content: TextField(autofocus: true)), + ), + child: const Text('dialog'), + ), + AppDestination.chat: (_) => const Text('chat body'), + }, + ), + ), + ); + await tester.tap(find.text('dialog')); + await tester.pumpAndSettle(); + await _alt(tester, LogicalKeyboardKey.keyN); + expect(actions, isEmpty); + }); +} + +class _FakeKeyboard extends HardwareKeyboard { + _FakeKeyboard(this.pressed); + final Set pressed; + @override + bool isLogicalKeyPressed(LogicalKeyboardKey key) => pressed.contains(key); +} diff --git a/app/tool/capture/examples/chat-quick-switch-recent.json b/app/tool/capture/examples/chat-quick-switch-recent.json new file mode 100644 index 00000000..88d08101 --- /dev/null +++ b/app/tool/capture/examples/chat-quick-switch-recent.json @@ -0,0 +1,25 @@ +{ + "size": "1440x1000", + "params": "chats=8&colors=1&activity=1&closed=2", + "steps": [ + { "open": "/chat/perf-chat-1" }, + { "wait": 1500 }, + { "press": "Alt+k", "wait": 800 }, + { "type": "billing", "wait": 500 }, + { "press": "Enter", "wait": 1200 }, + { "press": "Alt+k", "wait": 800 }, + { "shot": "recent-first-previous-selected" }, + { "press": "Enter", "wait": 1200 }, + { "shot": "back-to-previous" }, + { "press": "Alt+k", "wait": 800 }, + { "type": "s", "wait": 500 }, + { "shot": "closed-section" }, + { "type": "earch", "wait": 400 }, + { "press": "Enter", "wait": 1500 }, + { "shot": "closed-reopened" }, + { "press": "Alt+j", "wait": 1500 }, + { "shot": "alt-j-needs-you" }, + { "press": "Alt+n", "wait": 1200 }, + { "shot": "alt-n-new-chat" } + ] +} diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index ed38738f..62409f43 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -17,6 +17,8 @@ // them, and keeps colours picked with chat_color; // `?activity=1` (with `?chats=N`) lists a running chat, one with // background tasks and idle ones; +// `?closed=N` (with `?chats=N`) closes the last N chats (chat_reopen +// reopens one); // `?automations=N` reports N native automations for the selected chat; // `?msgs=`, `?rich=1`, `?older=1`, `?live=N` vary the chat transcripts for // scroll captures (tool/perf/chat_scroll_fixture.dart). @@ -91,8 +93,22 @@ const _colorNames = ['teal', 'purple', null, 'amber', 'red', null, 'blue']; final Map _pickedColors = {}; final _chatCatalog = ChatCatalogFixture(); +/// `?closed=N` (with `?chats=N`): the last N chats are closed until +/// chat_reopen reopens one. +int get _closedCount => int.tryParse(_params['closed'] ?? '') ?? 0; +final Set _reopened = {}; + JsonMap _chatRow(int i) { final id = perfChatId(i); + final closed = i >= _chats - _closedCount && !_reopened.contains(id); + return { + ..._openChatRow(i, id), + if (closed) + 'closed_at': DateTime.now().millisecondsSinceEpoch - (i + 1) * 60000, + }; +} + +JsonMap _openChatRow(int i, String id) { if (!_colors) { return { 'id': id, @@ -305,6 +321,10 @@ JsonMap? perfChatReply(JsonMap request) { 'type': 'chat_sessions', 'chat_sessions': [for (var i = 0; i < _chats; i++) _chatRow(i)], }; + case 'chat_reopen': + final query = request['chat_query']; + _reopened.add(query is Map ? '${query['session_id'] ?? ''}' : ''); + return {'id': id, 'type': 'chat_reopen'}; case 'chat_color': final query = request['chat_query']; final session = query is Map ? '${query['session_id'] ?? ''}' : '';