Chat quick switcher MRU, Closed section and markers; Alt+N, Alt+J and run tab keys

Ctrl+K lists open chats most recently used first (tracked on open and pane
focus, persisted per server) and preselects the previous chat, so Ctrl+K,
Enter returns to it. Rows mark needs you / working / unread; a query also
lists matching closed chats under Closed, and choosing one reopens it.
Alt+N (Option+N) starts a new chat and Alt+J (Option+J) opens the next chat
waiting for you, unread or failed, cycling; the terminal keeps both. In run
detail, bare 1-4 switch tabs when not typing. Cheatsheet entries added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:49:36 +00:00
parent accb9970b6
commit 12c7642e35
25 changed files with 1223 additions and 46 deletions
+23 -1
View File
@@ -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<PipelinesApp>
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<PipelinesApp>
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<PipelinesApp>
onDestinationReselected: _reselectDestination,
onOpenChat: _focusOpenChatComposer,
onChatQuickSwitch: _toggleChatQuickSwitch,
onChatAction: _chatAction,
destinationBodies: {
AppDestination.pipelines: (_) => FirstRunWalkthroughGate(
store: _walkthroughStore,
+17 -3
View File
@@ -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<String, ChatComposerController> composers = {};
@@ -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<ChatScreen>, _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.'),
),
);
}
}
@@ -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<ChatScreen>, _ChatScreenWorkspace {
ChatRuntime get _runtime;
ModalRoute<JsonMap>? _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<ChatScreen>, _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<ChatScreen>, _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<ChatScreen>, _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<void> _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'] ?? ''}';
@@ -365,6 +365,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
if (_workspaceSignature == signature) return;
_workspaceSignature = signature;
_syncOpenWorkspace();
_touchActiveChat();
void update() {
if (!mounted) return;
setState(() {});
@@ -379,6 +380,10 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
}
}
/// 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;
@@ -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<JsonMap> showChatQuickSwitch(
BuildContext context, {
required ChatSessionsController sessions,
required ValueChanged<JsonMap> onSelected,
String? Function(JsonMap session)? serverName,
List<String> 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<JsonMap> route = usesDesktopPopups(context)
? DialogRoute<JsonMap>(
context: context,
@@ -76,11 +87,23 @@ void closeChatQuickSwitch(ModalRoute<JsonMap> 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<String> recent;
/// The chat shown when the switcher opened, if any.
final String? currentId;
@override
State<ChatQuickSwitch> createState() => _ChatQuickSwitchState();
}
@@ -88,16 +111,52 @@ class ChatQuickSwitch extends StatefulWidget {
class _ChatQuickSwitchState extends State<ChatQuickSwitch> {
final _query = TextEditingController();
final _rowKeys = <String, GlobalKey>{};
int _selected = 0;
/// The row the operator moved to; null keeps the initial selection
/// ([chatQuickSwitchInitialSelection]).
int? _moved;
List<JsonMap> _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 <JsonMap>[]
: 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<ChatQuickSwitch> {
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<ChatQuickSwitch> {
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<ChatQuickSwitch> {
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<ChatQuickSwitch> {
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),
),
],
],
),
);
@@ -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;
@@ -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<ChatQuickSwitchMarker> 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,
),
),
),
);
}
}
@@ -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<List<String>> read();
Future<void> write(List<String> 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<String> _ids = const [];
Future<void>? _loading;
/// The remembered chats, most recent first.
List<String> get ids => _ids;
/// Reads the stored order once; later calls return the same read.
Future<void> load() => _loading ??= _read();
Future<void> _read() async {
List<String> 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<void> _write() async {
try {
await _store.write(_ids);
} catch (_) {
// The order is a convenience; the switcher still lists every chat.
}
}
List<String> _merged(List<String> front, List<String> rest) {
final seen = <String>{};
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<List<String>> read() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList(_key) ?? const [];
}
@override
Future<void> write(List<String> 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<String>? ids]) : ids = ids ?? [];
List<String> ids;
@override
Future<List<String>> read() async => List.of(ids);
@override
Future<void> write(List<String> ids) async => this.ids = List.of(ids);
}
@@ -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<JsonMap> 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;
}
@@ -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<JsonMap> chatQuickSwitchByRecency(
List<JsonMap> candidates,
List<String> 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<JsonMap> chatQuickSwitchClosed(List<JsonMap> 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<JsonMap> 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<ChatQuickSwitchMarker> chatQuickSwitchMarkers(
JsonMap session, {
required bool unread,
}) => [
if (chatSessionAwaitingOperator(session) > 0) ChatQuickSwitchMarker.needsYou,
if (session['running'] == true) ChatQuickSwitchMarker.working,
if (unread) ChatQuickSwitchMarker.unread,
];
+9 -1
View File
@@ -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<ChatScreen>
_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<ChatScreen>
_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<ChatScreen>
_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<ChatScreen>
_openWorkspace?.dispose();
_unbindWindows();
_unbindQuickSwitch();
_unbindAttention();
_workspace.removeListener(_workspaceChanged);
_workspace.dispose();
_sessions.removeListener(_nextChanged);
@@ -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();
}
@@ -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';
@@ -120,6 +122,19 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
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
@@ -136,6 +151,7 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_tabDigitKey);
_inputSection.dispose();
_outputSection.dispose();
_liveRun.dispose();
@@ -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,
@@ -273,6 +288,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',
+30 -1
View File
@@ -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<ShellChatAction>? onChatAction;
/// Runs needing the operator today, retained in the tab's accessible label.
final int attentionCount;
@@ -410,8 +417,20 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
}
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<AdaptiveShell> {
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);
@@ -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';
}