Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: fill out the keyboard shortcut registry (#9496)

Michael Hanbb351c0f27b9
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index 1d4e52b44c3..3c7de8cc8c1 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -24,6 +24,7 @@ on:
- 'tests/studio/playwright_heavy_thread.py'
- 'tests/studio/probe_dismiss_guard.py'
- 'tests/studio/playwright_settings_tabs.py'
+ - 'tests/studio/playwright_keyboard_shortcuts.py'
- 'tests/studio/playwright_stream_pacing.py'
- 'tests/studio/playwright_code_block_flicker.py'
- 'tests/studio/_code_block_flicker_analysis.py'
@@ -424,6 +425,15 @@ jobs:
working-directory: ${{ github.workspace }}
run: python3 tests/studio/playwright_settings_tabs.py
+ # A listener is not a pure function: what a chord does to a focused button, to a
+ # text field, on auto-repeat, or under AltGr is only answerable in a browser, and
+ # the node suite pins those through source text. Chromium here because that is what
+ # this job installs; SMOKE_ENGINES=chromium,firefox,webkit runs the same checks
+ # against all three when the matcher or the reserved sets change.
+ - name: Browser smoke for keyboard shortcuts
+ working-directory: ${{ github.workspace }}
+ run: python3 tests/studio/playwright_keyboard_shortcuts.py
+
# A panel that cannot be fetched is new with lazy loading, and nothing above the
# root-mounted dialog catches, so unguarded it unmounts Studio, not one panel.
- name: Browser smoke for a settings panel that cannot load
diff --git a/studio/frontend/smoke-shortcuts-main.tsx b/studio/frontend/smoke-shortcuts-main.tsx
new file mode 100644
index 00000000000..f711569072d
--- /dev/null
+++ b/studio/frontend/smoke-shortcuts-main.tsx
@@ -0,0 +1,185 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Harness for tests/studio/playwright_keyboard_shortcuts.py: a vite entry with no
+// backend, driving the real registry, the real store and the real useShortcut
+// against a real browser's keyboard. The node suite can reach the pure functions
+// but not the listener, so what a chord does to a focused button, to a text
+// field, on auto-repeat, or under AltGr is only answerable here.
+
+/* eslint-disable no-restricted-imports -- a harness entry point, not app code. */
+import { useChatNavigationStore } from "@/features/chat/stores/chat-navigation-store";
+import {
+ COMPOSER_INPUT_SELECTOR,
+ useShortcut,
+} from "@/features/settings/hooks/use-shortcut";
+import * as registry from "@/features/settings/lib/keyboard-shortcuts";
+import * as shortcutStore from "@/features/settings/stores/keyboard-shortcuts-store";
+/* eslint-enable no-restricted-imports */
+import { useState } from "react";
+import { createRoot } from "react-dom/client";
+
+/** How long a selection chord keeps a repeat press off the open chat. */
+const SELECTION_ACTION_GRACE_MS = 750;
+
+interface Fired {
+ action: string;
+ detail?: string;
+}
+
+declare global {
+ interface Window {
+ // Optional: the app typechecks this entry, only the harness page installs it.
+ __shortcutsSmoke?: {
+ registry: typeof registry;
+ store: typeof shortcutStore;
+ nav: typeof useChatNavigationStore;
+ fired: () => Fired[];
+ reset: () => void;
+ setActiveChat: (value: string | null) => void;
+ };
+ }
+}
+
+const fired: Fired[] = [];
+const record = (action: string, detail?: string) => fired.push({ action, detail });
+
+const latchRef = { current: null as { id: string; at: number } | null };
+const activeChat = { current: "chat-A" as string | null };
+
+// The shape app-sidebar registers these three with: a selection chord clears the
+// selection as it runs, so the latch is what keeps the next press off the open
+// chat. Keyed by action, so a different command straight after is not swallowed.
+const stampLatch = (id: string, run: () => void) => {
+ latchRef.current = { id, at: Date.now() };
+ run();
+};
+const followsSelectionAction = (id: string) => {
+ const last = latchRef.current;
+ return last?.id === id && Date.now() - last.at < SELECTION_ACTION_GRACE_MS;
+};
+
+const withActiveChat = (run: (item: string) => void) => {
+ if (!activeChat.current) {
+ record("toast.info", "Open a chat first");
+ return;
+ }
+ run(activeChat.current);
+};
+
+function Harness() {
+ const [selectionCount, setSelectionCount] = useState(0);
+ const [toolPending, setToolPending] = useState(true);
+
+ const selectionChord =
+ (id: string, onSelection: string, onSuppressed: string, onActive: string) =>
+ () => {
+ if (selectionCount > 0) {
+ stampLatch(id, () => {
+ record(onSelection, String(selectionCount));
+ setSelectionCount(0);
+ });
+ return;
+ }
+ if (followsSelectionAction(id)) {
+ record(onSuppressed);
+ return;
+ }
+ withActiveChat((item) => record(onActive, item));
+ };
+
+ useShortcut(
+ "archiveChat",
+ selectionChord("archiveChat", "archiveSelected", "archiveSuppressed", "archiveActive"),
+ );
+ useShortcut(
+ "togglePinChat",
+ selectionChord("togglePinChat", "pinSelected", "pinSuppressed", "pinActive"),
+ );
+ useShortcut("deleteSelectedChats", () => {
+ if (selectionCount > 0) {
+ record("deleteSelected", String(selectionCount));
+ setSelectionCount(0);
+ }
+ });
+ useShortcut("clearAllUnreads", () => {
+ const state = useChatNavigationStore.getState();
+ const cleared = state.unreadThreadIds.size;
+ if (cleared === 0) {
+ record("toast.info", "No unread chats");
+ return;
+ }
+ state.clearAllUnreads();
+ record(
+ "toast.success",
+ `Cleared ${cleared} unread ${cleared === 1 ? "chat" : "chats"}`,
+ );
+ });
+
+ // The bare-key pair, with the options tool-confirmation-controls uses.
+ useShortcut("approveToolRequest", () => record("approve"), {
+ enabled: toolPending,
+ skipInTextFields: true,
+ });
+ useShortcut("declineToolRequest", () => record("decline"), {
+ enabled: toolPending,
+ skipInTextFields: true,
+ textFieldException: COMPOSER_INPUT_SELECTOR,
+ });
+
+ useShortcut("nextChat", () => record("nextChat"), { repeats: true });
+ useShortcut("searchChats", () => record("searchChats"), {
+ skipInTextFields: true,
+ });
+ useShortcut("newChat", () => record("newChat"));
+ useShortcut("openSettings", () => record("openSettings"));
+ useShortcut("toggleSidebar", () => record("toggleSidebar"));
+ useShortcut("copySessionId", () => record("copySessionId"));
+
+ return (
+ <div>
+ <button type="button" id="smoke-button" onClick={() => record("buttonClick")}>
+ Deny
+ </button>
+ <a href="#smoke" id="smoke-link" onClick={() => record("linkClick")}>
+ link
+ </a>
+ <input id="smoke-input" aria-label="plain field" />
+ <textarea
+ id="smoke-composer"
+ aria-label="composer"
+ className="aui-composer-input"
+ />
+ <div id="smoke-editable" contentEditable suppressContentEditableWarning />
+ <span id="smoke-selection">{selectionCount}</span>
+ <button type="button" id="smoke-select" onClick={() => setSelectionCount(3)}>
+ select
+ </button>
+ <button
+ type="button"
+ id="smoke-tool-pending"
+ onClick={() => setToolPending((value) => !value)}
+ >
+ {String(toolPending)}
+ </button>
+ <span id="smoke-ready">ready</span>
+ </div>
+ );
+}
+
+window.__shortcutsSmoke = {
+ registry,
+ store: shortcutStore,
+ nav: useChatNavigationStore,
+ fired: () => fired.slice(),
+ reset: () => {
+ fired.length = 0;
+ latchRef.current = null;
+ activeChat.current = "chat-A";
+ },
+ setActiveChat: (value: string | null) => {
+ activeChat.current = value;
+ },
+};
+
+createRoot(document.getElementById("root") as HTMLElement).render(<Harness />);
diff --git a/studio/frontend/smoke-shortcuts.html b/studio/frontend/smoke-shortcuts.html
new file mode 100644
index 00000000000..60616445891
--- /dev/null
+++ b/studio/frontend/smoke-shortcuts.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <script src="/crypto-boot.js"></script>
+ <title>keyboard shortcuts smoke</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-shortcuts-main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 74137077c8c..7378531e19c 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -5,6 +5,7 @@ import { AppSidebar } from "@/components/app-sidebar";
import { Navbar } from "@/components/navbar";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
+import { videoNavHint } from "@/config/hardware-verdict";
import { ApiMonitorOverlay } from "@/features/api-monitor/api-monitor-overlay";
import {
AUTH_SESSION_CLEARED_EVENT,
@@ -279,6 +280,16 @@ function RootLayout() {
const isAuthFlowRoute = useMatches({
select: (matches) => matches.some((match) => match.staticData.isAuthFlow),
});
+ // Measured, not guessed: the same pair the sidebar reads to gray Train out.
+ const chatOnlyMeasured = usePlatformStore(
+ (s) => s.isChatOnly() && !s.capabilitiesUnknown(),
+ );
+ const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);
+ // Video is the other row the sidebar grays out, on the two verdicts its
+ // pipelines cannot run on at all. Same hint the row reads, so the two cannot
+ // disagree about which hosts they are.
+ const videoDisabled =
+ videoNavHint(chatOnlyMeasured, chatOnlyReason) !== undefined;
// Exact match: a prefix would treat /chatty as chat, hiding its not-found UI.
const isChatRoute = pathname === "/chat";
const { pinned, setPinned, togglePinned } = useSidebarPin();
@@ -308,8 +319,11 @@ function RootLayout() {
);
// Freeze the last /chat search and latch "mounted" via render-phase setState
// (React's "adjust state during render" pattern), avoiding effects/refs.
- const [frozenChatSearch, setFrozenChatSearch] =
- useState<ChatSearch>(liveChatSearch);
+ // Empty until /chat is visited: location.search is the raw URL's, not the
+ // matched route's, so seeding it would let another route's ?project= stand
+ // in for a chat the user has never opened. The adjustment below fills it on
+ // the first /chat render, so landing straight on /chat loses nothing.
+ const [frozenChatSearch, setFrozenChatSearch] = useState<ChatSearch>({});
const [chatMounted, setChatMounted] = useState(isChatRoute);
if (isChatRoute && frozenChatSearch !== liveChatSearch) {
setFrozenChatSearch(liveChatSearch);
@@ -403,17 +417,77 @@ function RootLayout() {
useSettingsDialogStore.getState().openDialog("keyboard-shortcuts"),
{ enabled: !isAuthFlowRoute },
);
- useShortcut("newChat", () => {
+ /** Every "new chat" chord lands here. `incognito` skips history,
+ * `standalone` leaves the open project. */
+ const startNewChat = (options?: {
+ incognito?: boolean;
+ standalone?: boolean;
+ }) => {
clearNewChatDraft(); // fresh chat starts empty, no bleed from the last one
const chatRuntime = useChatRuntimeStore.getState();
+ // The project on screen, which on Chat is the runtime's. The page keeps
+ // that in step with the route, the inferred ones included: a thread or a
+ // compare pair opened without ?project= still belongs to its project, and
+ // the page's own New chat button starts the next chat there. Reading the
+ // search param instead would leave that project without being asked to.
+ // Off Chat the page is hidden rather than unmounted, so its project is one
+ // the user cannot see and a new chat belongs to none.
+ const openProjectId = isChatRoute ? chatRuntime.activeProjectId : null;
+ const projectId = options?.standalone ? null : openProjectId;
chatRuntime.setActiveThreadId(null);
- chatRuntime.setActiveProjectId(null);
- chatRuntime.setIncognito(false);
+ chatRuntime.setActiveProjectId(projectId);
+ chatRuntime.setIncognito(Boolean(options?.incognito));
void navigate({
to: "/chat",
- search: { new: crypto.randomUUID() },
+ search: projectId ? { project: projectId } : { new: crypto.randomUUID() },
});
+ };
+
+ // Gated like the workspace chords below: /login has no shell, and /chat
+ // bounces straight back off requireAuth.
+ useShortcut("newChat", () => startNewChat(), { enabled: !isAuthFlowRoute });
+ useShortcut(
+ "newTemporaryChat",
+ () => startNewChat({ incognito: true, standalone: true }),
+ { enabled: !isAuthFlowRoute },
+ );
+ useShortcut("newStandaloneChat", () => startNewChat({ standalone: true }), {
+ enabled: !isAuthFlowRoute,
+ });
+
+ // Workspaces. The shell is mounted on every route, so the chords live here.
+ const goTo = (to: string) => () => void navigate({ to });
+ // Carry the frozen search back: a bare /chat is a fresh chat, so switching
+ // away and back would drop the thread, compare pair or project.
+ useShortcut(
+ "switchToChat",
+ () => void navigate({ to: "/chat", search: chatSearch }),
+ { enabled: !isAuthFlowRoute },
+ );
+ useShortcut("switchToProjects", goTo("/projects"), {
+ enabled: !isAuthFlowRoute,
+ });
+ useShortcut("switchToHub", goTo("/hub"), { enabled: !isAuthFlowRoute });
+ // Train is the one workspace the chat-only guard turns away, so its chord is
+ // the one that has to ask first: firing it on a host without the hardware
+ // would bounce off /studio and land the user on /chat, away from whatever
+ // they had open. The sidebar disables the row on the same measured check,
+ // and only once measured, since the guess is what the row waits out too.
+ useShortcut("switchToTrain", goTo("/studio"), {
+ enabled: !isAuthFlowRoute && !chatOnlyMeasured,
+ });
+ useShortcut("switchToRecipes", goTo("/data-recipes"), {
+ enabled: !isAuthFlowRoute,
+ });
+ useShortcut("switchToImages", goTo("/images"), { enabled: !isAuthFlowRoute });
+ // /video checks auth and nothing else, so an ungated chord would put the
+ // unsupported-hardware gate where the user's workspace was. Train's chord
+ // waits on the same measurement; this one has its own predicate to wait on.
+ useShortcut("switchToVideo", goTo("/video"), {
+ enabled: !isAuthFlowRoute && !videoDisabled,
});
+ useShortcut("switchToAudio", goTo("/audio"), { enabled: !isAuthFlowRoute });
+ useShortcut("switchToExport", goTo("/export"), { enabled: !isAuthFlowRoute });
useEffect(() => {
if (isChatRoute) return;
diff --git a/studio/frontend/src/components/app-sidebar.tsx b/studio/frontend/src/components/app-sidebar.tsx
index ea0bdf58518..38f96e05d25 100644
--- a/studio/frontend/src/components/app-sidebar.tsx
+++ b/studio/frontend/src/components/app-sidebar.tsx
@@ -69,6 +69,7 @@ import {
import { WORKFLOW_TABS, type WorkflowId } from "@/features/images/workflows";
/* eslint-enable no-restricted-imports */
import { cn } from "@/lib/utils";
+import { copyToClipboardFrom } from "@/lib/copy-to-clipboard";
import { isTauri } from "@/lib/api-base";
import { useWebUpdateCheck } from "@/hooks/use-web-update-check";
import {
@@ -138,7 +139,7 @@ import {
listStoredChatMessages,
listStoredChatThreads,
moveChatItemToProject,
- recordedSandboxSessionId,
+ allRecordedSandboxSessionIds,
notifyChatHistoryUpdated,
renameChatItem,
renameChatProject,
@@ -168,6 +169,13 @@ import {
CONVERSATION_MARKDOWN_LABEL,
type ProjectRecord,
type SidebarItem,
+ type ChatNavigationState,
+ adjacentChatItem,
+ countUnreadRows,
+ nextAttentionChatItem,
+ openChatItemById,
+ recentChatItemAtSlot,
+ useChatNavigationStore,
} from "@/features/chat";
import { sandboxSessionIdFor } from "@/components/assistant-ui/sandbox-files";
import {
@@ -178,7 +186,11 @@ import { NewProjectDialog } from "@/features/chat/components/new-project-dialog"
import {
useAppearanceCustomStore,
useSettingsDialogStore,
+ isSurfaceBackgrounded,
useShortcutLabel,
+ Shortcut,
+ type ShortcutId,
+ useShortcut,
} from "@/features/settings";
import type { SidebarNavItemId } from "@/features/settings";
import { useEffectiveProfile, UserAvatar } from "@/features/profile";
@@ -215,6 +227,9 @@ import { toast } from "@/lib/toast";
import { ShutdownDialog } from "@/components/shutdown-dialog";
import { translate, useT, type TranslationKey } from "@/i18n";
+/** The ⌥⌘1-6 Recents slots, as a constant so the list below is fixed-length. */
+const RECENT_SLOT_NUMBERS = [1, 2, 3, 4, 5, 6] as const;
+
const EMPHASIS_MARKER = "__UNSLOTH_I18N_EMPHASIS_MARKER__";
type AppT = ReturnType<typeof useT>;
@@ -562,6 +577,10 @@ const WORKFLOW_UNAVAILABLE = "The loaded model cannot do this";
// pays off after the user has repaired an install. A re-read outstanding longer than the stall
// window is given up on rather than latching the poll off: the backend it is waiting on is the
// one case this has to recover from.
+/** How long a selection chord keeps a repeat press off the open chat. */
+const SELECTION_ACTION_GRACE_MS = 750;
+/** The sidebar's own element, present on desktop and inside the mobile drawer. */
+const SIDEBAR_SELECTOR = '[data-slot="sidebar"]';
const VERDICT_UNKNOWN_POLL_MS = 3000;
const SELF_HEAL_POLL_MS = 15000;
const VERDICT_POLL_STALL_MS = 30000;
@@ -727,16 +746,20 @@ export function AppSidebar() {
// already render in the platform's own notation.
const searchShortcutLabel = useShortcutLabel("searchChats");
const settingsShortcutLabel = useShortcutLabel("openSettings");
- const { pathname, search } = useRouterState({
+ const { pathname, search, href } = useRouterState({
select: (s) => ({
pathname: s.location.pathname,
search: s.location.search as Record<string, string | undefined>,
+ // Pathname and search as one string, so a dep can follow it without a
+ // fresh object every render.
+ href: s.location.href,
}),
});
const {
pinned,
togglePinned,
isMobile,
+ openMobile,
setOpenMobile,
state: sidebarState,
} = useSidebar();
@@ -752,6 +775,13 @@ export function AppSidebar() {
const closeMobileIfOpen = () => {
if (isMobile) setOpenMobile(false);
};
+ // SidebarProvider is mounted at the route root and outlives the navigation,
+ // and the workspace chords register up there too, above it, so they cannot
+ // call what every row below calls by hand. Closing on the route covers both,
+ // and anything else that navigates from outside this file.
+ useEffect(() => {
+ if (isMobile) setOpenMobile(false);
+ }, [href, isMobile, setOpenMobile]);
const chatOnly = usePlatformStore((s) => s.isChatOnly());
const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);
@@ -929,6 +959,14 @@ export function AppSidebar() {
const isRecipesRoute = pathname.startsWith("/data-recipes");
const isExportRoute = pathname === "/export" || pathname.startsWith("/export/");
+ // Training runs surface as sidebar "Recents" on Train/Recipes/Export, else chat recents.
+ // Read up here because the chat lists below only exist when this is off.
+ const trainingRecentsRoute = isStudioRoute || isRecipesRoute || isExportRoute;
+ const { items: runItems } = useTrainingHistorySidebarItems(
+ !chatOnly && trainingRecentsRoute,
+ );
+ const showTrainingRecents =
+ !chatOnly && trainingRecentsRoute && runItems.length > 0;
const { displayTitle, avatarDataUrl } = useEffectiveProfile();
const { projects } = useChatProjects();
@@ -954,6 +992,16 @@ export function AppSidebar() {
(s) => s.alwaysDeleteChatFiles,
);
const pinnedIdSet = useMemo(() => new Set(pinnedIds), [pinnedIds]);
+ // Which row every thread belongs to, listed or not. The published lists carry
+ // only what is on screen, so this is what keeps an unread Compare row behind
+ // a collapsed section counting as one chat.
+ const rowIdByThreadId = useMemo(() => {
+ const map: Record<string, string> = {};
+ for (const item of allChatItems) {
+ for (const threadId of getSidebarItemThreadIds(item)) map[threadId] = item.id;
+ }
+ return map;
+ }, [allChatItems]);
const organizeBy = useSidebarOrganizationStore((s) => s.organizeBy);
const chatSort = useSidebarOrganizationStore((s) => s.chatSort);
const pinnedSort = useSidebarOrganizationStore((s) => s.pinnedSort);
@@ -1037,9 +1085,17 @@ export function AppSidebar() {
manualOrder,
chatsByProjectId,
]);
- const visibleProjectRecords = showAllProjects
- ? sidebarProjectRecords
- : sidebarProjectRecords.slice(0, SIDEBAR_PROJECT_LIMIT);
+ // Memoised for its identity, not for the slice. It feeds the rendered-row set
+ // the selection guard depends on, and that effect sets state: React re-renders
+ // once to find the bail-out, which would rebuild this array and schedule the
+ // effect again, without end.
+ const visibleProjectRecords = useMemo(
+ () =>
+ showAllProjects
+ ? sidebarProjectRecords
+ : sidebarProjectRecords.slice(0, SIDEBAR_PROJECT_LIMIT),
+ [showAllProjects, sidebarProjectRecords],
+ );
// Default expanded; the row toggles this. Show-more reveals chats past the limit.
const [collapsedProjectIds, setCollapsedProjectIds] = useState<Set<string>>(
() => new Set(),
@@ -1108,9 +1164,14 @@ export function AppSidebar() {
undefined
: undefined;
const queueByThreadId = usePromptQueueUI((s) => s.byThreadId);
- const [unreadThreadIds, setUnreadThreadIds] = useState<Set<string>>(
- () => new Set(),
+ // In the navigation store, not local state: the unread chords register
+ // outside this tree.
+ const unreadThreadIds = useChatNavigationStore((s) => s.unreadThreadIds);
+ const markThreadsUnread = useChatNavigationStore((s) => s.markThreadsUnread);
+ const clearThreadsUnread = useChatNavigationStore(
+ (s) => s.clearThreadsUnread,
);
+ const noteViewed = useChatNavigationStore((s) => s.noteViewed);
const previousRunningByThreadIdRef = useRef<Record<string, boolean>>({});
const activeVisibleThreadIds = useMemo(() => {
if (!activeThreadId) {
@@ -1163,6 +1224,31 @@ export function AppSidebar() {
() => sortChatItems(pinnedChatItems, PINNED_ORDER_SCOPE, pinnedSort),
[pinnedChatItems, sortChatItems, pinnedSort],
);
+ // The open chat heads the ⌃Tab stack, however it was opened.
+ useEffect(() => {
+ if (activeThreadId) noteViewed(activeThreadId);
+ }, [activeThreadId, noteViewed]);
+ // A walk ends when its modifiers come up, as an app switcher's does. A no-op
+ // when no walk is running.
+ useEffect(() => {
+ const end = () => useChatNavigationStore.getState().endTraversal();
+ const onKeyUp = (event: KeyboardEvent) => {
+ if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) {
+ return;
+ }
+ end();
+ };
+ window.addEventListener("keyup", onKeyUp);
+ // Losing the window ends it too: ⌘Tab away mid-walk and the release lands
+ // elsewhere, leaving the walk frozen, so the next press carries on instead
+ // of toggling back and the stack never takes the chat it landed on.
+ window.addEventListener("blur", end);
+ return () => {
+ window.removeEventListener("keyup", onKeyUp);
+ window.removeEventListener("blur", end);
+ };
+ }, []);
+
const sortedChatsByProjectId = useMemo(() => {
const map = new Map<string, SidebarItem[]>();
for (const [projectId, items] of chatsByProjectId) {
@@ -1185,6 +1271,114 @@ export function AppSidebar() {
);
// Whole lists, not the visible slices, so a drop cannot lose what a
// collapsed "Show more" is hiding.
+ // The project chats actually on screen. Grouping by project keeps them out of
+ // Recents, so without these the chords cannot see them at all. Same rule the
+ // Projects section renders by, collapsed folders and per-folder limit included.
+ // All three chat groups leave the tree on Train/Recipes/Export and are hidden
+ // on the icon rail, so a chord must not reach what they hold. Same rule a
+ // collapsed section follows, read off the sidebar as a whole. The mobile
+ // sheet is not part of it: it carries no collapsible state, and gating on it
+ // would strand the chords on any window narrow enough to count as mobile.
+ const chatListsOnScreen =
+ !isStudioRoute &&
+ !showTrainingRecents &&
+ (isMobile || sidebarState !== "collapsed");
+ // Selecting needs the rows, not just the lists. A closed mobile sheet unmounts
+ // them as the icon rail does, so Select All would build a selection with
+ // nothing on screen and Archive, Pin and Mark unread would take it over the
+ // open chat. Navigation is deliberately exempt: it moves the chat the user IS
+ // looking at, and the sheet is closed for most of its life on a narrow window.
+ const chatRowsOnScreen = chatListsOnScreen && (!isMobile || openMobile);
+ const renderedProjectChatItems = useMemo(() => {
+ if (!chatListsOnScreen || organizeBy !== "project" || !projectsOpen)
+ return [];
+ const out: SidebarItem[] = [];
+ for (const project of visibleProjectRecords) {
+ if (collapsedProjectIds.has(project.id)) continue;
+ const chats = sortedChatsByProjectId.get(project.id) ?? [];
+ out.push(
+ ...(expandedChatProjectIds.has(project.id)
+ ? chats
+ : chats.slice(0, PROJECT_CHAT_LIMIT)),
+ );
+ }
+ return out;
+ }, [
+ chatListsOnScreen,
+ organizeBy,
+ projectsOpen,
+ visibleProjectRecords,
+ collapsedProjectIds,
+ expandedChatProjectIds,
+ sortedChatsByProjectId,
+ ]);
+ // A collapsed section is not on screen either, so its rows are not walked or
+ // selected any more than a collapsed folder's are.
+ const visiblePinnedItems = useMemo(
+ () => (chatListsOnScreen && pinnedOpen ? sortedPinnedChatItems : []),
+ [chatListsOnScreen, pinnedOpen, sortedPinnedChatItems],
+ );
+ const visibleRecentItems = useMemo(
+ () => (chatListsOnScreen && chatOpen ? sortedRecentChatItems : []),
+ [chatListsOnScreen, chatOpen, sortedRecentChatItems],
+ );
+ // Every row on screen, in one set. The three arrays above already fold in
+ // each section's disclosure, each folder's, and the per-folder limit, so a
+ // selection can be held to what is rendered without restating any of it.
+ const renderedChatIds = useMemo(() => {
+ const ids = new Set<string>();
+ for (const item of visiblePinnedItems) ids.add(item.id);
+ for (const item of renderedProjectChatItems) ids.add(item.id);
+ for (const item of visibleRecentItems) ids.add(item.id);
+ return ids;
+ }, [visiblePinnedItems, renderedProjectChatItems, visibleRecentItems]);
+ // The folder rows, selectable in their own right and leaving the screen on
+ // their own terms: the section closes, the sidebar organizes by date, or a
+ // "show less" takes back the overflow. The chat sets above say nothing about
+ // that, since a folder with no chats in view is still a row.
+ const renderedProjectIds = useMemo(() => {
+ if (!chatListsOnScreen || organizeBy !== "project" || !projectsOpen) {
+ return new Set<string>();
+ }
+ return new Set(visibleProjectRecords.map((project) => project.id));
+ }, [chatListsOnScreen, organizeBy, projectsOpen, visibleProjectRecords]);
+ // Rows wanting attention, most urgent first. Same rule the Priority sort uses.
+ const attentionItemIds = useMemo(
+ () =>
+ [...visiblePinnedItems, ...renderedProjectChatItems, ...visibleRecentItems]
+ .filter((item) => chatPriorityRank(item) < 3)
+ .sort(
+ (a, b) =>
+ chatPriorityRank(a) - chatPriorityRank(b) ||
+ b.updatedAt - a.updatedAt,
+ )
+ .map((item) => item.id),
+ [
+ visiblePinnedItems,
+ renderedProjectChatItems,
+ visibleRecentItems,
+ chatPriorityRank,
+ ],
+ );
+ // Publish the finished order, so the chords cannot disagree with the screen.
+ const publishLists = useChatNavigationStore((s) => s.publishLists);
+ useEffect(() => {
+ publishLists({
+ pinnedItems: visiblePinnedItems,
+ projectItems: renderedProjectChatItems,
+ recentItems: visibleRecentItems,
+ attentionItemIds,
+ activeItemId: activeThreadId ?? null,
+ });
+ }, [
+ publishLists,
+ visiblePinnedItems,
+ renderedProjectChatItems,
+ visibleRecentItems,
+ attentionItemIds,
+ activeThreadId,
+ ]);
+
const projectRowIds = useMemo(
() => sidebarProjectRecords.map((project) => project.id),
[sidebarProjectRecords],
@@ -1263,15 +1457,97 @@ export function AppSidebar() {
dropProjectSelection();
}, [dropChatSelection, dropProjectSelection]);
- // Escape is the way out of a selection, as it is for the menus.
+ // Emptying the published lists is not enough: Archive, Pin, Mark unread and
+ // Delete all prefer the selection over the open chat, and a selection shows
+ // nowhere but the rows, its count living in their context menus. Carried onto
+ // Train or behind the icon rail it would be invisible and still be what the
+ // chords hit. Same reason opening a row drops it.
+ // Sections close one at a time, though, and a "show less" takes back only
+ // its own overflow, so the rest of the selection is still on screen and
+ // still worth acting on. Drop what went and keep what stayed.
useEffect(() => {
- if (selectionCount === 0 && projectSelectionCount === 0) return;
+ if (!chatRowsOnScreen) {
+ clearSelection();
+ return;
+ }
+ const anchor = selectionAnchorRef.current;
+ if (anchor && !renderedChatIds.has(anchor.id)) {
+ selectionAnchorRef.current = null;
+ }
+ setSelectedChatIds((prev) => {
+ if (prev.size === 0) return prev;
+ const kept = new Set<string>();
+ for (const id of prev) {
+ if (renderedChatIds.has(id)) kept.add(id);
+ }
+ return kept.size === prev.size ? prev : kept;
+ });
+ // Folder rows go the same way. Left behind, a project whose section the
+ // user closed keeps the selection alive with nothing on screen, and the
+ // tool card's Escape steps aside for it: the press that should have
+ // declined a call clears a selection instead.
+ const projectAnchor = projectAnchorRef.current;
+ if (projectAnchor && !renderedProjectIds.has(projectAnchor)) {
+ projectAnchorRef.current = null;
+ }
+ setSelectedProjectIds((prev) => {
+ if (prev.size === 0) return prev;
+ const kept = new Set<string>();
+ for (const id of prev) {
+ if (renderedProjectIds.has(id)) kept.add(id);
+ }
+ return kept.size === prev.size ? prev : kept;
+ });
+ }, [chatRowsOnScreen, clearSelection, renderedChatIds, renderedProjectIds]);
+
+ /** Select every chat row on screen, pinned block included. */
+ const selectAllChats = useCallback(() => {
+ if (!chatRowsOnScreen) return;
+ const ids = [
+ ...visiblePinnedItems,
+ ...renderedProjectChatItems,
+ ...visibleRecentItems,
+ ].map((item) => item.id);
+ if (ids.length === 0) return;
+ dropProjectSelection();
+ // No anchor: a shift click after this one has no row to reach back to.
+ selectionAnchorRef.current = null;
+ setSelectedChatIds(new Set(ids));
+ }, [
+ chatRowsOnScreen,
+ visiblePinnedItems,
+ renderedProjectChatItems,
+ visibleRecentItems,
+ dropProjectSelection,
+ ]);
+
+ // Escape leaves a selection, as it does the menus. A passive listener rather
+ // than one that consumes the key: dictation's Escape reads defaultPrevented
+ // first, and a stale selection must not outrank a live recording. Declining a
+ // tool call is the Escape that must not double up, and it steps aside on
+ // `selectionActive` below.
+ const selectionActive = selectionCount > 0 || projectSelectionCount > 0;
+ useEffect(() => {
+ if (!selectionActive) return;
const onKeyDown = (event: KeyboardEvent) => {
- if (event.key === "Escape") clearSelection();
+ // Bare, and only bare. Escape with a modifier is somebody else's chord,
+ // ⇧Esc for Clear all unreads among them, and dropping the selection under
+ // one would leave Archive or Pin pointing elsewhere. defaultPrevented for
+ // the same reason: a menu closing on Escape is not a request to lose it.
+ if (event.key !== "Escape" || event.defaultPrevented) return;
+ if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) {
+ return;
+ }
+ clearSelection();
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
- }, [selectionCount, projectSelectionCount, clearSelection]);
+ }, [selectionActive, clearSelection]);
+ const setSelectionActive = useChatNavigationStore((s) => s.setSelectionActive);
+ useEffect(() => {
+ setSelectionActive(selectionActive);
+ return () => setSelectionActive(false);
+ }, [selectionActive, setSelectionActive]);
/** True when the click was a selection gesture, so the row must not navigate. */
function handleSelectionClick(
@@ -1378,11 +1654,7 @@ export function AppSidebar() {
function markSelectedUnread() {
const threadIds = selectedChatItems.flatMap(getSidebarItemThreadIds);
clearSelection();
- setUnreadThreadIds((current) => {
- const next = new Set(current);
- for (const threadId of threadIds) next.add(threadId);
- return next;
- });
+ markThreadsUnread(threadIds, rowIdByThreadId);
}
async function archiveSelected() {
@@ -1555,39 +1827,20 @@ export function AppSidebar() {
if (completedThreadIds.length > 0 || activeVisibleThreadIdSet.size > 0) {
queueMicrotask(() => {
- setUnreadThreadIds((current) => {
- let next: Set<string> | null = null;
- const mutable = () => {
- next ??= new Set(current);
- return next;
- };
-
- for (const threadId of completedThreadIds) {
- if (!current.has(threadId)) {
- mutable().add(threadId);
- }
- }
-
- for (const threadId of activeVisibleThreadIdSet) {
- if (current.has(threadId)) {
- mutable().delete(threadId);
- }
- }
-
- return next ?? current;
- });
+ // A run that finished in the open chat is read, so clear after mark.
+ markThreadsUnread(completedThreadIds, rowIdByThreadId);
+ clearThreadsUnread([...activeVisibleThreadIdSet]);
});
}
previousRunningByThreadIdRef.current = runningByThreadId;
- }, [activeVisibleThreadIdKey, runningByThreadId]);
+ }, [
+ activeVisibleThreadIdKey,
+ runningByThreadId,
+ markThreadsUnread,
+ clearThreadsUnread,
+ rowIdByThreadId,
+ ]);
- // Training runs surface as sidebar "Recents" on Train/Recipes/Export, else chat recents.
- const trainingRecentsRoute = isStudioRoute || isRecipesRoute || isExportRoute;
- const { items: runItems } = useTrainingHistorySidebarItems(
- !chatOnly && trainingRecentsRoute,
- );
- const showTrainingRecents =
- !chatOnly && trainingRecentsRoute && runItems.length > 0;
const activeJobId = useTrainingRuntimeStore((s) => s.jobId);
const currentRunViewActive = useTrainingRuntimeStore((s) => s.currentRunViewActive);
const selectedHistoryRunId = useTrainingRuntimeStore((s) => s.selectedHistoryRunId);
@@ -1929,7 +2182,9 @@ export function AppSidebar() {
}
type RenameTarget =
- | { kind: "chat"; item: SidebarItem; current: string }
+ // `inline` is the row's own pill, and a chord has no row under the cursor
+ // and may have none on screen at all, so it opens the dialog instead.
+ | { kind: "chat"; item: SidebarItem; current: string; inline: boolean }
| { kind: "project"; project: ProjectRecord; current: string }
| { kind: "run"; run: TrainingRunSummary; current: string };
const [renamingTarget, setRenamingTarget] = useState<RenameTarget | null>(
@@ -1970,9 +2225,9 @@ export function AppSidebar() {
? renameTrimmed !== renamingTarget.current
: renamingTarget.run.display_name != null);
- function openRenameChat(item: SidebarItem) {
+ function openRenameChat(item: SidebarItem, inline = true) {
setRenameDraft(item.title);
- setRenamingTarget({ kind: "chat", item, current: item.title });
+ setRenamingTarget({ kind: "chat", item, current: item.title, inline });
}
function openRenameRun(run: TrainingRunSummary) {
const current = getTrainingRunDisplayTitle(run);
@@ -2211,19 +2466,378 @@ export function AppSidebar() {
}
function clearChatNotifications(item: SidebarItem) {
+ clearThreadsUnread(getSidebarItemThreadIds(item));
+ }
+
+ /** The chat as markdown, on the clipboard rather than in a download. */
+ async function copyChatItemAsMarkdown(item: SidebarItem) {
+ const empty = { value: false };
+ // The read runs inside the write: Safari drops the gesture across an
+ // await, and a chord has no second one to fall back on.
+ const copied = await copyToClipboardFrom(async () => {
+ const { buildChatItemMarkdown } = await import(
+ "@/features/chat/prompt-storage/prompt-storage-dialog"
+ );
+ // A compare row is two threads: keep both, each under its model's name.
+ const markdown = await buildChatItemMarkdown(item);
+ if (!markdown) {
+ empty.value = true;
+ throw new Error("nothing to copy");
+ }
+ return markdown;
+ });
+ if (copied) {
+ toast.success("Chat copied as Markdown");
+ } else if (empty.value) {
+ toast.info("No exportable content.");
+ } else {
+ // Denied permission, an unfocused document, a failed history read: the
+ // payload was fine and the write was not, and a chord has no cursor to
+ // show that with.
+ toast.error("Could not copy this chat.");
+ }
+ }
+
+ /** The sandbox sessions this chat's stored tool results name, if any. */
+ async function recordedSandboxSessionIds(ids: string[]): Promise<string[]> {
+ const recorded: string[] = [];
+ // Every id a thread names, not just its latest: one chat that ran a tool,
+ // moved between projects and ran another wrote to two folders on its own,
+ // and the newest would answer for both.
+ // One at a time, not Promise.all: this file's export contract forbids a
+ // concurrent await here, and two panes win nothing.
+ for (const threadId of ids) {
+ recorded.push(
+ ...allRecordedSandboxSessionIds(await listStoredChatMessages(threadId)),
+ );
+ }
+ return [...new Set(recorded)];
+ }
+
+ /**
+ * The folders this chat's files are actually in: what its tool results name,
+ * or, for a chat old enough that they name nothing, what is on disk.
+ *
+ * Chats stored before results carried a session recorded nothing, so one that
+ * ran loose and has since joined a project would be answered with the project
+ * workspace. Its thread sandbox is the only other candidate, and files there
+ * are this chat's, which is what makes them worth probing: a chat can join a
+ * project, record that session, and move back out, and current membership
+ * says nothing about where its older files went. The project workspace is
+ * not probed, because it belongs to every chat in the project alike.
+ *
+ * A union rather than a fallback. One recorded id is not evidence that the
+ * others are recorded too: a chat can have run a tool before recording
+ * existed, moved into a project, and run another one since, and taking the
+ * recorded id alone would answer for both folders while hiding the older.
+ *
+ * Shared by "Open chat folder" and "Copy session id", which drifted apart
+ * once: the copy path skipped the probe and reported success on a folder the
+ * chat had never written to.
+ */
+ async function sandboxSessionIdsHolding(ids: string[]): Promise<string[]> {
+ const recorded = await recordedSandboxSessionIds(ids);
+ // Thread folders only. A project sandbox is shared by every chat in the
+ // project, so files there are no evidence that THIS chat wrote them, and
+ // counting one would report a second folder for any chat that joined a
+ // project someone else had already used. Both callers already fall back to
+ // the folder membership gives them when nothing here names one, which is
+ // the honest answer where there is no evidence either way.
+ const held: string[] = [];
+ for (const candidate of ids) {
+ // Already named, so there is nothing a probe could add.
+ if (recorded.includes(candidate)) continue;
+ if (await sandboxHasFiles(candidate)) held.push(candidate);
+ }
+ return [...new Set([...recorded, ...held])];
+ }
+
+ /** The sandbox session this chat's tool calls write into. */
+ async function copyChatSessionId(item: SidebarItem) {
const threadIds = getSidebarItemThreadIds(item);
- setUnreadThreadIds((current) => {
- if (!threadIds.some((threadId) => current.has(threadId))) {
- return current;
+ const ids = threadIds.length > 0 ? threadIds : [item.id];
+ // The chat's own history names the folder it wrote to, which is not where
+ // current membership points once it has moved between projects. Same read
+ // as "Open chat folder", and the same answer when it names two, whether
+ // that is a compare row's two panes or one thread that outlived a move.
+ const refusal: { value: { title: string; description?: string } | null } = {
+ value: null,
+ };
+ // Read inside the write, for the same reason as the markdown copy above.
+ const copied = await copyToClipboardFrom(async () => {
+ let sessionId: string | undefined;
+ try {
+ const distinct = await sandboxSessionIdsHolding(ids);
+ if (distinct.length > 1) {
+ refusal.value = {
+ title: "This chat wrote to more than one folder.",
+ description: "Copy the session id from a tool card instead.",
+ };
+ throw new Error("more than one folder");
+ }
+ sessionId = distinct[0];
+ } catch (error) {
+ refusal.value ??= {
+ title: "Could not read this chat's session id.",
+ description: error instanceof Error ? error.message : String(error),
+ };
+ throw error;
}
- const next = new Set(current);
- for (const threadId of threadIds) {
- next.delete(threadId);
+ // Nothing recorded means no tool has run yet, so the id it would get is
+ // the one current membership gives it.
+ sessionId ??=
+ item.type === "single" || item.projectId
+ ? sandboxSessionIdFor(ids[0], item.projectId)
+ : undefined;
+ if (!sessionId) {
+ refusal.value = { title: "This chat has no single session id" };
+ throw new Error("no session id");
}
- return next;
+ return sessionId;
});
+ if (copied) {
+ toast.success("Session id copied");
+ return;
+ }
+ if (refusal.value) {
+ toast.error(refusal.value.title, {
+ description: refusal.value.description,
+ });
+ return;
+ }
+ // No refusal means the id was found and the clipboard write itself failed.
+ toast.error("Could not copy the session id.");
}
+ /** Open a chat row. Shared by the row and the navigation chords. */
+ function openChatItem(item: SidebarItem) {
+ // Archive/pin/unread act on the selection when there is one, so leaving it
+ // behind would point them at rows the user just navigated away from.
+ clearSelection();
+ clearChatNotifications(item);
+ noteViewed(item.id);
+ navigate({
+ to: "/chat",
+ search:
+ item.type === "single"
+ ? {
+ thread: item.id,
+ ...(item.projectId ? { project: item.projectId } : {}),
+ }
+ : {
+ compare: item.id,
+ ...(item.projectId ? { project: item.projectId } : {}),
+ },
+ });
+ closeMobileIfOpen();
+ }
+ // Through a ref: openChatItem is render-scoped, so registering it directly
+ // would rewrite the store every render.
+ const openChatItemRef = useRef(openChatItem);
+ useEffect(() => {
+ openChatItemRef.current = openChatItem;
+ });
+ // The sidebar is unmounted on the auth routes, so this is where a sign-out
+ // reaches: the store outlives the component that filled it, and the unread
+ // set and the walk belong to the account that just left.
+ useEffect(
+ () => () => useChatNavigationStore.getState().resetAccountState(),
+ [],
+ );
+ useEffect(() => {
+ const setOpenChatItem = useChatNavigationStore.getState().setOpenChatItem;
+ setOpenChatItem((item) => openChatItemRef.current(item));
+ return () => setOpenChatItem(null);
+ }, []);
+
+ // --- Chat shortcuts ----------------------------------------------------
+ // The sidebar is on every shell route and holds the list, the handlers and
+ // the router, so the chat chords register here.
+ const activeChatItem = useMemo(
+ () => allChatItems.find((item) => item.id === activeThreadId) ?? null,
+ [allChatItems, activeThreadId],
+ );
+ /** Run `fn` on the open chat, or say why nothing happened. */
+ const withActiveChat = (fn: (item: SidebarItem) => void) => {
+ if (!activeChatItem) {
+ toast.info("Open a chat first");
+ return;
+ }
+ fn(activeChatItem);
+ };
+ const goToChat = (pick: (state: ChatNavigationState) => SidebarItem | null) =>
+ openChatItemById(pick(useChatNavigationStore.getState()));
+
+ // With rows selected these act on the selection, matching the context menu;
+ // otherwise on the open chat. Acting on a selection clears it, so without
+ // this latch a second press would land on the open chat, which the user
+ // never selected.
+ // Keyed by action: the press to hold back is a repeat of the one that just
+ // took the selection, not a different command the user chose deliberately.
+ const selectionActedRef = useRef<{ id: ShortcutId; at: number } | null>(null);
+ const actOnSelection = (id: ShortcutId, fn: () => void) => {
+ selectionActedRef.current = { id, at: Date.now() };
+ fn();
+ };
+ const followsSelectionAction = (id: ShortcutId) => {
+ const last = selectionActedRef.current;
+ return (
+ last?.id === id && Date.now() - last.at < SELECTION_ACTION_GRACE_MS
+ );
+ };
+ // A project selection is not a chat selection: none of the chords below is on
+ // its context menu, so with only projects selected they stand aside rather
+ // than falling through to the open chat. Delete already behaves this way.
+ const projectsOnlySelected = () =>
+ selectionCount === 0 && projectSelectionCount > 0;
+ // A dialog leaves the sidebar mounted and inert behind it, and these chords
+ // are window-level, so Settings over Chat would archive or rename the chat
+ // behind it. Asked at press time, since `enabled` is read at render.
+ //
+ // Backgrounded, not "not in the foreground": reading a missing element as
+ // covered would kill these chords on the mobile drawer, which unmounts.
+ const sidebarCovered = () => {
+ if (isSurfaceBackgrounded(SIDEBAR_SELECTOR)) return true;
+ // With the mobile drawer closed the sidebar is unmounted, so the check
+ // above has nothing to read. The app root is always mounted and Radix
+ // aria-hides it for a modal's life. A fallback only: an open drawer is
+ // itself a dialog hiding the root, and the sidebar in it is the foreground.
+ return (
+ typeof document !== "undefined" &&
+ document.querySelector(SIDEBAR_SELECTOR) === null &&
+ isSurfaceBackgrounded("#root")
+ );
+ };
+ useShortcut("archiveChat", () => {
+ if (sidebarCovered()) return;
+ if (projectsOnlySelected()) return;
+ if (selectionCount > 0) {
+ actOnSelection("archiveChat", () => void archiveSelected());
+ return;
+ }
+ if (followsSelectionAction("archiveChat")) return;
+ withActiveChat((item) => void handleArchiveThread(item));
+ });
+ useShortcut("markChatUnread", () => {
+ if (sidebarCovered()) return;
+ if (projectsOnlySelected()) return;
+ if (selectionCount > 0) {
+ actOnSelection("markChatUnread", markSelectedUnread);
+ return;
+ }
+ if (followsSelectionAction("markChatUnread")) return;
+ withActiveChat((item) =>
+ markThreadsUnread(getSidebarItemThreadIds(item), rowIdByThreadId),
+ );
+ });
+ useShortcut("togglePinChat", () => {
+ if (sidebarCovered()) return;
+ if (projectsOnlySelected()) return;
+ if (selectionCount > 0) {
+ actOnSelection("togglePinChat", () => pinSelected(!allSelectedPinned));
+ return;
+ }
+ if (followsSelectionAction("togglePinChat")) return;
+ withActiveChat((item) => togglePinnedChat(item.id));
+ });
+ // A selection made behind a dialog is invisible and still what the mutating
+ // chords hit once the dialog closes, which is the thing those chords being
+ // guarded was meant to prevent.
+ useShortcut("selectAllChats", () => {
+ if (sidebarCovered()) return;
+ selectAllChats();
+ });
+ useShortcut("clearChatSelection", clearSelection);
+ useShortcut("deleteSelectedChats", () => {
+ if (sidebarCovered()) return;
+ if (selectionCount > 0) deleteSelected();
+ });
+ // Through the dialog: the row's inline pill is rendered by the row, and the
+ // open chat may be behind a collapsed section, past a folder's "show more",
+ // or on a route with no chat list at all, where the chord would look dead and
+ // leave a rename waiting to appear the moment the row came back.
+ useShortcut("renameChat", () => {
+ if (sidebarCovered()) return;
+ withActiveChat((item) => openRenameChat(item, false));
+ });
+ // The clipboard is outside the app, so writing a hidden chat's contents into
+ // it from behind a dialog is not something the user can take back by closing
+ // the dialog.
+ useShortcut("copyChatAsMarkdown", () => {
+ if (sidebarCovered()) return;
+ withActiveChat((item) => void copyChatItemAsMarkdown(item));
+ });
+ useShortcut("copySessionId", () => {
+ if (sidebarCovered()) return;
+ withActiveChat((item) => void copyChatSessionId(item));
+ });
+
+ // These four walk the list, so holding them steps through it, the way an
+ // arrow key does. The rest are one-shot and ignore auto-repeat.
+ useShortcut("nextChat", () => goToChat((s) => adjacentChatItem(s, 1)), {
+ repeats: true,
+ });
+ useShortcut("previousChat", () => goToChat((s) => adjacentChatItem(s, -1)), {
+ repeats: true,
+ });
+ // The walk holds the stack still while it runs, so a modifier held down
+ // reaches the third chat back and beyond; releasing it ends the walk and
+ // puts the chat it landed on at the top.
+ const walkRecentlyViewed = (delta: number) =>
+ openChatItemById(useChatNavigationStore.getState().stepRecentlyViewed(delta));
+ useShortcut("nextRecentlyViewedChat", () => walkRecentlyViewed(1), {
+ repeats: true,
+ });
+ useShortcut("previousRecentlyViewedChat", () => walkRecentlyViewed(-1), {
+ repeats: true,
+ });
+ useShortcut("nextChatNeedingAttention", () =>
+ goToChat(nextAttentionChatItem),
+ );
+ // No undo and no menu item anywhere, so it says what it did.
+ useShortcut("clearAllUnreads", () => {
+ if (sidebarCovered()) return;
+ const state = useChatNavigationStore.getState();
+ const cleared = countUnreadRows(state);
+ if (state.unreadThreadIds.size === 0) {
+ toast.info("No unread chats");
+ return;
+ }
+ state.clearAllUnreads();
+ toast.success(`Cleared ${cleared} unread ${cleared === 1 ? "chat" : "chats"}`);
+ });
+
+ // The six slots register as <Shortcut> elements: a loop of hooks would
+ // break the rules of hooks.
+ const slotShortcuts = (
+ <>
+ {RECENT_SLOT_NUMBERS.map((slot) => (
+ <Shortcut
+ key={`recent-${slot}`}
+ id={`goToRecentChat${slot}` as ShortcutId}
+ onTrigger={() => goToChat((s) => recentChatItemAtSlot(s, slot))}
+ />
+ ))}
+ </>
+ );
+
+ useShortcut(
+ "logOut",
+ () => {
+ // Desktop signs out through the OS account menu, not here.
+ if (isTauri) return;
+ void (async () => {
+ try {
+ await logout();
+ } catch {
+ clearAuthTokens();
+ }
+ void navigate({ to: "/login" });
+ })();
+ },
+ { enabled: !isTauri },
+ );
+
// The "..." every list header carries. Only chat lists regroup, so that half
// is opt-in; Pinned takes the sort half alone.
function renderSidebarHeaderMenu(options: {
@@ -2447,7 +3061,9 @@ export function AppSidebar() {
);
const isRenamingThis =
- renamingTarget?.kind === "chat" && renamingTarget.item.id === item.id;
+ renamingTarget?.kind === "chat" &&
+ renamingTarget.inline &&
+ renamingTarget.item.id === item.id;
// Inline rename edits the title in place as a rounded pill, no dialog.
if (isRenamingThis) {
@@ -2497,22 +3113,7 @@ export function AppSidebar() {
className={buttonClass}
onClick={(event) => {
if (list && handleSelectionClick(event, item, list)) return;
- clearSelection();
- clearChatNotifications(item);
- navigate({
- to: "/chat",
- search:
- item.type === "single"
- ? {
- thread: item.id,
- ...(item.projectId ? { project: item.projectId } : {}),
- }
- : {
- compare: item.id,
- ...(item.projectId ? { project: item.projectId } : {}),
- },
- });
- closeMobileIfOpen();
+ openChatItem(item);
}}
>
{isPinned && variant !== "project" && (
@@ -2621,46 +3222,17 @@ export function AppSidebar() {
try {
// A chat moved between projects keeps the sandbox it
// wrote to, so its own history names the folder, not
- // current membership. Every pane is read, since a
- // compare row can hold one folder per pane.
- // One at a time, not Promise.all: this file's export
- // contract forbids a concurrent await here, and two
- // panes win nothing. A failed read stops the loop and
- // is reported below rather than being caught per pane,
- // which would read as "never ran a tool" and fall back
- // to current membership, the answer the recorded id
- // exists to override.
+ // current membership. A failed read is reported
+ // below rather than caught per pane, which would
+ // read as "never ran a tool" and fall back to
+ // membership, the answer the recorded id overrides.
const ids =
threadIds.length > 0 ? threadIds : [item.id];
- const recorded: (string | undefined)[] = [];
- for (const threadId of ids) {
- recorded.push(
- recordedSandboxSessionId(
- await listStoredChatMessages(threadId),
- ),
- );
- }
- let distinct = [...new Set(recorded.filter(Boolean))];
- if (distinct.length === 0 && item.projectId) {
- // Chats stored before results carried a session
- // recorded nothing, so one that ran loose and has
- // since joined a project would be sent to the project
- // workspace. Its thread sandbox is the only other
- // candidate, and files there are this chat's. Only in
- // this direction: a chat moved OUT wrote under
- // project-<id>, and nothing retains which one.
- const held: string[] = [];
- for (const threadId of ids) {
- if (await sandboxHasFiles(threadId)) {
- held.push(threadId);
- }
- }
- distinct = [...new Set(held)];
- }
+ const distinct = await sandboxSessionIdsHolding(ids);
if (distinct.length > 1) {
toast.error("This chat wrote to more than one folder.", {
description:
- "Its panes ran before it joined this project, so open the folder from a tool card instead.",
+ "It ran tools on both sides of a move, so open the folder from a tool card instead.",
});
return;
}
@@ -2813,6 +3385,7 @@ export function AppSidebar() {
return (
<>
+ {slotShortcuts}
<Sidebar
collapsible="icon"
collapseToZero={isTauri}
@@ -4028,7 +4601,10 @@ export function AppSidebar() {
</DialogContent>
</Dialog>
<Dialog
- open={renamingTarget !== null && renamingTarget.kind !== "chat"}
+ open={
+ renamingTarget !== null &&
+ (renamingTarget.kind !== "chat" || !renamingTarget.inline)
+ }
onOpenChange={(open) => {
if (!open) setRenamingTarget(null);
}}
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index dc33f6ef125..51a6ae678be 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -67,6 +67,8 @@ import {
notifyStudioDictationUnavailable,
YoutubeTranscriptPrompt,
stripSearchImageTokens,
+ useChatActive,
+ useInComparePane,
} from "@/features/chat";
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
import {
@@ -146,6 +148,12 @@ import {
} from "@/features/chat/utils/continuation";
import { holdAutoContinueRun } from "@/features/chat/utils/auto-continue-run-keeper";
import { McpComposerButton } from "@/features/chat/mcp-composer-button";
+import {
+ COMPOSER_INPUT_SELECTOR,
+ isSurfaceInForeground,
+ useShortcut,
+} from "@/features/settings";
+import { create } from "zustand";
import { getExternalReasoningCapabilities } from "@/features/chat/provider-capabilities";
import { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";
import { BypassPermissionsMenuItem } from "@/features/chat/bypass-permissions-menu-item";
@@ -1861,7 +1869,9 @@ const GeneratedImageViewportOverlay: FC<{
if (!overlay) {
return;
}
- document.querySelector<HTMLTextAreaElement>(".aui-composer-input")?.focus();
+ document
+ .querySelector<HTMLTextAreaElement>(COMPOSER_INPUT_SELECTOR)
+ ?.focus();
}, [overlay]);
if (!overlay) {
@@ -4226,6 +4236,19 @@ const Composer: FC<{
// a new chat first persists, which is the same composer.
const composerIdentity = threadListItemId ?? "";
composerIdentityRef.current = composerIdentity;
+ // Keep the mic clickable: if the engine can't run here, explain and point to
+ // the local model instead of disabling the button.
+ const startDictation = useCallback(() => {
+ if (!isStudioDictationAvailable()) {
+ notifyStudioDictationUnavailable();
+ return;
+ }
+ try {
+ aui.composer().startDictation();
+ } catch {
+ notifyStudioDictationUnavailable();
+ }
+ }, [aui]);
const sendAfterDictation = useCallback(() => {
sendAfterDictationRef.current = true;
dictationComposerRef.current = composerIdentity;
@@ -4248,6 +4271,54 @@ const Composer: FC<{
hasAttachments,
hasPendingAudio,
});
+ // Both chords live here, not with the controls below: the recording bar
+ // replaces those while dictation runs, so a chord registered there could
+ // start dictation and never stop it.
+ const chatActive = useChatActive();
+ useShortcut(
+ "startDictation",
+ () => {
+ // Stopping first and ungated: the recording bar replaces the input, so
+ // the gate's selector is gone for exactly as long as there is something
+ // to stop.
+ if (isDictating) {
+ aui.composer().stopDictation();
+ return;
+ }
+ // A dialog over Chat leaves this registered, and a microphone opened
+ // behind one is neither visible nor stoppable from where the user is.
+ if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
+ startDictation();
+ },
+ { enabled: chatActive },
+ );
+ useShortcut(
+ "sendMessage",
+ () => {
+ // While recording, the bar's own send: it stops dictation first and lets
+ // the final transcript land, where submitting here would send the text
+ // so far and leave the rest of the sentence in an empty composer.
+ if (isDictating) {
+ if (!dictationBlocked) sendAfterDictation();
+ return;
+ }
+ // A dialog over Chat leaves this registered, and the draft behind it is
+ // not what the user is typing. Sending is not undoable, so it asks here.
+ if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
+ // requestSubmit, not the runtime's send: it runs handleSubmit first,
+ // which parks a send behind indexing, queues it behind a run, or
+ // refuses it.
+ formRef.current?.requestSubmit();
+ },
+ {
+ enabled: chatActive && !disabled,
+ // The model picker is a non-modal popover, so the composer stays the
+ // foreground while its search box has focus. Every text field but the
+ // composer keeps this chord.
+ skipInTextFields: true,
+ textFieldException: COMPOSER_INPUT_SELECTOR,
+ },
+ );
const wasDictatingRef = useRef(false);
useEffect(() => {
if (isDictating) {
@@ -4665,6 +4736,7 @@ const Composer: FC<{
// submitting the form, so run the complete queue/capacity path.
onSendClick={handleSubmit}
onStopClick={stopQueue}
+ onDictateClick={startDictation}
pendingSend={pendingSend}
menuSide={effectiveMenuSide}
queueThreadIds={promptQueueThreadIds}
@@ -5743,6 +5815,21 @@ const ComposerToolsMenu: FC<{
};
input.click();
}, [aui, audioAttachmentsEnabled]);
+ // Straight to the picker, skipping the "+" menu the item lives in. Off-route
+ // the chat pane is hidden rather than unmounted, so the chords gate on it
+ // being the visible tab; a window listener does not care about `inert`.
+ const chatActive = useChatActive();
+ useShortcut(
+ "attachFiles",
+ () => {
+ // `chatActive` is the visible tab, not the foreground, so a dialog over
+ // Chat left this live, and the OS file chooser is the least dismissable
+ // thing a chord can raise.
+ if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
+ pickAttachment();
+ },
+ { enabled: chatActive && composerCanAddAttachments },
+ );
// Exports are storage-backed; temporary chats intentionally never write there.
const messageCount = useAuiState(({ thread }) => thread.messages.length);
const exportDisabled = incognito || !activeThreadId || messageCount === 0;
@@ -6359,6 +6446,7 @@ const ComposerRightControls: FC<{
onQueueClick?: () => void;
onSendClick?: (event: { preventDefault: () => void }) => void;
onStopClick?: () => void;
+ onDictateClick?: () => void;
pendingSend?: boolean;
menuSide?: "top" | "bottom";
queueThreadIds: string[];
@@ -6368,6 +6456,7 @@ const ComposerRightControls: FC<{
onQueueClick,
onSendClick,
onStopClick,
+ onDictateClick,
pendingSend,
menuSide,
queueThreadIds,
@@ -6435,20 +6524,6 @@ const ComposerRightControls: FC<{
}
if (isQueueRunning) onStopClick?.();
};
- const aui = useAui();
- // Keep the mic clickable: if the engine can't run here, explain and point to
- // the local model instead of disabling the button.
- const startDictation = () => {
- if (!isStudioDictationAvailable()) {
- notifyStudioDictationUnavailable();
- return;
- }
- try {
- aui.composer().startDictation();
- } catch {
- notifyStudioDictationUnavailable();
- }
- };
return (
<div className="aui-composer-action-wrapper flex shrink-0 items-center gap-1.5">
<ReasoningToggle side={menuSide} />
@@ -6461,7 +6536,7 @@ const ComposerRightControls: FC<{
type="button"
variant="ghost"
className="size-8 rounded-full text-foreground"
- onClick={startDictation}
+ onClick={onDictateClick}
>
{/* size-[22px] is the fallback; unsloth-dictate-icon sets the size. */}
<MicIcon className="unsloth-dictate-icon size-[22px]" />
@@ -7355,6 +7430,10 @@ const AssistantMessage: FC = () => {
<BranchPicker className="mr-0.5" />
<AssistantActionBar />
</div>
+ {/* Renders nothing. `If last` keeps the hook off the other N-1. */}
+ <MessagePrimitive.If last={true}>
+ <ForkChatShortcut />
+ </MessagePrimitive.If>
{/*
The same reveal, for the other traversal direction.
@@ -7437,14 +7516,34 @@ const ForkCountBadge: FC = () => {
);
};
+/**
+ * One fork at a time, across every caller of the hook below.
+ *
+ * The chord and the button each hold their own instance, so a `useState` flag
+ * only disables the one that was used: pressing the chord and then clicking
+ * Fork before the first request lands would post two, each with its own new
+ * thread id, and race their navigations. A store is what both of them read.
+ */
+const useForkInFlight = create<{
+ forking: boolean;
+ setForking: (forking: boolean) => void;
+}>((set) => ({
+ forking: false,
+ setForking: (forking) => set({ forking }),
+}));
+
const useForkMessageAction = () => {
const aui = useAui();
const navigate = useNavigate();
const messageId = useAuiState(({ message }) => message.id);
const isRunning = useAuiState(({ thread }) => thread.isRunning);
- const [pending, setPending] = useState(false);
+ const pending = useForkInFlight((s) => s.forking);
+ const setPending = useForkInFlight((s) => s.setForking);
const handleFork = async () => {
+ // Read, do not trust the render: two handlers can run in one tick, before
+ // either sees the other's state.
+ if (useForkInFlight.getState().forking) return;
const remoteId = aui.threadListItem().getState().remoteId;
if (!remoteId) {
toast.error("Cannot fork an unsaved chat");
@@ -7502,6 +7601,37 @@ const useForkMessageAction = () => {
};
};
+/**
+ * The chord's registration, which no action bar can hold.
+ *
+ * The button below is the user bar's, and that bar is `autohide="always"`, so
+ * ActionBarPrimitive.Root returns null and takes the registration with it on
+ * every message that is not hovered. The assistant bar has its own fork call
+ * and never mounts the button at all, so on a thread that ended the ordinary
+ * way, with a reply, no message carried the chord.
+ *
+ * Mounted from both message roots under `If last`, so it exists once, for
+ * whichever message is last, whatever its role and wherever the pointer is.
+ */
+const ForkChatShortcut: FC = () => {
+ const { forkMessage, forkDisabled } = useForkMessageAction();
+ const chatActive = useChatActive();
+ // Compare mounts a thread in each pane, and the chord would go to whichever
+ // registered first. Fork from the button there.
+ const inComparePane = useInComparePane();
+ useShortcut(
+ "forkChat",
+ () => {
+ // `chatActive` is the visible tab, not the foreground, so a dialog over
+ // Chat would otherwise fork the conversation behind it.
+ if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
+ void forkMessage();
+ },
+ { enabled: chatActive && !inComparePane && !forkDisabled },
+ );
+ return null;
+};
+
const ForkMessageButton: FC = () => {
const { forkMessage, forkDisabled } = useForkMessageAction();
@@ -7941,6 +8071,11 @@ const UserMessage: FC = () => {
<BranchPicker className="aui-user-branch-picker ml-0.5" />
</div>
</div>
+ {/* The other half of the pair: last is a user message while a reply is
+ still to come, or once one has been deleted. */}
+ <MessagePrimitive.If last={true}>
+ <ForkChatShortcut />
+ </MessagePrimitive.If>
</MessagePrimitive.Root>
);
};
diff --git a/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx b/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx
index 89a15c61aba..3b43bc55cbd 100644
--- a/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx
@@ -6,11 +6,17 @@
import { Button } from "@/components/ui/button";
import { resolveToolConfirmation } from "@/features/chat/api/chat-api";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import {
+ COMPOSER_INPUT_SELECTOR,
+ isSurfaceBackgrounded,
+ useShortcut,
+} from "@/features/settings";
import type {
ToolCallMessagePartComponent,
ToolCallMessagePartStatus,
} from "@assistant-ui/react";
import { useCallback, useEffect, useState } from "react";
+import { useChatActive, useChatNavigationStore } from "@/features/chat";
/**
* Allow / Always allow / Deny controls for a tool call paused awaiting the
@@ -98,6 +104,64 @@ export function ToolConfirmationControls({
}
}, [showControls, autoAllowed, pending, failed, resolve]);
+ // ⏎ / Esc, only while this card is asking: an auto-approved one answers
+ // itself. Off route the chat pane is hidden rather than unmounted, so
+ // without the active check a bare key would decide a request nobody can
+ // see. With a second request parked, in the other Compare pane or further
+ // up the thread, the chord has no way to say which one it means, so both
+ // cards fall back to their buttons.
+ const chatActive = useChatActive();
+ const soleRequest = useChatRuntimeStore(
+ (s) => Object.keys(s.toolConfirmations).length === 1,
+ );
+ // A sidebar selection answers Escape already, and that listener does not
+ // consume the key, so both would run off one press and deny a call the user
+ // was only dismissing a selection with. Escape there costs nothing to undo
+ // and this does not, so this is the one that waits. Enter goes with it: the
+ // buttons are still there, and a card that takes half its keys is worse to
+ // explain than one that takes none.
+ const selectionActive = useChatNavigationStore((s) => s.selectionActive);
+ const keyboardReady =
+ chatActive &&
+ soleRequest &&
+ !selectionActive &&
+ showControls &&
+ pending === null &&
+ !(autoAllowed && !failed);
+ // The Chat route stays mounted under a dialog, so `keyboardReady` still says
+ // yes while the request is hidden behind one. Answering a tool call the user
+ // cannot see must not be reachable by accident, so both chords ask here.
+ const chatCovered = () => isSurfaceBackgrounded(COMPOSER_INPUT_SELECTOR);
+ useShortcut(
+ "approveToolRequest",
+ () => {
+ if (chatCovered()) return;
+ void resolve("allow");
+ },
+ {
+ enabled: keyboardReady,
+ // Enter belongs to the composer while it has focus.
+ skipInTextFields: true,
+ },
+ );
+ useShortcut(
+ "declineToolRequest",
+ () => {
+ if (chatCovered()) return;
+ void resolve("deny");
+ },
+ {
+ enabled: keyboardReady,
+ skipInTextFields: true,
+ // A request usually arrives with the composer still focused from the
+ // prompt that caused it, and Escape types nothing there, so the gate
+ // would hold the decline back at the one moment it is most wanted. Enter
+ // above gets no such pass: that key sends. Every other field keeps its
+ // Escape, the queued-prompt editor and the settings search included.
+ textFieldException: COMPOSER_INPUT_SELECTOR,
+ },
+ );
+
if (!showControls) return null;
// Auto-approved tools resolve silently unless the post fails.
if (autoAllowed && !failed) return null;
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
index a9aef3b90c1..e9babc47cda 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-overlay.tsx
@@ -10,6 +10,7 @@ import {
useFloatingPanelOrderStore,
useFloatingPanelZIndex,
} from "@/lib/floating-panel-order";
+import { useShortcut } from "@/features/settings";
import { cn } from "@/lib/utils";
import {
ArrowExpand01Icon,
@@ -127,6 +128,18 @@ export function ApiMonitorOverlay(): ReactElement | null {
ReturnType<typeof getApiMonitor>
> | null>(null);
+ // The chord lives with the panel: reaching this store from the shell would
+ // pull the whole feature index into the root chunk. The full page has
+ // nothing to toggle, being the panel's contents already.
+ useShortcut(
+ "toggleApiMonitor",
+ () => {
+ if (isOpen) close();
+ else open();
+ },
+ { enabled: !onFullPage },
+ );
+
// What this session has already shown, and when it started watching.
const watchRef = useRef<ApiMonitorWatch>(createWatch(0));
const lastNewEntryAtRef = useRef(0);
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index a3bb4114dda..8ce297bc645 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -131,6 +131,7 @@ import {
useSelectedChatArtifact,
} from "./artifacts/store";
import type { ChatArtifact, ChatArtifactSurface } from "./artifacts/types";
+import { McpServersDialogMount } from "./mcp-composer-button";
import { ChatSettingsPanel } from "./chat-settings-sheet";
import {
ResearchActivityPanel,
@@ -178,7 +179,13 @@ import {
providerSupportsBuiltinImageGeneration,
providerSupportsBuiltinWebFetch,
providerSupportsBuiltinWebSearch,
+ providerSupportsFastMode,
} from "./provider-capabilities";
+import {
+ COMPOSER_INPUT_SELECTOR,
+ isSurfaceBackgrounded,
+ useShortcut,
+} from "@/features/settings";
import {
ChatActiveContext,
ChatRuntimeProvider,
@@ -2164,6 +2171,8 @@ export function ChatPage({
}, [active, navigate, search.thread]);
const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
+ // Controlled, so the chord can open the switcher and not just its trigger.
+ const [projectPickerOpen, setProjectPickerOpen] = useState(false);
const [modelSelectorLocked, setModelSelectorLocked] = useState(false);
const viewBeforeCompareRef = useRef<ChatSearch | null>(null);
// Latest non-compare view, so exiting compare can restore it even when
@@ -3294,6 +3303,9 @@ export function ChatPage({
})();
}, [ejectModel, resetArtifacts]);
+ // Pins the picker open so a stray click cannot dismiss the step under it.
+ // Tour steps only: the effect below shuts anything left pinned once the tour
+ // is gone, so anyone else calling this would get a flash and nothing more.
const openModelSelector = useCallback(() => {
setModelSelectorLocked(true);
setModelSelectorOpen(true);
@@ -3304,6 +3316,13 @@ export function ChatPage({
setModelSelectorOpen(false);
}, []);
+ /** The chord's opener: no pin, so the picker stays dismissible. */
+ const toggleModelSelector = useCallback(() => {
+ // Pinned means a tour step is standing on it, and that step owns it.
+ if (modelSelectorLocked) return;
+ setModelSelectorOpen((open) => !open);
+ }, [modelSelectorLocked]);
+
const handleModelSelectorOpenChange = useCallback(
(open: boolean) => {
if (!open && modelSelectorLocked) return;
@@ -3319,6 +3338,119 @@ export function ChatPage({
() => setSettingsOpen(false),
[setSettingsOpen],
);
+
+ // --- Chat page shortcuts ----------------------------------------------
+ // The controls these drive are owned by this page.
+ // Both controls are the header's, and the header drops them in Compare,
+ // where each pane carries its own picker instead. Without the check the
+ // chord would toggle state nothing renders.
+ const headerPickersShown = active && view.mode !== "compare";
+ // This page stays mounted under a dialog, so `enabled` still says yes while
+ // the header is inert. Without a press-time check the chord opens a popover
+ // on the covered surface, or leaves the picker to reappear when the dialog
+ // closes. Backgrounded, not "not in the foreground": the composer travels
+ // with this header, and an unrendered layout is not a covered one.
+ const chatCovered = () => isSurfaceBackgrounded(COMPOSER_INPUT_SELECTOR);
+ useShortcut(
+ "openModelPicker",
+ () => {
+ if (chatCovered()) return;
+ toggleModelSelector();
+ },
+ { enabled: headerPickersShown },
+ );
+ // The same condition the switcher renders by, so the chord cannot open a
+ // control that is not there and the reset below cannot miss a way it goes.
+ const projectSwitcherShown = headerPickersShown && Boolean(currentProjectId);
+ useShortcut(
+ "openProjectPicker",
+ () => {
+ if (chatCovered()) return;
+ setProjectPickerOpen(true);
+ },
+ { enabled: projectSwitcherShown },
+ );
+ // A picker left open would come back on the next visit as a ghost of the
+ // last one. Off-route is one way to leave it: this page stays mounted. So is
+ // entering Compare, and so is a standalone chat taking the project away,
+ // both of which unmount the switcher while the page is still on screen.
+ // Adjusted during render, as React prescribes for state that has to follow a
+ // value it derives from.
+ if (!projectSwitcherShown && projectPickerOpen) {
+ setProjectPickerOpen(false);
+ }
+
+ /** Step the effort level, clamped at both ends unless we are cycling. */
+ const shiftReasoningEffort = useCallback(
+ (delta: number, wrap: boolean) => {
+ const state = useChatRuntimeStore.getState();
+ const levels = state.reasoningEffortLevels;
+ // Levels stay populated for an enable_thinking model, whose request path
+ // drops the effort. Same test as the composer's effort menu.
+ const isEffort =
+ state.reasoningStyle === "reasoning_effort" ||
+ state.reasoningStyle === "enable_thinking_effort";
+ if (!state.supportsReasoning || !isEffort || levels.length === 0) {
+ toast.info("This model has no reasoning effort setting");
+ return;
+ }
+ const current = levels.indexOf(state.reasoningEffort);
+ // Loading a model that drops the level in force leaves the effort set to
+ // one that is gone, and indexOf gives -1. The first press picks the
+ // lowest level offered rather than counting a step off a missing index.
+ if (current === -1) {
+ state.setReasoningEffort(levels[0]);
+ return;
+ }
+ const from = current;
+ const next = wrap
+ ? (from + delta + levels.length) % levels.length
+ : Math.min(Math.max(from + delta, 0), levels.length - 1);
+ if (levels[next] === state.reasoningEffort) return;
+ state.setReasoningEffort(levels[next]);
+ },
+ [],
+ );
+ useShortcut(
+ "cycleReasoningEffort",
+ () => {
+ if (chatCovered()) return;
+ shiftReasoningEffort(1, true);
+ },
+ { enabled: active },
+ );
+ useShortcut(
+ "increaseReasoningEffort",
+ () => {
+ if (chatCovered()) return;
+ shiftReasoningEffort(1, false);
+ },
+ { enabled: active },
+ );
+ useShortcut(
+ "decreaseReasoningEffort",
+ () => {
+ if (chatCovered()) return;
+ shiftReasoningEffort(-1, false);
+ },
+ { enabled: active },
+ );
+
+ const fastModeSupported = providerSupportsFastMode(
+ activeExternalProviderType,
+ parseExternalModelId(inferenceParams.checkpoint)?.modelId ?? null,
+ );
+ useShortcut(
+ "toggleFastMode",
+ () => {
+ if (chatCovered()) return;
+ const state = useChatRuntimeStore.getState();
+ const next = !state.params.fastMode;
+ state.setParams({ ...state.params, fastMode: next });
+ toast.success(next ? "Fast mode on" : "Fast mode off");
+ },
+ { enabled: active && fastModeSupported },
+ );
const { isMobile, pinned } = useSidebar();
const enterCompare = useCallback(() => {
@@ -3704,6 +3836,11 @@ export function ChatPage({
render their own copy and the shared-composer menu would have none. It
also portals to body, so gate it on `active` like the tour above. */}
{active && <BypassPermissionsConfirmDialog />}
+ {/* The MCP servers dialog: its chord has to work before MCP is switched
+ on, and the pill that used to own it only renders once it is. Mounted
+ through the route change, not gated on `active`, so it can close
+ itself on the way out instead of returning with the tab. */}
+ <McpServersDialogMount />
{/* `--studio-chat-notice-height` is 0 until ChatModelNotice is on screen; the
thread viewport adds it to the top padding it reserves for the header, so
without it the first message reads under an opaque bar. Declared on the
@@ -3826,6 +3963,8 @@ export function ChatPage({
isLoading={projectsLoading}
onSelectProject={openProjectLanding}
onViewAllProjects={openProjectsList}
+ open={projectPickerOpen}
+ onOpenChange={setProjectPickerOpen}
/>
{currentProject && activeThreadId ? (
<>
diff --git a/studio/frontend/src/features/chat/components/project-switcher.tsx b/studio/frontend/src/features/chat/components/project-switcher.tsx
index a37df882b43..5b1ec3040ac 100644
--- a/studio/frontend/src/features/chat/components/project-switcher.tsx
+++ b/studio/frontend/src/features/chat/components/project-switcher.tsx
@@ -22,12 +22,17 @@ export function ProjectSwitcher({
isLoading,
onSelectProject,
onViewAllProjects,
+ open: controlledOpen,
+ onOpenChange,
}: {
currentProject: ProjectRecord | null;
projects: ProjectRecord[];
isLoading: boolean;
onSelectProject: (projectId: string) => void;
onViewAllProjects: () => void;
+ /** Supplied by the page so the "Open project picker" chord can open it. */
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
}): ReactElement {
const showLoadingRow = isLoading && projects.length === 0;
const showEmptyRow = !isLoading && projects.length === 0;
@@ -35,7 +40,9 @@ export function ProjectSwitcher({
// Controlled so the body-portaled dropdown can't linger over another tab off-route.
const active = useChatActive();
- const [open, setOpen] = useState(false);
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
+ const open = controlledOpen ?? uncontrolledOpen;
+ const setOpen = onOpenChange ?? setUncontrolledOpen;
return (
<DropdownMenu open={active && open} onOpenChange={(o) => setOpen(active && o)}>
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
index 9968e3913d0..c7a0a3d3875 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-sidebar-items.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import {
CHAT_HISTORY_UPDATED_EVENT,
notifyChatHistoryUpdated,
@@ -165,8 +165,16 @@ export function useChatSidebarItems(options?: {
};
}, [enabled, options?.projectId, requireMessages]);
- const items = groupThreads(allThreads ?? []);
- const archivedItems = groupThreads(allThreads ?? [], true);
+ // Memoised for identity as much as for the work. These arrays are the root
+ // of every derived sidebar list, so rebuilding them on each render leaves
+ // each of those with a new identity too, and an effect that depends on one
+ // re-runs every render. Where such an effect also sets state, React
+ // re-renders once to find the bail-out, rebuilds these, and never settles.
+ const items = useMemo(() => groupThreads(allThreads ?? []), [allThreads]);
+ const archivedItems = useMemo(
+ () => groupThreads(allThreads ?? [], true),
+ [allThreads],
+ );
const canCompare = useChatRuntimeStore((s) => Boolean(s.params.checkpoint));
return { items, archivedItems, canCompare, loaded };
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index d535ed73a99..158b6b4fad7 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -51,6 +51,7 @@ export {
type Preset,
} from "./chat-settings-sheet";
export { useChatRuntimeStore } from "./stores/chat-runtime-store";
+export { useChatActive, useInComparePane } from "./runtime-provider";
export {
CHAT_RAG_CAPTION_KEY,
CHAT_RAG_OCR_KEY,
@@ -74,6 +75,16 @@ export {
export { useToolAwaitingApproval } from "./tool-approval";
export { PermissionModeDropdown } from "./permission-mode-select";
export { useChatSearchStore } from "./stores/chat-search-store";
+export type { ChatNavigationState } from "./stores/chat-navigation-store";
+export {
+ adjacentChatItem,
+ countUnreadRows,
+ nextAttentionChatItem,
+ openChatItemById,
+ recentChatItemAtSlot,
+ useChatNavigationStore,
+ visibleChatItems,
+} from "./stores/chat-navigation-store";
export { usePinnedChatsStore } from "./stores/pinned-chats-store";
export { usePinnedProjectsStore } from "./stores/pinned-projects-store";
export {
@@ -231,7 +242,7 @@ export {
listStoredChatThreads,
markThreadIncognito,
} from "./utils/chat-history-storage";
-export { recordedSandboxSessionId } from "./utils/recorded-sandbox-session";
+export { allRecordedSandboxSessionIds } from "./utils/recorded-sandbox-session";
export {
markChatThreadDeleted,
removeChatThreadTombstones,
diff --git a/studio/frontend/src/features/chat/mcp-composer-button.tsx b/studio/frontend/src/features/chat/mcp-composer-button.tsx
index 9bad60d40aa..951c35019c8 100644
--- a/studio/frontend/src/features/chat/mcp-composer-button.tsx
+++ b/studio/frontend/src/features/chat/mcp-composer-button.tsx
@@ -21,6 +21,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
+import { useShortcut } from "@/features/settings";
import {
type McpServerConfig,
@@ -30,6 +31,8 @@ import {
} from "./api/mcp-servers-api";
import { ChatMcpServersDialog } from "./chat-mcp-servers-dialog";
import { useChatRuntimeStore } from "./stores/chat-runtime-store";
+import { useMcpServersDialogStore } from "./stores/mcp-servers-dialog-store";
+import { useChatActive } from "./runtime-provider";
// Matches the Thinking pill chevron so the affordance reads the same.
const ArrowDownStandardIcon: FC<{ className?: string }> = ({ className }) => (
@@ -103,7 +106,8 @@ export function McpComposerButton({
const setToolsEnabled = useChatRuntimeStore((s) => s.setToolsEnabled);
const [servers, setServers] = useState<McpServerConfig[]>([]);
- const [dialogOpen, setDialogOpen] = useState(false);
+ const dialogOpen = useMcpServersDialogStore((s) => s.open);
+ const setDialogOpen = useMcpServersDialogStore((s) => s.setOpen);
const [menuOpen, setMenuOpen] = useState(false);
const [pendingUrl, setPendingUrl] = useState<string | null>(null);
const [hintKey, setHintKey] = useState<string | null>(null);
@@ -121,10 +125,12 @@ export function McpComposerButton({
}
}, []);
- // Load the server list on mount and whenever the menu opens.
+ // Load the server list on mount, and again when the dialog closes: it can
+ // be opened from the chord as well as from this menu.
useEffect(() => {
+ if (dialogOpen) return;
void refresh();
- }, [refresh]);
+ }, [refresh, dialogOpen]);
const enabledUrls = new Set(
servers.filter((s) => s.is_enabled).map((s) => normalizeMcpUrl(s.url)),
@@ -345,14 +351,36 @@ export function McpComposerButton({
</TooltipContent>
</Tooltip>
)}
- <ChatMcpServersDialog
- open={dialogOpen}
- onOpenChange={(next) => {
- setDialogOpen(next);
- // Resync after managing servers.
- if (!next) void refresh();
- }}
- />
</>
);
}
+
+/**
+ * The dialog itself, plus the chord that opens it, mounted for the chat rather
+ * than for the pill above: MCP ships off and the pill only renders once it is
+ * on, so anything living there is out of the shortcut's reach.
+ */
+export function McpServersDialogMount() {
+ const open = useMcpServersDialogStore((s) => s.open);
+ const setOpen = useMcpServersDialogStore((s) => s.setOpen);
+ // Not gated on tool support: this is where servers are configured, and a
+ // model that cannot use them yet is the usual reason to come here.
+ const chatActive = useChatActive();
+ useShortcut("openMcpServers", () => setOpen(true), { enabled: chatActive });
+ // Leaving the chat closes it for good rather than parking it: the flag
+ // outlives this subtree, so a dialog left open would come back on the next
+ // visit as a ghost of the last one.
+ useEffect(() => {
+ if (!chatActive && open) setOpen(false);
+ }, [chatActive, open, setOpen]);
+ // Going off-route is not the only way to leave. Logout, or a session that
+ // expires, moves the root to /login and takes this whole subtree with it, so
+ // no chatActive=false render ever happens and the flag above survives to
+ // reopen the dialog on the next visit. Close on the way out as well.
+ useEffect(() => {
+ return () => useMcpServersDialogStore.getState().setOpen(false);
+ }, []);
+ return (
+ <ChatMcpServersDialog open={chatActive && open} onOpenChange={setOpen} />
+ );
+}
diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
index 51ceb10c39f..d62e09bd213 100644
--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
@@ -59,7 +59,11 @@ import { notifyChatHistoryUpdated } from "../api/chat-api";
import { toolResultModelText } from "../api/chat-adapter";
import { usePlusMenuPrefsStore } from "../stores/plus-menu-prefs-store";
import type { ThreadRecord, MessageRecord } from "../types";
-import { createConversationMarkdownExporter } from "../utils/conversation-markdown-export";
+import {
+ buildNamedConversationsMarkdown,
+ createConversationMarkdownBuilder,
+ createConversationMarkdownExporter,
+} from "../utils/conversation-markdown-export";
import { parseCsv } from "../utils/csv-parse";
import { unwrapPastedTextContent } from "../utils/pasted-text.ts";
import {
@@ -450,6 +454,13 @@ export async function exportConversationCsv(threadId: string): Promise<void> {
);
}
+/** Same markdown the download produces, for the "Copy as Markdown" shortcut. */
+export const buildConversationMarkdownForThread =
+ createConversationMarkdownBuilder({
+ loadMessages: loadConversationMessages,
+ renderMessage: messageToMarkdown,
+ });
+
export const exportConversationMarkdown = createConversationMarkdownExporter({
loadMessages: loadConversationMessages,
renderMessage: messageToMarkdown,
@@ -516,6 +527,27 @@ export async function saveChatItemAsProjectSource(
}
}
+/**
+ * A sidebar row as one markdown document, for the "Copy as Markdown" shortcut.
+ * The halves of a compare pair are named the way saving them to project sources
+ * names them, after their models: the two arrive in whichever order they last
+ * answered in, so position alone would label them wrong.
+ */
+export async function buildChatItemMarkdown(item: {
+ id: string;
+ title: string;
+ type: string;
+}): Promise<string> {
+ const plans = planChatItemSources(
+ item,
+ item.type === "single" ? [] : await listStoredChatThreads({ pairId: item.id }),
+ );
+ return buildNamedConversationsMarkdown(
+ plans,
+ buildConversationMarkdownForThread,
+ );
+}
+
export type ConvExportFormat = "jsonl-raw" | "csv" | "sharegpt";
const EXPORT_FORMAT_LABELS: Record<ConvExportFormat, string> = {
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index d4d44cd6671..4900a214c39 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -2687,6 +2687,15 @@ export function useChatActive(): boolean {
return useContext(ChatActiveContext);
}
+// True inside a Compare pane. Both panes mount the same message controls, so a
+// window-level chord would otherwise be answered by whichever pane mounted
+// first, whatever the user was looking at.
+const ComparePaneContext = createContext(false);
+
+export function useInComparePane(): boolean {
+ return useContext(ComparePaneContext);
+}
+
export function ChatRuntimeProvider({
children,
modelType = "base",
@@ -2768,6 +2777,7 @@ export function ChatRuntimeProvider({
("call_0") can't bleed live output into each other's cards. */}
<ChatProjectScopeContext.Provider value={projectId ?? null}>
<ToolPaneScopeContext.Provider value={toolPaneScope(modelType, pairId)}>
+ <ComparePaneContext.Provider value={Boolean(pairId)}>
<ActiveThreadSync
enabled={
modelType === "base" &&
@@ -2828,6 +2838,7 @@ export function ChatRuntimeProvider({
{/* The view stays mounted (only CSS-hidden) while off-route so the run
stays attached and the stream alive; unmounting aborts generation. */}
{children}
+ </ComparePaneContext.Provider>
</ToolPaneScopeContext.Provider>
</ChatProjectScopeContext.Provider>
</AssistantRuntimeProvider>
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 6cdd34bbf43..300b0baa787 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -36,6 +36,11 @@ import {
notifyStudioDictationUnavailable,
} from "@/features/chat/adapters/studio-dictation-adapter";
import type { StudioDictationSession } from "@/features/chat/adapters/studio-web-speech-dictation-adapter";
+import {
+ COMPOSER_INPUT_SELECTOR,
+ isSurfaceInForeground,
+ useShortcut,
+} from "@/features/settings";
import { useVoiceSettingsStore } from "@/features/settings/stores/voice-settings-store";
import {
AUDIO_ACCEPT,
@@ -77,6 +82,7 @@ import {
PencilRulerIcon,
} from "@hugeicons/core-free-icons";
import { useNavigate } from "@tanstack/react-router";
+import { useChatActive } from "./runtime-provider";
import { HugeiconsIcon } from "@hugeicons/react";
import { toast } from "@/lib/toast";
import {
@@ -1893,6 +1899,56 @@ export function SharedComposer({
!isComposing &&
!isDictating;
+ // Compare mode swaps this composer in for the single-chat one, and only one
+ // of the two is ever on screen, so the chords register in both. Both gate on
+ // the chat tab being visible: off-route the pane is hidden, not unmounted.
+ const chatActive = useChatActive();
+ useShortcut(
+ "startDictation",
+ () => {
+ // As in the single-chat composer: a dialog over Chat leaves this
+ // registered, and a microphone opened behind one is neither visible nor
+ // stoppable from where the user is.
+ // Stopping first and ungated, as in the single-chat composer: a recording
+ // stays stoppable wherever the gate would say no.
+ if (isDictating) {
+ stopDictation();
+ return;
+ }
+ if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
+ startDictation();
+ },
+ { enabled: chatActive },
+ );
+ // Through the existing sendRef: `send` is render-scoped, which the React
+ // compiler will not let a hook outlive.
+ useShortcut(
+ "sendMessage",
+ () => {
+ // As in the single-chat composer: the draft behind a dialog is not what
+ // the user is typing.
+ if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
+ sendRef.current?.();
+ },
+ {
+ enabled: chatActive && canSend,
+ // As in the single-chat composer: a non-modal popover's search box is a
+ // text field the composer is still the foreground behind.
+ skipInTextFields: true,
+ textFieldException: COMPOSER_INPUT_SELECTOR,
+ },
+ );
+ useShortcut(
+ "attachFiles",
+ () => {
+ // As in the single-chat composer, which would otherwise raise the file
+ // chooser from behind a dialog.
+ if (!isSurfaceInForeground(COMPOSER_INPUT_SELECTOR)) return;
+ fileInputRef.current?.click();
+ },
+ { enabled: chatActive },
+ );
+
// Adjustable "+" menu items, keyed by id. Pinned ones render at the top
// level; the rest fall into the "More" overflow submenu. Core items (photos,
// web search, code) and "More" itself live outside this map.
@@ -2180,11 +2236,16 @@ export function SharedComposer({
setCompositionState(false);
}}
placeholder="Send to both models..."
- className="composer-input"
- rows={1}
// dir="auto" detects RTL (Arabic/Hebrew/Persian/Urdu) from the first
- // strong character; no effect on LTR scripts.
+ // strong character; no effect on LTR scripts. Kept next to the
+ // placeholder: the IME smoke reads this pair out of the source.
dir="auto"
+ // aui-composer-input carries no styling anywhere; it is the name both
+ // composers answer to, so one selector can mean "the composer" whichever
+ // of the two is on screen. Escape's decline exception and the dictation
+ // foreground check both rely on it.
+ className="composer-input aui-composer-input"
+ rows={1}
/>
<div className="composer-action-wrapper">
<div
diff --git a/studio/frontend/src/features/chat/stores/chat-navigation-store.ts b/studio/frontend/src/features/chat/stores/chat-navigation-store.ts
new file mode 100644
index 00000000000..c51a466593e
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/chat-navigation-store.ts
@@ -0,0 +1,345 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { create } from "zustand";
+import type { SidebarItem } from "../hooks/use-chat-sidebar-items";
+
+/**
+ * What the navigation chords need: the ordered rows the sidebar renders, the
+ * open chat, the unread set and the rows wanting attention. The sidebar owns
+ * the sorting and publishes its finished lists here, so nothing recomputes a
+ * second copy that could disagree with the screen.
+ */
+
+/** How many rows back ⌃Tab can walk, bounded so the array cannot grow all day. */
+const RECENTLY_VIEWED_LIMIT = 24;
+
+export interface ChatNavigationState {
+ /** The pinned block, in the order the sidebar draws it. */
+ pinnedItems: SidebarItem[];
+ /** Project chats on screen. Empty when the sidebar is organized as one list,
+ * where those chats are in Recents instead. */
+ projectItems: SidebarItem[];
+ /** Recents, likewise. ⌥⌘1-6 indexes into this list alone. */
+ recentItems: SidebarItem[];
+ /** Rows generating, queued or unread, most urgent first. */
+ attentionItemIds: string[];
+ activeItemId: string | null;
+ unreadThreadIds: Set<string>;
+ /** Which row each unread thread belongs to, for rows no longer published. */
+ unreadRowIds: Record<string, string>;
+ /** Row ids, most recently opened first. */
+ recentlyViewedIds: string[];
+ /** A walk through the stack in progress: the order frozen at the first step,
+ * and where in it the walk has got to. */
+ traversal: { order: string[]; index: number } | null;
+ /** Registered by the sidebar, the only code that can route to a row. */
+ openChatItem: ((item: SidebarItem) => void) | null;
+ /** Rows or folders are selected, so Escape is already spoken for. Published
+ * because bare Escape also declines a waiting tool call, and one press must
+ * not do both. */
+ selectionActive: boolean;
+
+ publishLists: (next: {
+ pinnedItems: SidebarItem[];
+ projectItems: SidebarItem[];
+ recentItems: SidebarItem[];
+ attentionItemIds: string[];
+ activeItemId: string | null;
+ }) => void;
+ setOpenChatItem: (fn: ((item: SidebarItem) => void) | null) => void;
+ /** Drop one account's rows, unread set and walk. Called as the sidebar goes. */
+ resetAccountState: () => void;
+ setSelectionActive: (active: boolean) => void;
+ /**
+ * `rowIdByThreadId` groups threads by their row, so a Compare row still
+ * counts once after a collapsed section takes it out of the published lists
+ * while its threads stay unread.
+ */
+ markThreadsUnread: (
+ threadIds: string[],
+ rowIdByThreadId?: Record<string, string>,
+ ) => void;
+ clearThreadsUnread: (threadIds: string[]) => void;
+ clearAllUnreads: () => void;
+ noteViewed: (itemId: string) => void;
+ stepRecentlyViewed: (delta: number) => SidebarItem | null;
+ endTraversal: () => void;
+}
+
+/**
+ * Everything the chords read off a row: which chat, where it routes, and the
+ * threads behind it. Compared by value, not identity, since the sidebar
+ * rebuilds its items; ids alone would keep a row whose project changed and
+ * route the next jump to the project it left. Titles and timestamps churn and
+ * nobody here reads them.
+ */
+function sameRows(a: SidebarItem[], b: SidebarItem[]): boolean {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ const before = a[i];
+ const after = b[i];
+ if (
+ before.id !== after.id ||
+ before.type !== after.type ||
+ (before.projectId ?? null) !== (after.projectId ?? null) ||
+ (before.threadIds ?? []).join("\u0000") !==
+ (after.threadIds ?? []).join("\u0000")
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function sameStrings(a: string[], b: string[]): boolean {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+}
+
+/**
+ * One account's chats. The unread set used to live in component state and died
+ * with it; a module store does not, so signing out has to say so or the next
+ * account inherits these rows and this walk.
+ */
+const ACCOUNT_STATE = {
+ pinnedItems: [] as SidebarItem[],
+ projectItems: [] as SidebarItem[],
+ recentItems: [] as SidebarItem[],
+ attentionItemIds: [] as string[],
+ activeItemId: null as string | null,
+ unreadThreadIds: new Set<string>(),
+ unreadRowIds: {} as Record<string, string>,
+ recentlyViewedIds: [] as string[],
+ traversal: null as { order: string[]; index: number } | null,
+ selectionActive: false,
+};
+
+export const useChatNavigationStore = create<ChatNavigationState>(
+ (set, get) => ({
+ ...ACCOUNT_STATE,
+ unreadThreadIds: new Set(),
+ openChatItem: null,
+
+ // Published from an effect on every render, so bail out when nothing moved.
+ publishLists: (next) =>
+ set((state) => {
+ if (
+ state.activeItemId === next.activeItemId &&
+ sameRows(state.pinnedItems, next.pinnedItems) &&
+ sameRows(state.projectItems, next.projectItems) &&
+ sameRows(state.recentItems, next.recentItems) &&
+ sameStrings(state.attentionItemIds, next.attentionItemIds)
+ ) {
+ return state;
+ }
+ return next;
+ }),
+
+ setOpenChatItem: (fn) => set({ openChatItem: fn }),
+
+ // A fresh Set each time, or every account after the first shares one.
+ resetAccountState: () =>
+ set({ ...ACCOUNT_STATE, unreadThreadIds: new Set(), unreadRowIds: {} }),
+
+ setSelectionActive: (active) =>
+ set((state) =>
+ state.selectionActive === active ? state : { selectionActive: active },
+ ),
+
+ markThreadsUnread: (threadIds, rowIdByThreadId) =>
+ set((state) => {
+ if (threadIds.length === 0) return state;
+ const unreadThreadIds = new Set(state.unreadThreadIds);
+ for (const id of threadIds) unreadThreadIds.add(id);
+ const unreadRowIds = { ...state.unreadRowIds };
+ for (const id of threadIds) {
+ const rowId = rowIdByThreadId?.[id];
+ if (rowId) unreadRowIds[id] = rowId;
+ }
+ return { unreadThreadIds, unreadRowIds };
+ }),
+
+ clearThreadsUnread: (threadIds) =>
+ set((state) => {
+ if (!threadIds.some((id) => state.unreadThreadIds.has(id))) {
+ return state;
+ }
+ const unreadThreadIds = new Set(state.unreadThreadIds);
+ const unreadRowIds = { ...state.unreadRowIds };
+ for (const id of threadIds) {
+ unreadThreadIds.delete(id);
+ delete unreadRowIds[id];
+ }
+ return { unreadThreadIds, unreadRowIds };
+ }),
+
+ clearAllUnreads: () =>
+ set((state) =>
+ state.unreadThreadIds.size === 0
+ ? state
+ : { unreadThreadIds: new Set(), unreadRowIds: {} },
+ ),
+
+ noteViewed: (itemId) => {
+ const { recentlyViewedIds, traversal } = get();
+ // Mid-walk the stack holds still: promoting each chat it lands on would
+ // swap the top two, so the next step comes straight back and everything
+ // below stays unreachable.
+ if (traversal && traversal.order[traversal.index] === itemId) return;
+ if (recentlyViewedIds[0] === itemId) {
+ if (traversal) set({ traversal: null });
+ return;
+ }
+ set({
+ traversal: null,
+ recentlyViewedIds: [
+ itemId,
+ ...recentlyViewedIds.filter((id) => id !== itemId),
+ ].slice(0, RECENTLY_VIEWED_LIMIT),
+ });
+ },
+
+ stepRecentlyViewed: (delta) => {
+ const state = get();
+ const byId = new Map(
+ visibleChatItems(state).map((item) => [item.id, item]),
+ );
+ // Rows deleted or archived since the walk began would be dead stops.
+ const order = (state.traversal?.order ?? state.recentlyViewedIds).filter(
+ (id) => byId.has(id),
+ );
+ if (order.length === 0) return null;
+ const from = state.traversal
+ ? order.indexOf(state.traversal.order[state.traversal.index])
+ : state.activeItemId
+ ? order.indexOf(state.activeItemId)
+ : -1;
+ // Nothing open, or a chat outside the stack: the walk starts outside it,
+ // so the first step lands on the end it walks from.
+ const index =
+ from === -1
+ ? delta > 0
+ ? 0
+ : order.length - 1
+ : (from + delta + order.length) % order.length;
+ set({ traversal: { order, index } });
+ return byId.get(order[index]) ?? null;
+ },
+
+ endTraversal: () => {
+ const { traversal, recentlyViewedIds } = get();
+ if (!traversal) return;
+ // The walk is over, so the chat it finished on takes the top, the way it
+ // would have if it had been opened by hand.
+ const landed = traversal.order[traversal.index];
+ set({
+ traversal: null,
+ recentlyViewedIds: [
+ landed,
+ ...recentlyViewedIds.filter((id) => id !== landed),
+ ].slice(0, RECENTLY_VIEWED_LIMIT),
+ });
+ },
+ }),
+);
+
+/**
+ * Every chat row the sidebar shows, in the order it draws them: pinned, then
+ * the project folders, then Recents. A pinned project chat is drawn twice, so
+ * the first of the pair wins and the walk does not stop on it again.
+ */
+export function visibleChatItems(state: ChatNavigationState): SidebarItem[] {
+ const seen = new Set<string>();
+ const out: SidebarItem[] = [];
+ for (const item of [
+ ...state.pinnedItems,
+ ...state.projectItems,
+ ...state.recentItems,
+ ]) {
+ if (seen.has(item.id)) continue;
+ seen.add(item.id);
+ out.push(item);
+ }
+ return out;
+}
+
+/**
+ * How many chats hold an unread thread. Not the set's size: a Compare row is
+ * backed by two threads and marked unread by both, so the set counted it twice.
+ * Unreads no row accounts for still count one each, since the wipe clears them.
+ */
+export function countUnreadRows(state: ChatNavigationState): number {
+ const listed = new Set<string>();
+ let rows = 0;
+ for (const item of visibleChatItems(state)) {
+ const own = (item.threadIds?.length ? item.threadIds : [item.id]).filter(
+ (id) => state.unreadThreadIds.has(id),
+ );
+ if (own.length === 0) continue;
+ rows += 1;
+ for (const id of own) listed.add(id);
+ }
+ // Plus the unreads no row accounts for: a chat archived while unread leaves
+ // its thread in the set, and the wipe clears those too. Grouped by row, so a
+ // hidden Compare row counts once rather than once per pane; an id with no
+ // group recorded stands for itself.
+ const hidden = new Set<string>();
+ for (const id of state.unreadThreadIds) {
+ if (!listed.has(id)) hidden.add(state.unreadRowIds[id] ?? id);
+ }
+ return rows + hidden.size;
+}
+
+/** The row `slot` (1-based) of Recents only, ignoring the pinned block. */
+export function recentChatItemAtSlot(
+ state: ChatNavigationState,
+ slot: number,
+): SidebarItem | null {
+ return state.recentItems[slot - 1] ?? null;
+}
+
+/** The row `delta` places from the open one, wrapping. With nothing open, the
+ * first row or the last, so the chord still does something. */
+export function adjacentChatItem(
+ state: ChatNavigationState,
+ delta: number,
+): SidebarItem | null {
+ const items = visibleChatItems(state);
+ if (items.length === 0) return null;
+ const current = items.findIndex((item) => item.id === state.activeItemId);
+ if (current === -1) return delta > 0 ? items[0] : items[items.length - 1];
+ const next = (current + delta + items.length) % items.length;
+ return items[next];
+}
+
+/** The next row wanting attention after the open one, wrapping. The list
+ * arrives already ordered, so this only picks the next entry. */
+export function nextAttentionChatItem(
+ state: ChatNavigationState,
+): SidebarItem | null {
+ const { attentionItemIds } = state;
+ if (attentionItemIds.length === 0) return null;
+ const byId = new Map(visibleChatItems(state).map((item) => [item.id, item]));
+ const current = state.activeItemId
+ ? attentionItemIds.indexOf(state.activeItemId)
+ : -1;
+ for (let step = 1; step <= attentionItemIds.length; step++) {
+ const id =
+ attentionItemIds[
+ (current + step + attentionItemIds.length) % attentionItemIds.length
+ ];
+ const item = byId.get(id);
+ if (item && item.id !== state.activeItemId) return item;
+ }
+ return null;
+}
+
+/** Open a row through the callback the sidebar registered. */
+export function openChatItemById(item: SidebarItem | null): void {
+ if (!item) return;
+ useChatNavigationStore.getState().openChatItem?.(item);
+}
diff --git a/studio/frontend/src/features/chat/stores/mcp-servers-dialog-store.ts b/studio/frontend/src/features/chat/stores/mcp-servers-dialog-store.ts
new file mode 100644
index 00000000000..0e64318238a
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/mcp-servers-dialog-store.ts
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { create } from "zustand";
+
+/**
+ * One MCP servers dialog for the chat, opened from either side: the composer
+ * pill's menu and the keyboard shortcut. The pill only exists once MCP is on
+ * for the chat, and it ships off, so the dialog cannot live there or the
+ * shortcut would do nothing until the user found the pill by hand.
+ */
+interface McpServersDialogState {
+ open: boolean;
+ setOpen: (open: boolean) => void;
+}
+
+export const useMcpServersDialogStore = create<McpServersDialogState>(
+ (set) => ({
+ open: false,
+ setOpen: (open) => set({ open }),
+ }),
+);
diff --git a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
index d05aaccc147..9f6ad53a240 100644
--- a/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
+++ b/studio/frontend/src/features/chat/utils/conversation-markdown-export.ts
@@ -29,30 +29,82 @@ type ConversationMarkdownExportDependencies<
readonly notifyNoContent: () => void;
};
-export function createConversationMarkdownExporter<
+/** The markdown for one thread: null when it could not be loaded, empty when
+ * it holds nothing exportable. Shared by the download and the copy shortcut. */
+export function createConversationMarkdownBuilder<
Message extends StoredConversationMessage,
>({
loadMessages,
renderMessage,
- download,
- exportTimestamp,
- notifyNoContent,
-}: ConversationMarkdownExportDependencies<Message>): (
- threadId: string,
-) => Promise<void> {
+}: Pick<
+ ConversationMarkdownExportDependencies<Message>,
+ "loadMessages" | "renderMessage"
+>): (threadId: string) => Promise<string | null> {
return async (threadId) => {
const messages = await loadMessages(threadId);
if (!messages) {
- return;
+ return null;
}
const normalizedMessages: ConversationMarkdownMessage[] = messages.map(
(message) => ({
role: String(message.role ?? ""),
- // Renderer markup, never prose: an exported answer must not carry raw tokens.
+ // Renderer markup, never prose: an exported answer must not carry raw
+ // tokens. Here rather than in the exporter, so the copy chord strips
+ // them too.
content: stripSearchImageTokens(renderMessage(message)),
}),
);
- const markdown = buildConversationMarkdown(normalizedMessages);
+ return buildConversationMarkdown(normalizedMessages);
+ };
+}
+
+/** A title safe to interpolate into a heading: a line break would end it. */
+function headingText(title: string): string {
+ return title.replace(/\s+/g, " ").trim();
+}
+
+/**
+ * One document from several threads, each under its own heading. A compare row
+ * is two models answering the same prompt, and the transcripts carry only role
+ * headings, so unnamed halves cannot be told apart. A lone thread is left
+ * exactly as the download writes it.
+ */
+export async function buildNamedConversationsMarkdown(
+ conversations: readonly { readonly id: string; readonly title: string }[],
+ build: (threadId: string) => Promise<string | null>,
+): Promise<string> {
+ const parts: string[] = [];
+ for (const conversation of conversations) {
+ const markdown = await build(conversation.id);
+ if (!markdown) continue;
+ parts.push(
+ conversations.length > 1
+ ? `# ${headingText(conversation.title)}\n\n${markdown}`
+ : markdown,
+ );
+ }
+ return parts.join("\n---\n\n");
+}
+
+export function createConversationMarkdownExporter<
+ Message extends StoredConversationMessage,
+>({
+ loadMessages,
+ renderMessage,
+ download,
+ exportTimestamp,
+ notifyNoContent,
+}: ConversationMarkdownExportDependencies<Message>): (
+ threadId: string,
+) => Promise<void> {
+ const build = createConversationMarkdownBuilder({
+ loadMessages,
+ renderMessage,
+ });
+ return async (threadId) => {
+ const markdown = await build(threadId);
+ // null already reported itself.
+ if (markdown === null) return;
if (!markdown) {
notifyNoContent();
return;
diff --git a/studio/frontend/src/features/chat/utils/recorded-sandbox-session.ts b/studio/frontend/src/features/chat/utils/recorded-sandbox-session.ts
index 9d635687ebd..e02d21e6799 100644
--- a/studio/frontend/src/features/chat/utils/recorded-sandbox-session.ts
+++ b/studio/frontend/src/features/chat/utils/recorded-sandbox-session.ts
@@ -9,18 +9,23 @@ import {
import type { MessageRecord } from "../types";
/**
- * The sandbox a chat's tool calls actually wrote to, read back from its history.
+ * Every sandbox a chat's tool calls actually wrote to, read back from its
+ * history, newest first.
*
* Moving a chat between projects rewrites only its `projectId` while the files
* stay put, so a scope from current membership can name a folder this chat
* never used; the id recorded on a tool result is the one its files are under.
+ * A chat that ran tools on both sides of such a move names both, which is why
+ * this returns a list: the newest alone would hide the folder it left behind.
*
* Gated on the tool name and the full wrapper shape, as the adapter is: a
* custom or MCP tool with its own `sessionId` would name an unrelated folder.
*/
-export function recordedSandboxSessionId(
+export function allRecordedSandboxSessionIds(
messages: MessageRecord[],
-): string | undefined {
+): string[] {
+ const found: string[] = [];
+ const seen = new Set<string>();
for (let index = messages.length - 1; index >= 0; index -= 1) {
const content = messages[index]?.content;
if (!Array.isArray(content)) continue;
@@ -39,8 +44,11 @@ export function recordedSandboxSessionId(
}
const result: unknown = entry.result;
if (!isSandboxToolResult(result)) continue;
- if (result.sessionId.length > 0) return result.sessionId;
+ if (result.sessionId.length === 0) continue;
+ if (seen.has(result.sessionId)) continue;
+ seen.add(result.sessionId);
+ found.push(result.sessionId);
}
}
- return undefined;
+ return found;
}
diff --git a/studio/frontend/src/features/settings/components/shortcut.tsx b/studio/frontend/src/features/settings/components/shortcut.tsx
new file mode 100644
index 00000000000..4a01491fb15
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/shortcut.tsx
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { ShortcutId } from "../lib/keyboard-shortcuts";
+import { useShortcut } from "../hooks/use-shortcut";
+
+/** `useShortcut` as a component, for registering a family of chords at once.
+ * A loop of hooks would break the rules of hooks; one element per slot does
+ * not, and each still registers exactly one action. */
+export function Shortcut({
+ id,
+ onTrigger,
+ enabled,
+ skipInTextFields,
+}: {
+ id: ShortcutId;
+ onTrigger: (event: KeyboardEvent) => void;
+ enabled?: boolean;
+ skipInTextFields?: boolean;
+}): null {
+ useShortcut(id, onTrigger, { enabled, skipInTextFields });
+ return null;
+}
diff --git a/studio/frontend/src/features/settings/hooks/use-shortcut.ts b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
index 7e7afbae064..46b6cdfe2ad 100644
--- a/studio/frontend/src/features/settings/hooks/use-shortcut.ts
+++ b/studio/frontend/src/features/settings/hooks/use-shortcut.ts
@@ -3,6 +3,9 @@
import { useEffect, useMemo, useRef } from "react";
import {
+ SHORTCUT_SLOTS,
+ activationBelongsToFocus,
+ type ShortcutBinding,
type ShortcutId,
formatBindingLabel,
matchesBinding,
@@ -14,15 +17,75 @@ import {
useKeyboardShortcutsStore,
} from "../stores/keyboard-shortcuts-store";
-function isTextEntryFocused(): boolean {
+/** The chat composer's textarea, which some chords are allowed to fire from. */
+export const COMPOSER_INPUT_SELECTOR = ".aui-composer-input";
+
+/** Exported for the test: the gate is easier to pin here than through React. */
+export function isTextEntryFocused(exceptFor?: string): boolean {
if (typeof document === "undefined") return false;
const el = document.activeElement as HTMLElement | null;
const tag = el?.tagName;
+ const typing =
+ tag === "INPUT" || tag === "TEXTAREA" || Boolean(el?.isContentEditable);
+ if (!typing) return false;
+ // A named field does not type this chord, so it does not shield it either.
+ return !(exceptFor && el?.matches(exceptFor) === true);
+}
+
+/**
+ * A keydown the IME is still composing with. Escape cancels a candidate and
+ * Enter commits one, so without this, declining a tool call takes the Escape a
+ * CJK user aimed at the candidate window. Both signals: isComposing on WebKit,
+ * the legacy 229 on Chromium.
+ */
+export function isImeComposing(event: KeyboardEvent): boolean {
+ return event.isComposing || event.keyCode === 229;
+}
+
+/**
+ * Whether `selector`'s element is the foreground rather than under a modal. A
+ * dialog leaves the route mounted, so a route-gated chord still fires behind
+ * it, and `enabled` is read at render, which a dialog opening need not trigger.
+ * So anything irreversible asks here, at press time.
+ */
+export function isSurfaceInForeground(selector: string): boolean {
+ if (typeof document === "undefined") return false;
+ // Every match, not the first: Compare keeps the base view mounted and inert
+ // behind the panes, so the first composer found is the hidden one. Radix
+ // marks the rest of the page aria-hidden (older React: inert) for a modal's
+ // life, which is the general signal, not a per-dialog store.
+ return [...document.querySelectorAll(selector)].some(
+ (el) => !el.closest('[aria-hidden="true"], [inert]'),
+ );
+}
+
+/**
+ * Whether every `selector` match sits under a modal. Not the complement of the
+ * check above: an unrendered surface is not backgrounded, and reading it that
+ * way would kill a chord on a layout that never renders the element. The mobile
+ * sidebar is the case, unmounted while its drawer is closed.
+ */
+export function isSurfaceBackgrounded(selector: string): boolean {
+ if (typeof document === "undefined") return false;
+ const found = [...document.querySelectorAll(selector)];
return (
- tag === "INPUT" || tag === "TEXTAREA" || Boolean(el?.isContentEditable)
+ found.length > 0 &&
+ found.every((el) => el.closest('[aria-hidden="true"], [inert]') !== null)
);
}
+/**
+ * Whether pressing `binding` in a focused text field would put something in it.
+ * Narrow on purpose: only Escape, the function keys, and anything held with a
+ * modifier other than Shift. A caret key inserts nothing but still has an edit
+ * to stand aside for, so it counts as typing.
+ */
+export function typesInTextField(binding: ShortcutBinding): boolean {
+ if (binding.mod || binding.ctrl || binding.alt) return false;
+ if (binding.code === "Escape") return false;
+ return !/^F([1-9]|1[0-9]|2[0-4])$/.test(binding.code);
+}
+
export interface UseShortcutOptions {
/** Skip registration entirely (route gating, dialogs). Defaults to true. */
enabled?: boolean;
@@ -31,55 +94,106 @@ export interface UseShortcutOptions {
* otherwise steal a keystroke the composer wants.
*/
skipInTextFields?: boolean;
+ /**
+ * A selector for text fields the gate above does not apply to, for a chord
+ * that types nothing in them. Escape in the composer is the case: it leaves
+ * the text alone, so a prompt still focused from the message that opened a
+ * tool request must not be what stops the request being declined.
+ */
+ textFieldException?: string;
+ /**
+ * Run again on each auto-repeat while the chord is held. For walking a list,
+ * where holding is the gesture. Everything else is one-shot: a toggle held
+ * past the repeat delay would land wherever the user let go.
+ */
+ repeats?: boolean;
+}
+
+/** The chords `id` answers to now, joined so the effect re-runs only on a real change. */
+function useBindingValues(id: ShortcutId): string {
+ return useKeyboardShortcutsStore((s) =>
+ SHORTCUT_SLOTS.map((slot) => resolveBinding(s.overrides, id, slot) ?? "")
+ .join("\0"),
+ );
}
/**
- * Run `handler` when the user presses whatever chord `id` is currently bound
- * to. The binding is read from the shortcuts store, so an edit in Settings
- * takes effect without a reload; an unassigned action registers nothing.
+ * Run `handler` when the user presses either chord `id` is currently bound to.
+ * Bindings are read from the shortcuts store, so an edit in Settings takes
+ * effect without a reload; an unassigned action registers nothing.
*/
export function useShortcut(
id: ShortcutId,
handler: (event: KeyboardEvent) => void,
options: UseShortcutOptions = {},
): void {
- const { enabled = true, skipInTextFields = false } = options;
- const value = useKeyboardShortcutsStore((s) =>
- resolveBinding(s.overrides, id),
- );
+ const {
+ enabled = true,
+ skipInTextFields = false,
+ textFieldException,
+ repeats = false,
+ } = options;
+ const values = useBindingValues(id);
// A chord claimed by two actions is consumed by whichever listener runs
- // first, so only its owner registers. Otherwise the winner would follow mount
- // order and change from route to route.
- const owned = useKeyboardShortcutsStore(
- (s) =>
- shortcutOwningBinding(s.overrides, resolveBinding(s.overrides, id)) ===
- id,
+ // first, so a slot only registers when this action owns it. Otherwise the
+ // winner follows mount order and changes from route to route.
+ const ownedFlags = useKeyboardShortcutsStore((s) =>
+ SHORTCUT_SLOTS.map((slot) => {
+ const value = resolveBinding(s.overrides, id, slot);
+ return value && shortcutOwningBinding(s.overrides, value) === id
+ ? "1"
+ : "0";
+ }).join(""),
);
- const binding = useMemo(() => parseBinding(value), [value]);
+ const bindings = useMemo(() => {
+ const out: ShortcutBinding[] = [];
+ values.split("\0").forEach((value, index) => {
+ if (ownedFlags[index] !== "1") return;
+ const parsed = parseBinding(value);
+ if (parsed) out.push(parsed);
+ });
+ return out;
+ }, [values, ownedFlags]);
// The handler usually closes over fresh props, so keep it in a ref rather
// than tearing down and re-adding the listener on every render.
const handlerRef = useRef(handler);
handlerRef.current = handler;
useEffect(() => {
- if (!binding || !enabled || !owned) return;
+ if (bindings.length === 0 || !enabled) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
- if (!matchesBinding(binding, event)) return;
- if (skipInTextFields && isTextEntryFocused()) return;
+ if (isImeComposing(event)) return;
+ const hit = bindings.find((binding) => matchesBinding(binding, event));
+ if (!hit) return;
+ // The exception is for a chord that types nothing there. Decline ships
+ // on Escape; rebound to Enter or a letter, the same pass would deny the
+ // request as the user edits the prompt.
+ const exception = typesInTextField(hit) ? undefined : textFieldException;
+ if (skipInTextFields && isTextEntryFocused(exception)) return;
+ // The focused control keeps its own Enter or Space.
+ if (
+ typeof document !== "undefined" &&
+ activationBelongsToFocus(hit, document.activeElement)
+ ) {
+ return;
+ }
event.preventDefault();
+ // Held past the OS repeat delay the chord arrives again and again. It
+ // stays consumed either way, but only an action that asked for repeats
+ // runs on them.
+ if (event.repeat && !repeats) return;
handlerRef.current(event);
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
- }, [binding, enabled, owned, skipInTextFields]);
+ }, [bindings, enabled, skipInTextFields, textFieldException, repeats]);
}
/**
- * Label for the chord `id` is bound to right now, in the platform's own
- * notation, or null when the action is unassigned. Hints that render the
- * shipped default instead would tell the user to press a chord that stopped
- * working the moment they rebound or cleared the action in Settings.
+ * Label for the primary chord `id` is bound to now, in the platform's notation,
+ * or null when the slot is unassigned. Rendering the shipped default instead
+ * would name a chord that stopped working the moment the user rebound it.
*/
export function useShortcutLabel(id: ShortcutId): string | null {
const value = useKeyboardShortcutsStore((s) =>
@@ -90,3 +204,17 @@ export function useShortcutLabel(id: ShortcutId): string | null {
return binding ? formatBindingLabel(binding) : null;
}, [value]);
}
+
+/** Both chords, for surfaces that want to show the alternate too. */
+export function useShortcutLabels(id: ShortcutId): string[] {
+ const values = useBindingValues(id);
+ return useMemo(
+ () =>
+ values
+ .split("\0")
+ .map((value) => parseBinding(value))
+ .filter((binding): binding is ShortcutBinding => binding !== null)
+ .map((binding) => formatBindingLabel(binding)),
+ [values],
+ );
+}
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index ae0cbe88925..16d5da33001 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -60,7 +60,15 @@ export type {
PersonalizationAppearance,
PersonalizationProfile,
} from "./api/personalization";
-export { useShortcut, useShortcutLabel } from "./hooks/use-shortcut";
+export {
+ COMPOSER_INPUT_SELECTOR,
+ isSurfaceBackgrounded,
+ isSurfaceInForeground,
+ useShortcut,
+ useShortcutLabel,
+ useShortcutLabels,
+} from "./hooks/use-shortcut";
+export { Shortcut } from "./components/shortcut";
export {
currentBinding,
useKeyboardShortcutsStore,
diff --git a/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts b/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts
index 880c027f06d..b73433cfd7b 100644
--- a/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts
+++ b/studio/frontend/src/features/settings/lib/keyboard-shortcuts.ts
@@ -5,31 +5,99 @@ import type { TranslationKey } from "@/i18n";
/**
* Every rebindable action. To add one: an entry in SHORTCUT_DEFS, its two i18n
- * keys, and a `useShortcut(id, ...)` where the action runs.
+ * keys in all twelve locales, its label in settings-search.ts, and a
+ * `useShortcut(id, ...)` where the action runs.
+ *
+ * Order is the render order and decides who owns a contested chord, so the
+ * most reached-for actions come first. An action only earns a row when Studio
+ * has the feature behind it.
*/
export type ShortcutId =
- | "openSettings"
- | "openKeyboardShortcuts"
+ // Chat navigation, first because it is what the list is mostly for.
| "newChat"
+ | "newTemporaryChat"
+ | "archiveChat"
+ | "newStandaloneChat"
+ | "markChatUnread"
+ | "togglePinChat"
+ | "selectAllChats"
+ | "clearChatSelection"
+ | "deleteSelectedChats"
+ | "nextRecentlyViewedChat"
+ | "nextChat"
+ | "nextChatNeedingAttention"
+ | "previousRecentlyViewedChat"
+ | "previousChat"
+ | "goToRecentChat1"
+ | "goToRecentChat2"
+ | "goToRecentChat3"
+ | "goToRecentChat4"
+ | "goToRecentChat5"
+ | "goToRecentChat6"
+ // Workspaces
+ | "switchToChat"
+ | "switchToProjects"
+ | "switchToHub"
+ | "switchToTrain"
+ | "switchToRecipes"
+ | "switchToImages"
+ | "switchToVideo"
+ | "switchToAudio"
+ | "switchToExport"
+ // Panels and app-level actions
+ | "toggleApiMonitor"
+ | "toggleSidebar"
+ | "openMcpServers"
+ | "clearAllUnreads"
+ | "logOut"
+ | "openSettings"
+ | "approveToolRequest"
+ | "declineToolRequest"
+ // Composer
+ | "attachFiles"
+ | "cycleReasoningEffort"
+ | "decreaseReasoningEffort"
+ | "increaseReasoningEffort"
+ | "openModelPicker"
+ | "openProjectPicker"
+ | "startDictation"
+ | "sendMessage"
+ | "toggleFastMode"
+ // Chat actions
+ | "copyChatAsMarkdown"
+ | "copySessionId"
+ | "forkChat"
| "searchChats"
- | "toggleSidebar";
+ | "renameChat"
+ | "openKeyboardShortcuts";
-export type ShortcutGroup = "general" | "chat";
+/** Which of an action's two chords a value belongs to. */
+export type ShortcutSlot = "primary" | "alternate";
+
+export const SHORTCUT_SLOTS: ShortcutSlot[] = ["primary", "alternate"];
export interface ShortcutDef {
id: ShortcutId;
labelKey: TranslationKey;
descriptionKey: TranslationKey;
- group: ShortcutGroup;
/** Serialized binding, or null for an action that ships unassigned. */
defaultBinding: string | null;
+ /** Second chord for the same action, e.g. ⌥⌘→ beside ⇧⌘]. Both fire. */
+ defaultAlternateBinding?: string | null;
+ /** Off macOS Ctrl is Mod, so a ⌃ default would be unreachable there. */
+ nonMacDefaultBinding?: string | null;
+ nonMacDefaultAlternateBinding?: string | null;
+ /** Allow a chord with no modifier. Only for prompt-gated actions. */
+ allowBareKey?: boolean;
+ /**
+ * Hide the row on the desktop build. The handler returns there, so offering
+ * the row offers a key that does nothing.
+ */
+ webOnly?: boolean;
}
-/**
- * `code` is KeyboardEvent.code, not `key`: the physical key, so a binding
- * survives a layout change and does not shift under Shift/Option. `mod` is Cmd
- * on macOS and Ctrl elsewhere, as every handler here already treated it.
- */
+/** `code` is KeyboardEvent.code, so a binding survives a layout change. `mod`
+ * is Cmd on macOS and Ctrl elsewhere. */
export interface ShortcutBinding {
code: string;
mod: boolean;
@@ -38,62 +106,303 @@ export interface ShortcutBinding {
alt: boolean;
}
-export const SHORTCUT_GROUPS: ShortcutGroup[] = ["general", "chat"];
+/** Short-hand for the many rows whose two i18n keys follow the id. */
+function def(
+ id: ShortcutId,
+ defaultBinding: string | null,
+ extra: Omit<
+ ShortcutDef,
+ "id" | "labelKey" | "descriptionKey" | "defaultBinding"
+ > = {},
+): ShortcutDef {
+ return {
+ id,
+ labelKey:
+ `settings.keyboardShortcuts.actions.${id}.label` as TranslationKey,
+ descriptionKey:
+ `settings.keyboardShortcuts.actions.${id}.description` as TranslationKey,
+ defaultBinding,
+ ...extra,
+ };
+}
+
+/** Rows 1-6 of Recents. ⌘1-9 would read better but is browser tab switching. */
+const RECENT_SLOT_DEFS: ShortcutDef[] = Array.from({ length: 6 }, (_, i) =>
+ def(`goToRecentChat${i + 1}` as ShortcutId, `Mod+Alt+Digit${i + 1}`),
+);
+
+const WORKSPACE_IDS = [
+ "switchToChat",
+ "switchToProjects",
+ "switchToHub",
+ "switchToTrain",
+ "switchToRecipes",
+ "switchToImages",
+ "switchToVideo",
+ "switchToAudio",
+ "switchToExport",
+] as const;
+
+/** ⌃1-9 on macOS. Off macOS that run is Ctrl+1-9, browser tab switching, so
+ * Shift joins it. */
+const WORKSPACE_DEFS: ShortcutDef[] = WORKSPACE_IDS.map((id, i) =>
+ def(id, `Ctrl+Digit${i + 1}`, {
+ nonMacDefaultBinding: `Mod+Shift+Digit${i + 1}`,
+ }),
+);
+/** Most-used first: the list renders in this order, and it settles which
+ * action owns a chord two of them claim, rather than mount order. */
export const SHORTCUT_DEFS: ShortcutDef[] = [
- {
- id: "newChat",
- labelKey: "settings.keyboardShortcuts.actions.newChat.label",
- descriptionKey: "settings.keyboardShortcuts.actions.newChat.description",
- group: "chat",
- defaultBinding: "Mod+Shift+KeyO",
- },
- {
- id: "searchChats",
- labelKey: "settings.keyboardShortcuts.actions.searchChats.label",
- descriptionKey:
- "settings.keyboardShortcuts.actions.searchChats.description",
- group: "chat",
- defaultBinding: "Mod+KeyK",
- },
- {
- id: "toggleSidebar",
- labelKey: "settings.keyboardShortcuts.actions.toggleSidebar.label",
- descriptionKey:
- "settings.keyboardShortcuts.actions.toggleSidebar.description",
- group: "general",
- defaultBinding: "Mod+KeyB",
- },
- {
- id: "openSettings",
- labelKey: "settings.keyboardShortcuts.actions.openSettings.label",
- descriptionKey:
- "settings.keyboardShortcuts.actions.openSettings.description",
- group: "general",
- defaultBinding: "Mod+Comma",
- },
- {
- id: "openKeyboardShortcuts",
- labelKey: "settings.keyboardShortcuts.actions.openKeyboardShortcuts.label",
- descriptionKey:
- "settings.keyboardShortcuts.actions.openKeyboardShortcuts.description",
- group: "general",
- defaultBinding: "Mod+Slash",
- },
+ // -- Chat navigation ----------------------------------------------------
+ // ⌘N opens a browser window and cannot be prevented, and ⇧⌘O already
+ // shipped, so ⌘N rides along as the alternate for the desktop build.
+ def("newChat", "Mod+Shift+KeyO", { defaultAlternateBinding: "Mod+KeyN" }),
+ def("newTemporaryChat", "Mod+Shift+KeyN"),
+ // ⇧⌘A is Chrome's tab search and Firefox's add-ons manager, so E, the archive
+ // key every mail client uses, on the ⌥ run the rest of these chat chords sit on.
+ def("archiveChat", "Mod+Alt+KeyE"),
+ def("newStandaloneChat", "Mod+Alt+KeyO"),
+ // ⌃⇧U off macOS is GTK's hex entry, hard-coded in GtkIMContextSimple and
+ // bound again by IBus, so a focused composer is where it would be fought
+ // over. U stays the mnemonic on the ⌥ run, beside Clear all unreads.
+ def("markChatUnread", "Mod+Shift+KeyU", {
+ nonMacDefaultBinding: "Mod+Alt+KeyU",
+ }),
+ // ⌥⌘P is Chrome's Page Setup on macOS, so P moves to the ⌃⇧ run there, the
+ // same swap the API monitor and the composer pair make.
+ def("togglePinChat", "Ctrl+Shift+KeyP", {
+ nonMacDefaultBinding: "Mod+Alt+KeyP",
+ }),
+ // Archive, pin and mark unread above already act on the selection when
+ // there is one, so these only cover what a selection alone needs.
+ def("selectAllChats", "Mod+Alt+KeyS"),
+ // Escape clears the selection too, from the sidebar's own listener: this
+ // registry cannot bind it, since declining a tool call owns bare Escape.
+ def("clearChatSelection", null),
+ // Unassigned on purpose: nothing that deletes chats should ship on a chord.
+ def("deleteSelectedChats", null),
+ def("nextRecentlyViewedChat", "Ctrl+Tab", {
+ nonMacDefaultBinding: "Mod+Tab",
+ }),
+ // No arrow alternate: ⌥⌘→ is Chrome's next tab, and off macOS the same chord
+ // reads as Ctrl+Alt+→, desktop switching on GNOME and KDE and screen rotation
+ // on Intel graphics. Taken everywhere, so the bracket pair carries these.
+ def("nextChat", "Mod+Shift+BracketRight"),
+ def("nextChatNeedingAttention", "Mod+Alt+KeyA"),
+ def("previousRecentlyViewedChat", "Ctrl+Shift+Tab", {
+ nonMacDefaultBinding: "Mod+Shift+Tab",
+ }),
+ def("previousChat", "Mod+Shift+BracketLeft"),
+ ...RECENT_SLOT_DEFS,
+
+ // -- Workspaces ---------------------------------------------------------
+ ...WORKSPACE_DEFS,
+
+ // -- Panels and app-level actions ---------------------------------------
+ // ⌥⌘U is view source on macOS, so U keeps its mnemonic on ⌃⇧ there instead,
+ // the same swap the composer pair below makes. Off macOS it gives U up
+ // altogether: three actions wanted that letter and only two chords carry it
+ // safely there, so the two that mean "unread" have them and this one, whose
+ // U was never a mnemonic, takes M for monitor.
+ def("toggleApiMonitor", "Ctrl+Shift+KeyU", {
+ nonMacDefaultBinding: "Mod+Alt+Shift+KeyM",
+ }),
+ def("toggleSidebar", "Mod+KeyB"),
+ def("openMcpServers", null),
+ // ⇧Esc is Chrome's and Edge's task manager off macOS.
+ def("clearAllUnreads", "Shift+Escape", {
+ nonMacDefaultBinding: "Mod+Alt+Shift+KeyU",
+ }),
+ // Desktop signs out through the OS account menu, and the sidebar hides its
+ // own logout item there, so this row would bind a chord that cannot fire.
+ def("logOut", null, { webOnly: true }),
+ def("openSettings", "Mod+Comma"),
+ // Bare ⏎ / Esc: both register only while a tool call is waiting.
+ def("approveToolRequest", "Enter", { allowBareKey: true }),
+ def("declineToolRequest", "Escape", { allowBareKey: true }),
+
+ // -- Composer -----------------------------------------------------------
+ def("attachFiles", null),
+ def("cycleReasoningEffort", null),
+ def("decreaseReasoningEffort", null),
+ def("increaseReasoningEffort", null),
+ // Off macOS the ⇧ pair collides with Chrome's profile switcher and its
+ // bookmark-every-tab, so both move to Alt.
+ def("openModelPicker", "Ctrl+Shift+KeyM", {
+ nonMacDefaultBinding: "Mod+Alt+KeyM",
+ }),
+ def("openProjectPicker", "Mod+Alt+Shift+KeyO"),
+ def("startDictation", "Ctrl+Shift+KeyD", {
+ nonMacDefaultBinding: "Mod+Alt+KeyV",
+ }),
+ def("sendMessage", null),
+ def("toggleFastMode", null),
+
+ // -- Chat actions -------------------------------------------------------
+ def("copyChatAsMarkdown", null),
+ // ⌥⌘C is Firefox's element picker and Safari's console, so C moves the same
+ // way U did above.
+ def("copySessionId", "Ctrl+Shift+KeyC", {
+ nonMacDefaultBinding: "Mod+Alt+KeyC",
+ }),
+ def("forkChat", null),
+ // No ⇧⌘P alternate: it is the command-menu chord everywhere else, but in
+ // Firefox it opens a private window, and ⌘K is the one people reach for.
+ def("searchChats", "Mod+KeyK"),
+ def("renameChat", "Mod+Alt+KeyR"),
+ def("openKeyboardShortcuts", "Mod+Slash"),
];
export const SHORTCUT_DEF_BY_ID: Record<ShortcutId, ShortcutDef> =
- Object.fromEntries(SHORTCUT_DEFS.map((def) => [def.id, def])) as Record<
+ Object.fromEntries(SHORTCUT_DEFS.map((d) => [d.id, d])) as Record<
ShortcutId,
ShortcutDef
>;
-const SHORTCUT_IDS = new Set<string>(SHORTCUT_DEFS.map((def) => def.id));
+const SHORTCUT_IDS = new Set<string>(SHORTCUT_DEFS.map((d) => d.id));
export function isShortcutId(value: unknown): value is ShortcutId {
return typeof value === "string" && SHORTCUT_IDS.has(value);
}
+export function isShortcutSlot(value: unknown): value is ShortcutSlot {
+ return value === "primary" || value === "alternate";
+}
+
+/** The chord this build ships for `id`'s `slot` on this platform. */
+export function defaultBindingFor(
+ def: ShortcutDef,
+ slot: ShortcutSlot,
+ mac = isMacPlatform(),
+): string | null {
+ if (slot === "alternate") {
+ if (!mac && def.nonMacDefaultAlternateBinding !== undefined) {
+ return def.nonMacDefaultAlternateBinding;
+ }
+ return def.defaultAlternateBinding ?? null;
+ }
+ if (!mac && def.nonMacDefaultBinding !== undefined) {
+ return def.nonMacDefaultBinding;
+ }
+ return def.defaultBinding;
+}
+
+/**
+ * Chords the browser owns. Tab and window management never reaches the page at
+ * all; the rest is cancellable, but taking it breaks the browser's own action.
+ * Both work in the desktop build, so they still ship as defaults and the tab
+ * flags them on the web.
+ *
+ * What gets in, here and in the two platform sets below: a chord the browser
+ * takes from every user out of the box. These sets drive a warning the user
+ * reads and a test no default may fail, and both are only worth anything if
+ * the chord really is gone on the machine in front of them. A chord that only
+ * binds once a hidden developer menu is switched on does not qualify -- Safari
+ * puts Empty Caches on ⌥⌘E and reloads from origin on ⌥⌘R, but only for
+ * someone who went and enabled the Develop menu, so warning every macOS user
+ * about them would be telling almost all of them something untrue. Where a
+ * default and an opt-in chord do collide, the tab that raised the menu is also
+ * the tab that rebinds.
+ */
+const BROWSER_RESERVED_VALUES = new Set<string>([
+ "Mod+KeyN",
+ "Mod+Shift+KeyN",
+ "Mod+KeyT",
+ "Mod+Shift+KeyT",
+ "Mod+KeyW",
+ "Mod+Shift+KeyW",
+ "Mod+KeyL",
+ "Mod+KeyR",
+ "Mod+Shift+KeyR",
+ "Mod+KeyP",
+ // Firefox's new private window, on both platforms. Chrome puts that on
+ // ⇧⌘N, which is already here; this is the other half of the same pair.
+ "Mod+Shift+KeyP",
+ // Chrome's tab search, and Firefox's add-ons manager.
+ "Mod+Shift+KeyA",
+ "Mod+Tab",
+ "Mod+Shift+Tab",
+ "Ctrl+Tab",
+ "Ctrl+Shift+Tab",
+ ...Array.from({ length: 9 }, (_, i) => `Mod+Digit${i + 1}`),
+]);
+
+/**
+ * Owned on macOS only, where ⌥⌘ is the browsers' own run. From Chrome's
+ * shortcut list: U view source, I dev tools, J console, B bookmarks, N split
+ * view, F search, and the arrows for tabs and toolbar focus. Firefox adds C,
+ * its element picker, and K, its console. Off macOS the same values read as
+ * Ctrl+Alt, which none of them claim.
+ */
+const MAC_RESERVED_VALUES = new Set<string>([
+ "Mod+Alt+KeyU",
+ "Mod+Alt+KeyI",
+ "Mod+Alt+KeyJ",
+ "Mod+Alt+KeyB",
+ "Mod+Alt+KeyN",
+ "Mod+Alt+KeyF",
+ "Mod+Alt+KeyC",
+ "Mod+Alt+KeyK",
+ // Page Setup, which Chrome lists beside ⌘P on its own shortcuts page.
+ "Mod+Alt+KeyP",
+ // Safari's Show Next Tab and Show Previous Tab, per Apple's own shortcut
+ // list, and Chrome carries the same pair on macOS. Off macOS they read as
+ // Ctrl+Shift+bracket, which no browser claims. The chat walk ships on them
+ // for the desktop build, where nothing intercepts them; reserving them is
+ // what puts the warning in front of a web user who is about to rebind.
+ "Mod+Shift+BracketLeft",
+ "Mod+Shift+BracketRight",
+ "Mod+Alt+ArrowLeft",
+ "Mod+Alt+ArrowRight",
+ "Mod+Alt+ArrowUp",
+ "Mod+Alt+ArrowDown",
+]);
+
+/** Owned off macOS only: Chrome's task manager, and Firefox on Alt. */
+const NON_MAC_RESERVED_VALUES = new Set<string>([
+ "Shift+Escape",
+ "Mod+PageUp",
+ "Mod+PageDown",
+ "Alt+ArrowLeft",
+ "Alt+ArrowRight",
+ ...Array.from({ length: 9 }, (_, i) => `Alt+Digit${i + 1}`),
+]);
+
+export function isBrowserReservedBinding(
+ value: string | null,
+ mac = isMacPlatform(),
+): boolean {
+ if (value === null) return false;
+ if (BROWSER_RESERVED_VALUES.has(value)) return true;
+ return mac
+ ? MAC_RESERVED_VALUES.has(value)
+ : NON_MAC_RESERVED_VALUES.has(value);
+}
+
+/**
+ * Keys the browser turns into a click on whatever control has focus. A chord
+ * built from one of these with no modifier has to leave that click alone, or
+ * pressing Enter on a focused Deny button would run the shortcut instead and
+ * preventDefault would cancel the button's own activation.
+ */
+const ACTIVATION_CODES = new Set(["Enter", "NumpadEnter", "Space"]);
+
+const ACTIVATABLE_TAGS = new Set(["BUTTON", "A", "SUMMARY", "SELECT", "OPTION"]);
+
+/** True when this chord is a bare activation key and focus is on a control. */
+export function activationBelongsToFocus(
+ binding: ShortcutBinding,
+ el: { tagName?: string; getAttribute?: (name: string) => string | null } | null,
+): boolean {
+ if (binding.mod || binding.ctrl || binding.alt || binding.shift) return false;
+ if (!ACTIVATION_CODES.has(binding.code)) return false;
+ if (!el) return false;
+ if (ACTIVATABLE_TAGS.has(el.tagName ?? "")) return true;
+ const role = el.getAttribute?.("role") ?? null;
+ return role === "button" || role === "link" || role === "menuitem";
+}
+
/** Modifier codes are never a binding's key on their own. */
const MODIFIER_CODES = new Set([
"MetaLeft",
@@ -182,6 +491,7 @@ export function bindingFromEvent(
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
+ getModifierState?: (key: string) => boolean;
},
mac = isMacPlatform(),
): ShortcutBinding | null {
@@ -193,6 +503,8 @@ export function bindingFromEvent(
// while the one they pressed never matches. Record nothing instead, the same
// answer the recorder already gets while only modifiers are held.
if (!mac && event.metaKey) return null;
+ // matchesBinding will not fire an AltGr chord, so do not record one.
+ if (!mac && isAltGraphEvent(event)) return null;
// Cmd on macOS and Ctrl elsewhere both record as Mod, so one binding reads
// naturally on either platform. A macOS user pressing Ctrl means Ctrl.
return {
@@ -204,6 +516,17 @@ export function bindingFromEvent(
};
}
+/**
+ * AltGr rather than a real Ctrl+Alt. AltGr reports both, so typing ą or € would
+ * otherwise fire every Ctrl+Alt chord and eat the character. Callers gate this
+ * on being off macOS: Option reports AltGraph too, and it is a plain Alt.
+ */
+function isAltGraphEvent(event: {
+ getModifierState?: (key: string) => boolean;
+}): boolean {
+ return event.getModifierState?.("AltGraph") === true;
+}
+
/** Last-resort code for engines that report an empty `code` (some IMEs). */
function keyToCode(key: string): string {
if (!key) return "";
@@ -234,11 +557,16 @@ export function matchesBinding(
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
+ getModifierState?: (key: string) => boolean;
},
mac = isMacPlatform(),
): boolean {
const code = event.code || keyToCode(event.key ?? "");
if (code !== binding.code) return false;
+ // Off macOS a Ctrl chord is unreachable, and without this a value stored on
+ // a Mac would fall through the checks below and fire on the bare key.
+ if (!mac && binding.ctrl) return false;
+ if (!mac && binding.alt && isAltGraphEvent(event)) return false;
const modHeld = mac ? event.metaKey : event.ctrlKey;
// Off-platform modifier: on macOS a bare Ctrl must not satisfy a Mod binding,
// and on Windows/Linux the Meta (Windows) key must not either.
@@ -318,9 +646,23 @@ export function formatBindingValueLabel(
/**
* A binding with no modifier at all would swallow plain typing, so the
- * recorder refuses it. Function keys and Escape are self-contained.
+ * recorder refuses it. Function keys are self-contained, and an action gated on
+ * an on-screen prompt (`allowBareKey`) may take any key.
*/
-export function isAcceptableBinding(binding: ShortcutBinding): boolean {
+export function isAcceptableBinding(
+ binding: ShortcutBinding,
+ allowBareKey = false,
+): boolean {
if (binding.mod || binding.ctrl || binding.alt) return true;
- return /^F\d{1,2}$/.test(binding.code) || binding.code === "Escape";
+ // Tab moves focus, and a chord consumes the key it answers to. Bound bare,
+ // even on a prompt-gated action, it makes that prompt's own buttons
+ // unreachable by keyboard. Held with a modifier it is a chord like any
+ // other, which is where the recently-viewed walk sits.
+ if (binding.code === "Tab") return false;
+ if (allowBareKey) return true;
+ if (/^F\d{1,2}$/.test(binding.code)) return true;
+ // Escape is self-contained too, but bare it belongs to declining a tool call
+ // and is the way out of the recorder. Held with Shift it is free, which is
+ // where clearAllUnreads sits. Anything else has to say so with allowBareKey.
+ return binding.code === "Escape" && binding.shift;
}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 54dd503285b..661ac19156c 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -161,15 +161,60 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.voice.readAloud.previewLabel",
],
"keyboard-shortcuts": [
- // Both the section titles and each action label, so searching "sidebar" or
+ // The tab title and every action label, so searching "sidebar" or
// "new chat" from the settings search lands on the row itself.
"settings.keyboardShortcuts.title",
- "settings.keyboardShortcuts.groups.general",
- "settings.keyboardShortcuts.groups.chat",
"settings.keyboardShortcuts.actions.newChat.label",
- "settings.keyboardShortcuts.actions.searchChats.label",
+ "settings.keyboardShortcuts.actions.newTemporaryChat.label",
+ "settings.keyboardShortcuts.actions.archiveChat.label",
+ "settings.keyboardShortcuts.actions.newStandaloneChat.label",
+ "settings.keyboardShortcuts.actions.markChatUnread.label",
+ "settings.keyboardShortcuts.actions.togglePinChat.label",
+ "settings.keyboardShortcuts.actions.selectAllChats.label",
+ "settings.keyboardShortcuts.actions.clearChatSelection.label",
+ "settings.keyboardShortcuts.actions.deleteSelectedChats.label",
+ "settings.keyboardShortcuts.actions.nextRecentlyViewedChat.label",
+ "settings.keyboardShortcuts.actions.nextChat.label",
+ "settings.keyboardShortcuts.actions.nextChatNeedingAttention.label",
+ "settings.keyboardShortcuts.actions.previousRecentlyViewedChat.label",
+ "settings.keyboardShortcuts.actions.previousChat.label",
+ "settings.keyboardShortcuts.actions.goToRecentChat1.label",
+ "settings.keyboardShortcuts.actions.goToRecentChat2.label",
+ "settings.keyboardShortcuts.actions.goToRecentChat3.label",
+ "settings.keyboardShortcuts.actions.goToRecentChat4.label",
+ "settings.keyboardShortcuts.actions.goToRecentChat5.label",
+ "settings.keyboardShortcuts.actions.goToRecentChat6.label",
+ "settings.keyboardShortcuts.actions.switchToChat.label",
+ "settings.keyboardShortcuts.actions.switchToProjects.label",
+ "settings.keyboardShortcuts.actions.switchToHub.label",
+ "settings.keyboardShortcuts.actions.switchToTrain.label",
+ "settings.keyboardShortcuts.actions.switchToRecipes.label",
+ "settings.keyboardShortcuts.actions.switchToImages.label",
+ "settings.keyboardShortcuts.actions.switchToVideo.label",
+ "settings.keyboardShortcuts.actions.switchToAudio.label",
+ "settings.keyboardShortcuts.actions.switchToExport.label",
+ "settings.keyboardShortcuts.actions.toggleApiMonitor.label",
"settings.keyboardShortcuts.actions.toggleSidebar.label",
+ "settings.keyboardShortcuts.actions.openMcpServers.label",
+ "settings.keyboardShortcuts.actions.clearAllUnreads.label",
+ "settings.keyboardShortcuts.actions.logOut.label",
"settings.keyboardShortcuts.actions.openSettings.label",
+ "settings.keyboardShortcuts.actions.approveToolRequest.label",
+ "settings.keyboardShortcuts.actions.declineToolRequest.label",
+ "settings.keyboardShortcuts.actions.attachFiles.label",
+ "settings.keyboardShortcuts.actions.cycleReasoningEffort.label",
+ "settings.keyboardShortcuts.actions.decreaseReasoningEffort.label",
+ "settings.keyboardShortcuts.actions.increaseReasoningEffort.label",
+ "settings.keyboardShortcuts.actions.openModelPicker.label",
+ "settings.keyboardShortcuts.actions.openProjectPicker.label",
+ "settings.keyboardShortcuts.actions.startDictation.label",
+ "settings.keyboardShortcuts.actions.sendMessage.label",
+ "settings.keyboardShortcuts.actions.toggleFastMode.label",
+ "settings.keyboardShortcuts.actions.copyChatAsMarkdown.label",
+ "settings.keyboardShortcuts.actions.copySessionId.label",
+ "settings.keyboardShortcuts.actions.forkChat.label",
+ "settings.keyboardShortcuts.actions.searchChats.label",
+ "settings.keyboardShortcuts.actions.renameChat.label",
"settings.keyboardShortcuts.actions.openKeyboardShortcuts.label",
],
debugging: [
diff --git a/studio/frontend/src/features/settings/stores/keyboard-shortcuts-store.ts b/studio/frontend/src/features/settings/stores/keyboard-shortcuts-store.ts
index 291a06e9bcd..85196e5d2c5 100644
--- a/studio/frontend/src/features/settings/stores/keyboard-shortcuts-store.ts
+++ b/studio/frontend/src/features/settings/stores/keyboard-shortcuts-store.ts
@@ -5,7 +5,10 @@ import { create } from "zustand";
import {
SHORTCUT_DEFS,
SHORTCUT_DEF_BY_ID,
+ SHORTCUT_SLOTS,
type ShortcutId,
+ type ShortcutSlot,
+ defaultBindingFor,
isShortcutId,
// Explicit extension: this module is imported directly by the node test
// runner, which does not do bundler-style resolution.
@@ -18,28 +21,61 @@ import {
export const KEYBOARD_SHORTCUTS_STORAGE_KEY = "unsloth_keyboard_shortcuts";
const STORAGE_KEY = KEYBOARD_SHORTCUTS_STORAGE_KEY;
+/** Per-slot delta. An absent slot means "use the shipped default". */
+export type ShortcutOverrideEntry = Partial<
+ Record<ShortcutSlot, string | null>
+>;
+
/**
* Deltas only, so a changed default still reaches rows the user never touched.
* `null` means "unassigned"; an absent key means "use the default".
*/
-export type ShortcutOverrides = Partial<Record<ShortcutId, string | null>>;
+export type ShortcutOverrides = Partial<
+ Record<ShortcutId, ShortcutOverrideEntry>
+>;
+
+/** Builds before alternates stored `id -> string | null`. Read that as the
+ * primary slot, or every existing customization reverts to defaults. */
+function normalizeEntry(value: unknown): ShortcutOverrideEntry | null {
+ // A null back then cleared the action, which had one chord, so it has to
+ // clear both now. Left to the primary alone it would pick up whatever
+ // alternate has shipped since and start answering again, which is the
+ // opposite of what the user asked for.
+ if (value === null) return { primary: null, alternate: null };
+ // A rebind is different: the user chose a primary and never saw an
+ // alternate, so that slot is untouched and takes the shipped default, the
+ // same as it does for someone who never opened the tab.
+ if (typeof value === "string") return { primary: value };
+ if (!value || typeof value !== "object") return null;
+ const entry: ShortcutOverrideEntry = {};
+ for (const slot of SHORTCUT_SLOTS) {
+ const slotValue = (value as Record<string, unknown>)[slot];
+ if (slotValue === null || typeof slotValue === "string") {
+ entry[slot] = slotValue;
+ }
+ }
+ return Object.keys(entry).length > 0 ? entry : null;
+}
+
+/** Parsed JSON to overrides, tolerating both the current and the older shape. */
+export function migrateStoredOverrides(parsed: unknown): ShortcutOverrides {
+ if (!parsed || typeof parsed !== "object") return {};
+ const out: ShortcutOverrides = {};
+ for (const [id, value] of Object.entries(parsed as Record<string, unknown>)) {
+ // Drop ids from an older build so a removed action cannot resurrect.
+ if (!isShortcutId(id)) continue;
+ const entry = normalizeEntry(value);
+ if (entry) out[id] = entry;
+ }
+ return out;
+}
function loadOverrides(): ShortcutOverrides {
if (typeof window === "undefined") return {};
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return {};
- const parsed = JSON.parse(raw) as unknown;
- if (!parsed || typeof parsed !== "object") return {};
- const out: ShortcutOverrides = {};
- for (const [id, value] of Object.entries(
- parsed as Record<string, unknown>,
- )) {
- // Drop ids from an older build so a removed action cannot resurrect.
- if (!isShortcutId(id)) continue;
- if (value === null || typeof value === "string") out[id] = value;
- }
- return out;
+ return migrateStoredOverrides(JSON.parse(raw) as unknown);
} catch {
return {};
}
@@ -58,56 +94,100 @@ function persist(overrides: ShortcutOverrides): void {
}
}
-/** The binding actually in force for `id`, given a set of overrides. */
+/** Write one slot, dropping the whole entry once nothing is overridden. */
+function withSlot(
+ overrides: ShortcutOverrides,
+ id: ShortcutId,
+ slot: ShortcutSlot,
+ value: string | null | undefined,
+): ShortcutOverrides {
+ const entry: ShortcutOverrideEntry = { ...overrides[id] };
+ if (value === undefined) delete entry[slot];
+ else entry[slot] = value;
+ const next = { ...overrides };
+ if (Object.keys(entry).length === 0) delete next[id];
+ else next[id] = entry;
+ return next;
+}
+
+/** The binding actually in force for one slot of `id`. */
export function resolveBinding(
overrides: ShortcutOverrides,
id: ShortcutId,
+ slot: ShortcutSlot = "primary",
): string | null {
- return Object.hasOwn(overrides, id)
- ? (overrides[id] ?? null)
- : SHORTCUT_DEF_BY_ID[id].defaultBinding;
+ const entry = overrides[id];
+ if (entry && Object.hasOwn(entry, slot)) return entry[slot] ?? null;
+ return defaultBindingFor(SHORTCUT_DEF_BY_ID[id], slot);
+}
+
+/** Both chords in force for `id`, in slot order. */
+export function resolveBindings(
+ overrides: ShortcutOverrides,
+ id: ShortcutId,
+): Record<ShortcutSlot, string | null> {
+ return {
+ primary: resolveBinding(overrides, id, "primary"),
+ alternate: resolveBinding(overrides, id, "alternate"),
+ };
+}
+
+/** True when this slot carries a user edit rather than the shipped default. */
+export function isSlotOverridden(
+ overrides: ShortcutOverrides,
+ id: ShortcutId,
+ slot: ShortcutSlot,
+): boolean {
+ const entry = overrides[id];
+ return Boolean(entry && Object.hasOwn(entry, slot));
}
export function resolveAllBindings(
overrides: ShortcutOverrides,
-): Record<ShortcutId, string | null> {
+): Record<ShortcutId, Record<ShortcutSlot, string | null>> {
return Object.fromEntries(
- SHORTCUT_DEFS.map((def) => [def.id, resolveBinding(overrides, def.id)]),
- ) as Record<ShortcutId, string | null>;
+ SHORTCUT_DEFS.map((d) => [d.id, resolveBindings(overrides, d.id)]),
+ ) as Record<ShortcutId, Record<ShortcutSlot, string | null>>;
}
/**
* Which action a chord runs when more than one claims it. The first window
* listener consumes the event, so without a rule the winner would be whichever
- * component mounted first, and that varies by route. Registry order decides.
+ * component mounted first, and that varies by route. Registry order decides,
+ * and an action's own two slots count as one claim.
*/
export function shortcutOwningBinding(
overrides: ShortcutOverrides,
value: string | null,
): ShortcutId | null {
if (!value) return null;
- for (const def of SHORTCUT_DEFS) {
- if (resolveBinding(overrides, def.id) === value) return def.id;
+ for (const d of SHORTCUT_DEFS) {
+ for (const slot of SHORTCUT_SLOTS) {
+ if (resolveBinding(overrides, d.id, slot) === value) return d.id;
+ }
}
return null;
}
/**
- * Ids sharing a binding with at least one other action. Only the owner above
- * runs, so the tab flags the clash rather than silently refusing the edit.
+ * Ids sharing a chord with at least one other action, counting either slot on
+ * either side. Only the owner above runs, so the tab flags the clash rather
+ * than silently refusing the edit.
*/
export function findConflicts(overrides: ShortcutOverrides): Set<ShortcutId> {
- const byValue = new Map<string, ShortcutId[]>();
- for (const def of SHORTCUT_DEFS) {
- const value = resolveBinding(overrides, def.id);
- if (!value) continue;
- const ids = byValue.get(value);
- if (ids) ids.push(def.id);
- else byValue.set(value, [def.id]);
+ const byValue = new Map<string, Set<ShortcutId>>();
+ for (const d of SHORTCUT_DEFS) {
+ for (const slot of SHORTCUT_SLOTS) {
+ const value = resolveBinding(overrides, d.id, slot);
+ if (!value) continue;
+ const ids = byValue.get(value);
+ if (ids) ids.add(d.id);
+ else byValue.set(value, new Set([d.id]));
+ }
}
const out = new Set<ShortcutId>();
for (const ids of byValue.values()) {
- if (ids.length > 1) for (const id of ids) out.add(id);
+ if (ids.size > 1) for (const id of ids) out.add(id);
}
return out;
}
@@ -115,30 +195,39 @@ export function findConflicts(overrides: ShortcutOverrides): Set<ShortcutId> {
interface KeyboardShortcutsState {
overrides: ShortcutOverrides;
/** Assign a serialized binding, e.g. "Mod+Shift+KeyO". */
- setBinding: (id: ShortcutId, value: string) => void;
- /** Leave the action with no binding at all. */
- clearBinding: (id: ShortcutId) => void;
+ setBinding: (id: ShortcutId, slot: ShortcutSlot, value: string) => void;
+ /** Leave the slot with no binding at all. */
+ clearBinding: (id: ShortcutId, slot: ShortcutSlot) => void;
/** Drop the override so the shipped default applies again. */
- resetBinding: (id: ShortcutId) => void;
+ resetBinding: (id: ShortcutId, slot: ShortcutSlot) => void;
+ /** Drop both of an action's slots. */
+ resetAction: (id: ShortcutId) => void;
resetAll: () => void;
}
export const useKeyboardShortcutsStore = create<KeyboardShortcutsState>(
(set) => ({
overrides: loadOverrides(),
- setBinding: (id, value) =>
+ setBinding: (id, slot, value) =>
set((state) => {
- const overrides = { ...state.overrides, [id]: value };
+ const overrides = withSlot(state.overrides, id, slot, value);
persist(overrides);
return { overrides };
}),
- clearBinding: (id) =>
+ clearBinding: (id, slot) =>
set((state) => {
- const overrides = { ...state.overrides, [id]: null };
+ const overrides = withSlot(state.overrides, id, slot, null);
persist(overrides);
return { overrides };
}),
- resetBinding: (id) =>
+ resetBinding: (id, slot) =>
+ set((state) => {
+ if (!isSlotOverridden(state.overrides, id, slot)) return state;
+ const overrides = withSlot(state.overrides, id, slot, undefined);
+ persist(overrides);
+ return { overrides };
+ }),
+ resetAction: (id) =>
set((state) => {
if (!Object.hasOwn(state.overrides, id)) return state;
const overrides = { ...state.overrides };
@@ -155,6 +244,9 @@ export const useKeyboardShortcutsStore = create<KeyboardShortcutsState>(
);
/** Binding in force right now, for non-React callers (keydown handlers). */
-export function currentBinding(id: ShortcutId): string | null {
- return resolveBinding(useKeyboardShortcutsStore.getState().overrides, id);
+export function currentBinding(
+ id: ShortcutId,
+ slot: ShortcutSlot = "primary",
+): string | null {
+ return resolveBinding(useKeyboardShortcutsStore.getState().overrides, id, slot);
}
diff --git a/studio/frontend/src/features/settings/tabs/keyboard-shortcuts-tab.tsx b/studio/frontend/src/features/settings/tabs/keyboard-shortcuts-tab.tsx
index 3f287453900..6d86b4c2426 100644
--- a/studio/frontend/src/features/settings/tabs/keyboard-shortcuts-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/keyboard-shortcuts-tab.tsx
@@ -9,6 +9,7 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useT } from "@/i18n";
+import { isTauri } from "@/lib/api-base";
import { cn } from "@/lib/utils";
import {
Alert01Icon,
@@ -18,46 +19,47 @@ import {
Search01Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useEffect, useMemo, useState } from "react";
-import { SettingsRow } from "../components/settings-row";
-import { SettingsSection } from "../components/settings-section";
+import { type ReactNode, useEffect, useMemo, useState } from "react";
import {
SHORTCUT_DEFS,
- SHORTCUT_GROUPS,
+ SHORTCUT_SLOTS,
type ShortcutDef,
- type ShortcutGroup,
type ShortcutId,
+ type ShortcutSlot,
bindingFromEvent,
+ defaultBindingFor,
formatBindingLabel,
formatBindingValue,
isAcceptableBinding,
+ isBrowserReservedBinding,
isMacPlatform,
parseBinding,
} from "../lib/keyboard-shortcuts";
import {
findConflicts,
+ isSlotOverridden,
resolveBinding,
shortcutOwningBinding,
useKeyboardShortcutsStore,
} from "../stores/keyboard-shortcuts-store";
-const GROUP_LABEL_KEYS = {
- general: "settings.keyboardShortcuts.groups.general",
- chat: "settings.keyboardShortcuts.groups.chat",
-} as const satisfies Record<ShortcutGroup, string>;
-
-/** The ⌘⇧O chip. Renders the placeholder text when nothing is bound. */
-function BindingChip({
+/** The ⇧⌘O key cap. Plain text when the slot carries no chord. */
+function Chord({
label,
tone,
+ note,
}: {
label: string;
tone: "assigned" | "unassigned" | "recording";
+ /** Why the browser may swallow this chord. Hover only, so the caps stay a
+ * clean column. */
+ note?: string;
}) {
- return (
+ const cap = (
<span
className={cn(
- "inline-flex min-w-16 items-center justify-center rounded-md px-2 py-1 text-xs font-medium tabular-nums",
+ // Width hugs the chord, so ⌘, and ⇧⌘O share a left edge.
+ "inline-flex h-7 items-center rounded-md px-2.5 text-xs font-medium tabular-nums",
tone === "assigned" && "bg-muted text-foreground",
tone === "unassigned" && "text-muted-foreground",
tone === "recording" &&
@@ -67,39 +69,55 @@ function BindingChip({
{label}
</span>
);
+ if (!note) return cap;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>{cap}</TooltipTrigger>
+ <TooltipContent className="max-w-[260px] leading-snug">
+ {note}
+ </TooltipContent>
+ </Tooltip>
+ );
}
-function IconButton({
+/** Borderless pencil / trash / undo. */
+function RowIconButton({
icon,
label,
onClick,
- disabled,
+ className,
}: {
icon: typeof PencilEdit02Icon;
label: string;
onClick: () => void;
- disabled?: boolean;
+ className?: string;
}) {
return (
<Tooltip>
<TooltipTrigger asChild={true}>
- <Button
+ <button
type="button"
- variant="ghost"
- size="icon"
- className="size-8 text-muted-foreground hover:text-foreground"
aria-label={label}
- disabled={disabled}
onClick={onClick}
+ className={cn(
+ "inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
+ className,
+ )}
>
<HugeiconsIcon icon={icon} strokeWidth={1.75} className="size-4" />
- </Button>
+ </button>
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
);
}
+/** Which row and which of its two chords the recorder is listening for. */
+interface RecordingTarget {
+ id: ShortcutId;
+ slot: ShortcutSlot;
+}
+
export function KeyboardShortcutsTab() {
const t = useT();
const overrides = useKeyboardShortcutsStore((s) => s.overrides);
@@ -109,7 +127,7 @@ export function KeyboardShortcutsTab() {
const resetAll = useKeyboardShortcutsStore((s) => s.resetAll);
const [query, setQuery] = useState("");
- const [recordingId, setRecordingId] = useState<ShortcutId | null>(null);
+ const [recording, setRecording] = useState<RecordingTarget | null>(null);
// Shown under the row being recorded when the pressed chord is rejected.
const [recordingError, setRecordingError] = useState<string | null>(null);
@@ -119,36 +137,57 @@ export function KeyboardShortcutsTab() {
// Capture phase, so the chord being recorded reaches this listener before the
// shortcut it is replacing fires and before Radix's Escape-to-close.
useEffect(() => {
- if (!recordingId) return;
+ if (!recording) return;
+ const def = SHORTCUT_DEFS.find((entry) => entry.id === recording.id);
const onKeyDown = (event: KeyboardEvent) => {
+ // Tab held bare is never an acceptable binding, so it is still what it
+ // was: the way out. Left swallowed with the rest, a row that records
+ // bare keys had no keyboard exit at all, since Escape is a chord there
+ // and Enter or Space on the focused pencil records instead of pressing
+ // it. Not prevented, so focus moves on as it would have.
+ if (
+ event.code === "Tab" &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.altKey
+ ) {
+ setRecording(null);
+ setRecordingError(null);
+ return;
+ }
event.preventDefault();
event.stopPropagation();
+ // Every keydown is swallowed above, so bare Escape is the only way out of
+ // recording. The exception is a row that takes bare keys: Escape is the
+ // chord it ships, so recording it has to be possible, and the pencil
+ // cancels there instead.
if (
event.code === "Escape" &&
!event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
- !event.shiftKey
+ !event.shiftKey &&
+ !def?.allowBareKey
) {
- setRecordingId(null);
+ setRecording(null);
setRecordingError(null);
return;
}
const binding = bindingFromEvent(event);
// Modifier held on its own: the user is still assembling the chord.
if (!binding) return;
- if (!isAcceptableBinding(binding)) {
+ if (!isAcceptableBinding(binding, def?.allowBareKey)) {
setRecordingError(t("settings.keyboardShortcuts.needsModifier"));
return;
}
- setBinding(recordingId, formatBindingValue(binding));
- setRecordingId(null);
+ setBinding(recording.id, recording.slot, formatBindingValue(binding));
+ setRecording(null);
setRecordingError(null);
};
window.addEventListener("keydown", onKeyDown, { capture: true });
return () =>
window.removeEventListener("keydown", onKeyDown, { capture: true });
- }, [recordingId, setBinding, t]);
+ }, [recording, setBinding, t]);
const matches = useMemo(() => {
const q = query.trim().toLowerCase();
@@ -157,53 +196,127 @@ export function KeyboardShortcutsTab() {
SHORTCUT_DEFS.filter((def) => {
const haystack = `${t(def.labelKey)} ${t(def.descriptionKey)}`;
if (haystack.toLowerCase().includes(q)) return true;
- const value = resolveBinding(overrides, def.id);
- const parsed = parseBinding(value);
- return parsed
- ? formatBindingLabel(parsed, mac).toLowerCase().includes(q)
- : false;
+ return SHORTCUT_SLOTS.some((slot) => {
+ const parsed = parseBinding(resolveBinding(overrides, def.id, slot));
+ return parsed
+ ? formatBindingLabel(parsed, mac).toLowerCase().includes(q)
+ : false;
+ });
}).map((def) => def.id),
);
}, [query, t, overrides, mac]);
- const groups = SHORTCUT_GROUPS.map((group) => ({
- group,
- defs: SHORTCUT_DEFS.filter(
- (def) => def.group === group && (!matches || matches.has(def.id)),
- ),
- })).filter((entry) => entry.defs.length > 0);
+ // One list, in registry order, so the daily rows sit above the fold.
+ const visible = SHORTCUT_DEFS.filter(
+ // A web-only row on the desktop build would bind a chord whose handler
+ // returns, so it is left out rather than shown as a key that does nothing.
+ (def) => (!matches || matches.has(def.id)) && !(isTauri && def.webOnly),
+ );
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Chip, hint, badge and buttons all read one resolved binding; splitting only passes it around.
- const renderRow = (def: ShortcutDef) => {
- const value = resolveBinding(overrides, def.id);
+ const startRecording = (def: ShortcutDef, slot: ShortcutSlot) => {
+ setRecordingError(null);
+ setRecording(
+ recording?.id === def.id && recording.slot === slot
+ ? null
+ : { id: def.id, slot },
+ );
+ };
+
+ /** One chord line: cap and pencil left, trash right. A row with an
+ * alternate stacks two. */
+ const renderSlot = (def: ShortcutDef, slot: ShortcutSlot): ReactNode => {
+ const value = resolveBinding(overrides, def.id, slot);
const parsed = parseBinding(value);
- const recording = recordingId === def.id;
- const conflicted = conflicts.has(def.id) && !recording;
+ const isRecording = recording?.id === def.id && recording.slot === slot;
+ const slotName = t(
+ slot === "primary"
+ ? "settings.keyboardShortcuts.primarySlot"
+ : "settings.keyboardShortcuts.alternateSlot",
+ );
+ // The warning rides the cap's tooltip, not a third line of description.
+ const reserved =
+ !isTauri && !isRecording && isBrowserReservedBinding(value);
+
+ return (
+ <div key={slot} className="flex items-center justify-between gap-3">
+ <div className="flex items-center gap-1">
+ <Chord
+ label={
+ isRecording
+ ? t("settings.keyboardShortcuts.recording")
+ : parsed
+ ? formatBindingLabel(parsed, mac)
+ : t("settings.keyboardShortcuts.unassigned")
+ }
+ tone={
+ isRecording ? "recording" : parsed ? "assigned" : "unassigned"
+ }
+ note={
+ reserved
+ ? t("settings.keyboardShortcuts.browserReserved")
+ : undefined
+ }
+ />
+ <RowIconButton
+ icon={PencilEdit02Icon}
+ label={`${t("settings.keyboardShortcuts.edit")} (${slotName})`}
+ onClick={() => startRecording(def, slot)}
+ />
+ {isSlotOverridden(overrides, def.id, slot) ? (
+ <RowIconButton
+ icon={ArrowTurnBackwardIcon}
+ label={`${t("settings.keyboardShortcuts.reset")} (${slotName})`}
+ onClick={() => resetBinding(def.id, slot)}
+ />
+ ) : null}
+ </div>
+ {parsed && !isRecording ? (
+ <RowIconButton
+ icon={Delete02Icon}
+ label={`${t("settings.keyboardShortcuts.clear")} (${slotName})`}
+ onClick={() => clearBinding(def.id, slot)}
+ />
+ ) : null}
+ </div>
+ );
+ };
+
+ const renderRow = (def: ShortcutDef) => {
+ const isRecording = recording?.id === def.id;
+ const conflicted = conflicts.has(def.id) && !isRecording;
// Say which side of a clash this row is on, since only the owner runs.
const shadowed =
- conflicted && shortcutOwningBinding(overrides, value) !== def.id;
- const label = recording
- ? t("settings.keyboardShortcuts.recording")
- : parsed
- ? formatBindingLabel(parsed, mac)
- : t("settings.keyboardShortcuts.unassigned");
- const overridden = Object.hasOwn(overrides, def.id);
+ conflicted &&
+ SHORTCUT_SLOTS.every((slot) => {
+ const value = resolveBinding(overrides, def.id, slot);
+ return !value || shortcutOwningBinding(overrides, value) !== def.id;
+ });
+ // Anything this action ships an alternate for keeps its line, cleared or
+ // not: hiding a cleared slot would take its restore control with it, and
+ // Reset all is not a way back from one edit.
+ const hasAlternate =
+ defaultBindingFor(def, "alternate", mac) !== null ||
+ resolveBinding(overrides, def.id, "alternate") !== null ||
+ (recording?.id === def.id && recording.slot === "alternate");
return (
- <SettingsRow
+ <div
key={def.id}
- label={t(def.labelKey)}
- description={
- <span className="flex flex-col gap-0.5">
- <span>{t(def.descriptionKey)}</span>
- {recording ? (
- <span className="text-xs text-primary">
+ data-settings-label={t(def.labelKey)}
+ className="group/row flex items-center gap-6 py-3.5"
+ >
+ <div className="flex min-w-0 flex-1 basis-0 flex-col gap-0.5">
+ <span className="text-sm font-medium text-foreground">
+ {t(def.labelKey)}
+ </span>
+ <span className="text-xs leading-snug text-muted-foreground">
+ {isRecording ? (
+ <span className="text-primary">
{recordingError ??
t("settings.keyboardShortcuts.recordingHint")}
</span>
- ) : null}
- {conflicted ? (
- <span className="flex items-center gap-1 text-xs text-amber-500">
+ ) : conflicted ? (
+ <span className="flex items-center gap-1 text-amber-500">
<HugeiconsIcon
icon={Alert01Icon}
strokeWidth={1.75}
@@ -213,83 +326,73 @@ export function KeyboardShortcutsTab() {
? t("settings.keyboardShortcuts.conflictShadowed")
: t("settings.keyboardShortcuts.conflict")}
</span>
- ) : null}
+ ) : (
+ t(def.descriptionKey)
+ )}
</span>
- }
- >
- <div className="flex items-center gap-1">
- <BindingChip
- label={label}
- tone={recording ? "recording" : parsed ? "assigned" : "unassigned"}
- />
- <IconButton
- icon={PencilEdit02Icon}
- label={t("settings.keyboardShortcuts.edit")}
- onClick={() => {
- setRecordingError(null);
- setRecordingId(recording ? null : def.id);
- }}
- />
- {overridden ? (
- <IconButton
- icon={ArrowTurnBackwardIcon}
- label={t("settings.keyboardShortcuts.reset")}
- onClick={() => resetBinding(def.id)}
- />
- ) : null}
- <IconButton
- icon={Delete02Icon}
- label={t("settings.keyboardShortcuts.clear")}
- disabled={!parsed}
- onClick={() => clearBinding(def.id)}
- />
</div>
- </SettingsRow>
+ {/* pl-10 nudges the caps off the descriptions: the labels run long
+ enough that a bare half-and-half split left them crowding. */}
+ <div className="flex flex-1 basis-0 flex-col gap-1.5 pl-10">
+ {renderSlot(def, "primary")}
+ {/* Only the actions that ship an alternate have a second line: there
+ is no affordance for adding one. */}
+ {hasAlternate ? renderSlot(def, "alternate") : null}
+ </div>
+ </div>
);
};
return (
- <div className="flex flex-col gap-6">
- <SettingsSection
- title={t("settings.keyboardShortcuts.title")}
- description={t("settings.keyboardShortcuts.description")}
- >
- <div className="relative py-3">
- <HugeiconsIcon
- icon={Search01Icon}
- strokeWidth={2}
- className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
- />
- <Input
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder={t("settings.keyboardShortcuts.searchPlaceholder")}
- className="pl-9"
- aria-label={t("settings.keyboardShortcuts.searchPlaceholder")}
- />
- </div>
- </SettingsSection>
+ <div className="flex flex-col gap-5">
+ <div className="flex flex-col gap-1">
+ <h2
+ data-settings-label={t("settings.keyboardShortcuts.title")}
+ className="font-heading text-base font-semibold text-foreground"
+ >
+ {t("settings.keyboardShortcuts.title")}
+ </h2>
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ {t("settings.keyboardShortcuts.description")}
+ </p>
+ </div>
+
+ <div className="relative">
+ <HugeiconsIcon
+ icon={Search01Icon}
+ strokeWidth={2}
+ className="pointer-events-none absolute left-4 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
+ />
+ <Input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t("settings.keyboardShortcuts.searchPlaceholder")}
+ className="h-11 rounded-full pl-11"
+ aria-label={t("settings.keyboardShortcuts.searchPlaceholder")}
+ />
+ </div>
- {groups.length === 0 ? (
+ {visible.length === 0 ? (
<p className="text-sm text-muted-foreground">
{t("settings.keyboardShortcuts.noResults")}
</p>
) : (
- groups.map(({ group, defs }) => (
- <SettingsSection key={group} title={t(GROUP_LABEL_KEYS[group])}>
- {defs.map(renderRow)}
- </SettingsSection>
- ))
+ // Rows carry the padding, so the dividers sit inset from the edge.
+ <div className="rounded-xl border border-border/70 px-5">
+ <div className="divide-y divide-border/60">
+ {visible.map(renderRow)}
+ </div>
+ </div>
)}
- <div className="flex justify-start border-t border-border/60 pt-4">
+ <div className="flex justify-start pt-1">
<Button
type="button"
variant="outline"
size="sm"
disabled={Object.keys(overrides).length === 0}
onClick={() => {
- setRecordingId(null);
+ setRecording(null);
setRecordingError(null);
resetAll();
}}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index c0d5352c235..6298f4c021a 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -217,30 +217,218 @@ export const ar = {
clear: "إزالة الاختصار",
reset: "استعادة الافتراضي",
resetAll: "إعادة تعيين الكل إلى الافتراضي",
- groups: {
- general: "عام",
- chat: "المحادثة",
- },
+ primarySlot: "الاختصار",
+ alternateSlot: "اختصار بديل",
+ browserReserved:
+ "قد يحتفظ متصفحك بهذه التركيبة لنفسه. تعمل في تطبيق سطح المكتب.",
actions: {
- newChat: {
- label: "محادثة جديدة",
- description: "بدء محادثة جديدة",
+ openSettings: {
+ label: "فتح الإعدادات",
+ description: "فتح مربع حوار الإعدادات",
+ },
+ openKeyboardShortcuts: {
+ label: "اختصارات لوحة المفاتيح",
+ description: "فتح قائمة الاختصارات هذه",
},
searchChats: {
label: "بحث في المحادثات",
description: "فتح مربع حوار بحث المحادثات",
},
+ openMcpServers: {
+ label: "خوادم MCP",
+ description: "إعداد خوادم MCP لهذه المحادثة",
+ },
+ logOut: {
+ label: "تسجيل الخروج",
+ description: "تسجيل الخروج من Unsloth",
+ },
+ approveToolRequest: {
+ label: "الموافقة على الطلب",
+ description: "السماح باستدعاء الأداة قيد الانتظار",
+ },
+ declineToolRequest: {
+ label: "رفض الطلب",
+ description: "رفض استدعاء الأداة قيد الانتظار",
+ },
+ newChat: {
+ label: "محادثة جديدة",
+ description: "بدء محادثة جديدة",
+ },
+ newTemporaryChat: {
+ label: "محادثة مؤقتة جديدة",
+ description: "بدء محادثة لا تُحفظ في السجل",
+ },
+ newStandaloneChat: {
+ label: "محادثة مستقلة جديدة",
+ description: "بدء محادثة خارج أي مشروع",
+ },
+ archiveChat: {
+ label: "أرشفة المحادثة",
+ description: "أرشفة المحادثات المحددة، أو المحادثة الحالية",
+ },
+ markChatUnread: {
+ label: "وضع علامة كغير مقروءة",
+ description: "وضع علامة غير مقروءة على المحادثات المحددة، أو المحادثة الحالية",
+ },
+ togglePinChat: {
+ label: "تبديل التثبيت",
+ description: "تثبيت المحادثات المحددة أو إلغاء تثبيتها، أو المحادثة الحالية",
+ },
+ selectAllChats: {
+ label: "تحديد كل المحادثات",
+ description: "تحديد كل محادثة في الشريط الجانبي",
+ },
+ clearChatSelection: {
+ label: "مسح التحديد",
+ description: "إلغاء تحديد المحادثات المحددة. زر Escape يمسحه أيضًا",
+ },
+ deleteSelectedChats: {
+ label: "حذف المحادثات المحددة",
+ description: "حذف كل محادثة محددة",
+ },
+ nextRecentlyViewedChat: {
+ label: "المحادثة التالية التي عُرضت مؤخرًا",
+ description: "التقدم بين المحادثات المعروضة مؤخرًا",
+ },
+ previousRecentlyViewedChat: {
+ label: "المحادثة السابقة التي عُرضت مؤخرًا",
+ description: "الرجوع بين المحادثات المعروضة مؤخرًا",
+ },
+ nextChat: {
+ label: "المحادثة التالية",
+ description: "الانتقال إلى المحادثة التالية في الشريط الجانبي",
+ },
+ previousChat: {
+ label: "المحادثة السابقة",
+ description: "الانتقال إلى المحادثة السابقة في الشريط الجانبي",
+ },
+ nextChatNeedingAttention: {
+ label: "المحادثة التالية التي تحتاج انتباهًا",
+ description: "الانتقال إلى المحادثة التالية قيد التوليد أو الانتظار أو غير المقروءة",
+ },
+ clearAllUnreads: {
+ label: "وضع علامة مقروء على الكل",
+ description: "وضع علامة مقروءة على كل المحادثات",
+ },
+ goToRecentChat1: {
+ label: "الانتقال إلى المحادثة الأخيرة 1",
+ description: "فتح المحادثة 1 ضمن «الأخيرة»",
+ },
+ goToRecentChat2: {
+ label: "الانتقال إلى المحادثة الأخيرة 2",
+ description: "فتح المحادثة 2 ضمن «الأخيرة»",
+ },
+ goToRecentChat3: {
+ label: "الانتقال إلى المحادثة الأخيرة 3",
+ description: "فتح المحادثة 3 ضمن «الأخيرة»",
+ },
+ goToRecentChat4: {
+ label: "الانتقال إلى المحادثة الأخيرة 4",
+ description: "فتح المحادثة 4 ضمن «الأخيرة»",
+ },
+ goToRecentChat5: {
+ label: "الانتقال إلى المحادثة الأخيرة 5",
+ description: "فتح المحادثة 5 ضمن «الأخيرة»",
+ },
+ goToRecentChat6: {
+ label: "الانتقال إلى المحادثة الأخيرة 6",
+ description: "فتح المحادثة 6 ضمن «الأخيرة»",
+ },
+ switchToChat: {
+ label: "التبديل إلى المحادثة",
+ description: "الانتقال إلى مساحة عمل المحادثة",
+ },
+ switchToProjects: {
+ label: "التبديل إلى المشاريع",
+ description: "الانتقال إلى مساحة عمل المشاريع",
+ },
+ switchToHub: {
+ label: "التبديل إلى مركز النماذج",
+ description: "الانتقال إلى مركز النماذج",
+ },
+ switchToTrain: {
+ label: "التبديل إلى التدريب",
+ description: "الانتقال إلى مساحة عمل التدريب",
+ },
+ switchToRecipes: {
+ label: "التبديل إلى Recipes",
+ description: "الانتقال إلى Data Recipes",
+ },
+ switchToImages: {
+ label: "التبديل إلى الصور",
+ description: "الانتقال إلى مساحة عمل الصور",
+ },
+ switchToVideo: {
+ label: "التبديل إلى الفيديو",
+ description: "الانتقال إلى مساحة عمل الفيديو",
+ },
+ switchToAudio: {
+ label: "التبديل إلى الصوت",
+ description: "الانتقال إلى مساحة عمل الصوت",
+ },
+ switchToExport: {
+ label: "التبديل إلى التصدير",
+ description: "الانتقال إلى مساحة عمل التصدير",
+ },
toggleSidebar: {
label: "تبديل الشريط الجانبي",
description: "إظهار الشريط الجانبي أو إخفاؤه",
},
- openSettings: {
- label: "فتح الإعدادات",
- description: "فتح مربع حوار الإعدادات",
+ toggleApiMonitor: {
+ label: "تبديل نشاط API",
+ description: "إظهار مراقب نشاط API أو إخفاؤه",
},
- openKeyboardShortcuts: {
- label: "اختصارات لوحة المفاتيح",
- description: "فتح قائمة الاختصارات هذه",
+ openModelPicker: {
+ label: "فتح منتقي النموذج",
+ description: "اختيار النموذج لهذه المحادثة",
+ },
+ openProjectPicker: {
+ label: "فتح منتقي المشروع",
+ description: "الانتقال إلى مشروع آخر من ترويسة المحادثة",
+ },
+ startDictation: {
+ label: "الإملاء",
+ description: "بدء الإملاء في مربع الكتابة أو إيقافه",
+ },
+ attachFiles: {
+ label: "إرفاق صور وملفات",
+ description: "إضافة مرفق إلى مربع الكتابة",
+ },
+ sendMessage: {
+ label: "إرسال الرسالة",
+ description: "إرسال ما في مربع الكتابة",
+ },
+ cycleReasoningEffort: {
+ label: "تدوير مستوى التفكير",
+ description: "التنقل بين مستويات جهد التفكير",
+ },
+ increaseReasoningEffort: {
+ label: "زيادة جهد التفكير",
+ description: "رفع جهد التفكير مستوى واحدًا",
+ },
+ decreaseReasoningEffort: {
+ label: "خفض جهد التفكير",
+ description: "خفض جهد التفكير مستوى واحدًا",
+ },
+ toggleFastMode: {
+ label: "تبديل وضع Fast",
+ description: "تشغيل وضع Fast أو إيقافه",
+ },
+ renameChat: {
+ label: "إعادة تسمية المحادثة",
+ description: "إعادة تسمية المحادثة الحالية",
+ },
+ forkChat: {
+ label: "تفريع المحادثة",
+ description: "إنشاء محادثة جديدة من آخر رسالة",
+ },
+ copyChatAsMarkdown: {
+ label: "نسخ بصيغة Markdown",
+ description: "نسخ المحادثة كاملة إلى الحافظة بصيغة Markdown",
+ },
+ copySessionId: {
+ label: "نسخ معرّف الجلسة",
+ description: "نسخ معرّف جلسة البيئة المعزولة لهذه المحادثة",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 7db19c11799..38296deb414 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -221,30 +221,218 @@ export const de = {
clear: "Kürzel entfernen",
reset: "Standard wiederherstellen",
resetAll: "Alle auf Standard zurücksetzen",
- groups: {
- general: "Allgemein",
- chat: "Chat",
- },
+ primarySlot: "Kürzel",
+ alternateSlot: "Alternatives Kürzel",
+ browserReserved:
+ "Dein Browser behält diese Tastenkombination unter Umständen für sich. In der Desktop-App funktioniert sie.",
actions: {
- newChat: {
- label: "Neuer Chat",
- description: "Einen neuen Chat starten",
+ openSettings: {
+ label: "Einstellungen öffnen",
+ description: "Den Einstellungsdialog öffnen",
+ },
+ openKeyboardShortcuts: {
+ label: "Tastenkürzel",
+ description: "Diese Kürzelliste öffnen",
},
searchChats: {
label: "Chats durchsuchen",
description: "Die Chat-Suche öffnen",
},
+ openMcpServers: {
+ label: "MCP-Server",
+ description: "MCP-Server für diesen Chat einrichten",
+ },
+ logOut: {
+ label: "Abmelden",
+ description: "Von Unsloth abmelden",
+ },
+ approveToolRequest: {
+ label: "Anfrage genehmigen",
+ description: "Den wartenden Tool-Aufruf zulassen",
+ },
+ declineToolRequest: {
+ label: "Anfrage ablehnen",
+ description: "Den wartenden Tool-Aufruf ablehnen",
+ },
+ newChat: {
+ label: "Neuer Chat",
+ description: "Einen neuen Chat starten",
+ },
+ newTemporaryChat: {
+ label: "Neuer temporärer Chat",
+ description: "Einen Chat starten, der nicht im Verlauf gespeichert wird",
+ },
+ newStandaloneChat: {
+ label: "Neuer eigenständiger Chat",
+ description: "Einen neuen Chat außerhalb jedes Projekts starten",
+ },
+ archiveChat: {
+ label: "Chat archivieren",
+ description: "Die ausgewählten Chats archivieren, sonst den aktuellen",
+ },
+ markChatUnread: {
+ label: "Als ungelesen markieren",
+ description: "Die ausgewählten Chats als ungelesen markieren, sonst den aktuellen",
+ },
+ togglePinChat: {
+ label: "Anheften umschalten",
+ description: "Die ausgewählten Chats anheften oder lösen, sonst den aktuellen",
+ },
+ selectAllChats: {
+ label: "Alle Chats auswählen",
+ description: "Jeden Chat in der Seitenleiste auswählen",
+ },
+ clearChatSelection: {
+ label: "Auswahl aufheben",
+ description: "Die ausgewählten Chats abwählen. Escape hebt sie ebenfalls auf",
+ },
+ deleteSelectedChats: {
+ label: "Ausgewählte Chats löschen",
+ description: "Jeden ausgewählten Chat löschen",
+ },
+ nextRecentlyViewedChat: {
+ label: "Nächster zuletzt geöffneter Chat",
+ description: "Vorwärts durch zuletzt geöffnete Chats blättern",
+ },
+ previousRecentlyViewedChat: {
+ label: "Vorheriger zuletzt geöffneter Chat",
+ description: "Rückwärts durch zuletzt geöffnete Chats blättern",
+ },
+ nextChat: {
+ label: "Nächster Chat",
+ description: "Zum nächsten Chat in der Seitenleiste wechseln",
+ },
+ previousChat: {
+ label: "Vorheriger Chat",
+ description: "Zum vorherigen Chat in der Seitenleiste wechseln",
+ },
+ nextChatNeedingAttention: {
+ label: "Nächster Chat mit Aktivität",
+ description: "Zum nächsten generierenden, wartenden oder ungelesenen Chat wechseln",
+ },
+ clearAllUnreads: {
+ label: "Alle als gelesen markieren",
+ description: "Jeden Chat als gelesen markieren",
+ },
+ goToRecentChat1: {
+ label: "Zu letztem Chat 1 wechseln",
+ description: "Chat 1 unter „Zuletzt“ öffnen",
+ },
+ goToRecentChat2: {
+ label: "Zu letztem Chat 2 wechseln",
+ description: "Chat 2 unter „Zuletzt“ öffnen",
+ },
+ goToRecentChat3: {
+ label: "Zu letztem Chat 3 wechseln",
+ description: "Chat 3 unter „Zuletzt“ öffnen",
+ },
+ goToRecentChat4: {
+ label: "Zu letztem Chat 4 wechseln",
+ description: "Chat 4 unter „Zuletzt“ öffnen",
+ },
+ goToRecentChat5: {
+ label: "Zu letztem Chat 5 wechseln",
+ description: "Chat 5 unter „Zuletzt“ öffnen",
+ },
+ goToRecentChat6: {
+ label: "Zu letztem Chat 6 wechseln",
+ description: "Chat 6 unter „Zuletzt“ öffnen",
+ },
+ switchToChat: {
+ label: "Zu Chat wechseln",
+ description: "Zum Chat-Arbeitsbereich gehen",
+ },
+ switchToProjects: {
+ label: "Zu Projekte wechseln",
+ description: "Zum Projekte-Arbeitsbereich gehen",
+ },
+ switchToHub: {
+ label: "Zu Modell-Hub wechseln",
+ description: "Zum Modell-Hub gehen",
+ },
+ switchToTrain: {
+ label: "Zu Training wechseln",
+ description: "Zum Trainings-Arbeitsbereich gehen",
+ },
+ switchToRecipes: {
+ label: "Zu Recipes wechseln",
+ description: "Zu Data Recipes gehen",
+ },
+ switchToImages: {
+ label: "Zu Bilder wechseln",
+ description: "Zum Bilder-Arbeitsbereich gehen",
+ },
+ switchToVideo: {
+ label: "Zu Video wechseln",
+ description: "Zum Video-Arbeitsbereich gehen",
+ },
+ switchToAudio: {
+ label: "Zu Audio wechseln",
+ description: "Zum Audio-Arbeitsbereich gehen",
+ },
+ switchToExport: {
+ label: "Zu Export wechseln",
+ description: "Zum Export-Arbeitsbereich gehen",
+ },
toggleSidebar: {
label: "Seitenleiste umschalten",
description: "Seitenleiste ein- oder ausblenden",
},
- openSettings: {
- label: "Einstellungen öffnen",
- description: "Den Einstellungsdialog öffnen",
+ toggleApiMonitor: {
+ label: "API-Aktivität umschalten",
+ description: "Den API-Aktivitätsmonitor ein- oder ausblenden",
},
- openKeyboardShortcuts: {
- label: "Tastenkürzel",
- description: "Diese Kürzelliste öffnen",
+ openModelPicker: {
+ label: "Modellauswahl öffnen",
+ description: "Das Modell für diesen Chat wählen",
+ },
+ openProjectPicker: {
+ label: "Projektauswahl öffnen",
+ description: "Über die Chat-Kopfzeile zu einem anderen Projekt wechseln",
+ },
+ startDictation: {
+ label: "Diktat",
+ description: "Diktat im Eingabefeld starten oder stoppen",
+ },
+ attachFiles: {
+ label: "Fotos und Dateien anhängen",
+ description: "Einen Anhang zum Eingabefeld hinzufügen",
+ },
+ sendMessage: {
+ label: "Nachricht senden",
+ description: "Den Inhalt des Eingabefelds senden",
+ },
+ cycleReasoningEffort: {
+ label: "Denkaufwand durchschalten",
+ description: "Durch die Stufen des Denkaufwands blättern",
+ },
+ increaseReasoningEffort: {
+ label: "Denkaufwand erhöhen",
+ description: "Den Denkaufwand um eine Stufe anheben",
+ },
+ decreaseReasoningEffort: {
+ label: "Denkaufwand verringern",
+ description: "Den Denkaufwand um eine Stufe senken",
+ },
+ toggleFastMode: {
+ label: "Fast-Modus umschalten",
+ description: "Den Fast-Modus ein- oder ausschalten",
+ },
+ renameChat: {
+ label: "Chat umbenennen",
+ description: "Den aktuellen Chat umbenennen",
+ },
+ forkChat: {
+ label: "Chat verzweigen",
+ description: "Aus der letzten Nachricht einen neuen Chat abzweigen",
+ },
+ copyChatAsMarkdown: {
+ label: "Als Markdown kopieren",
+ description: "Den gesamten Chat als Markdown in die Zwischenablage kopieren",
+ },
+ copySessionId: {
+ label: "Sitzungs-ID kopieren",
+ description: "Die Sandbox-Sitzungs-ID dieses Chats kopieren",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 0f55767546e..540b8c25f64 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -217,30 +217,218 @@ export const en = {
clear: "Remove shortcut",
reset: "Restore default",
resetAll: "Reset all to defaults",
- groups: {
- general: "General",
- chat: "Chat",
- },
+ primarySlot: "Shortcut",
+ alternateSlot: "Alternate shortcut",
+ browserReserved:
+ "Your browser may keep this chord for itself. It works in the desktop app.",
actions: {
- newChat: {
- label: "New chat",
- description: "Start a new chat",
+ openSettings: {
+ label: "Open settings",
+ description: "Open the settings dialog",
+ },
+ openKeyboardShortcuts: {
+ label: "Keyboard shortcuts",
+ description: "Open this shortcuts list",
},
searchChats: {
label: "Search chats",
description: "Open the chat search dialog",
},
+ openMcpServers: {
+ label: "MCP servers",
+ description: "Configure MCP servers for this chat",
+ },
+ logOut: {
+ label: "Log out",
+ description: "Sign out of Unsloth",
+ },
+ approveToolRequest: {
+ label: "Approve request",
+ description: "Allow the tool call waiting for approval",
+ },
+ declineToolRequest: {
+ label: "Decline request",
+ description: "Deny the tool call waiting for approval",
+ },
+ newChat: {
+ label: "New chat",
+ description: "Start a new chat",
+ },
+ newTemporaryChat: {
+ label: "New temporary chat",
+ description: "Start a chat that is not saved to history",
+ },
+ newStandaloneChat: {
+ label: "New standalone chat",
+ description: "Start a new chat outside of any project",
+ },
+ archiveChat: {
+ label: "Archive chat",
+ description: "Archive the selected chats, or the current one",
+ },
+ markChatUnread: {
+ label: "Mark as unread",
+ description: "Mark the selected chats unread, or the current one",
+ },
+ togglePinChat: {
+ label: "Toggle pin",
+ description: "Pin or unpin the selected chats, or the current one",
+ },
+ selectAllChats: {
+ label: "Select all chats",
+ description: "Select every chat in the sidebar",
+ },
+ clearChatSelection: {
+ label: "Clear selection",
+ description: "Deselect the selected chats. Escape does too",
+ },
+ deleteSelectedChats: {
+ label: "Delete selected chats",
+ description: "Delete every selected chat",
+ },
+ nextRecentlyViewedChat: {
+ label: "Next recently viewed chat",
+ description: "Cycle forward through recently viewed chats",
+ },
+ previousRecentlyViewedChat: {
+ label: "Previous recently viewed chat",
+ description: "Cycle back through recently viewed chats",
+ },
+ nextChat: {
+ label: "Next chat",
+ description: "Switch to the next chat in the sidebar",
+ },
+ previousChat: {
+ label: "Previous chat",
+ description: "Switch to the previous chat in the sidebar",
+ },
+ nextChatNeedingAttention: {
+ label: "Next chat needing attention",
+ description: "Switch to the next generating, queued or unread chat",
+ },
+ clearAllUnreads: {
+ label: "Clear all unreads",
+ description: "Mark every chat as read",
+ },
+ goToRecentChat1: {
+ label: "Go to recent chat 1",
+ description: "Open the first chat under Recents",
+ },
+ goToRecentChat2: {
+ label: "Go to recent chat 2",
+ description: "Open the second chat under Recents",
+ },
+ goToRecentChat3: {
+ label: "Go to recent chat 3",
+ description: "Open the third chat under Recents",
+ },
+ goToRecentChat4: {
+ label: "Go to recent chat 4",
+ description: "Open the fourth chat under Recents",
+ },
+ goToRecentChat5: {
+ label: "Go to recent chat 5",
+ description: "Open the fifth chat under Recents",
+ },
+ goToRecentChat6: {
+ label: "Go to recent chat 6",
+ description: "Open the sixth chat under Recents",
+ },
+ switchToChat: {
+ label: "Switch to Chat",
+ description: "Go to the chat workspace",
+ },
+ switchToProjects: {
+ label: "Switch to Projects",
+ description: "Go to the projects workspace",
+ },
+ switchToHub: {
+ label: "Switch to Model hub",
+ description: "Go to the model hub",
+ },
+ switchToTrain: {
+ label: "Switch to Train",
+ description: "Go to the training workspace",
+ },
+ switchToRecipes: {
+ label: "Switch to Recipes",
+ description: "Go to Data Recipes",
+ },
+ switchToImages: {
+ label: "Switch to Images",
+ description: "Go to the images workspace",
+ },
+ switchToVideo: {
+ label: "Switch to Video",
+ description: "Go to the video workspace",
+ },
+ switchToAudio: {
+ label: "Switch to Audio",
+ description: "Go to the audio workspace",
+ },
+ switchToExport: {
+ label: "Switch to Export",
+ description: "Go to the export workspace",
+ },
toggleSidebar: {
label: "Toggle sidebar",
description: "Show or hide the sidebar",
},
- openSettings: {
- label: "Open settings",
- description: "Open the settings dialog",
+ toggleApiMonitor: {
+ label: "Toggle API activity",
+ description: "Show or hide the API activity monitor",
},
- openKeyboardShortcuts: {
- label: "Keyboard shortcuts",
- description: "Open this shortcuts list",
+ openModelPicker: {
+ label: "Open model picker",
+ description: "Choose the model for this chat",
+ },
+ openProjectPicker: {
+ label: "Open project picker",
+ description: "Switch to another project from the chat header",
+ },
+ startDictation: {
+ label: "Dictation",
+ description: "Start or stop dictating into the composer",
+ },
+ attachFiles: {
+ label: "Attach photos and files",
+ description: "Add an attachment to the composer",
+ },
+ sendMessage: {
+ label: "Send message",
+ description: "Send what is in the composer",
+ },
+ cycleReasoningEffort: {
+ label: "Cycle reasoning effort",
+ description: "Step through the reasoning effort levels",
+ },
+ increaseReasoningEffort: {
+ label: "Increase reasoning effort",
+ description: "Raise reasoning effort one level",
+ },
+ decreaseReasoningEffort: {
+ label: "Decrease reasoning effort",
+ description: "Lower reasoning effort one level",
+ },
+ toggleFastMode: {
+ label: "Toggle Fast mode",
+ description: "Turn Fast mode on or off",
+ },
+ renameChat: {
+ label: "Rename chat",
+ description: "Rename the current chat",
+ },
+ forkChat: {
+ label: "Fork chat",
+ description: "Branch a new chat from the latest message",
+ },
+ copyChatAsMarkdown: {
+ label: "Copy as Markdown",
+ description: "Copy the whole chat to the clipboard as Markdown",
+ },
+ copySessionId: {
+ label: "Copy session id",
+ description: "Copy this chat's sandbox session id",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 9e18929ba04..7e63b6fcc74 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -220,30 +220,218 @@ export const es = {
clear: "Quitar atajo",
reset: "Restaurar el valor predeterminado",
resetAll: "Restablecer todo",
- groups: {
- general: "General",
- chat: "Chat",
- },
+ primarySlot: "Atajo",
+ alternateSlot: "Atajo alternativo",
+ browserReserved:
+ "Puede que tu navegador se reserve esta combinación. En la app de escritorio funciona.",
actions: {
- newChat: {
- label: "Nuevo chat",
- description: "Iniciar un chat nuevo",
+ openSettings: {
+ label: "Abrir ajustes",
+ description: "Abrir el diálogo de ajustes",
+ },
+ openKeyboardShortcuts: {
+ label: "Atajos de teclado",
+ description: "Abrir esta lista de atajos",
},
searchChats: {
label: "Buscar chats",
description: "Abrir el diálogo de búsqueda de chats",
},
+ openMcpServers: {
+ label: "Servidores MCP",
+ description: "Configurar los servidores MCP de este chat",
+ },
+ logOut: {
+ label: "Cerrar sesión",
+ description: "Salir de Unsloth",
+ },
+ approveToolRequest: {
+ label: "Aprobar solicitud",
+ description: "Permitir la llamada de herramienta en espera",
+ },
+ declineToolRequest: {
+ label: "Rechazar solicitud",
+ description: "Denegar la llamada de herramienta en espera",
+ },
+ newChat: {
+ label: "Nuevo chat",
+ description: "Iniciar un chat nuevo",
+ },
+ newTemporaryChat: {
+ label: "Nuevo chat temporal",
+ description: "Iniciar un chat que no se guarda en el historial",
+ },
+ newStandaloneChat: {
+ label: "Nuevo chat independiente",
+ description: "Iniciar un chat fuera de cualquier proyecto",
+ },
+ archiveChat: {
+ label: "Archivar chat",
+ description: "Archivar los chats seleccionados o el chat actual",
+ },
+ markChatUnread: {
+ label: "Marcar como no leído",
+ description: "Marcar como no leídos los chats seleccionados o el chat actual",
+ },
+ togglePinChat: {
+ label: "Alternar fijado",
+ description: "Fijar o desfijar los chats seleccionados o el chat actual",
+ },
+ selectAllChats: {
+ label: "Seleccionar todos los chats",
+ description: "Seleccionar todos los chats de la barra lateral",
+ },
+ clearChatSelection: {
+ label: "Borrar selección",
+ description: "Anular la selección de los chats. Escape también la anula",
+ },
+ deleteSelectedChats: {
+ label: "Eliminar los chats seleccionados",
+ description: "Eliminar todos los chats seleccionados",
+ },
+ nextRecentlyViewedChat: {
+ label: "Siguiente chat visto",
+ description: "Avanzar por los chats vistos recientemente",
+ },
+ previousRecentlyViewedChat: {
+ label: "Chat visto anterior",
+ description: "Retroceder por los chats vistos recientemente",
+ },
+ nextChat: {
+ label: "Chat siguiente",
+ description: "Ir al siguiente chat de la barra lateral",
+ },
+ previousChat: {
+ label: "Chat anterior",
+ description: "Ir al chat anterior de la barra lateral",
+ },
+ nextChatNeedingAttention: {
+ label: "Siguiente chat con actividad",
+ description: "Ir al siguiente chat generando, en cola o no leído",
+ },
+ clearAllUnreads: {
+ label: "Marcar todo como leído",
+ description: "Marcar todos los chats como leídos",
+ },
+ goToRecentChat1: {
+ label: "Ir al chat reciente 1",
+ description: "Abrir el chat 1 de Recientes",
+ },
+ goToRecentChat2: {
+ label: "Ir al chat reciente 2",
+ description: "Abrir el chat 2 de Recientes",
+ },
+ goToRecentChat3: {
+ label: "Ir al chat reciente 3",
+ description: "Abrir el chat 3 de Recientes",
+ },
+ goToRecentChat4: {
+ label: "Ir al chat reciente 4",
+ description: "Abrir el chat 4 de Recientes",
+ },
+ goToRecentChat5: {
+ label: "Ir al chat reciente 5",
+ description: "Abrir el chat 5 de Recientes",
+ },
+ goToRecentChat6: {
+ label: "Ir al chat reciente 6",
+ description: "Abrir el chat 6 de Recientes",
+ },
+ switchToChat: {
+ label: "Ir a Chat",
+ description: "Ir al espacio de trabajo de chat",
+ },
+ switchToProjects: {
+ label: "Ir a Proyectos",
+ description: "Ir al espacio de trabajo de proyectos",
+ },
+ switchToHub: {
+ label: "Ir al Hub de modelos",
+ description: "Ir al hub de modelos",
+ },
+ switchToTrain: {
+ label: "Ir a Entrenar",
+ description: "Ir al espacio de trabajo de entrenamiento",
+ },
+ switchToRecipes: {
+ label: "Ir a Recipes",
+ description: "Ir a Data Recipes",
+ },
+ switchToImages: {
+ label: "Ir a Imágenes",
+ description: "Ir al espacio de trabajo de imágenes",
+ },
+ switchToVideo: {
+ label: "Ir a Vídeo",
+ description: "Ir al espacio de trabajo de vídeo",
+ },
+ switchToAudio: {
+ label: "Ir a Audio",
+ description: "Ir al espacio de trabajo de audio",
+ },
+ switchToExport: {
+ label: "Ir a Exportar",
+ description: "Ir al espacio de trabajo de exportación",
+ },
toggleSidebar: {
label: "Alternar barra lateral",
description: "Mostrar u ocultar la barra lateral",
},
- openSettings: {
- label: "Abrir ajustes",
- description: "Abrir el diálogo de ajustes",
+ toggleApiMonitor: {
+ label: "Alternar actividad de API",
+ description: "Mostrar u ocultar el monitor de actividad de API",
},
- openKeyboardShortcuts: {
- label: "Atajos de teclado",
- description: "Abrir esta lista de atajos",
+ openModelPicker: {
+ label: "Abrir selector de modelo",
+ description: "Elegir el modelo de este chat",
+ },
+ openProjectPicker: {
+ label: "Abrir selector de proyecto",
+ description: "Cambiar a otro proyecto desde la cabecera del chat",
+ },
+ startDictation: {
+ label: "Dictado",
+ description: "Iniciar o detener el dictado en el redactor",
+ },
+ attachFiles: {
+ label: "Adjuntar fotos y archivos",
+ description: "Añadir un adjunto al redactor",
+ },
+ sendMessage: {
+ label: "Enviar mensaje",
+ description: "Enviar lo que hay en el redactor",
+ },
+ cycleReasoningEffort: {
+ label: "Alternar esfuerzo de razonamiento",
+ description: "Recorrer los niveles de esfuerzo de razonamiento",
+ },
+ increaseReasoningEffort: {
+ label: "Aumentar esfuerzo de razonamiento",
+ description: "Subir un nivel el esfuerzo de razonamiento",
+ },
+ decreaseReasoningEffort: {
+ label: "Reducir esfuerzo de razonamiento",
+ description: "Bajar un nivel el esfuerzo de razonamiento",
+ },
+ toggleFastMode: {
+ label: "Alternar modo Fast",
+ description: "Activar o desactivar el modo Fast",
+ },
+ renameChat: {
+ label: "Renombrar chat",
+ description: "Renombrar el chat actual",
+ },
+ forkChat: {
+ label: "Bifurcar chat",
+ description: "Ramificar un chat nuevo desde el último mensaje",
+ },
+ copyChatAsMarkdown: {
+ label: "Copiar como Markdown",
+ description: "Copiar todo el chat al portapapeles como Markdown",
+ },
+ copySessionId: {
+ label: "Copiar ID de sesión",
+ description: "Copiar el ID de sesión de sandbox de este chat",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 7f27bd259c8..e19052093b5 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -221,30 +221,218 @@ export const fr = {
clear: "Supprimer le raccourci",
reset: "Rétablir la valeur par défaut",
resetAll: "Tout réinitialiser",
- groups: {
- general: "Général",
- chat: "Discussion",
- },
+ primarySlot: "Raccourci",
+ alternateSlot: "Raccourci alternatif",
+ browserReserved:
+ "Votre navigateur peut réserver cette combinaison. Elle fonctionne dans l’application de bureau.",
actions: {
- newChat: {
- label: "Nouvelle discussion",
- description: "Démarrer une nouvelle discussion",
+ openSettings: {
+ label: "Ouvrir les paramètres",
+ description: "Ouvrir la fenêtre des paramètres",
+ },
+ openKeyboardShortcuts: {
+ label: "Raccourcis clavier",
+ description: "Ouvrir cette liste de raccourcis",
},
searchChats: {
label: "Rechercher dans les discussions",
description: "Ouvrir la recherche de discussions",
},
+ openMcpServers: {
+ label: "Serveurs MCP",
+ description: "Configurer les serveurs MCP de cette discussion",
+ },
+ logOut: {
+ label: "Se déconnecter",
+ description: "Se déconnecter d’Unsloth",
+ },
+ approveToolRequest: {
+ label: "Approuver la demande",
+ description: "Autoriser l’appel d’outil en attente",
+ },
+ declineToolRequest: {
+ label: "Refuser la demande",
+ description: "Refuser l’appel d’outil en attente",
+ },
+ newChat: {
+ label: "Nouvelle discussion",
+ description: "Démarrer une nouvelle discussion",
+ },
+ newTemporaryChat: {
+ label: "Nouvelle discussion temporaire",
+ description: "Démarrer une discussion qui n’est pas enregistrée dans l’historique",
+ },
+ newStandaloneChat: {
+ label: "Nouvelle discussion autonome",
+ description: "Démarrer une discussion en dehors de tout projet",
+ },
+ archiveChat: {
+ label: "Archiver la discussion",
+ description: "Archiver les discussions sélectionnées, sinon celle en cours",
+ },
+ markChatUnread: {
+ label: "Marquer comme non lu",
+ description: "Marquer comme non lues les discussions sélectionnées, sinon celle en cours",
+ },
+ togglePinChat: {
+ label: "Épingler/désépingler",
+ description: "Épingler ou désépingler les discussions sélectionnées, sinon celle en cours",
+ },
+ selectAllChats: {
+ label: "Tout sélectionner",
+ description: "Sélectionner tous les chats de la barre latérale",
+ },
+ clearChatSelection: {
+ label: "Effacer la sélection",
+ description: "Désélectionner les chats sélectionnés. Échap le fait aussi",
+ },
+ deleteSelectedChats: {
+ label: "Supprimer les chats sélectionnés",
+ description: "Supprimer tous les chats sélectionnés",
+ },
+ nextRecentlyViewedChat: {
+ label: "Discussion consultée suivante",
+ description: "Avancer dans les discussions récemment consultées",
+ },
+ previousRecentlyViewedChat: {
+ label: "Discussion consultée précédente",
+ description: "Reculer dans les discussions récemment consultées",
+ },
+ nextChat: {
+ label: "Discussion suivante",
+ description: "Passer à la discussion suivante de la barre latérale",
+ },
+ previousChat: {
+ label: "Discussion précédente",
+ description: "Passer à la discussion précédente de la barre latérale",
+ },
+ nextChatNeedingAttention: {
+ label: "Discussion à traiter suivante",
+ description: "Passer à la discussion suivante en cours, en file ou non lue",
+ },
+ clearAllUnreads: {
+ label: "Tout marquer comme lu",
+ description: "Marquer toutes les discussions comme lues",
+ },
+ goToRecentChat1: {
+ label: "Aller à la discussion récente 1",
+ description: "Ouvrir la discussion 1 sous Récents",
+ },
+ goToRecentChat2: {
+ label: "Aller à la discussion récente 2",
+ description: "Ouvrir la discussion 2 sous Récents",
+ },
+ goToRecentChat3: {
+ label: "Aller à la discussion récente 3",
+ description: "Ouvrir la discussion 3 sous Récents",
+ },
+ goToRecentChat4: {
+ label: "Aller à la discussion récente 4",
+ description: "Ouvrir la discussion 4 sous Récents",
+ },
+ goToRecentChat5: {
+ label: "Aller à la discussion récente 5",
+ description: "Ouvrir la discussion 5 sous Récents",
+ },
+ goToRecentChat6: {
+ label: "Aller à la discussion récente 6",
+ description: "Ouvrir la discussion 6 sous Récents",
+ },
+ switchToChat: {
+ label: "Aller à Discussion",
+ description: "Ouvrir l’espace de discussion",
+ },
+ switchToProjects: {
+ label: "Aller à Projets",
+ description: "Ouvrir l’espace des projets",
+ },
+ switchToHub: {
+ label: "Aller au Hub de modèles",
+ description: "Ouvrir le hub de modèles",
+ },
+ switchToTrain: {
+ label: "Aller à Entraînement",
+ description: "Ouvrir l’espace d’entraînement",
+ },
+ switchToRecipes: {
+ label: "Aller à Recipes",
+ description: "Ouvrir Data Recipes",
+ },
+ switchToImages: {
+ label: "Aller à Images",
+ description: "Ouvrir l’espace des images",
+ },
+ switchToVideo: {
+ label: "Aller à Vidéo",
+ description: "Ouvrir l’espace vidéo",
+ },
+ switchToAudio: {
+ label: "Aller à Audio",
+ description: "Ouvrir l’espace audio",
+ },
+ switchToExport: {
+ label: "Aller à Export",
+ description: "Ouvrir l’espace d’export",
+ },
toggleSidebar: {
label: "Afficher/masquer la barre latérale",
description: "Afficher ou masquer la barre latérale",
},
- openSettings: {
- label: "Ouvrir les paramètres",
- description: "Ouvrir la fenêtre des paramètres",
+ toggleApiMonitor: {
+ label: "Afficher/masquer l’activité API",
+ description: "Afficher ou masquer le moniteur d’activité API",
},
- openKeyboardShortcuts: {
- label: "Raccourcis clavier",
- description: "Ouvrir cette liste de raccourcis",
+ openModelPicker: {
+ label: "Ouvrir le sélecteur de modèle",
+ description: "Choisir le modèle de cette discussion",
+ },
+ openProjectPicker: {
+ label: "Ouvrir le sélecteur de projet",
+ description: "Passer à un autre projet depuis l'en-tête du chat",
+ },
+ startDictation: {
+ label: "Dictée",
+ description: "Démarrer ou arrêter la dictée dans la zone de saisie",
+ },
+ attachFiles: {
+ label: "Joindre photos et fichiers",
+ description: "Ajouter une pièce jointe à la zone de saisie",
+ },
+ sendMessage: {
+ label: "Envoyer le message",
+ description: "Envoyer le contenu de la zone de saisie",
+ },
+ cycleReasoningEffort: {
+ label: "Faire défiler l’effort de raisonnement",
+ description: "Parcourir les niveaux d’effort de raisonnement",
+ },
+ increaseReasoningEffort: {
+ label: "Augmenter l’effort de raisonnement",
+ description: "Monter d’un niveau l’effort de raisonnement",
+ },
+ decreaseReasoningEffort: {
+ label: "Diminuer l’effort de raisonnement",
+ description: "Descendre d’un niveau l’effort de raisonnement",
+ },
+ toggleFastMode: {
+ label: "Activer/désactiver le mode Fast",
+ description: "Activer ou désactiver le mode Fast",
+ },
+ renameChat: {
+ label: "Renommer la discussion",
+ description: "Renommer la discussion en cours",
+ },
+ forkChat: {
+ label: "Dupliquer la discussion",
+ description: "Créer une branche à partir du dernier message",
+ },
+ copyChatAsMarkdown: {
+ label: "Copier en Markdown",
+ description: "Copier toute la discussion dans le presse-papiers en Markdown",
+ },
+ copySessionId: {
+ label: "Copier l’ID de session",
+ description: "Copier l’ID de session sandbox de cette discussion",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index f0e5c35ce10..c30524a9ada 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -220,30 +220,218 @@ export const hi = {
clear: "शॉर्टकट हटाएँ",
reset: "डिफ़ॉल्ट पर लौटाएँ",
resetAll: "सभी को डिफ़ॉल्ट पर रीसेट करें",
- groups: {
- general: "सामान्य",
- chat: "चैट",
- },
+ primarySlot: "शॉर्टकट",
+ alternateSlot: "वैकल्पिक शॉर्टकट",
+ browserReserved:
+ "आपका ब्राउज़र यह कुंजी संयोजन अपने पास रख सकता है। डेस्कटॉप ऐप में यह काम करता है।",
actions: {
- newChat: {
- label: "नई चैट",
- description: "नई चैट शुरू करें",
+ openSettings: {
+ label: "सेटिंग्स खोलें",
+ description: "सेटिंग्स संवाद खोलें",
+ },
+ openKeyboardShortcuts: {
+ label: "कीबोर्ड शॉर्टकट",
+ description: "यह शॉर्टकट सूची खोलें",
},
searchChats: {
label: "चैट खोजें",
description: "चैट खोज संवाद खोलें",
},
+ openMcpServers: {
+ label: "MCP सर्वर",
+ description: "इस चैट के लिए MCP सर्वर कॉन्फ़िगर करें",
+ },
+ logOut: {
+ label: "लॉग आउट",
+ description: "Unsloth से साइन आउट करें",
+ },
+ approveToolRequest: {
+ label: "अनुरोध स्वीकारें",
+ description: "प्रतीक्षारत टूल कॉल की अनुमति दें",
+ },
+ declineToolRequest: {
+ label: "अनुरोध अस्वीकारें",
+ description: "प्रतीक्षारत टूल कॉल को मना करें",
+ },
+ newChat: {
+ label: "नई चैट",
+ description: "नई चैट शुरू करें",
+ },
+ newTemporaryChat: {
+ label: "नई अस्थायी चैट",
+ description: "ऐसी चैट शुरू करें जो इतिहास में सहेजी न जाए",
+ },
+ newStandaloneChat: {
+ label: "नई स्वतंत्र चैट",
+ description: "किसी भी प्रोजेक्ट के बाहर नई चैट शुरू करें",
+ },
+ archiveChat: {
+ label: "चैट संग्रहित करें",
+ description: "चुनी गई चैट संग्रहित करें, या मौजूदा चैट",
+ },
+ markChatUnread: {
+ label: "अपठित के रूप में चिह्नित करें",
+ description: "चुनी गई चैट को अपठित चिह्नित करें, या मौजूदा चैट",
+ },
+ togglePinChat: {
+ label: "पिन टॉगल करें",
+ description: "चुनी गई चैट पिन या अनपिन करें, या मौजूदा चैट",
+ },
+ selectAllChats: {
+ label: "सभी चैट चुनें",
+ description: "साइडबार की हर चैट चुनें",
+ },
+ clearChatSelection: {
+ label: "चयन हटाएँ",
+ description: "चुनी गई चैट का चयन हटाएँ। Escape से भी चयन हटता है",
+ },
+ deleteSelectedChats: {
+ label: "चुनी गई चैट हटाएँ",
+ description: "हर चुनी गई चैट को हटाएँ",
+ },
+ nextRecentlyViewedChat: {
+ label: "अगली हाल में देखी चैट",
+ description: "हाल में देखी चैट में आगे बढ़ें",
+ },
+ previousRecentlyViewedChat: {
+ label: "पिछली हाल में देखी चैट",
+ description: "हाल में देखी चैट में पीछे जाएँ",
+ },
+ nextChat: {
+ label: "अगली चैट",
+ description: "साइडबार की अगली चैट पर जाएँ",
+ },
+ previousChat: {
+ label: "पिछली चैट",
+ description: "साइडबार की पिछली चैट पर जाएँ",
+ },
+ nextChatNeedingAttention: {
+ label: "ध्यान चाहने वाली अगली चैट",
+ description: "अगली उत्पन्न होती, कतार में या अपठित चैट पर जाएँ",
+ },
+ clearAllUnreads: {
+ label: "सभी अपठित हटाएँ",
+ description: "हर चैट को पढ़ा हुआ चिह्नित करें",
+ },
+ goToRecentChat1: {
+ label: "हाल की चैट 1 पर जाएँ",
+ description: "“हाल के” में 1वीं चैट खोलें",
+ },
+ goToRecentChat2: {
+ label: "हाल की चैट 2 पर जाएँ",
+ description: "“हाल के” में 2वीं चैट खोलें",
+ },
+ goToRecentChat3: {
+ label: "हाल की चैट 3 पर जाएँ",
+ description: "“हाल के” में 3वीं चैट खोलें",
+ },
+ goToRecentChat4: {
+ label: "हाल की चैट 4 पर जाएँ",
+ description: "“हाल के” में 4वीं चैट खोलें",
+ },
+ goToRecentChat5: {
+ label: "हाल की चैट 5 पर जाएँ",
+ description: "“हाल के” में 5वीं चैट खोलें",
+ },
+ goToRecentChat6: {
+ label: "हाल की चैट 6 पर जाएँ",
+ description: "“हाल के” में 6वीं चैट खोलें",
+ },
+ switchToChat: {
+ label: "चैट पर जाएँ",
+ description: "चैट कार्यक्षेत्र पर जाएँ",
+ },
+ switchToProjects: {
+ label: "प्रोजेक्ट पर जाएँ",
+ description: "प्रोजेक्ट कार्यक्षेत्र पर जाएँ",
+ },
+ switchToHub: {
+ label: "मॉडल हब पर जाएँ",
+ description: "मॉडल हब पर जाएँ",
+ },
+ switchToTrain: {
+ label: "ट्रेन पर जाएँ",
+ description: "प्रशिक्षण कार्यक्षेत्र पर जाएँ",
+ },
+ switchToRecipes: {
+ label: "Recipes पर जाएँ",
+ description: "Data Recipes पर जाएँ",
+ },
+ switchToImages: {
+ label: "इमेज पर जाएँ",
+ description: "इमेज कार्यक्षेत्र पर जाएँ",
+ },
+ switchToVideo: {
+ label: "वीडियो पर जाएँ",
+ description: "वीडियो कार्यक्षेत्र पर जाएँ",
+ },
+ switchToAudio: {
+ label: "ऑडियो पर जाएँ",
+ description: "ऑडियो कार्यक्षेत्र पर जाएँ",
+ },
+ switchToExport: {
+ label: "एक्सपोर्ट पर जाएँ",
+ description: "एक्सपोर्ट कार्यक्षेत्र पर जाएँ",
+ },
toggleSidebar: {
label: "साइडबार टॉगल करें",
description: "साइडबार दिखाएँ या छिपाएँ",
},
- openSettings: {
- label: "सेटिंग्स खोलें",
- description: "सेटिंग्स संवाद खोलें",
+ toggleApiMonitor: {
+ label: "API गतिविधि टॉगल करें",
+ description: "API गतिविधि मॉनिटर दिखाएँ या छिपाएँ",
},
- openKeyboardShortcuts: {
- label: "कीबोर्ड शॉर्टकट",
- description: "यह शॉर्टकट सूची खोलें",
+ openModelPicker: {
+ label: "मॉडल चयनकर्ता खोलें",
+ description: "इस चैट के लिए मॉडल चुनें",
+ },
+ openProjectPicker: {
+ label: "प्रोजेक्ट चयनकर्ता खोलें",
+ description: "चैट हेडर से किसी दूसरे प्रोजेक्ट पर जाएँ",
+ },
+ startDictation: {
+ label: "श्रुतलेख",
+ description: "लिखने के बॉक्स में श्रुतलेख शुरू या बंद करें",
+ },
+ attachFiles: {
+ label: "फ़ोटो और फ़ाइलें संलग्न करें",
+ description: "लिखने के बॉक्स में अनुलग्नक जोड़ें",
+ },
+ sendMessage: {
+ label: "संदेश भेजें",
+ description: "लिखने के बॉक्स की सामग्री भेजें",
+ },
+ cycleReasoningEffort: {
+ label: "तर्क प्रयास बदलें",
+ description: "तर्क प्रयास के स्तरों में क्रमशः बदलें",
+ },
+ increaseReasoningEffort: {
+ label: "तर्क प्रयास बढ़ाएँ",
+ description: "तर्क प्रयास एक स्तर बढ़ाएँ",
+ },
+ decreaseReasoningEffort: {
+ label: "तर्क प्रयास घटाएँ",
+ description: "तर्क प्रयास एक स्तर घटाएँ",
+ },
+ toggleFastMode: {
+ label: "Fast मोड टॉगल करें",
+ description: "Fast मोड चालू या बंद करें",
+ },
+ renameChat: {
+ label: "चैट का नाम बदलें",
+ description: "मौजूदा चैट का नाम बदलें",
+ },
+ forkChat: {
+ label: "चैट फ़ोर्क करें",
+ description: "अंतिम संदेश से नई चैट अलग करें",
+ },
+ copyChatAsMarkdown: {
+ label: "Markdown के रूप में कॉपी करें",
+ description: "पूरी चैट को Markdown के रूप में क्लिपबोर्ड पर कॉपी करें",
+ },
+ copySessionId: {
+ label: "सत्र आईडी कॉपी करें",
+ description: "इस चैट की सैंडबॉक्स सत्र आईडी कॉपी करें",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 937b4e8e1f5..56f43493880 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -185,30 +185,218 @@ export const it = {
clear: "Rimuovi scorciatoia",
reset: "Ripristina il valore predefinito",
resetAll: "Ripristina tutto",
- groups: {
- general: "Generali",
- chat: "Chat",
- },
+ primarySlot: "Scorciatoia",
+ alternateSlot: "Scorciatoia alternativa",
+ browserReserved:
+ "Il browser potrebbe riservare questa combinazione per sé. Nell’app desktop funziona.",
actions: {
- newChat: {
- label: "Nuova chat",
- description: "Avvia una nuova chat",
+ openSettings: {
+ label: "Apri le impostazioni",
+ description: "Apri la finestra delle impostazioni",
+ },
+ openKeyboardShortcuts: {
+ label: "Scorciatoie da tastiera",
+ description: "Apri questo elenco di scorciatoie",
},
searchChats: {
label: "Cerca nelle chat",
description: "Apri la ricerca delle chat",
},
+ openMcpServers: {
+ label: "Server MCP",
+ description: "Configura i server MCP per questa chat",
+ },
+ logOut: {
+ label: "Esci",
+ description: "Esci da Unsloth",
+ },
+ approveToolRequest: {
+ label: "Approva la richiesta",
+ description: "Consenti la chiamata allo strumento in attesa",
+ },
+ declineToolRequest: {
+ label: "Rifiuta la richiesta",
+ description: "Nega la chiamata allo strumento in attesa",
+ },
+ newChat: {
+ label: "Nuova chat",
+ description: "Avvia una nuova chat",
+ },
+ newTemporaryChat: {
+ label: "Nuova chat temporanea",
+ description: "Avvia una chat che non viene salvata nella cronologia",
+ },
+ newStandaloneChat: {
+ label: "Nuova chat autonoma",
+ description: "Avvia una chat fuori da qualsiasi progetto",
+ },
+ archiveChat: {
+ label: "Archivia chat",
+ description: "Archivia le chat selezionate, o quella corrente",
+ },
+ markChatUnread: {
+ label: "Segna come non letta",
+ description: "Segna come non lette le chat selezionate, o quella corrente",
+ },
+ togglePinChat: {
+ label: "Fissa/sblocca",
+ description: "Fissa o sblocca le chat selezionate, o quella corrente",
+ },
+ selectAllChats: {
+ label: "Seleziona tutte le chat",
+ description: "Seleziona tutte le chat nella barra laterale",
+ },
+ clearChatSelection: {
+ label: "Annulla selezione",
+ description: "Deseleziona le chat scelte. Anche Esc le annulla",
+ },
+ deleteSelectedChats: {
+ label: "Elimina le chat selezionate",
+ description: "Elimina tutte le chat selezionate",
+ },
+ nextRecentlyViewedChat: {
+ label: "Chat vista successiva",
+ description: "Avanza tra le chat viste di recente",
+ },
+ previousRecentlyViewedChat: {
+ label: "Chat vista precedente",
+ description: "Torna indietro tra le chat viste di recente",
+ },
+ nextChat: {
+ label: "Chat successiva",
+ description: "Passa alla chat successiva nella barra laterale",
+ },
+ previousChat: {
+ label: "Chat precedente",
+ description: "Passa alla chat precedente nella barra laterale",
+ },
+ nextChatNeedingAttention: {
+ label: "Chat da seguire successiva",
+ description: "Passa alla prossima chat in generazione, in coda o non letta",
+ },
+ clearAllUnreads: {
+ label: "Segna tutto come letto",
+ description: "Segna ogni chat come letta",
+ },
+ goToRecentChat1: {
+ label: "Vai alla chat recente 1",
+ description: "Apri la chat 1 in Recenti",
+ },
+ goToRecentChat2: {
+ label: "Vai alla chat recente 2",
+ description: "Apri la chat 2 in Recenti",
+ },
+ goToRecentChat3: {
+ label: "Vai alla chat recente 3",
+ description: "Apri la chat 3 in Recenti",
+ },
+ goToRecentChat4: {
+ label: "Vai alla chat recente 4",
+ description: "Apri la chat 4 in Recenti",
+ },
+ goToRecentChat5: {
+ label: "Vai alla chat recente 5",
+ description: "Apri la chat 5 in Recenti",
+ },
+ goToRecentChat6: {
+ label: "Vai alla chat recente 6",
+ description: "Apri la chat 6 in Recenti",
+ },
+ switchToChat: {
+ label: "Vai a Chat",
+ description: "Vai allo spazio di lavoro chat",
+ },
+ switchToProjects: {
+ label: "Vai a Progetti",
+ description: "Vai allo spazio di lavoro progetti",
+ },
+ switchToHub: {
+ label: "Vai all’Hub modelli",
+ description: "Vai all’hub dei modelli",
+ },
+ switchToTrain: {
+ label: "Vai ad Addestramento",
+ description: "Vai allo spazio di lavoro di addestramento",
+ },
+ switchToRecipes: {
+ label: "Vai a Recipes",
+ description: "Vai a Data Recipes",
+ },
+ switchToImages: {
+ label: "Vai a Immagini",
+ description: "Vai allo spazio di lavoro immagini",
+ },
+ switchToVideo: {
+ label: "Vai a Video",
+ description: "Vai allo spazio di lavoro video",
+ },
+ switchToAudio: {
+ label: "Vai ad Audio",
+ description: "Vai allo spazio di lavoro audio",
+ },
+ switchToExport: {
+ label: "Vai a Esporta",
+ description: "Vai allo spazio di lavoro di esportazione",
+ },
toggleSidebar: {
label: "Mostra/nascondi barra laterale",
description: "Mostra o nascondi la barra laterale",
},
- openSettings: {
- label: "Apri le impostazioni",
- description: "Apri la finestra delle impostazioni",
+ toggleApiMonitor: {
+ label: "Mostra/nascondi attività API",
+ description: "Mostra o nascondi il monitor di attività API",
},
- openKeyboardShortcuts: {
- label: "Scorciatoie da tastiera",
- description: "Apri questo elenco di scorciatoie",
+ openModelPicker: {
+ label: "Apri selettore modello",
+ description: "Scegli il modello per questa chat",
+ },
+ openProjectPicker: {
+ label: "Apri selettore progetto",
+ description: "Passa a un altro progetto dall'intestazione della chat",
+ },
+ startDictation: {
+ label: "Dettatura",
+ description: "Avvia o interrompi la dettatura nell’editor",
+ },
+ attachFiles: {
+ label: "Allega foto e file",
+ description: "Aggiungi un allegato all’editor",
+ },
+ sendMessage: {
+ label: "Invia messaggio",
+ description: "Invia il contenuto dell’editor",
+ },
+ cycleReasoningEffort: {
+ label: "Scorri lo sforzo di ragionamento",
+ description: "Passa in rassegna i livelli di sforzo di ragionamento",
+ },
+ increaseReasoningEffort: {
+ label: "Aumenta lo sforzo di ragionamento",
+ description: "Alza di un livello lo sforzo di ragionamento",
+ },
+ decreaseReasoningEffort: {
+ label: "Riduci lo sforzo di ragionamento",
+ description: "Abbassa di un livello lo sforzo di ragionamento",
+ },
+ toggleFastMode: {
+ label: "Attiva/disattiva la modalità Fast",
+ description: "Attiva o disattiva la modalità Fast",
+ },
+ renameChat: {
+ label: "Rinomina chat",
+ description: "Rinomina la chat corrente",
+ },
+ forkChat: {
+ label: "Dirama chat",
+ description: "Crea una nuova chat a partire dall’ultimo messaggio",
+ },
+ copyChatAsMarkdown: {
+ label: "Copia come Markdown",
+ description: "Copia l’intera chat negli appunti come Markdown",
+ },
+ copySessionId: {
+ label: "Copia ID sessione",
+ description: "Copia l’ID di sessione sandbox di questa chat",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index f3bd926cfc6..0137b08d723 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -219,30 +219,218 @@ export const ja = {
clear: "ショートカットを削除",
reset: "既定値に戻す",
resetAll: "すべて既定値に戻す",
- groups: {
- general: "一般",
- chat: "チャット",
- },
+ primarySlot: "ショートカット",
+ alternateSlot: "代替ショートカット",
+ browserReserved:
+ "ブラウザがこのキーを使う場合があります。デスクトップアプリでは動作します。",
actions: {
- newChat: {
- label: "新しいチャット",
- description: "新しいチャットを開始します",
+ openSettings: {
+ label: "設定を開く",
+ description: "設定ダイアログを開きます",
+ },
+ openKeyboardShortcuts: {
+ label: "キーボードショートカット",
+ description: "このショートカット一覧を開きます",
},
searchChats: {
label: "チャットを検索",
description: "チャット検索ダイアログを開きます",
},
+ openMcpServers: {
+ label: "MCP サーバー",
+ description: "このチャットの MCP サーバーを設定します",
+ },
+ logOut: {
+ label: "ログアウト",
+ description: "Unsloth からサインアウトします",
+ },
+ approveToolRequest: {
+ label: "リクエストを承認",
+ description: "承認待ちのツール呼び出しを許可します",
+ },
+ declineToolRequest: {
+ label: "リクエストを拒否",
+ description: "承認待ちのツール呼び出しを拒否します",
+ },
+ newChat: {
+ label: "新しいチャット",
+ description: "新しいチャットを開始します",
+ },
+ newTemporaryChat: {
+ label: "新しい一時チャット",
+ description: "履歴に保存されないチャットを開始します",
+ },
+ newStandaloneChat: {
+ label: "新しい単独チャット",
+ description: "プロジェクトの外で新しいチャットを開始します",
+ },
+ archiveChat: {
+ label: "チャットをアーカイブ",
+ description: "選択中のチャット、なければ現在のチャットをアーカイブします",
+ },
+ markChatUnread: {
+ label: "未読にする",
+ description: "選択中のチャット、なければ現在のチャットを未読にします",
+ },
+ togglePinChat: {
+ label: "ピン留めの切り替え",
+ description: "選択中のチャット、なければ現在のチャットをピン留め、または解除します",
+ },
+ selectAllChats: {
+ label: "すべてのチャットを選択",
+ description: "サイドバーのすべてのチャットを選択します",
+ },
+ clearChatSelection: {
+ label: "選択を解除",
+ description: "選択中のチャットを解除します。Esc でも解除できます",
+ },
+ deleteSelectedChats: {
+ label: "選択したチャットを削除",
+ description: "選択したすべてのチャットを削除します",
+ },
+ nextRecentlyViewedChat: {
+ label: "次に見ていたチャット",
+ description: "最近開いたチャットを前に送ります",
+ },
+ previousRecentlyViewedChat: {
+ label: "前に見ていたチャット",
+ description: "最近開いたチャットを後ろに戻します",
+ },
+ nextChat: {
+ label: "次のチャット",
+ description: "サイドバーの次のチャットに切り替えます",
+ },
+ previousChat: {
+ label: "前のチャット",
+ description: "サイドバーの前のチャットに切り替えます",
+ },
+ nextChatNeedingAttention: {
+ label: "対応が必要な次のチャット",
+ description: "生成中・待機中・未読の次のチャットに切り替えます",
+ },
+ clearAllUnreads: {
+ label: "未読をすべて解除",
+ description: "すべてのチャットを既読にします",
+ },
+ goToRecentChat1: {
+ label: "最近のチャット 1 へ移動",
+ description: "「最近」の 1 番目のチャットを開きます",
+ },
+ goToRecentChat2: {
+ label: "最近のチャット 2 へ移動",
+ description: "「最近」の 2 番目のチャットを開きます",
+ },
+ goToRecentChat3: {
+ label: "最近のチャット 3 へ移動",
+ description: "「最近」の 3 番目のチャットを開きます",
+ },
+ goToRecentChat4: {
+ label: "最近のチャット 4 へ移動",
+ description: "「最近」の 4 番目のチャットを開きます",
+ },
+ goToRecentChat5: {
+ label: "最近のチャット 5 へ移動",
+ description: "「最近」の 5 番目のチャットを開きます",
+ },
+ goToRecentChat6: {
+ label: "最近のチャット 6 へ移動",
+ description: "「最近」の 6 番目のチャットを開きます",
+ },
+ switchToChat: {
+ label: "チャットへ切り替え",
+ description: "チャットのワークスペースへ移動します",
+ },
+ switchToProjects: {
+ label: "プロジェクトへ切り替え",
+ description: "プロジェクトのワークスペースへ移動します",
+ },
+ switchToHub: {
+ label: "モデルハブへ切り替え",
+ description: "モデルハブへ移動します",
+ },
+ switchToTrain: {
+ label: "トレーニングへ切り替え",
+ description: "トレーニングのワークスペースへ移動します",
+ },
+ switchToRecipes: {
+ label: "Recipes へ切り替え",
+ description: "Data Recipes へ移動します",
+ },
+ switchToImages: {
+ label: "画像へ切り替え",
+ description: "画像のワークスペースへ移動します",
+ },
+ switchToVideo: {
+ label: "動画へ切り替え",
+ description: "動画のワークスペースへ移動します",
+ },
+ switchToAudio: {
+ label: "音声へ切り替え",
+ description: "音声のワークスペースへ移動します",
+ },
+ switchToExport: {
+ label: "エクスポートへ切り替え",
+ description: "エクスポートのワークスペースへ移動します",
+ },
toggleSidebar: {
label: "サイドバーの表示切り替え",
description: "サイドバーを表示または非表示にします",
},
- openSettings: {
- label: "設定を開く",
- description: "設定ダイアログを開きます",
+ toggleApiMonitor: {
+ label: "API アクティビティの表示切り替え",
+ description: "API アクティビティモニターを表示または非表示にします",
},
- openKeyboardShortcuts: {
- label: "キーボードショートカット",
- description: "このショートカット一覧を開きます",
+ openModelPicker: {
+ label: "モデル選択を開く",
+ description: "このチャットのモデルを選びます",
+ },
+ openProjectPicker: {
+ label: "プロジェクト選択を開く",
+ description: "チャットヘッダーから別のプロジェクトに切り替えます",
+ },
+ startDictation: {
+ label: "音声入力",
+ description: "入力欄への音声入力を開始または停止します",
+ },
+ attachFiles: {
+ label: "写真とファイルを添付",
+ description: "入力欄に添付ファイルを追加します",
+ },
+ sendMessage: {
+ label: "メッセージを送信",
+ description: "入力欄の内容を送信します",
+ },
+ cycleReasoningEffort: {
+ label: "思考の深さを順に切り替え",
+ description: "思考の深さのレベルを順に切り替えます",
+ },
+ increaseReasoningEffort: {
+ label: "思考の深さを上げる",
+ description: "思考の深さを 1 段階上げます",
+ },
+ decreaseReasoningEffort: {
+ label: "思考の深さを下げる",
+ description: "思考の深さを 1 段階下げます",
+ },
+ toggleFastMode: {
+ label: "Fast モードの切り替え",
+ description: "Fast モードをオンまたはオフにします",
+ },
+ renameChat: {
+ label: "チャット名を変更",
+ description: "現在のチャットの名前を変更します",
+ },
+ forkChat: {
+ label: "チャットを分岐",
+ description: "最後のメッセージから新しいチャットを分岐します",
+ },
+ copyChatAsMarkdown: {
+ label: "Markdown としてコピー",
+ description: "チャット全体を Markdown としてクリップボードにコピーします",
+ },
+ copySessionId: {
+ label: "セッション ID をコピー",
+ description: "このチャットのサンドボックスのセッション ID をコピーします",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index e035a0cd4dd..122f14db540 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -217,30 +217,218 @@ export const ko = {
clear: "단축키 제거",
reset: "기본값 복원",
resetAll: "모두 기본값으로 초기화",
- groups: {
- general: "일반",
- chat: "채팅",
- },
+ primarySlot: "단축키",
+ alternateSlot: "대체 단축키",
+ browserReserved:
+ "브라우저가 이 조합을 가져갈 수 있습니다. 데스크톱 앱에서는 동작합니다.",
actions: {
- newChat: {
- label: "새 채팅",
- description: "새 채팅을 시작합니다",
+ openSettings: {
+ label: "설정 열기",
+ description: "설정 창을 엽니다",
+ },
+ openKeyboardShortcuts: {
+ label: "키보드 단축키",
+ description: "이 단축키 목록을 엽니다",
},
searchChats: {
label: "채팅 검색",
description: "채팅 검색 창을 엽니다",
},
+ openMcpServers: {
+ label: "MCP 서버",
+ description: "이 채팅의 MCP 서버를 설정합니다",
+ },
+ logOut: {
+ label: "로그아웃",
+ description: "Unsloth에서 로그아웃합니다",
+ },
+ approveToolRequest: {
+ label: "요청 승인",
+ description: "대기 중인 도구 호출을 허용합니다",
+ },
+ declineToolRequest: {
+ label: "요청 거부",
+ description: "대기 중인 도구 호출을 거부합니다",
+ },
+ newChat: {
+ label: "새 채팅",
+ description: "새 채팅을 시작합니다",
+ },
+ newTemporaryChat: {
+ label: "새 임시 채팅",
+ description: "기록에 저장되지 않는 채팅을 시작합니다",
+ },
+ newStandaloneChat: {
+ label: "새 독립 채팅",
+ description: "프로젝트 밖에서 새 채팅을 시작합니다",
+ },
+ archiveChat: {
+ label: "채팅 보관",
+ description: "선택한 채팅을, 없으면 현재 채팅을 보관합니다",
+ },
+ markChatUnread: {
+ label: "읽지 않음으로 표시",
+ description: "선택한 채팅을, 없으면 현재 채팅을 읽지 않음으로 표시합니다",
+ },
+ togglePinChat: {
+ label: "고정 전환",
+ description: "선택한 채팅을, 없으면 현재 채팅을 고정하거나 해제합니다",
+ },
+ selectAllChats: {
+ label: "모든 채팅 선택",
+ description: "사이드바의 모든 채팅을 선택합니다",
+ },
+ clearChatSelection: {
+ label: "선택 해제",
+ description: "선택한 채팅을 해제합니다. Esc로도 해제됩니다",
+ },
+ deleteSelectedChats: {
+ label: "선택한 채팅 삭제",
+ description: "선택한 모든 채팅을 삭제합니다",
+ },
+ nextRecentlyViewedChat: {
+ label: "다음에 본 채팅",
+ description: "최근 본 채팅을 앞으로 넘깁니다",
+ },
+ previousRecentlyViewedChat: {
+ label: "이전에 본 채팅",
+ description: "최근 본 채팅을 뒤로 넘깁니다",
+ },
+ nextChat: {
+ label: "다음 채팅",
+ description: "사이드바의 다음 채팅으로 이동합니다",
+ },
+ previousChat: {
+ label: "이전 채팅",
+ description: "사이드바의 이전 채팅으로 이동합니다",
+ },
+ nextChatNeedingAttention: {
+ label: "확인이 필요한 다음 채팅",
+ description: "생성 중이거나 대기 중이거나 읽지 않은 다음 채팅으로 이동합니다",
+ },
+ clearAllUnreads: {
+ label: "모두 읽음으로 표시",
+ description: "모든 채팅을 읽음으로 표시합니다",
+ },
+ goToRecentChat1: {
+ label: "최근 채팅 1(으)로 이동",
+ description: "최근 항목의 1번째 채팅을 엽니다",
+ },
+ goToRecentChat2: {
+ label: "최근 채팅 2(으)로 이동",
+ description: "최근 항목의 2번째 채팅을 엽니다",
+ },
+ goToRecentChat3: {
+ label: "최근 채팅 3(으)로 이동",
+ description: "최근 항목의 3번째 채팅을 엽니다",
+ },
+ goToRecentChat4: {
+ label: "최근 채팅 4(으)로 이동",
+ description: "최근 항목의 4번째 채팅을 엽니다",
+ },
+ goToRecentChat5: {
+ label: "최근 채팅 5(으)로 이동",
+ description: "최근 항목의 5번째 채팅을 엽니다",
+ },
+ goToRecentChat6: {
+ label: "최근 채팅 6(으)로 이동",
+ description: "최근 항목의 6번째 채팅을 엽니다",
+ },
+ switchToChat: {
+ label: "채팅으로 전환",
+ description: "채팅 작업 공간으로 이동합니다",
+ },
+ switchToProjects: {
+ label: "프로젝트로 전환",
+ description: "프로젝트 작업 공간으로 이동합니다",
+ },
+ switchToHub: {
+ label: "모델 허브로 전환",
+ description: "모델 허브로 이동합니다",
+ },
+ switchToTrain: {
+ label: "학습으로 전환",
+ description: "학습 작업 공간으로 이동합니다",
+ },
+ switchToRecipes: {
+ label: "Recipes로 전환",
+ description: "Data Recipes로 이동합니다",
+ },
+ switchToImages: {
+ label: "이미지로 전환",
+ description: "이미지 작업 공간으로 이동합니다",
+ },
+ switchToVideo: {
+ label: "비디오로 전환",
+ description: "비디오 작업 공간으로 이동합니다",
+ },
+ switchToAudio: {
+ label: "오디오로 전환",
+ description: "오디오 작업 공간으로 이동합니다",
+ },
+ switchToExport: {
+ label: "내보내기로 전환",
+ description: "내보내기 작업 공간으로 이동합니다",
+ },
toggleSidebar: {
label: "사이드바 토글",
description: "사이드바를 표시하거나 숨깁니다",
},
- openSettings: {
- label: "설정 열기",
- description: "설정 창을 엽니다",
+ toggleApiMonitor: {
+ label: "API 활동 토글",
+ description: "API 활동 모니터를 표시하거나 숨깁니다",
},
- openKeyboardShortcuts: {
- label: "키보드 단축키",
- description: "이 단축키 목록을 엽니다",
+ openModelPicker: {
+ label: "모델 선택 열기",
+ description: "이 채팅에 사용할 모델을 고릅니다",
+ },
+ openProjectPicker: {
+ label: "프로젝트 선택 열기",
+ description: "채팅 헤더에서 다른 프로젝트로 전환합니다",
+ },
+ startDictation: {
+ label: "받아쓰기",
+ description: "입력창 받아쓰기를 시작하거나 중지합니다",
+ },
+ attachFiles: {
+ label: "사진 및 파일 첨부",
+ description: "입력창에 첨부 파일을 추가합니다",
+ },
+ sendMessage: {
+ label: "메시지 보내기",
+ description: "입력창의 내용을 보냅니다",
+ },
+ cycleReasoningEffort: {
+ label: "추론 강도 순환",
+ description: "추론 강도 단계를 차례로 바꿉니다",
+ },
+ increaseReasoningEffort: {
+ label: "추론 강도 높이기",
+ description: "추론 강도를 한 단계 올립니다",
+ },
+ decreaseReasoningEffort: {
+ label: "추론 강도 낮추기",
+ description: "추론 강도를 한 단계 내립니다",
+ },
+ toggleFastMode: {
+ label: "Fast 모드 토글",
+ description: "Fast 모드를 켜거나 끕니다",
+ },
+ renameChat: {
+ label: "채팅 이름 바꾸기",
+ description: "현재 채팅의 이름을 바꿉니다",
+ },
+ forkChat: {
+ label: "채팅 분기",
+ description: "마지막 메시지에서 새 채팅으로 분기합니다",
+ },
+ copyChatAsMarkdown: {
+ label: "Markdown으로 복사",
+ description: "채팅 전체를 Markdown으로 클립보드에 복사합니다",
+ },
+ copySessionId: {
+ label: "세션 ID 복사",
+ description: "이 채팅의 샌드박스 세션 ID를 복사합니다",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4aa19ea74ea..4bc1352689c 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -219,30 +219,218 @@ export const ptBR = {
clear: "Remover atalho",
reset: "Restaurar o padrão",
resetAll: "Redefinir tudo para o padrão",
- groups: {
- general: "Geral",
- chat: "Chat",
- },
+ primarySlot: "Atalho",
+ alternateSlot: "Atalho alternativo",
+ browserReserved:
+ "Seu navegador pode reservar essa combinação. No app para desktop ela funciona.",
actions: {
- newChat: {
- label: "Novo chat",
- description: "Iniciar um novo chat",
+ openSettings: {
+ label: "Abrir configurações",
+ description: "Abrir a janela de configurações",
+ },
+ openKeyboardShortcuts: {
+ label: "Atalhos de teclado",
+ description: "Abrir esta lista de atalhos",
},
searchChats: {
label: "Pesquisar chats",
description: "Abrir a busca de chats",
},
+ openMcpServers: {
+ label: "Servidores MCP",
+ description: "Configurar os servidores MCP deste chat",
+ },
+ logOut: {
+ label: "Sair",
+ description: "Sair do Unsloth",
+ },
+ approveToolRequest: {
+ label: "Aprovar solicitação",
+ description: "Permitir a chamada de ferramenta em espera",
+ },
+ declineToolRequest: {
+ label: "Recusar solicitação",
+ description: "Negar a chamada de ferramenta em espera",
+ },
+ newChat: {
+ label: "Novo chat",
+ description: "Iniciar um novo chat",
+ },
+ newTemporaryChat: {
+ label: "Novo chat temporário",
+ description: "Iniciar um chat que não é salvo no histórico",
+ },
+ newStandaloneChat: {
+ label: "Novo chat independente",
+ description: "Iniciar um chat fora de qualquer projeto",
+ },
+ archiveChat: {
+ label: "Arquivar chat",
+ description: "Arquivar os chats selecionados ou o chat atual",
+ },
+ markChatUnread: {
+ label: "Marcar como não lida",
+ description: "Marcar como não lidos os chats selecionados ou o chat atual",
+ },
+ togglePinChat: {
+ label: "Alternar fixação",
+ description: "Fixar ou desafixar os chats selecionados ou o chat atual",
+ },
+ selectAllChats: {
+ label: "Selecionar todos os chats",
+ description: "Selecionar todos os chats da barra lateral",
+ },
+ clearChatSelection: {
+ label: "Limpar seleção",
+ description: "Desmarcar os chats selecionados. Esc também desmarca",
+ },
+ deleteSelectedChats: {
+ label: "Excluir os chats selecionados",
+ description: "Excluir todos os chats selecionados",
+ },
+ nextRecentlyViewedChat: {
+ label: "Próximo chat visto",
+ description: "Avançar pelos chats vistos recentemente",
+ },
+ previousRecentlyViewedChat: {
+ label: "Chat visto anterior",
+ description: "Voltar pelos chats vistos recentemente",
+ },
+ nextChat: {
+ label: "Próximo chat",
+ description: "Ir para o próximo chat da barra lateral",
+ },
+ previousChat: {
+ label: "Chat anterior",
+ description: "Ir para o chat anterior da barra lateral",
+ },
+ nextChatNeedingAttention: {
+ label: "Próximo chat com atividade",
+ description: "Ir para o próximo chat gerando, na fila ou não lido",
+ },
+ clearAllUnreads: {
+ label: "Marcar tudo como lido",
+ description: "Marcar todos os chats como lidos",
+ },
+ goToRecentChat1: {
+ label: "Ir para o chat recente 1",
+ description: "Abrir o chat 1 em Recentes",
+ },
+ goToRecentChat2: {
+ label: "Ir para o chat recente 2",
+ description: "Abrir o chat 2 em Recentes",
+ },
+ goToRecentChat3: {
+ label: "Ir para o chat recente 3",
+ description: "Abrir o chat 3 em Recentes",
+ },
+ goToRecentChat4: {
+ label: "Ir para o chat recente 4",
+ description: "Abrir o chat 4 em Recentes",
+ },
+ goToRecentChat5: {
+ label: "Ir para o chat recente 5",
+ description: "Abrir o chat 5 em Recentes",
+ },
+ goToRecentChat6: {
+ label: "Ir para o chat recente 6",
+ description: "Abrir o chat 6 em Recentes",
+ },
+ switchToChat: {
+ label: "Ir para Chat",
+ description: "Ir para a área de trabalho de chat",
+ },
+ switchToProjects: {
+ label: "Ir para Projetos",
+ description: "Ir para a área de trabalho de projetos",
+ },
+ switchToHub: {
+ label: "Ir para o Hub de modelos",
+ description: "Ir para o hub de modelos",
+ },
+ switchToTrain: {
+ label: "Ir para Treinar",
+ description: "Ir para a área de trabalho de treinamento",
+ },
+ switchToRecipes: {
+ label: "Ir para Recipes",
+ description: "Ir para Data Recipes",
+ },
+ switchToImages: {
+ label: "Ir para Imagens",
+ description: "Ir para a área de trabalho de imagens",
+ },
+ switchToVideo: {
+ label: "Ir para Vídeo",
+ description: "Ir para a área de trabalho de vídeo",
+ },
+ switchToAudio: {
+ label: "Ir para Áudio",
+ description: "Ir para a área de trabalho de áudio",
+ },
+ switchToExport: {
+ label: "Ir para Exportar",
+ description: "Ir para a área de trabalho de exportação",
+ },
toggleSidebar: {
label: "Alternar barra lateral",
description: "Mostrar ou ocultar a barra lateral",
},
- openSettings: {
- label: "Abrir configurações",
- description: "Abrir a janela de configurações",
+ toggleApiMonitor: {
+ label: "Alternar atividade da API",
+ description: "Mostrar ou ocultar o monitor de atividade da API",
},
- openKeyboardShortcuts: {
- label: "Atalhos de teclado",
- description: "Abrir esta lista de atalhos",
+ openModelPicker: {
+ label: "Abrir seletor de modelo",
+ description: "Escolher o modelo deste chat",
+ },
+ openProjectPicker: {
+ label: "Abrir seletor de projeto",
+ description: "Trocar de projeto pelo cabeçalho do chat",
+ },
+ startDictation: {
+ label: "Ditado",
+ description: "Iniciar ou parar o ditado no compositor",
+ },
+ attachFiles: {
+ label: "Anexar fotos e arquivos",
+ description: "Adicionar um anexo ao compositor",
+ },
+ sendMessage: {
+ label: "Enviar mensagem",
+ description: "Enviar o que está no compositor",
+ },
+ cycleReasoningEffort: {
+ label: "Alternar esforço de raciocínio",
+ description: "Percorrer os níveis de esforço de raciocínio",
+ },
+ increaseReasoningEffort: {
+ label: "Aumentar esforço de raciocínio",
+ description: "Subir um nível o esforço de raciocínio",
+ },
+ decreaseReasoningEffort: {
+ label: "Reduzir esforço de raciocínio",
+ description: "Descer um nível o esforço de raciocínio",
+ },
+ toggleFastMode: {
+ label: "Alternar modo Fast",
+ description: "Ligar ou desligar o modo Fast",
+ },
+ renameChat: {
+ label: "Renomear chat",
+ description: "Renomear o chat atual",
+ },
+ forkChat: {
+ label: "Bifurcar chat",
+ description: "Ramificar um novo chat a partir da última mensagem",
+ },
+ copyChatAsMarkdown: {
+ label: "Copiar como Markdown",
+ description: "Copiar todo o chat para a área de transferência como Markdown",
+ },
+ copySessionId: {
+ label: "Copiar ID da sessão",
+ description: "Copiar o ID de sessão do sandbox deste chat",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index dc677f05e41..01c883a6d4d 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -219,30 +219,218 @@ export const ru = {
clear: "Удалить сочетание",
reset: "Вернуть значение по умолчанию",
resetAll: "Сбросить всё до значений по умолчанию",
- groups: {
- general: "Общие",
- chat: "Чат",
- },
+ primarySlot: "Сочетание",
+ alternateSlot: "Альтернативное сочетание",
+ browserReserved:
+ "Браузер может оставить это сочетание себе. В настольном приложении оно работает.",
actions: {
- newChat: {
- label: "Новый чат",
- description: "Начать новый чат",
+ openSettings: {
+ label: "Открыть настройки",
+ description: "Открыть окно настроек",
+ },
+ openKeyboardShortcuts: {
+ label: "Сочетания клавиш",
+ description: "Открыть этот список сочетаний",
},
searchChats: {
label: "Поиск по чатам",
description: "Открыть окно поиска по чатам",
},
+ openMcpServers: {
+ label: "Серверы MCP",
+ description: "Настроить серверы MCP для этого чата",
+ },
+ logOut: {
+ label: "Выйти",
+ description: "Выйти из Unsloth",
+ },
+ approveToolRequest: {
+ label: "Одобрить запрос",
+ description: "Разрешить ожидающий вызов инструмента",
+ },
+ declineToolRequest: {
+ label: "Отклонить запрос",
+ description: "Запретить ожидающий вызов инструмента",
+ },
+ newChat: {
+ label: "Новый чат",
+ description: "Начать новый чат",
+ },
+ newTemporaryChat: {
+ label: "Новый временный чат",
+ description: "Начать чат, который не сохраняется в истории",
+ },
+ newStandaloneChat: {
+ label: "Новый отдельный чат",
+ description: "Начать чат вне какого-либо проекта",
+ },
+ archiveChat: {
+ label: "Архивировать чат",
+ description: "Архивировать выбранные чаты или текущий чат",
+ },
+ markChatUnread: {
+ label: "Отметить как непрочитанный",
+ description: "Отметить выбранные чаты или текущий чат как непрочитанные",
+ },
+ togglePinChat: {
+ label: "Закрепить или открепить",
+ description: "Закрепить или открепить выбранные чаты или текущий чат",
+ },
+ selectAllChats: {
+ label: "Выбрать все чаты",
+ description: "Выбрать все чаты на боковой панели",
+ },
+ clearChatSelection: {
+ label: "Снять выделение",
+ description: "Снять выделение с выбранных чатов. Escape тоже снимает выделение",
+ },
+ deleteSelectedChats: {
+ label: "Удалить выбранные чаты",
+ description: "Удалить все выбранные чаты",
+ },
+ nextRecentlyViewedChat: {
+ label: "Следующий просмотренный чат",
+ description: "Листать вперёд по недавно открытым чатам",
+ },
+ previousRecentlyViewedChat: {
+ label: "Предыдущий просмотренный чат",
+ description: "Листать назад по недавно открытым чатам",
+ },
+ nextChat: {
+ label: "Следующий чат",
+ description: "Перейти к следующему чату в боковой панели",
+ },
+ previousChat: {
+ label: "Предыдущий чат",
+ description: "Перейти к предыдущему чату в боковой панели",
+ },
+ nextChatNeedingAttention: {
+ label: "Следующий чат с активностью",
+ description: "Перейти к следующему генерирующему, ожидающему или непрочитанному чату",
+ },
+ clearAllUnreads: {
+ label: "Отметить всё прочитанным",
+ description: "Отметить все чаты прочитанными",
+ },
+ goToRecentChat1: {
+ label: "Перейти к недавнему чату 1",
+ description: "Открыть чат 1 в разделе «Недавние»",
+ },
+ goToRecentChat2: {
+ label: "Перейти к недавнему чату 2",
+ description: "Открыть чат 2 в разделе «Недавние»",
+ },
+ goToRecentChat3: {
+ label: "Перейти к недавнему чату 3",
+ description: "Открыть чат 3 в разделе «Недавние»",
+ },
+ goToRecentChat4: {
+ label: "Перейти к недавнему чату 4",
+ description: "Открыть чат 4 в разделе «Недавние»",
+ },
+ goToRecentChat5: {
+ label: "Перейти к недавнему чату 5",
+ description: "Открыть чат 5 в разделе «Недавние»",
+ },
+ goToRecentChat6: {
+ label: "Перейти к недавнему чату 6",
+ description: "Открыть чат 6 в разделе «Недавние»",
+ },
+ switchToChat: {
+ label: "Перейти в Чат",
+ description: "Открыть рабочую область чата",
+ },
+ switchToProjects: {
+ label: "Перейти в Проекты",
+ description: "Открыть рабочую область проектов",
+ },
+ switchToHub: {
+ label: "Перейти в Хаб моделей",
+ description: "Открыть хаб моделей",
+ },
+ switchToTrain: {
+ label: "Перейти в Обучение",
+ description: "Открыть рабочую область обучения",
+ },
+ switchToRecipes: {
+ label: "Перейти в Recipes",
+ description: "Открыть Data Recipes",
+ },
+ switchToImages: {
+ label: "Перейти в Изображения",
+ description: "Открыть рабочую область изображений",
+ },
+ switchToVideo: {
+ label: "Перейти в Видео",
+ description: "Открыть рабочую область видео",
+ },
+ switchToAudio: {
+ label: "Перейти в Аудио",
+ description: "Открыть рабочую область аудио",
+ },
+ switchToExport: {
+ label: "Перейти в Экспорт",
+ description: "Открыть рабочую область экспорта",
+ },
toggleSidebar: {
label: "Показать/скрыть боковую панель",
description: "Показать или скрыть боковую панель",
},
- openSettings: {
- label: "Открыть настройки",
- description: "Открыть окно настроек",
+ toggleApiMonitor: {
+ label: "Показать/скрыть активность API",
+ description: "Показать или скрыть монитор активности API",
},
- openKeyboardShortcuts: {
- label: "Сочетания клавиш",
- description: "Открыть этот список сочетаний",
+ openModelPicker: {
+ label: "Открыть выбор модели",
+ description: "Выбрать модель для этого чата",
+ },
+ openProjectPicker: {
+ label: "Открыть выбор проекта",
+ description: "Перейти к другому проекту из заголовка чата",
+ },
+ startDictation: {
+ label: "Диктовка",
+ description: "Начать или остановить диктовку в поле ввода",
+ },
+ attachFiles: {
+ label: "Прикрепить фото и файлы",
+ description: "Добавить вложение в поле ввода",
+ },
+ sendMessage: {
+ label: "Отправить сообщение",
+ description: "Отправить содержимое поля ввода",
+ },
+ cycleReasoningEffort: {
+ label: "Переключать усилие рассуждения",
+ description: "Перебрать уровни усилия рассуждения",
+ },
+ increaseReasoningEffort: {
+ label: "Увеличить усилие рассуждения",
+ description: "Поднять усилие рассуждения на один уровень",
+ },
+ decreaseReasoningEffort: {
+ label: "Уменьшить усилие рассуждения",
+ description: "Снизить усилие рассуждения на один уровень",
+ },
+ toggleFastMode: {
+ label: "Переключить режим Fast",
+ description: "Включить или выключить режим Fast",
+ },
+ renameChat: {
+ label: "Переименовать чат",
+ description: "Переименовать текущий чат",
+ },
+ forkChat: {
+ label: "Ответвить чат",
+ description: "Создать новый чат от последнего сообщения",
+ },
+ copyChatAsMarkdown: {
+ label: "Скопировать как Markdown",
+ description: "Скопировать весь чат в буфер обмена как Markdown",
+ },
+ copySessionId: {
+ label: "Скопировать ID сессии",
+ description: "Скопировать ID песочницы этого чата",
},
},
},
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 5ba2c3dba1f..eb7c2fa78ca 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -215,30 +215,218 @@ export const zhCN = {
clear: "移除快捷键",
reset: "恢复默认",
resetAll: "全部恢复默认",
- groups: {
- general: "通用",
- chat: "聊天",
- },
+ primarySlot: "快捷键",
+ alternateSlot: "备用快捷键",
+ browserReserved:
+ "浏览器可能会占用该组合键。桌面应用中可正常使用。",
actions: {
- newChat: {
- label: "新建聊天",
- description: "开始一个新的聊天",
+ openSettings: {
+ label: "打开设置",
+ description: "打开设置对话框",
+ },
+ openKeyboardShortcuts: {
+ label: "键盘快捷键",
+ description: "打开该快捷键列表",
},
searchChats: {
label: "搜索聊天",
description: "打开聊天搜索对话框",
},
+ openMcpServers: {
+ label: "MCP 服务器",
+ description: "为该聊天配置 MCP 服务器",
+ },
+ logOut: {
+ label: "退出登录",
+ description: "退出 Unsloth",
+ },
+ approveToolRequest: {
+ label: "批准请求",
+ description: "允许正在等待批准的工具调用",
+ },
+ declineToolRequest: {
+ label: "拒绝请求",
+ description: "拒绝正在等待批准的工具调用",
+ },
+ newChat: {
+ label: "新建聊天",
+ description: "开始一个新的聊天",
+ },
+ newTemporaryChat: {
+ label: "新建临时聊天",
+ description: "开始一个不写入历史记录的聊天",
+ },
+ newStandaloneChat: {
+ label: "新建独立聊天",
+ description: "在所有项目之外开始新聊天",
+ },
+ archiveChat: {
+ label: "归档聊天",
+ description: "归档已选聊天,没有则归档当前聊天",
+ },
+ markChatUnread: {
+ label: "标记为未读",
+ description: "将已选聊天标记为未读,没有则标记当前聊天",
+ },
+ togglePinChat: {
+ label: "切换置顶",
+ description: "置顶或取消置顶已选聊天,没有则操作当前聊天",
+ },
+ selectAllChats: {
+ label: "选择全部对话",
+ description: "选择侧边栏中的所有对话",
+ },
+ clearChatSelection: {
+ label: "清除选择",
+ description: "取消选择已选对话。按 Esc 同样可以取消选择",
+ },
+ deleteSelectedChats: {
+ label: "删除所选对话",
+ description: "删除所有已选对话",
+ },
+ nextRecentlyViewedChat: {
+ label: "下一个最近查看的聊天",
+ description: "在最近查看的聊天中向前切换",
+ },
+ previousRecentlyViewedChat: {
+ label: "上一个最近查看的聊天",
+ description: "在最近查看的聊天中向后切换",
+ },
+ nextChat: {
+ label: "下一个聊天",
+ description: "切换到侧边栏中的下一个聊天",
+ },
+ previousChat: {
+ label: "上一个聊天",
+ description: "切换到侧边栏中的上一个聊天",
+ },
+ nextChatNeedingAttention: {
+ label: "下一个需要处理的聊天",
+ description: "切换到下一个正在生成、排队或未读的聊天",
+ },
+ clearAllUnreads: {
+ label: "全部标记为已读",
+ description: "将所有聊天标记为已读",
+ },
+ goToRecentChat1: {
+ label: "转到最近聊天 1",
+ description: "打开“最近”中的第 1 个聊天",
+ },
+ goToRecentChat2: {
+ label: "转到最近聊天 2",
+ description: "打开“最近”中的第 2 个聊天",
+ },
+ goToRecentChat3: {
+ label: "转到最近聊天 3",
+ description: "打开“最近”中的第 3 个聊天",
+ },
+ goToRecentChat4: {
+ label: "转到最近聊天 4",
+ description: "打开“最近”中的第 4 个聊天",
+ },
+ goToRecentChat5: {
+ label: "转到最近聊天 5",
+ description: "打开“最近”中的第 5 个聊天",
+ },
+ goToRecentChat6: {
+ label: "转到最近聊天 6",
+ description: "打开“最近”中的第 6 个聊天",
+ },
+ switchToChat: {
+ label: "切换到聊天",
+ description: "前往聊天工作区",
+ },
+ switchToProjects: {
+ label: "切换到项目",
+ description: "前往项目工作区",
+ },
+ switchToHub: {
+ label: "切换到模型中心",
+ description: "前往模型中心",
+ },
+ switchToTrain: {
+ label: "切换到训练",
+ description: "前往训练工作区",
+ },
+ switchToRecipes: {
+ label: "切换到 Recipes",
+ description: "前往 Data Recipes",
+ },
+ switchToImages: {
+ label: "切换到图像",
+ description: "前往图像工作区",
+ },
+ switchToVideo: {
+ label: "切换到视频",
+ description: "前往视频工作区",
+ },
+ switchToAudio: {
+ label: "切换到音频",
+ description: "前往音频工作区",
+ },
+ switchToExport: {
+ label: "切换到导出",
+ description: "前往导出工作区",
+ },
toggleSidebar: {
label: "切换侧边栏",
description: "显示或隐藏侧边栏",
},
- openSettings: {
- label: "打开设置",
- description: "打开设置对话框",
+ toggleApiMonitor: {
+ label: "切换 API 活动",
+ description: "显示或隐藏 API 活动监视器",
},
- openKeyboardShortcuts: {
- label: "键盘快捷键",
- description: "打开该快捷键列表",
+ openModelPicker: {
+ label: "打开模型选择器",
+ description: "为该聊天选择模型",
+ },
+ openProjectPicker: {
+ label: "打开项目选择器",
+ description: "从聊天标题栏切换到其他项目",
+ },
+ startDictation: {
+ label: "语音输入",
+ description: "开始或停止在输入框中语音输入",
+ },
+ attachFiles: {
+ label: "添加照片和文件",
+ description: "为输入框添加附件",
+ },
+ sendMessage: {
+ label: "发送消息",
+ description: "发送输入框中的内容",
+ },
+ cycleReasoningEffort: {
+ label: "循环切换推理强度",
+ description: "在各推理强度等级之间循环",
+ },
+ increaseReasoningEffort: {
+ label: "提高推理强度",
+ description: "将推理强度提高一级",
+ },
+ decreaseReasoningEffort: {
+ label: "降低推理强度",
+ description: "将推理强度降低一级",
+ },
+ toggleFastMode: {
+ label: "切换 Fast 模式",
+ description: "开启或关闭 Fast 模式",
+ },
+ renameChat: {
+ label: "重命名聊天",
+ description: "重命名当前聊天",
+ },
+ forkChat: {
+ label: "分叉聊天",
+ description: "从最后一条消息分出新的聊天",
+ },
+ copyChatAsMarkdown: {
+ label: "复制为 Markdown",
+ description: "将整个聊天以 Markdown 复制到剪贴板",
+ },
+ copySessionId: {
+ label: "复制会话 ID",
+ description: "复制该聊天的沙箱会话 ID",
},
},
},
diff --git a/studio/frontend/src/lib/copy-to-clipboard.ts b/studio/frontend/src/lib/copy-to-clipboard.ts
index a98b409bec5..f0b04e76f83 100644
--- a/studio/frontend/src/lib/copy-to-clipboard.ts
+++ b/studio/frontend/src/lib/copy-to-clipboard.ts
@@ -72,3 +72,46 @@ export async function copyToClipboard(text: string): Promise<boolean> {
// Fallback: execCommand (works in Safari when called during user gesture)
return copyWithExecCommand(text);
}
+
+/**
+ * Copy the result of a read that has to happen first, without losing the
+ * gesture that asked for it. Safari drops transient activation across an
+ * await, so both writers below fail when the text only arrives after one; the
+ * write starts synchronously with a promised payload instead, where the
+ * browser has it. A payload that rejects, which is how a caller says it found
+ * nothing to copy, leaves the clipboard untouched.
+ */
+export async function copyToClipboardFrom(
+ load: () => Promise<string>,
+): Promise<boolean> {
+ const payload = load();
+ // The write paths below each decide what to do with a rejection; this keeps
+ // it from being reported as unhandled in the meantime.
+ payload.catch(() => undefined);
+
+ if (
+ !isTauri &&
+ typeof ClipboardItem === "function" &&
+ typeof navigator?.clipboard?.write === "function"
+ ) {
+ try {
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ "text/plain": payload.then((text) => {
+ if (!text) throw new Error("nothing to copy");
+ return new Blob([text], { type: "text/plain" });
+ }),
+ }),
+ ]);
+ return true;
+ } catch (error) {
+ console.warn("Promised clipboard write failed, falling back", error);
+ }
+ }
+
+ try {
+ return await copyToClipboard(await payload);
+ } catch {
+ return false;
+ }
+}
diff --git a/studio/frontend/tests/chat-navigation-store.test.ts b/studio/frontend/tests/chat-navigation-store.test.ts
new file mode 100644
index 00000000000..a15d8fc5cc4
--- /dev/null
+++ b/studio/frontend/tests/chat-navigation-store.test.ts
@@ -0,0 +1,342 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ adjacentChatItem,
+ nextAttentionChatItem,
+ countUnreadRows,
+ recentChatItemAtSlot,
+ useChatNavigationStore,
+ visibleChatItems,
+} from "../src/features/chat/stores/chat-navigation-store.ts";
+import type { SidebarItem } from "../src/features/chat/hooks/use-chat-sidebar-items.ts";
+
+function row(id: string): SidebarItem {
+ return { id, title: id, type: "single", updatedAt: 0 } as SidebarItem;
+}
+
+const store = () => useChatNavigationStore.getState();
+
+/** Four rows, visited D, C, B, A, so the stack reads A, B, C, D. */
+function seed(): void {
+ useChatNavigationStore.setState({
+ recentlyViewedIds: [],
+ traversal: null,
+ unreadThreadIds: new Set(),
+ });
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: ["A", "B", "C", "D"].map(row),
+ attentionItemIds: [],
+ activeItemId: "A",
+ });
+ for (const id of ["D", "C", "B", "A"]) store().noteViewed(id);
+}
+
+/** One press: step, open the row, and let the sidebar note the new chat. */
+function press(delta: number): string | null {
+ const next = store().stepRecentlyViewed(delta);
+ if (!next) return null;
+ store().noteViewed(next.id);
+ useChatNavigationStore.setState({ activeItemId: next.id });
+ return next.id;
+}
+
+test("a held walk reaches past the second chat", () => {
+ seed();
+ assert.deepEqual(store().recentlyViewedIds, ["A", "B", "C", "D"]);
+ // Promoting each chat as the walk lands on it would swap the top two and
+ // send the next press straight back, stranding everything below them.
+ assert.deepEqual(
+ [press(1), press(1), press(1), press(1)],
+ ["B", "C", "D", "A"],
+ );
+});
+
+test("releasing the modifier puts the chat it landed on on top", () => {
+ seed();
+ press(1);
+ press(1);
+ assert.deepEqual(store().recentlyViewedIds, ["A", "B", "C", "D"]);
+ store().endTraversal();
+ assert.deepEqual(store().recentlyViewedIds, ["C", "A", "B", "D"]);
+ assert.equal(store().traversal, null);
+});
+
+test("tapping the chord toggles the two most recent chats", () => {
+ seed();
+ // Tap, release, tap: the same two chats, as an app switcher does.
+ const taps: (string | null)[] = [];
+ for (let i = 0; i < 3; i++) {
+ taps.push(press(1));
+ store().endTraversal();
+ }
+ assert.deepEqual(taps, ["B", "A", "B"]);
+});
+
+// A walk holds the stack still until it ends. If the release never arrives,
+// because the window went away with the modifier still down, the walk is
+// still running and the next press carries on from where it stopped.
+test("a walk left running sends the next press onward, not back", () => {
+ seed();
+ assert.equal(press(1), "B");
+ // The release lands in another app, so nothing ends the walk.
+ assert.deepEqual(store().recentlyViewedIds, ["A", "B", "C", "D"]);
+ assert.notEqual(store().traversal, null);
+ assert.equal(press(1), "C");
+
+ // Ending it on the way out is what makes the next press a toggle again.
+ seed();
+ assert.equal(press(1), "B");
+ store().endTraversal();
+ assert.deepEqual(store().recentlyViewedIds, ["B", "A", "C", "D"]);
+ assert.equal(press(1), "A");
+});
+
+test("a chat outside the stack walks onto the end it started from", () => {
+ seed();
+ // A brand new chat is in no stack, so the first press has to reach the most
+ // recently viewed one rather than stepping past it.
+ useChatNavigationStore.setState({ activeItemId: "unsaved", traversal: null });
+ assert.equal(store().stepRecentlyViewed(1)?.id, "A");
+ useChatNavigationStore.setState({ activeItemId: "unsaved", traversal: null });
+ assert.equal(store().stepRecentlyViewed(-1)?.id, "D");
+});
+
+test("walking backwards is the mirror of walking forwards", () => {
+ seed();
+ assert.deepEqual([press(-1), press(-1)], ["D", "C"]);
+});
+
+test("opening a chat by hand ends the walk and promotes it", () => {
+ seed();
+ press(1);
+ store().noteViewed("D");
+ assert.equal(store().traversal, null);
+ assert.deepEqual(store().recentlyViewedIds, ["D", "A", "B", "C"]);
+});
+
+test("a row that disappears mid-walk is stepped over", () => {
+ seed();
+ press(1);
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: ["A", "B", "D"].map(row),
+ attentionItemIds: [],
+ activeItemId: "B",
+ });
+ // C was next in the frozen order, and is gone.
+ assert.equal(press(1), "D");
+});
+
+test("an empty stack has nothing to walk", () => {
+ useChatNavigationStore.setState({ recentlyViewedIds: [], traversal: null });
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: [],
+ attentionItemIds: [],
+ activeItemId: null,
+ });
+ assert.equal(store().stepRecentlyViewed(1), null);
+ // Ending a walk that never began is a no-op, not a crash.
+ store().endTraversal();
+ assert.deepEqual(store().recentlyViewedIds, []);
+});
+
+test("the other navigation selectors read the published lists", () => {
+ seed();
+ assert.deepEqual(
+ visibleChatItems(store()).map((item) => item.id),
+ ["A", "B", "C", "D"],
+ );
+ assert.equal(recentChatItemAtSlot(store(), 2)?.id, "B");
+ assert.equal(adjacentChatItem(store(), 1)?.id, "B");
+ // Wraps at the top rather than stopping.
+ assert.equal(adjacentChatItem(store(), -1)?.id, "D");
+ assert.equal(nextAttentionChatItem(store()), null);
+});
+
+test("a chat that lives in a project folder is still navigable", () => {
+ useChatNavigationStore.setState({ recentlyViewedIds: [], traversal: null });
+ // Organized by project, an unpinned project chat is drawn under its folder
+ // and never reaches Recents, so it has to be published in its own right.
+ store().publishLists({
+ pinnedItems: [row("pinned")],
+ projectItems: [row("in-project")],
+ recentItems: [row("loose")],
+ attentionItemIds: [],
+ activeItemId: "in-project",
+ });
+ assert.deepEqual(
+ visibleChatItems(store()).map((item) => item.id),
+ ["pinned", "in-project", "loose"],
+ );
+ // Next from the project chat is its neighbour, not the top of the list.
+ assert.equal(adjacentChatItem(store(), 1)?.id, "loose");
+ assert.equal(adjacentChatItem(store(), -1)?.id, "pinned");
+});
+
+test("a row that moves project is republished, not kept by id", () => {
+ const inProject = (projectId: string) => ({
+ ...row("c1"),
+ projectId,
+ });
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [inProject("a")],
+ recentItems: [],
+ attentionItemIds: [],
+ activeItemId: "c1",
+ });
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [inProject("b")],
+ recentItems: [],
+ attentionItemIds: [],
+ activeItemId: "c1",
+ });
+ // The chords route with this projectId, so a stale one opens the chat in
+ // the project it just left.
+ assert.equal(visibleChatItems(store())[0].projectId, "b");
+});
+
+test("a title-only change does not republish", () => {
+ // The sidebar rebuilds its rows every render, so the guard has to hold for
+ // the fields nothing here reads, or every render writes to the store.
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: [row("c1")],
+ attentionItemIds: [],
+ activeItemId: "c1",
+ });
+ const before = visibleChatItems(store())[0];
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: [{ ...row("c1"), title: "renamed" }],
+ attentionItemIds: [],
+ activeItemId: "c1",
+ });
+ assert.equal(visibleChatItems(store())[0], before);
+});
+
+test("a pinned project chat is drawn twice but walked once", () => {
+ useChatNavigationStore.setState({ recentlyViewedIds: [], traversal: null });
+ store().publishLists({
+ pinnedItems: [row("both")],
+ projectItems: [row("both"), row("other")],
+ recentItems: [],
+ attentionItemIds: [],
+ activeItemId: "both",
+ });
+ assert.deepEqual(
+ visibleChatItems(store()).map((item) => item.id),
+ ["both", "other"],
+ );
+ assert.equal(adjacentChatItem(store(), 1)?.id, "other");
+});
+
+test("a Compare row counts once, not once per pane", () => {
+ const compare = {
+ id: "cmp",
+ title: "cmp",
+ type: "compare",
+ updatedAt: 0,
+ threadIds: ["left", "right"],
+ } as SidebarItem;
+ useChatNavigationStore.setState({ unreadThreadIds: new Set() });
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: [compare, row("A")],
+ attentionItemIds: [],
+ activeItemId: null,
+ });
+
+ // Both panes finishing marks the one row unread twice.
+ store().markThreadsUnread(["left", "right"]);
+ assert.equal(store().unreadThreadIds.size, 2);
+ assert.equal(countUnreadRows(store()), 1);
+
+ store().markThreadsUnread(["A"]);
+ assert.equal(countUnreadRows(store()), 2);
+});
+
+test("unreads whose row is gone still get a count", () => {
+ useChatNavigationStore.setState({ unreadThreadIds: new Set() });
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: [],
+ attentionItemIds: [],
+ activeItemId: null,
+ });
+ store().markThreadsUnread(["deleted-1", "deleted-2"]);
+ assert.equal(countUnreadRows(store()), 2);
+});
+
+test("an unread chat that left the list still counts", () => {
+ useChatNavigationStore.setState({ unreadThreadIds: new Set() });
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: [row("A")],
+ attentionItemIds: [],
+ activeItemId: null,
+ });
+ // One listed, one whose row was archived out from under it. Clearing wipes
+ // both, so reporting only the visible row undercounts what it did.
+ store().markThreadsUnread(["A", "gone"]);
+ assert.equal(countUnreadRows(store()), 2);
+});
+
+test("a hidden Compare row counts once, not once per pane", () => {
+ const compare = {
+ id: "cmp",
+ title: "cmp",
+ type: "compare",
+ updatedAt: 0,
+ threadIds: ["left", "right"],
+ } as SidebarItem;
+ useChatNavigationStore.setState({
+ unreadThreadIds: new Set(),
+ unreadRowIds: {},
+ });
+ // Marked while it was on screen, then the section closes and the published
+ // lists no longer carry it. Both threads stay unread.
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: [compare],
+ attentionItemIds: [],
+ activeItemId: null,
+ });
+ store().markThreadsUnread(["left", "right"], { left: "cmp", right: "cmp" });
+ assert.equal(countUnreadRows(store()), 1);
+ store().publishLists({
+ pinnedItems: [],
+ projectItems: [],
+ recentItems: [],
+ attentionItemIds: [],
+ activeItemId: null,
+ });
+ assert.equal(store().unreadThreadIds.size, 2);
+ assert.equal(countUnreadRows(store()), 1);
+});
+
+test("clearing an unread drops the row it was grouped under", () => {
+ useChatNavigationStore.setState({
+ unreadThreadIds: new Set(),
+ unreadRowIds: {},
+ });
+ store().markThreadsUnread(["left"], { left: "cmp" });
+ store().clearThreadsUnread(["left"]);
+ assert.deepEqual(store().unreadRowIds, {});
+});
diff --git a/studio/frontend/tests/conversation-markdown-export.test.ts b/studio/frontend/tests/conversation-markdown-export.test.ts
index 40eab123994..0c7dc61033d 100644
--- a/studio/frontend/tests/conversation-markdown-export.test.ts
+++ b/studio/frontend/tests/conversation-markdown-export.test.ts
@@ -3,7 +3,11 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { createConversationMarkdownExporter } from "../src/features/chat/utils/conversation-markdown-export.ts";
+import {
+ buildNamedConversationsMarkdown,
+ createConversationMarkdownBuilder,
+ createConversationMarkdownExporter,
+} from "../src/features/chat/utils/conversation-markdown-export.ts";
type TestMessage = {
readonly role: unknown;
@@ -83,3 +87,78 @@ test("notifies when every message is empty", async () => {
assert.deepEqual(downloads, []);
assert.deepEqual(notifications, ["empty"]);
});
+
+test("a compare pair copies with each half under its model", async () => {
+ const build = async (id: string) => `## User\n\nhi\n\n## Assistant\n\nfrom ${id}`;
+ const markdown = await buildNamedConversationsMarkdown(
+ [
+ { id: "thread-1", title: "Chat - Qwen3-8B" },
+ { id: "thread-2", title: "Chat - gpt-oss-20b" },
+ ],
+ build,
+ );
+ // Named, so the reader can tell which model wrote which answer.
+ assert.match(markdown, /^# Chat - Qwen3-8B\n\n## User/);
+ assert.ok(markdown.includes("\n---\n\n# Chat - gpt-oss-20b\n\n## User"));
+});
+
+test("a single chat copies exactly as the download writes it", async () => {
+ const body = "## User\n\nhi";
+ const markdown = await buildNamedConversationsMarkdown(
+ [{ id: "thread-1", title: "Chat" }],
+ async () => body,
+ );
+ assert.equal(markdown, body);
+});
+
+test("a half that loads nothing is dropped, not left as a bare heading", async () => {
+ const markdown = await buildNamedConversationsMarkdown(
+ [
+ { id: "thread-1", title: "Chat - base" },
+ { id: "thread-2", title: "Chat - fine-tuned" },
+ ],
+ async (id) => (id === "thread-1" ? "## User\n\nhi" : ""),
+ );
+ assert.equal(markdown, "# Chat - base\n\n## User\n\nhi");
+});
+
+test("a title carrying a line break stays on its heading", async () => {
+ const markdown = await buildNamedConversationsMarkdown(
+ [
+ { id: "thread-1", title: "Two\nlines - base" },
+ { id: "thread-2", title: "Two lines - lora" },
+ ],
+ async () => "## User\n\nhi",
+ );
+ assert.match(markdown, /^# Two lines - base\n\n## User/);
+});
+
+// Search results render their images from tokens the answer text carries. Both
+// ways out of a thread go through the one builder, so neither can start
+// shipping them as prose.
+test("renderer tokens never leave a thread, downloaded or copied", async () => {
+ const answer = "Golden Retriever\n\n[[img:0123456789ab]]\n\nDone.";
+ const stripped = "Golden Retriever\n\nDone.";
+ const messages: TestMessage[] = [{ role: "assistant", text: answer }];
+
+ const downloads: Array<{
+ content: string;
+ filename: string;
+ mimeType: string;
+ }> = [];
+ await exporterFor(messages, downloads, [])("thread-1");
+ assert.equal(downloads.length, 1);
+ assert.ok(!downloads[0].content.includes("[[img:"));
+ assert.ok(downloads[0].content.includes(stripped));
+
+ const build = createConversationMarkdownBuilder<TestMessage>({
+ loadMessages: async () => messages,
+ renderMessage: (message) => message.text,
+ });
+ const copied = await buildNamedConversationsMarkdown(
+ [{ id: "thread-1", title: "Dogs" }],
+ build,
+ );
+ assert.ok(!copied.includes("[[img:"));
+ assert.ok(copied.includes(stripped));
+});
diff --git a/studio/frontend/tests/keyboard-shortcuts.test.ts b/studio/frontend/tests/keyboard-shortcuts.test.ts
index df00e15b91c..a232006c895 100644
--- a/studio/frontend/tests/keyboard-shortcuts.test.ts
+++ b/studio/frontend/tests/keyboard-shortcuts.test.ts
@@ -6,10 +6,14 @@ import { readFile } from "node:fs/promises";
import test from "node:test";
import {
SHORTCUT_DEFS,
+ SHORTCUT_SLOTS,
bindingFromEvent,
+ defaultBindingFor,
formatBindingLabel,
formatBindingValue,
+ activationBelongsToFocus,
isAcceptableBinding,
+ isBrowserReservedBinding,
isShortcutId,
matchesBinding,
parseBinding,
@@ -17,8 +21,11 @@ import {
import {
KEYBOARD_SHORTCUTS_STORAGE_KEY,
findConflicts,
+ isSlotOverridden,
+ migrateStoredOverrides,
resolveAllBindings,
resolveBinding,
+ resolveBindings,
shortcutOwningBinding,
} from "../src/features/settings/stores/keyboard-shortcuts-store.ts";
import { SETTINGS_TABS } from "../src/features/settings/stores/settings-dialog-store.ts";
@@ -30,15 +37,19 @@ function keyEvent(
ctrlKey: boolean;
shiftKey: boolean;
altKey: boolean;
+ /** What a Windows or Linux layout reports for AltGr, alongside Ctrl+Alt. */
+ altGraph: boolean;
}> = {},
) {
+ const { altGraph = false, ...rest } = mods;
return {
code,
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
- ...mods,
+ ...rest,
+ getModifierState: (key: string) => key === "AltGraph" && altGraph,
};
}
@@ -62,16 +73,106 @@ test("parse rejects junk, empties and modifier-only values", () => {
assert.equal(parseBinding("Hyper+KeyO"), null);
});
-test("every shipped default parses", () => {
+test("every shipped default parses, on either platform", () => {
for (const def of SHORTCUT_DEFS) {
- if (def.defaultBinding === null) continue;
- assert.ok(
- parseBinding(def.defaultBinding),
- `${def.id} has an unparseable default: ${def.defaultBinding}`,
- );
+ for (const mac of [true, false]) {
+ for (const slot of SHORTCUT_SLOTS) {
+ const value = defaultBindingFor(def, slot, mac);
+ if (value === null) continue;
+ assert.ok(
+ parseBinding(value),
+ `${def.id}.${slot} has an unparseable default: ${value}`,
+ );
+ }
+ }
+ }
+});
+
+// formatBindingValue emits Mod, Ctrl, Alt, Shift, key. A default written in any
+// other order would never equal a chord the recorder produces, so rebinding to
+// the shipped chord would read as a change and the reset button would never
+// appear to have worked.
+test("every shipped default is already in canonical order", () => {
+ for (const def of SHORTCUT_DEFS) {
+ for (const mac of [true, false]) {
+ for (const slot of SHORTCUT_SLOTS) {
+ const value = defaultBindingFor(def, slot, mac);
+ if (value === null) continue;
+ const parsed = parseBinding(value);
+ assert.ok(parsed);
+ assert.equal(
+ formatBindingValue(parsed),
+ value,
+ `${def.id}.${slot} is not canonical: ${value}`,
+ );
+ }
+ }
+ }
+});
+
+// Off macOS there is no ⌃-versus-⌘ distinction, so a Ctrl-only default would be
+// both unreachable and a duplicate of the Mod row. Those actions must ship a
+// different chord there.
+test("no Ctrl-only default survives onto Windows and Linux", () => {
+ for (const def of SHORTCUT_DEFS) {
+ for (const slot of SHORTCUT_SLOTS) {
+ const parsed = parseBinding(defaultBindingFor(def, slot, false));
+ if (!parsed) continue;
+ assert.ok(
+ !parsed.ctrl,
+ `${def.id}.${slot} keeps a Ctrl chord off macOS: ${formatBindingValue(parsed)}`,
+ );
+ }
}
});
+test("a focused control keeps its own Enter", () => {
+ const enter = parseBinding("Enter");
+ assert.ok(enter);
+ const deny = { tagName: "BUTTON", getAttribute: () => null };
+ // preventDefault on a window keydown cancels the click the browser would
+ // have made, so approving here would overrule the button the user picked.
+ assert.equal(activationBelongsToFocus(enter, deny), true);
+ assert.equal(activationBelongsToFocus(enter, null), false);
+ assert.equal(
+ activationBelongsToFocus(enter, { tagName: "DIV", getAttribute: () => null }),
+ false,
+ );
+ // A div acting as a button counts too.
+ assert.equal(
+ activationBelongsToFocus(enter, {
+ tagName: "DIV",
+ getAttribute: (name: string) => (name === "role" ? "button" : null),
+ }),
+ true,
+ );
+ // Escape activates nothing, so declining still works from any focus.
+ const escape = parseBinding("Escape");
+ assert.ok(escape);
+ assert.equal(activationBelongsToFocus(escape, deny), false);
+ // A chord with a modifier is nobody else's.
+ const modEnter = parseBinding("Mod+Enter");
+ assert.ok(modEnter);
+ assert.equal(activationBelongsToFocus(modEnter, deny), false);
+});
+
+test("nothing that deletes chats ships on a chord", () => {
+ const del = SHORTCUT_DEFS.find((def) => def.id === "deleteSelectedChats");
+ assert.ok(del);
+ for (const slot of SHORTCUT_SLOTS) {
+ for (const mac of [true, false]) {
+ assert.equal(defaultBindingFor(del, slot, mac), null);
+ }
+ }
+});
+
+test("an unassigned action ships both slots empty", () => {
+ const forkChat = SHORTCUT_DEFS.find((def) => def.id === "forkChat");
+ assert.ok(forkChat);
+ assert.equal(defaultBindingFor(forkChat, "primary", true), null);
+ assert.equal(defaultBindingFor(forkChat, "alternate", true), null);
+});
+
test("matching is exact about modifiers", () => {
const binding = parseBinding("Mod+Shift+KeyO");
assert.ok(binding);
@@ -132,6 +233,307 @@ test("on macOS Mod is Cmd, and a bare Ctrl is not a substitute", () => {
);
});
+test("a Ctrl chord from a Mac cannot fire on Windows or Linux", () => {
+ // Ctrl is Mod off macOS, so this value is unreachable there. What it must
+ // not do is drop the modifier it cannot express and fire on the bare key.
+ const binding = parseBinding("Ctrl+KeyB");
+ assert.ok(binding);
+ assert.equal(matchesBinding(binding, keyEvent("KeyB"), false), false);
+ assert.equal(
+ matchesBinding(binding, keyEvent("KeyB", { ctrlKey: true }), false),
+ false,
+ );
+});
+
+test("AltGr typing does not fire an Alt chord off macOS", () => {
+ const binding = parseBinding("Mod+Alt+KeyC");
+ assert.ok(binding);
+ // A real Ctrl+Alt press on a US layout still works.
+ assert.ok(
+ matchesBinding(
+ binding,
+ keyEvent("KeyC", { ctrlKey: true, altKey: true }),
+ false,
+ ),
+ );
+ // AltGr+C, which types ć on a Polish layout, must not.
+ assert.equal(
+ matchesBinding(
+ binding,
+ keyEvent("KeyC", { ctrlKey: true, altKey: true, altGraph: true }),
+ false,
+ ),
+ false,
+ );
+ assert.equal(
+ bindingFromEvent(
+ keyEvent("KeyC", { ctrlKey: true, altKey: true, altGraph: true }),
+ false,
+ ),
+ null,
+ );
+});
+
+test("macOS Option still fires an ⌥ chord when AltGraph is reported", () => {
+ // WebKit and Chromium report AltGraph for Option, so the guard above has to
+ // stay off macOS or every ⌥ chord in the list would stop working.
+ const binding = parseBinding("Mod+Alt+KeyC");
+ assert.ok(binding);
+ assert.ok(
+ matchesBinding(
+ binding,
+ keyEvent("KeyC", { metaKey: true, altKey: true, altGraph: true }),
+ true,
+ ),
+ );
+});
+
+test("the tab-search chord counts as browser-owned on both platforms", () => {
+ // Chrome's tab search on both, and Firefox's add-ons manager off macOS, so
+ // the tab warns about it wherever a user picks it.
+ assert.ok(isBrowserReservedBinding("Mod+Shift+KeyA", true));
+ assert.ok(isBrowserReservedBinding("Mod+Shift+KeyA", false));
+});
+
+// The walk is the one chord whose end is a key coming up rather than going
+// down, so it is the one that a window losing focus can strand.
+test("the recent walk ends on losing the window, not just on keyup", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ const at = sidebar.indexOf("const end = () =>");
+ assert.ok(at !== -1, "the traversal listener moved");
+ const body = sidebar.slice(at, sidebar.indexOf("}, []);", at));
+ // Both signals reach the same end, and both are torn down again.
+ assert.match(body, /window\.addEventListener\("keyup", onKeyUp\);/);
+ assert.match(body, /window\.addEventListener\("blur", end\);/);
+ assert.match(body, /window\.removeEventListener\("blur", end\);/);
+ // Still only once every modifier is up: a walk is held, so a Tab release
+ // with Ctrl still down is mid-walk, not the end of it.
+ assert.match(
+ body,
+ /if \(event\.ctrlKey \|\| event\.metaKey \|\| event\.altKey \|\| event\.shiftKey\)/,
+ );
+});
+
+// Firefox's new private window, which no page can cancel. Chrome's incognito
+// on ⇧⌘N was already reserved; this is the other half of the same pair.
+test("the private-window chord is reserved and carries no default", () => {
+ for (const mac of [true, false]) {
+ assert.ok(isBrowserReservedBinding("Mod+Shift+KeyP", mac));
+ assert.ok(isBrowserReservedBinding("Mod+Shift+KeyN", mac));
+ }
+ // Search keeps ⌘K alone rather than moving the alternate somewhere else.
+ const search = SHORTCUT_DEFS.find((d) => d.id === "searchChats");
+ assert.ok(search);
+ for (const mac of [true, false]) {
+ assert.equal(defaultBindingFor(search, "primary", mac), "Mod+KeyK");
+ assert.equal(defaultBindingFor(search, "alternate", mac), null);
+ }
+});
+
+// Train and Video are the two rows the sidebar grays out on a measured
+// verdict, so they are the two workspace chords that can put a gate where the
+// user's workspace was.
+test("the workspace chords land where the guard lets them", async () => {
+ const root = await readFile(
+ new URL("../src/app/routes/__root.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ root,
+ /const chatOnlyMeasured = usePlatformStore\(\n\s*\(s\) => s\.isChatOnly\(\) && !s\.capabilitiesUnknown\(\),/,
+ );
+ assert.match(
+ root,
+ /useShortcut\("switchToTrain", goTo\("\/studio"\), \{\n\s*enabled: !isAuthFlowRoute && !chatOnlyMeasured,/,
+ );
+ // Video has its own predicate rather than the chat-only one: /video checks
+ // auth and nothing else, so the chord would land on the unsupported-hardware
+ // gate. Read through the same helper the disabled row reads.
+ assert.match(
+ root,
+ /const videoDisabled =\n\s*videoNavHint\(chatOnlyMeasured, chatOnlyReason\) !== undefined;/,
+ );
+ assert.match(
+ root,
+ /useShortcut\("switchToVideo", goTo\("\/video"\), \{\n\s*enabled: !isAuthFlowRoute && !videoDisabled,/,
+ );
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ sidebar,
+ /const videoDisabledHint = videoNavHint\(chatOnlyMeasured, chatOnlyReason\);/,
+ );
+ assert.match(sidebar, /disabled: videoDisabled,/);
+
+ // The rest are on the allowlist, so they stay reachable and ungated: gating
+ // them would take away a page the guard is happy to serve.
+ for (const [id, path] of [
+ ["switchToProjects", "/projects"],
+ ["switchToHub", "/hub"],
+ ["switchToExport", "/export"],
+ ] as const) {
+ const at = root.indexOf(`useShortcut("${id}"`);
+ assert.ok(at !== -1, `${id} lost its call site`);
+ assert.ok(
+ !root.slice(at, root.indexOf(");", at)).includes("chatOnlyMeasured"),
+ `${id} gated on a verdict its route does not answer to`,
+ );
+ assert.match(root, new RegExp(`goTo\\("${path.replace("/", "\\/")}"\\)`));
+ }
+});
+
+// A chord behind a hidden developer menu is not one the browser took from the
+// user, and these sets drive a warning the user reads. Safari has both of
+// these, but only once the Develop menu is switched on, so reserving them
+// would tell every macOS user something untrue about their own keyboard.
+test("an opt-in developer chord is not treated as taken", () => {
+ for (const value of ["Mod+Alt+KeyE", "Mod+Alt+KeyR"]) {
+ for (const mac of [true, false]) {
+ assert.equal(
+ isBrowserReservedBinding(value, mac),
+ false,
+ `${value} warns about a menu most users never turn on`,
+ );
+ }
+ }
+ // So they stay usable as defaults, which is where the chat chords sit.
+ for (const [id, value] of [
+ ["archiveChat", "Mod+Alt+KeyE"],
+ ["renameChat", "Mod+Alt+KeyR"],
+ ] as const) {
+ const def = SHORTCUT_DEFS.find((d) => d.id === id);
+ assert.ok(def);
+ assert.equal(defaultBindingFor(def, "primary", true), value);
+ }
+ // The bar is what the browser takes out of the box, which ⌥⌘U is: Chrome
+ // ships view source on it with nothing to enable.
+ assert.ok(isBrowserReservedBinding("Mod+Alt+KeyU", true));
+});
+
+test("the browsers' own run on macOS is reserved there and only there", () => {
+ // ⌥⌘ is Chrome's run: view source, dev tools, console, bookmarks, split
+ // view, web search, Page Setup, tab switching; Firefox adds its element
+ // picker and console. Off macOS these read as Ctrl+Alt, which none claim.
+ const macOwned = [
+ "Mod+Alt+KeyU",
+ "Mod+Alt+KeyP",
+ "Mod+Alt+KeyI",
+ "Mod+Alt+KeyJ",
+ "Mod+Alt+KeyB",
+ "Mod+Alt+KeyN",
+ "Mod+Alt+KeyF",
+ "Mod+Alt+KeyC",
+ "Mod+Alt+KeyK",
+ "Mod+Alt+ArrowLeft",
+ "Mod+Alt+ArrowRight",
+ "Mod+Alt+ArrowUp",
+ "Mod+Alt+ArrowDown",
+ ];
+ for (const value of macOwned) {
+ assert.ok(isBrowserReservedBinding(value, true), `${value} unflagged`);
+ assert.equal(
+ isBrowserReservedBinding(value, false),
+ false,
+ `${value} warns off macOS for nothing`,
+ );
+ }
+ // The letters left on that run stay usable, or the chat chords lose the
+ // family they are built on.
+ for (const value of [
+ "Mod+Alt+KeyE",
+ "Mod+Alt+KeyO",
+ "Mod+Alt+KeyS",
+ "Mod+Alt+KeyA",
+ "Mod+Alt+KeyR",
+ "Mod+Alt+Digit1",
+ ]) {
+ assert.equal(isBrowserReservedBinding(value, true), false, value);
+ }
+});
+
+// Three actions whose macOS chord Chrome owns: view source, the element picker
+// and Page Setup. Each keeps its letter on the run the composer pair uses, so
+// the mnemonic survives the platform swap.
+test("view source, the element picker and Page Setup carry no Studio action", () => {
+ for (const [id, mac, other] of [
+ ["toggleApiMonitor", "Ctrl+Shift+KeyU", "Mod+Alt+Shift+KeyM"],
+ ["copySessionId", "Ctrl+Shift+KeyC", "Mod+Alt+KeyC"],
+ ["togglePinChat", "Ctrl+Shift+KeyP", "Mod+Alt+KeyP"],
+ ] as const) {
+ const def = SHORTCUT_DEFS.find((d) => d.id === id);
+ assert.ok(def);
+ assert.equal(defaultBindingFor(def, "primary", true), mac);
+ assert.equal(defaultBindingFor(def, "primary", false), other);
+ assert.equal(isBrowserReservedBinding(mac, true), false);
+ assert.equal(isBrowserReservedBinding(other, false), false);
+ }
+ // The API monitor is the one that gives its letter up rather than swapping
+ // runs: off macOS U carries the two unread actions and has nothing left.
+ for (const [id, value] of [
+ ["markChatUnread", "Mod+Alt+KeyU"],
+ ["clearAllUnreads", "Mod+Alt+Shift+KeyU"],
+ ] as const) {
+ const def = SHORTCUT_DEFS.find((d) => d.id === id);
+ assert.ok(def);
+ assert.equal(defaultBindingFor(def, "primary", false), value);
+ }
+});
+
+// GTK binds hex entry to Ctrl+Shift+U in GtkIMContextSimple, and IBus binds it
+// again, so off macOS that chord belongs to text composition. A composer with
+// focus is where Mark unread is most likely to be pressed, so it cannot be a
+// chord the input method is also listening for.
+test("no default sits on Linux's own text-composition prefix", () => {
+ for (const def of SHORTCUT_DEFS) {
+ for (const slot of SHORTCUT_SLOTS) {
+ assert.notEqual(
+ defaultBindingFor(def, slot, false),
+ "Mod+Shift+KeyU",
+ `${def.id}.${slot} ships GTK's hex-entry prefix off macOS`,
+ );
+ }
+ }
+ // Still fine on macOS, which has no such prefix.
+ const unread = SHORTCUT_DEFS.find((d) => d.id === "markChatUnread");
+ assert.ok(unread);
+ assert.equal(defaultBindingFor(unread, "primary", true), "Mod+Shift+KeyU");
+});
+
+test("no default takes a chord the browser owns without a reason", () => {
+ // The exceptions are the spec chords Studio keeps for the desktop build,
+ // where they work; everything else has to be reachable on the web.
+ const deliberate = new Set([
+ "Mod+KeyN",
+ "Mod+Shift+KeyN",
+ "Mod+Tab",
+ "Mod+Shift+Tab",
+ "Ctrl+Tab",
+ "Ctrl+Shift+Tab",
+ // The chat walk. Safari and Chrome own the bracket pair on macOS only, and
+ // the desktop build is where these are pressed.
+ "Mod+Shift+BracketLeft",
+ "Mod+Shift+BracketRight",
+ ]);
+ for (const def of SHORTCUT_DEFS) {
+ for (const slot of SHORTCUT_SLOTS) {
+ for (const mac of [true, false]) {
+ const value = defaultBindingFor(def, slot, mac);
+ if (!value || deliberate.has(value)) continue;
+ assert.equal(
+ isBrowserReservedBinding(value, mac),
+ false,
+ `${def.id}.${slot} defaults to ${value}, which the browser owns (mac=${mac})`,
+ );
+ }
+ }
+ }
+});
+
test("recording a chord ignores a lone modifier", () => {
assert.equal(
bindingFromEvent(keyEvent("ShiftLeft", { shiftKey: true }), false),
@@ -169,6 +571,80 @@ test("a bare letter is refused but function keys stand alone", () => {
alt: false,
}),
);
+ // Enter is bare, and only allowed for the two actions that register solely
+ // while an approval prompt is on screen.
+ const enter = {
+ code: "Enter",
+ mod: false,
+ ctrl: false,
+ shift: false,
+ alt: false,
+ };
+ assert.equal(isAcceptableBinding(enter), false);
+ assert.ok(isAcceptableBinding(enter, true));
+});
+
+test("bare Escape is the recorder's own exit, so only a prompt-gated row takes it", async () => {
+ const bare = {
+ code: "Escape",
+ mod: false,
+ ctrl: false,
+ shift: false,
+ alt: false,
+ };
+ assert.equal(isAcceptableBinding(bare), false);
+ assert.ok(isAcceptableBinding(bare, true));
+ // Shift keeps it clear of the exit, which is where clearAllUnreads ships.
+ assert.ok(isAcceptableBinding({ ...bare, shift: true }));
+
+ // The recorder swallows every keydown, so bare Escape has to stay its way
+ // out, except on the rows whose own chord it is.
+ const tab = await readFile(
+ new URL(
+ "../src/features/settings/tabs/keyboard-shortcuts-tab.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(
+ tab,
+ /event\.code === "Escape" &&\n(?:\s*![a-zA-Z.]+ &&\n)+\s*!def\?\.allowBareKey\n\s*\) \{\n\s*setRecording\(null\);/,
+ );
+
+ // Which leaves no shipped bare Escape that its own tab could not record.
+ for (const def of SHORTCUT_DEFS) {
+ for (const slot of SHORTCUT_SLOTS) {
+ for (const mac of [true, false]) {
+ if (defaultBindingFor(def, slot, mac) !== "Escape") continue;
+ assert.ok(
+ def.allowBareKey,
+ `${def.id}.${slot} ships bare Escape without allowBareKey`,
+ );
+ }
+ }
+ }
+});
+
+test("only prompt-gated actions ship a bare-key default", () => {
+ for (const def of SHORTCUT_DEFS) {
+ for (const slot of SHORTCUT_SLOTS) {
+ for (const mac of [true, false]) {
+ const parsed = parseBinding(defaultBindingFor(def, slot, mac));
+ if (!parsed) continue;
+ assert.ok(
+ isAcceptableBinding(parsed, def.allowBareKey),
+ `${def.id}.${slot} ships a chord the recorder would refuse`,
+ );
+ }
+ }
+ }
+ const bareKeyIds = SHORTCUT_DEFS.filter((def) => def.allowBareKey).map(
+ (def) => def.id,
+ );
+ assert.deepEqual(bareKeyIds.sort(), [
+ "approveToolRequest",
+ "declineToolRequest",
+ ]);
});
test("labels use each platform's own modifier notation", () => {
@@ -184,29 +660,171 @@ test("labels use each platform's own modifier notation", () => {
test("an override wins, and null means unassigned", () => {
assert.equal(resolveBinding({}, "toggleSidebar"), "Mod+KeyB");
assert.equal(
- resolveBinding({ toggleSidebar: "Mod+Alt+KeyB" }, "toggleSidebar"),
+ resolveBinding(
+ { toggleSidebar: { primary: "Mod+Alt+KeyB" } },
+ "toggleSidebar",
+ ),
"Mod+Alt+KeyB",
);
// Present-but-null is a deliberate clear, not a fallback to the default.
- assert.equal(resolveBinding({ toggleSidebar: null }, "toggleSidebar"), null);
+ assert.equal(
+ resolveBinding({ toggleSidebar: { primary: null } }, "toggleSidebar"),
+ null,
+ );
+ // Overriding one slot leaves the other on its shipped chord. newChat, not
+ // nextChat: the ⌥⌘→ pair is macOS only, and resolveBinding reads the host's
+ // platform, so asserting it here would pass on a Mac and fail on CI.
+ assert.equal(
+ resolveBinding({ newChat: { primary: null } }, "newChat", "alternate"),
+ "Mod+KeyN",
+ );
+});
+
+test("both slots resolve together", () => {
+ // Platform-independent chords only: resolveBindings reads the host's.
+ assert.deepEqual(resolveBindings({}, "newChat"), {
+ primary: "Mod+Shift+KeyO",
+ alternate: "Mod+KeyN",
+ });
+ assert.deepEqual(resolveBindings({}, "archiveChat"), {
+ primary: "Mod+Alt+KeyE",
+ alternate: null,
+ });
+});
+
+test("the chat walk ships no arrow alternate on either platform", () => {
+ // ⌥⌘→ is Chrome's own next tab, and the same chord off macOS is Ctrl+Alt+→,
+ // desktop switching on GNOME and KDE. Taken everywhere, so the bracket pair
+ // carries these alone.
+ for (const id of ["nextChat", "previousChat"] as const) {
+ const def = SHORTCUT_DEFS.find((d) => d.id === id);
+ assert.ok(def);
+ for (const mac of [true, false]) {
+ assert.equal(defaultBindingFor(def, "alternate", mac), null);
+ }
+ assert.match(
+ String(defaultBindingFor(def, "primary", true)),
+ /^Mod\+Shift\+Bracket(Left|Right)$/,
+ );
+ }
+ assert.ok(isBrowserReservedBinding("Mod+Alt+ArrowRight", true));
+ assert.ok(isBrowserReservedBinding("Mod+Alt+ArrowLeft", true));
+});
+
+test("a slot reports whether it carries an edit", () => {
+ assert.equal(isSlotOverridden({}, "nextChat", "primary"), false);
+ const overrides = { nextChat: { alternate: null } };
+ assert.equal(isSlotOverridden(overrides, "nextChat", "primary"), false);
+ assert.ok(isSlotOverridden(overrides, "nextChat", "alternate"));
});
-test("defaults ship without conflicts", () => {
+// Builds before alternates existed stored `id -> string | null`. Read as-is,
+// that shape would resolve to nothing and silently revert every customization
+// made since the shortcuts tab shipped.
+test("the pre-alternate override shape migrates to the primary slot", () => {
+ const legacy = JSON.stringify({
+ toggleSidebar: "Mod+Alt+KeyB",
+ searchChats: null,
+ newChat: "Mod+Alt+KeyJ",
+ someRemovedAction: "Mod+KeyZ",
+ });
+ const migrated = migrateStoredOverrides(JSON.parse(legacy));
+ assert.deepEqual(migrated, {
+ toggleSidebar: { primary: "Mod+Alt+KeyB" },
+ // A clear reaches both slots, a rebind only the one the user set.
+ searchChats: { primary: null, alternate: null },
+ newChat: { primary: "Mod+Alt+KeyJ" },
+ });
+ assert.equal(resolveBinding(migrated, "toggleSidebar"), "Mod+Alt+KeyB");
+ assert.equal(resolveBinding(migrated, "searchChats"), null);
+ // The alternate is untouched, so the shipped one still reaches a user who
+ // rebound the primary before alternates existed.
+ assert.equal(resolveBinding(migrated, "newChat", "alternate"), "Mod+KeyN");
+});
+
+// Back then an action had one chord, so a stored null meant the action was
+// off. Clearing only the primary would hand it whatever alternate has shipped
+// since and switch it back on, which is what newChat carries on ⌘N.
+test("an action cleared before alternates existed stays cleared", () => {
+ const migrated = migrateStoredOverrides(JSON.parse('{"newChat":null}'));
+ assert.deepEqual(migrated, { newChat: { primary: null, alternate: null } });
+ assert.deepEqual(resolveBindings(migrated, "newChat"), {
+ primary: null,
+ alternate: null,
+ });
+ // The shipped alternate is real, so this is the slot that would have come
+ // back had the clear stopped at the primary.
+ const shipped = SHORTCUT_DEFS.find((d) => d.id === "newChat");
+ assert.ok(shipped);
+ assert.equal(defaultBindingFor(shipped, "alternate", true), "Mod+KeyN");
+ // Both slots read as edits, so the tab offers to reset them.
+ for (const slot of SHORTCUT_SLOTS) {
+ assert.ok(isSlotOverridden(migrated, "newChat", slot), slot);
+ }
+});
+
+test("the current override shape round-trips unchanged", () => {
+ const stored = { nextChat: { primary: "Mod+KeyG", alternate: null } };
+ assert.deepEqual(migrateStoredOverrides(stored), stored);
+});
+
+test("defaults ship without conflicts on either platform", () => {
+ // findConflicts resolves against this process's platform, so check the other
+ // one by hand: ⌘1-9 and ⌃1-9 collapse onto each other off macOS, and the
+ // registry has to have moved one of them.
assert.equal(findConflicts({}).size, 0);
+ for (const mac of [true, false]) {
+ const seen = new Map<string, string>();
+ for (const def of SHORTCUT_DEFS) {
+ for (const slot of SHORTCUT_SLOTS) {
+ const value = defaultBindingFor(def, slot, mac);
+ if (value === null) continue;
+ const owner = seen.get(value);
+ assert.ok(
+ owner === undefined || owner === def.id,
+ `${value} is claimed by both ${owner} and ${def.id} (mac=${mac})`,
+ );
+ seen.set(value, def.id);
+ }
+ }
+ }
const all = resolveAllBindings({});
- assert.equal(all.newChat, "Mod+Shift+KeyO");
+ assert.equal(all.newChat.primary, "Mod+Shift+KeyO");
+ assert.equal(all.newChat.alternate, "Mod+KeyN");
});
test("two actions on one chord are both flagged", () => {
- const conflicts = findConflicts({ toggleSidebar: "Mod+KeyK" });
+ const conflicts = findConflicts({ toggleSidebar: { primary: "Mod+KeyK" } });
assert.deepEqual(
[...conflicts].sort(),
["searchChats", "toggleSidebar"].sort(),
);
});
+// A clash across slots is just as real as one between two primaries: both
+// chords fire the same listener path, so the tab has to say so.
+test("an alternate clashing with another action's primary is flagged", () => {
+ const conflicts = findConflicts({
+ archiveChat: { alternate: "Mod+KeyB" },
+ });
+ assert.deepEqual(
+ [...conflicts].sort(),
+ ["archiveChat", "toggleSidebar"].sort(),
+ );
+});
+
+test("an action's own two slots never conflict with each other", () => {
+ const conflicts = findConflicts({
+ archiveChat: { alternate: "Mod+Alt+KeyE" },
+ });
+ assert.equal(conflicts.size, 0);
+});
+
test("cleared actions never count as conflicting", () => {
- const conflicts = findConflicts({ toggleSidebar: null, searchChats: null });
+ const conflicts = findConflicts({
+ toggleSidebar: { primary: null },
+ searchChats: { primary: null, alternate: null },
+ });
assert.equal(conflicts.size, 0);
});
@@ -215,31 +833,53 @@ test("ids from an older build are rejected", () => {
assert.equal(isShortcutId("someRemovedAction"), false);
});
+/** Position in SHORTCUT_DEFS, which is what ownership is decided by. */
+const registryIndex = (id: string) =>
+ SHORTCUT_DEFS.findIndex((def) => def.id === id);
+
test("a contested chord is owned by the earlier action in registry order", () => {
- // searchChats is declared before toggleSidebar, so it keeps Mod+K.
- const overrides = { toggleSidebar: "Mod+KeyK" };
- assert.equal(shortcutOwningBinding(overrides, "Mod+KeyK"), "searchChats");
+ // Derived, not hard-coded: the list is deliberately ordered for the UI, so a
+ // reorder must keep this rule rather than trip a name-shaped assertion.
+ const overrides = { toggleSidebar: { primary: "Mod+KeyK" } };
+ const owner = shortcutOwningBinding(overrides, "Mod+KeyK");
+ assert.ok(owner);
+ const claimants = ["searchChats", "toggleSidebar"];
+ assert.deepEqual(
+ owner,
+ claimants.sort((a, b) => registryIndex(a) - registryIndex(b))[0],
+ );
// The loser keeps its own binding elsewhere, so ownership is per chord.
assert.equal(shortcutOwningBinding(overrides, "Mod+Comma"), "openSettings");
});
test("exactly one owner exists per contested chord", () => {
- const overrides = { toggleSidebar: "Mod+KeyK", newChat: "Mod+KeyK" };
+ const overrides = {
+ toggleSidebar: { primary: "Mod+KeyK" },
+ newChat: { primary: "Mod+KeyK" },
+ };
const contested = [...findConflicts(overrides)];
assert.equal(contested.length, 3);
const owners = new Set(
contested.map(() => shortcutOwningBinding(overrides, "Mod+KeyK")),
);
assert.equal(owners.size, 1);
- // newChat is declared first, so it wins over searchChats and toggleSidebar.
- assert.equal(shortcutOwningBinding(overrides, "Mod+KeyK"), "newChat");
+ assert.equal(
+ shortcutOwningBinding(overrides, "Mod+KeyK"),
+ contested.sort((a, b) => registryIndex(a) - registryIndex(b))[0],
+ );
});
test("an unbound or unclaimed chord has no owner", () => {
assert.equal(shortcutOwningBinding({}, null), null);
assert.equal(shortcutOwningBinding({}, "Mod+Alt+KeyZ"), null);
// A cleared action does not own the chord it used to have.
- assert.equal(shortcutOwningBinding({ searchChats: null }, "Mod+KeyK"), null);
+ assert.equal(
+ shortcutOwningBinding(
+ { searchChats: { primary: null } },
+ "Mod+KeyK",
+ ),
+ null,
+ );
});
// Reset-all is the documented escape hatch. A chord bound to something the
@@ -280,21 +920,541 @@ test("every locale overlay carries the shortcut strings", async () => {
`${locale} is missing the settings.keyboardShortcuts subtree`,
);
const subtree = source.slice(at, source.indexOf("\n },", at));
- for (const key of ["title", "resetAll", "conflictShadowed", "groups"]) {
+ for (const key of ["title", "resetAll", "conflictShadowed", "unassigned"]) {
assert.ok(
subtree.includes(`${key}:`),
`${locale} is missing settings.keyboardShortcuts.${key}`,
);
}
for (const def of SHORTCUT_DEFS) {
- assert.ok(
- subtree.includes(`${def.id}: {`),
- `${locale} is missing settings.keyboardShortcuts.actions.${def.id}`,
+ // Both halves: a row with a label and no description renders an empty
+ // second line rather than falling back to English.
+ const row = new RegExp(
+ `\\n ${def.id}: \\{\\n label: "[^"]+",\\n description: "[^"]+",\\n \\},`,
+ );
+ assert.match(
+ subtree,
+ row,
+ `${locale} is missing a label or description for settings.keyboardShortcuts.actions.${def.id}`,
);
}
}
});
+test("a cleared alternate keeps its row, so it can be restored", async () => {
+ const source = await readFile(
+ new URL("../src/features/settings/tabs/keyboard-shortcuts-tab.tsx", import.meta.url),
+ "utf8",
+ );
+ // Clearing a slot stores null, so a row that keys off the resolved value
+ // alone would hide the slot's own restore control along with the chord.
+ assert.match(
+ source,
+ /hasAlternate =\s*\n\s*defaultBindingFor\(def, "alternate", mac\) !== null/,
+ );
+});
+
+test("the chords that need one target do not fire where there are two", async () => {
+ // No React renderer here, so this asserts on source, like its siblings.
+ const read = async (path: string) =>
+ readFile(new URL(path, import.meta.url), "utf8");
+ const chatPage = await read("../src/features/chat/chat-page.tsx");
+ const thread = await read("../src/components/assistant-ui/thread.tsx");
+ const toolCard = await read(
+ "../src/components/assistant-ui/tool-confirmation-controls.tsx",
+ );
+
+ // Compare drops the header pickers and gives each pane its own, so the
+ // header chord would toggle state nothing renders.
+ assert.match(
+ chatPage,
+ /const headerPickersShown = active && view\.mode !== "compare";/,
+ );
+ assert.match(chatPage, /enabled: headerPickersShown[,\s]*\}/);
+ // Both panes mount the last message, and the chord would go to whichever
+ // registered its listener first. `If last` carries the other half.
+ assert.match(thread, /enabled: chatActive && !inComparePane && !forkDisabled/);
+ // Same for a second parked tool request: neither card claims the keys.
+ assert.match(
+ toolCard,
+ /soleRequest &&\n\s*!selectionActive &&\n\s*showControls &&/,
+ );
+});
+
+// Both of these open a surface whose "is it open" flag outlives the thing it
+// opens, so leaving without closing brings it back on the next visit.
+test("a chord's surface does not come back open on the next visit", async () => {
+ const read = async (path: string) =>
+ readFile(new URL(path, import.meta.url), "utf8");
+ const chatPage = await read("../src/features/chat/chat-page.tsx");
+ const mcp = await read("../src/features/chat/mcp-composer-button.tsx");
+
+ // The switcher renders on Chat, outside Compare, with a project. Reading the
+ // whole condition means Compare and a standalone chat reset it too, not just
+ // going off-route.
+ assert.match(
+ chatPage,
+ /const projectSwitcherShown = headerPickersShown && Boolean\(currentProjectId\);/,
+ );
+ assert.match(chatPage, /useShortcut\(\n\s*"openProjectPicker",[\s\S]*?enabled: projectSwitcherShown/);
+ assert.match(
+ chatPage,
+ /if \(!projectSwitcherShown && projectPickerOpen\) \{\n\s*setProjectPickerOpen\(false\);/,
+ );
+ assert.match(
+ chatPage,
+ /\{view\.mode !== "compare" && currentProjectId && \(/,
+ "the reset no longer matches what the switcher renders by",
+ );
+
+ // The MCP dialog's flag lives in a store, so an unmount with no
+ // chatActive=false render in front of it leaves the dialog armed.
+ assert.match(mcp, /if \(!chatActive && open\) setOpen\(false\);/);
+ assert.match(
+ mcp,
+ /useEffect\(\(\) => \{\n\s*return \(\) => useMcpServersDialogStore\.getState\(\)\.setOpen\(false\);\n\s*\}, \[\]\);/,
+ );
+});
+
+// Escape clears the selection from the sidebar's own listener, not the
+// registry, so nothing stops another chord built on Escape from reaching it.
+// Clear all unreads ships one on macOS.
+test("only bare Escape drops the selection", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ const at = sidebar.indexOf('if (event.key !== "Escape"');
+ assert.notEqual(at, -1, "the selection listener moved");
+ const block = sidebar.slice(at, sidebar.indexOf("clearSelection();", at));
+ // Every modifier, so ⇧Esc goes to Clear all unreads alone.
+ for (const modifier of ["metaKey", "ctrlKey", "altKey", "shiftKey"]) {
+ assert.ok(
+ block.includes(`event.${modifier}`),
+ `${modifier} still reaches the selection listener`,
+ );
+ }
+ assert.ok(block.includes("event.defaultPrevented"));
+ // The chord it has to stay clear of.
+ const clearAll = SHORTCUT_DEFS.find((d) => d.id === "clearAllUnreads");
+ assert.ok(clearAll);
+ assert.equal(defaultBindingFor(clearAll, "primary", true), "Shift+Escape");
+});
+
+// The mobile drawer is a Sheet owned by SidebarProvider, which __root mounts
+// outside the Outlet, so it survives a navigation. Every sidebar row closes it
+// by hand afterwards; the chords are registered above that provider and cannot.
+test("the workspace chords do not leave the mobile drawer over the workspace", async () => {
+ const read = async (path: string) =>
+ readFile(new URL(path, import.meta.url), "utf8");
+ const root = await read("../src/app/routes/__root.tsx");
+ const sidebar = await read("../src/components/app-sidebar.tsx");
+
+ // The provider outlives the route, which is what makes this necessary.
+ assert.match(root, /<SidebarProvider/);
+ assert.match(root, /useShortcut\("switchToProjects", goTo\("\/projects"\)/);
+
+ // Closed on the location instead, which the chords change and the rows do
+ // too. href, not pathname: a new chat from /chat only moves the search.
+ assert.match(
+ sidebar,
+ /useEffect\(\(\) => \{\n\s*if \(isMobile\) setOpenMobile\(false\);\n\s*\}, \[href, isMobile, setOpenMobile\]\);/,
+ );
+ assert.match(sidebar, /href: s\.location\.href,/);
+
+ // The rows keep their own call: opening a chat moves neither, and the drawer
+ // still has to go.
+ assert.match(
+ sidebar,
+ /const closeMobileIfOpen = \(\) => \{\n\s*if \(isMobile\) setOpenMobile\(false\);\n\s*\};/,
+ );
+});
+
+// An action bar is the wrong place to register a chord: ActionBarRoot returns
+// null when hidden and the user bar is autohide="always", so its children are
+// gone unless the message is hovered. The assistant bar never mounted the fork
+// button, so any thread ending in a reply had no listener at all.
+test("the fork chord is registered where it mounts, not from an action bar", async () => {
+ const thread = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+
+ // The registration is its own component, rendering nothing.
+ const start = thread.indexOf("const ForkChatShortcut: FC = () => {");
+ assert.notEqual(start, -1, "the fork registration moved");
+ const block = thread.slice(start, thread.indexOf("\n};", start));
+ assert.match(block, /useShortcut\(\n\s*"forkChat",/);
+ assert.match(block, /return null;/);
+
+ // The button keeps the click and takes no part in the chord.
+ const buttonAt = thread.indexOf("const ForkMessageButton: FC = () => {");
+ const button = thread.slice(buttonAt, thread.indexOf("\n};", buttonAt));
+ assert.ok(
+ !button.includes("useShortcut"),
+ "an autohidden bar cannot hold the registration",
+ );
+
+ // Two instances of the action now exist on the last message, the chord's and
+ // the button's, so the in-flight flag cannot be either one's own state: the
+ // chord followed by a click would post two forks with two thread ids.
+ assert.match(
+ thread,
+ /const useForkInFlight = create<\{\n\s*forking: boolean;/,
+ );
+ assert.match(thread, /const pending = useForkInFlight\(\(s\) => s\.forking\);/);
+ assert.match(
+ thread,
+ /if \(useForkInFlight\.getState\(\)\.forking\) return;/,
+ );
+ assert.ok(
+ !thread.includes("const [pending, setPending] = useState(false);"),
+ "the per-instance flag is what let two forks run",
+ );
+
+ // Mounted from both roles, since either can be the last message, and only
+ // for the last one, which is the message a fork may be taken from.
+ const mounts = thread.match(
+ /<MessagePrimitive\.If last=\{true\}>\n\s*<ForkChatShortcut \/>\n\s*<\/MessagePrimitive\.If>/g,
+ );
+ assert.equal(mounts?.length, 2);
+ for (const role of ["const AssistantMessage", "const UserMessage: FC"]) {
+ const at = thread.indexOf(role);
+ assert.notEqual(at, -1, `${role} moved`);
+ assert.ok(
+ thread.slice(at, thread.indexOf("\n};", at)).includes("<ForkChatShortcut />"),
+ `${role} does not mount the fork chord`,
+ );
+ }
+});
+
+// The tour's opener pins the picker open, and an effect shuts anything left
+// pinned while no tour is running. A chord routed through it would open the
+// picker and lose it on the next tick.
+test("the model picker chord opens without the tour's pin", async () => {
+ const chatPage = await readFile(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+
+ // The pin, and the effect that keys on it.
+ assert.match(
+ chatPage,
+ /const openModelSelector = useCallback\(\(\) => \{\n\s*setModelSelectorLocked\(true\);/,
+ );
+ assert.match(
+ chatPage,
+ /if \(tour\.open\) return;\n\s*if \(!modelSelectorLocked\) return;[\s\S]{0,200}?setModelSelectorOpen\(false\);/,
+ );
+
+ // So the chord takes its own door, and stands aside while a step is on it.
+ assert.match(
+ chatPage,
+ /const toggleModelSelector = useCallback\(\(\) => \{\n(?:\s*\/\/[^\n]*\n)*\s*if \(modelSelectorLocked\) return;\n\s*setModelSelectorOpen\(\(open\) => !open\);/,
+ );
+ assert.match(chatPage, /useShortcut\(\n\s*"openModelPicker",[\s\S]*?toggleModelSelector\(\);/);
+
+ // Three mentions left, all the tour's: the declaration, the step builder's
+ // argument, and that memo's dependency. Nothing else may pin it open.
+ assert.equal((chatPage.match(/openModelSelector/g) ?? []).length, 3);
+});
+
+// The inline rename pill is rendered by the row, so it needs the row to be on
+// screen. A chord has no row under the cursor, and the open chat may be behind
+// a collapsed section, past a folder's limit, or on a route with no chat list.
+test("the rename chord does not land in a surface only a row can show", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ // The chord asks for the dialog; the context menu, which has a row under the
+ // cursor by definition, keeps the pill.
+ assert.match(
+ sidebar,
+ /useShortcut\("renameChat", \(\) => \{[\s\S]*?withActiveChat\(\(item\) => openRenameChat\(item, false\)\);/,
+ );
+ assert.match(sidebar, /onSelect=\{\(\) => openRenameChat\(item\)\}/);
+ assert.match(
+ sidebar,
+ /function openRenameChat\(item: SidebarItem, inline = true\)/,
+ );
+
+ // The pill is gated on it, so a dialog rename cannot also arm a row that is
+ // off screen and surprise the user when it comes back.
+ assert.match(
+ sidebar,
+ /const isRenamingThis =\n\s*renamingTarget\?\.kind === "chat" &&\n\s*renamingTarget\.inline &&/,
+ );
+ // And the dialog takes chats now, which is what its chat strings were always
+ // written for.
+ assert.match(
+ sidebar,
+ /\(renamingTarget\.kind !== "chat" \|\| !renamingTarget\.inline\)/,
+ );
+ assert.ok(sidebar.includes('t("shell.dialog.renameChat.title")'));
+});
+
+// Bare Escape has more than one owner. The sidebar answers it while rows are
+// selected and does not consume it, so without a guard one press would clear
+// the selection and deny a waiting tool call at the same time.
+test("one Escape does not both drop a selection and deny a tool call", async () => {
+ const read = async (path: string) =>
+ readFile(new URL(path, import.meta.url), "utf8");
+ const sidebar = await read("../src/components/app-sidebar.tsx");
+ const toolCard = await read(
+ "../src/components/assistant-ui/tool-confirmation-controls.tsx",
+ );
+ const store = await read(
+ "../src/features/chat/stores/chat-navigation-store.ts",
+ );
+
+ // The tool card is the one that stands down: dropping a selection is undone
+ // by selecting again, and denying a call is not.
+ assert.match(toolCard, /const selectionActive = useChatNavigationStore\(/);
+ assert.match(toolCard, /!selectionActive &&/);
+ // Both keys, not just Escape: the buttons stay either way.
+ for (const id of ["approveToolRequest", "declineToolRequest"]) {
+ const at = toolCard.indexOf(`"${id}",`);
+ assert.ok(at !== -1, `${id} lost its call site`);
+ assert.match(
+ toolCard.slice(at, toolCard.indexOf("\n );", at)),
+ /enabled: keyboardReady/,
+ );
+ }
+
+ // Published from the sidebar, cleared on unmount so an unmounted sidebar
+ // cannot leave the card mute.
+ assert.match(
+ sidebar,
+ /const selectionActive = selectionCount > 0 \|\| projectSelectionCount > 0;/,
+ );
+ assert.match(
+ sidebar,
+ /setSelectionActive\(selectionActive\);\n\s*return \(\) => setSelectionActive\(false\);/,
+ );
+ assert.match(store, /selectionActive: boolean;/);
+ assert.match(store, /selectionActive: false,/);
+
+ // And the sidebar listener stays passive. Dictation reads defaultPrevented
+ // before cancelling, so consuming Escape here would let a stale selection
+ // outrank a live recording.
+ const at = sidebar.indexOf("Escape is the way out of a selection");
+ const body = sidebar.slice(at, sidebar.indexOf("}, [selectionActive", at));
+ assert.ok(!body.includes("preventDefault"), "the listener consumes Escape");
+ assert.ok(!body.includes(", true)"), "the listener moved to capture");
+});
+
+test("the composer chords outlive the recording bar", async () => {
+ const thread = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ // Dictation swaps ComposerRightControls out for the recording bar, so a
+ // chord registered in there could start dictation and never stop it.
+ const controls = thread.indexOf("const ComposerRightControls:");
+ assert.ok(controls !== -1, "the controls component moved");
+ for (const id of ["startDictation", "sendMessage"]) {
+ const at = thread.indexOf(`useShortcut(\n "${id}"`);
+ const inline = thread.indexOf(`useShortcut("${id}"`);
+ const found = at === -1 ? inline : at;
+ assert.ok(found !== -1, `${id} lost its call site`);
+ assert.ok(found < controls, `${id} registers inside the recording swap`);
+ }
+ // Send goes through the form, which runs the parking, queueing and refusing
+ // that the runtime's own send knows nothing about, and through the recording
+ // bar's own path while dictation is running.
+ assert.match(thread, /formRef\.current\?\.requestSubmit\(\);/);
+ assert.match(
+ thread,
+ /if \(isDictating\) \{\n\s*if \(!dictationBlocked\) sendAfterDictation\(\);/,
+ );
+});
+
+test("a collapsed sidebar section is not published for the chords", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ // Navigation and Select all walk what is on screen, so a section the user
+ // closed counts as gone, the same as a closed project folder.
+ assert.match(
+ sidebar,
+ /chatListsOnScreen && pinnedOpen \? sortedPinnedChatItems/,
+ );
+ assert.match(
+ sidebar,
+ /chatListsOnScreen && chatOpen \? sortedRecentChatItems/,
+ );
+ assert.match(sidebar, /organizeBy !== "project" \|\| !projectsOpen/);
+ // And the published lists are the filtered ones.
+ assert.match(sidebar, /pinnedItems: visiblePinnedItems,/);
+ assert.match(sidebar, /recentItems: visibleRecentItems,/);
+});
+
+test("the MCP chord does not live behind the MCP pill", async () => {
+ const button = await readFile(
+ new URL("../src/features/chat/mcp-composer-button.tsx", import.meta.url),
+ "utf8",
+ );
+ const page = await readFile(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+ // MCP ships off for a chat and the pill only renders once it is on, so a
+ // chord registered inside the pill would do nothing until it was found by
+ // hand. The dialog and its chord mount for the chat instead.
+ const pill = button.indexOf("export function McpComposerButton");
+ const mount = button.indexOf("export function McpServersDialogMount");
+ assert.ok(pill !== -1 && mount > pill, "the mount moved");
+ assert.ok(
+ button.indexOf('useShortcut("openMcpServers"') > mount,
+ "the chord is back inside the pill",
+ );
+ // Mounted through the route change, not gated on `active`: the flag lives in
+ // a store, so a dialog left open has to be closed on the way out rather than
+ // unmounted with it still set.
+ assert.match(page, /\n\s*<McpServersDialogMount \/>/);
+ assert.match(button, /if \(!chatActive && open\) setOpen\(false\);/);
+ assert.match(button, /open=\{chatActive && open\}/);
+});
+
+test("the copy chords keep their gesture across the read", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ const clipboard = await readFile(
+ new URL("../src/lib/copy-to-clipboard.ts", import.meta.url),
+ "utf8",
+ );
+ // Both copies read storage first, and a strict engine drops the gesture
+ // across that await, leaving writeText and its execCommand fallback with
+ // nothing to run inside. The write starts with a promised payload instead.
+ assert.match(clipboard, /"text\/plain": payload\.then\(/);
+ for (const fn of ["copyChatItemAsMarkdown", "copyChatSessionId"]) {
+ const at = sidebar.indexOf(`async function ${fn}(`);
+ assert.ok(at !== -1, `${fn} moved`);
+ const body = sidebar.slice(at, sidebar.indexOf("\n }", at));
+ assert.ok(
+ body.includes("copyToClipboardFrom(async () =>"),
+ `${fn} awaits its read before starting the write`,
+ );
+ }
+});
+
+test("the project picker chord is described by what it does", async () => {
+ const page = await readFile(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+ // The header switcher navigates to the chosen project's landing; moving a
+ // chat between projects is a different flow, on the chat row's own menu.
+ assert.match(page, /onSelectProject=\{openProjectLanding\}/);
+ const strings = await readFile(
+ new URL("../src/i18n/locales/en.ts", import.meta.url),
+ "utf8",
+ );
+ const at = strings.indexOf("openProjectPicker: {");
+ const entry = strings.slice(at, strings.indexOf("},", at));
+ assert.ok(!/move/i.test(entry), "no move-to-project promise");
+ assert.ok(entry.includes("project"));
+});
+
+test("the new-chat chords stay out of the auth flow", async () => {
+ const root = await readFile(
+ new URL("../src/app/routes/__root.tsx", import.meta.url),
+ "utf8",
+ );
+ // /login has no shell, and requireAuth bounces /chat straight back, so these
+ // are gated like the workspace chords beside them.
+ for (const id of ["newChat", "newTemporaryChat", "newStandaloneChat"]) {
+ // The id, not the whole call: two of the three wrap onto their own line.
+ const at = root.indexOf(`"${id}"`);
+ assert.ok(at !== -1, `${id} is registered`);
+ const call = root.slice(at, root.indexOf("\n );", at) + 5);
+ assert.match(call, /enabled: !isAuthFlowRoute/, `${id} is gated`);
+ }
+});
+
+test("switching back to Chat lands on the view the user left", async () => {
+ const root = await readFile(
+ new URL("../src/app/routes/__root.tsx", import.meta.url),
+ "utf8",
+ );
+ // ChatPage renders the frozen search while off-route, and a bare /chat is a
+ // fresh chat, so the chord has to hand that search back to the router.
+ const at = root.indexOf('"switchToChat"');
+ assert.ok(at !== -1, "switchToChat is registered");
+ const call = root.slice(at, root.indexOf("\n );", at) + 5);
+ assert.match(call, /navigate\(\{ to: "\/chat", search: chatSearch \}\)/);
+ assert.match(call, /enabled: !isAuthFlowRoute/);
+ // The other workspaces keep the bare helper; only chat carries a search.
+ assert.match(root, /useShortcut\("switchToImages", goTo\("\/images"\)/);
+ // location.search is the raw URL's, not the matched route's, so a seeded
+ // freeze would hand /images?project=x to the chord as a chat never opened.
+ assert.match(root, /useState<ChatSearch>\(\{\}\)/);
+});
+
+test("opening a chat by chord drops the selection, as clicking a row does", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ // Archive, pin and mark-unread prefer the selection when there is one, so a
+ // stale one sends them to rows that are no longer on screen.
+ const at = sidebar.indexOf("function openChatItem(");
+ const body = sidebar.slice(at, sidebar.indexOf("\n }", at));
+ assert.ok(body.includes("clearSelection()"), "the shared opener clears it");
+ // One path only: the row reaches it through the same function.
+ assert.ok(
+ !sidebar.includes("clearSelection();\n openChatItem(item);"),
+ "the row no longer clears it separately",
+ );
+});
+
+test("effort chords only run for a model whose effort is read", async () => {
+ const page = await readFile(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+ const at = page.indexOf("const shiftReasoningEffort");
+ const body = page.slice(at, page.indexOf("useShortcut(\"cycleReasoningEffort\"", at));
+ // enable_thinking models still list levels, but the request drops the effort.
+ assert.match(body, /state\.reasoningStyle === "reasoning_effort"/);
+ assert.match(body, /state\.reasoningStyle === "enable_thinking_effort"/);
+ assert.match(body, /!state\.supportsReasoning \|\| !isEffort/);
+});
+
+test("New chat inherits the project on screen, inferred or not", async () => {
+ const root = await readFile(
+ new URL("../src/app/routes/__root.tsx", import.meta.url),
+ "utf8",
+ );
+ const page = await readFile(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+ // On Chat the runtime's project is the visible one, inferred ones included:
+ // the page resolves it from the thread or the compare pair when the URL
+ // carries no ?project=, so a chat in a project stays in it.
+ assert.match(root, /isChatRoute \? chatRuntime\.activeProjectId : null/);
+ assert.match(page, /const projectId = thread\?\.projectId \?\? null;/);
+ assert.match(page, /const projectId = threads\[0\]\?\.projectId \?\? null;/);
+ assert.match(page, /setCurrentProjectId\(projectId\);\n\s*useChatRuntimeStore\.getState\(\)\.setActiveProjectId\(projectId\);/);
+ // The page's own New chat button starts from the same value, so the chord
+ // and the button cannot disagree about which project a new chat is in.
+ assert.match(page, /runtime\.setActiveProjectId\(currentProjectId\);/);
+ // Off Chat the page is hidden rather than unmounted, so the runtime still
+ // names a project the user is not looking at. That one stays excluded.
+ assert.match(root, /isChatRoute \? chatRuntime\.activeProjectId : null/);
+ // Leaving the project is its own action, so this one must not also do it.
+ assert.match(
+ root,
+ /useShortcut\("newStandaloneChat", \(\) => startNewChat\(\{ standalone: true \}\)/,
+ );
+ assert.match(root, /const projectId = options\?\.standalone \? null : openProjectId;/);
+});
+
test("every settings tab survives a reload", () => {
// The persisted-tab check reads this same list, so a tab added to the union
// alone can no longer be rejected back to General.
@@ -350,12 +1510,475 @@ test("the sidebar hints render the bound chord, not the shipped default", async
});
test("a hint label follows the override and disappears when cleared", () => {
- const label = (overrides: Parameters<typeof resolveBinding>[0], id: "searchChats" | "openSettings") => {
+ const label = (
+ overrides: Parameters<typeof resolveBinding>[0],
+ id: "searchChats" | "openSettings",
+ ) => {
const binding = parseBinding(resolveBinding(overrides, id));
return binding ? formatBindingLabel(binding, false) : null;
};
assert.equal(label({}, "searchChats"), "Ctrl+K");
- assert.equal(label({ searchChats: "Mod+Shift+KeyF" }, "searchChats"), "Ctrl+Shift+F");
- assert.equal(label({ searchChats: null }, "searchChats"), null);
+ assert.equal(
+ label({ searchChats: { primary: "Mod+Shift+KeyF" } }, "searchChats"),
+ "Ctrl+Shift+F",
+ );
+ assert.equal(label({ searchChats: { primary: null } }, "searchChats"), null);
assert.equal(label({}, "openSettings"), "Ctrl+,");
});
+
+// A row with no i18n keys renders a raw key path, and one missing from the
+// search index cannot be found from the settings search box.
+test("every action is translated and indexed for settings search", async () => {
+ const en = await readFile(
+ new URL("../src/i18n/locales/en.ts", import.meta.url),
+ "utf8",
+ );
+ const at = en.indexOf(" keyboardShortcuts: {");
+ assert.notEqual(at, -1);
+ const subtree = en.slice(at, en.indexOf("\n },", at));
+ for (const def of SHORTCUT_DEFS) {
+ assert.ok(
+ subtree.includes(`${def.id}: {`),
+ `en.ts is missing settings.keyboardShortcuts.actions.${def.id}`,
+ );
+ assert.equal(
+ def.labelKey,
+ `settings.keyboardShortcuts.actions.${def.id}.label`,
+ );
+ assert.equal(
+ def.descriptionKey,
+ `settings.keyboardShortcuts.actions.${def.id}.description`,
+ );
+ }
+
+ const index = await readFile(
+ new URL("../src/features/settings/settings-search.ts", import.meta.url),
+ "utf8",
+ );
+ for (const def of SHORTCUT_DEFS) {
+ assert.ok(
+ index.includes(`"${def.labelKey}"`),
+ `${def.id} is missing from the settings search index`,
+ );
+ }
+});
+
+// Every action needs a place to run, or the row is a control that does nothing.
+test("every action has a useShortcut call site", async () => {
+ const files = [
+ "../src/app/routes/__root.tsx",
+ "../src/components/app-sidebar.tsx",
+ "../src/components/ui/sidebar.tsx",
+ "../src/components/assistant-ui/thread.tsx",
+ "../src/components/assistant-ui/tool-confirmation-controls.tsx",
+ "../src/features/chat/chat-page.tsx",
+ "../src/features/chat/shared-composer.tsx",
+ "../src/features/chat/mcp-composer-button.tsx",
+ "../src/features/chat/components/chat-search-dialog.tsx",
+ "../src/features/api-monitor/api-monitor-overlay.tsx",
+ ];
+ const sources = await Promise.all(
+ files.map((file) => readFile(new URL(file, import.meta.url), "utf8")),
+ );
+ const joined = sources.join("\n");
+ for (const def of SHORTCUT_DEFS) {
+ // Biome wraps longer calls, so the id can land on its own line.
+ const called = new RegExp(`useShortcut\\(\\s*"${def.id}"`).test(joined);
+ // The numbered slots register through <Shortcut> elements built from a
+ // template id, because a loop of hooks breaks the rules of hooks.
+ const slot = /^(goToChat|goToRecentChat)(\d)$/.exec(def.id);
+ const rendered =
+ slot !== null &&
+ joined.includes(`id={\`${slot[1]}\${slot}\` as ShortcutId}`);
+ assert.ok(called || rendered, `${def.id} has no useShortcut call site`);
+ }
+});
+
+// Holding a chord past the OS repeat delay resends it. A toggle would land
+// wherever the user let go, and an archive would run once per repeat.
+test("auto-repeat only reaches the actions that walk a list", async () => {
+ const read = async (path: string) =>
+ readFile(new URL(path, import.meta.url), "utf8");
+ const hook = await read("../src/features/settings/hooks/use-shortcut.ts");
+ // Suppressed after preventDefault: the chord is ours either way, so the
+ // browser must not act on the repeats we drop.
+ const at = hook.indexOf("event.preventDefault();");
+ assert.ok(at !== -1, "the hook stopped consuming the chord");
+ assert.match(
+ hook.slice(at),
+ /event\.preventDefault\(\);\n(?:\s*\/\/[^\n]*\n)*\s*if \(event\.repeat && !repeats\) return;/,
+ );
+ // Off by default, so a new call site is one-shot until it says otherwise.
+ assert.match(hook, /repeats = false,\n\s*\} = options;/);
+ assert.match(
+ hook,
+ /\[bindings, enabled, skipInTextFields, textFieldException, repeats\]/,
+ );
+
+ const sidebar = await read("../src/components/app-sidebar.tsx");
+ const walkers = [
+ "nextChat",
+ "previousChat",
+ "nextRecentlyViewedChat",
+ "previousRecentlyViewedChat",
+ ];
+ for (const id of walkers) {
+ const call = sidebar.indexOf(`useShortcut("${id}"`);
+ assert.ok(call !== -1, `${id} lost its call site`);
+ assert.match(
+ sidebar.slice(call, sidebar.indexOf(");", call)),
+ /repeats: true/,
+ `${id} should step while held`,
+ );
+ }
+ // Everything else is one-shot. A held toggle or archive is not a gesture.
+ const optedIn = sidebar.match(/repeats: true/g) ?? [];
+ assert.equal(optedIn.length, walkers.length);
+});
+
+// The chords read the published lists, so those have to end where the screen
+// does: whole-sidebar gates included, not just each section's disclosure.
+test("the published chat lists stop where the sidebar stops", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ // The same two conditions the three chat groups render behind, plus the
+ // icon rail, which hides them in CSS rather than dropping them.
+ assert.match(
+ sidebar,
+ /const chatListsOnScreen =\n\s*!isStudioRoute &&\n\s*!showTrainingRecents &&\n\s*\(isMobile \|\| sidebarState !== "collapsed"\);/,
+ );
+ for (const group of [
+ /if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !projectsOpen\)/,
+ /\(chatListsOnScreen && pinnedOpen \? sortedPinnedChatItems : \[\]\)/,
+ /\(chatListsOnScreen && chatOpen \? sortedRecentChatItems : \[\]\)/,
+ ]) {
+ assert.match(sidebar, group);
+ }
+ // Select All reads the same three arrays, so it cannot reach further than
+ // the walk does.
+ const selectAll = sidebar.indexOf("const selectAllChats = useCallback(");
+ assert.ok(selectAll !== -1, "selectAllChats moved");
+ assert.match(
+ sidebar.slice(selectAll, sidebar.indexOf("\n }, [", selectAll)),
+ /\.\.\.visiblePinnedItems,\n\s*\.\.\.renderedProjectChatItems,\n\s*\.\.\.visibleRecentItems,/,
+ );
+ // Gating the arrays is enough because nothing renders from them.
+ const rendered = sidebar.slice(sidebar.indexOf("return (", selectAll));
+ for (const name of [
+ "visiblePinnedItems",
+ "visibleRecentItems",
+ "renderedProjectChatItems",
+ ]) {
+ assert.ok(!rendered.includes(name), `${name} is read by the JSX too`);
+ }
+});
+
+// The bulk chords take the selection over the open chat, and a selection has
+// no presence outside the rows, so one carried off screen is invisible and
+// still live.
+test("a selection does not outlive the rows it was made on", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ // The whole sidebar going takes the whole selection with it.
+ assert.match(
+ sidebar,
+ /if \(!chatRowsOnScreen\) \{\n\s*clearSelection\(\);\n\s*return;\n\s*\}/,
+ );
+ // Which is the stricter of the two: the lists can exist while their rows do
+ // not, because a closed mobile sheet unmounts them the way the rail does.
+ assert.match(
+ sidebar,
+ /const chatRowsOnScreen = chatListsOnScreen && \(!isMobile \|\| openMobile\);/,
+ );
+ // Select All is the one that builds a selection out of nothing, so it takes
+ // the same gate rather than waiting for the cleanup to undo it.
+ assert.match(
+ sidebar,
+ /const selectAllChats = useCallback\(\(\) => \{\n\s*if \(!chatRowsOnScreen\) return;/,
+ );
+ // Navigation is deliberately left on the looser one.
+ assert.match(
+ sidebar,
+ /\(chatListsOnScreen && chatOpen \? sortedRecentChatItems : \[\]\)/,
+ );
+ // A single section closing takes only its own rows: the rest are still on
+ // screen, so the selection is held to what is rendered rather than dropped.
+ assert.match(
+ sidebar,
+ /for \(const id of prev\) \{\n\s*if \(renderedChatIds\.has\(id\)\) kept\.add\(id\);/,
+ );
+ assert.match(
+ sidebar,
+ /return kept\.size === prev\.size \? prev : kept;/,
+ );
+ assert.match(
+ sidebar,
+ /\}, \[chatRowsOnScreen, clearSelection, renderedChatIds, renderedProjectIds\]\);/,
+ );
+ // Folder rows are selectable too, and selectionActive counts them, so one
+ // left behind by a closed section keeps the tool card's Escape standing
+ // aside for a selection with nothing on screen to show for it.
+ assert.match(
+ sidebar,
+ /for \(const id of prev\) \{\n\s*if \(renderedProjectIds\.has\(id\)\) kept\.add\(id\);/,
+ );
+ assert.match(
+ sidebar,
+ /if \(projectAnchor && !renderedProjectIds\.has\(projectAnchor\)\) \{\n\s*projectAnchorRef\.current = null;/,
+ );
+ // The three ways a folder row leaves without the sidebar going with it.
+ assert.match(
+ sidebar,
+ /const renderedProjectIds = useMemo\(\(\) => \{\n\s*if \(!chatListsOnScreen \|\| organizeBy !== "project" \|\| !projectsOpen\) \{\n\s*return new Set<string>\(\);\n\s*\}\n\s*return new Set\(visibleProjectRecords\.map\(\(project\) => project\.id\)\);/,
+ );
+ // Both counts feed the flag, which is why both have to be pruned.
+ assert.match(
+ sidebar,
+ /const selectionActive =\n?\s*selectionCount > 0 \|\| projectSelectionCount > 0;/,
+ );
+ // Built from the three arrays that already carry every disclosure state, so
+ // a collapse or a "show less" needs nothing restated here.
+ assert.match(
+ sidebar,
+ /const renderedChatIds = useMemo\(\(\) => \{[\s\S]*?visiblePinnedItems[\s\S]*?renderedProjectChatItems[\s\S]*?visibleRecentItems/,
+ );
+ // Which is what makes the four bulk branches safe to leave as they are.
+ for (const id of [
+ "archiveChat",
+ "markChatUnread",
+ "togglePinChat",
+ "deleteSelectedChats",
+ ]) {
+ const at = sidebar.indexOf(`useShortcut("${id}"`);
+ assert.ok(at !== -1, `${id} lost its call site`);
+ assert.match(
+ sidebar.slice(at, sidebar.indexOf("\n });", at)),
+ /selectionCount > 0/,
+ `${id} no longer prefers the selection`,
+ );
+ }
+ // The anchor goes with its row, so a later shift-click cannot reach back to
+ // one that is no longer there.
+ assert.match(
+ sidebar,
+ /if \(anchor && !renderedChatIds\.has\(anchor\.id\)\) \{\n\s*selectionAnchorRef\.current = null;/,
+ );
+});
+
+// Acting on a selection clears it, so the same chord pressed again reads
+// selectionCount as 0. Without a latch it archives the open chat, which was
+// never selected, and says nothing about it.
+test("a selection chord does not fall through to the open chat", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(sidebar, /const SELECTION_ACTION_GRACE_MS = \d+;/);
+ for (const id of ["archiveChat", "markChatUnread", "togglePinChat"]) {
+ const body = sidebar.slice(
+ sidebar.indexOf(`useShortcut("${id}"`),
+ sidebar.indexOf("\n });", sidebar.indexOf(`useShortcut("${id}"`)),
+ );
+ // Both halves name the action. A shared latch would hold back Archive
+ // after Pin took the selection, and that is a different command the user
+ // chose, not the repeat this guard exists for.
+ assert.match(
+ body,
+ new RegExp(`actOnSelection\\("${id}",`),
+ `${id} does not stamp the latch under its own name`,
+ );
+ assert.match(
+ body,
+ new RegExp(
+ `if \\(followsSelectionAction\\("${id}"\\)\\) return;[\\s\\S]*withActiveChat\\(`,
+ ),
+ `${id} reaches the open chat without checking its own latch`,
+ );
+ }
+ // deleteSelectedChats needs none of this: it has no open-chat branch.
+ const del = sidebar.slice(
+ sidebar.indexOf('useShortcut("deleteSelectedChats"'),
+ sidebar.indexOf("\n });", sidebar.indexOf('useShortcut("deleteSelectedChats"')),
+ );
+ assert.doesNotMatch(del, /withActiveChat\(/);
+});
+
+// The only action with no menu item anywhere and no undo, so a silent wipe
+// leaves the user nothing to tell it apart from a dead key.
+test("clearing every unread says what it cleared", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ const body = sidebar.slice(
+ sidebar.indexOf('useShortcut("clearAllUnreads"'),
+ sidebar.indexOf("\n });", sidebar.indexOf('useShortcut("clearAllUnreads"')),
+ );
+ // Counted before the wipe, or the toast reports zero every time. Rows, not
+ // threads: a Compare row is backed by two and would be cleared as two chats.
+ assert.match(body, /const cleared = countUnreadRows\(state\);[\s\S]*state\.clearAllUnreads\(\)/);
+ assert.match(body, /if \(state\.unreadThreadIds\.size === 0\) \{\n\s*toast\.info\(/);
+ assert.match(body, /toast\.success\(/);
+});
+
+// Two parked requests must count as two, or both cards claim Enter and mount
+// order picks the winner. Compare panes make that easy to get wrong: the
+// backend reuses "call_0" per response, so the store key cannot be it.
+test("a parked tool request is keyed by its own approval, not call_0", async () => {
+ const adapter = await readFile(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+ );
+ // Scope first, so two panes differ even before the approval token does.
+ assert.match(
+ adapter,
+ /const toolConfirmationScopeId = resolvedThreadId\n\s*\? `\$\{sandboxSessionId \|\| "_default"\}:\$\{resolvedThreadId\}`/,
+ );
+ assert.match(adapter, /\? `\$\{toolConfirmationScopeId\}:\$\{approvalId\}`/);
+ // The other branch mints a unique part id rather than reusing the backend's.
+ assert.match(
+ adapter,
+ /\(\) => `\$\{backendToolCallId\}:\$\{crypto\.randomUUID\(\)\}`/,
+ );
+
+ const { resolveToolCallPartId } = await import(
+ "../src/features/chat/tool-call-id.ts"
+ );
+ // One run's map cannot hand another run's the same id for "call_0".
+ let minted = 0;
+ const mint = () => `call_0:${(minted += 1)}`;
+ const paneA = resolveToolCallPartId(new Map(), "call_0", undefined, "", mint);
+ const paneB = resolveToolCallPartId(new Map(), "call_0", undefined, "", mint);
+ assert.notEqual(paneA, paneB);
+ // Within a run the same backend id keeps resolving to the one card.
+ const ids = new Map<string, string>();
+ const first = resolveToolCallPartId(ids, "call_0", undefined, "", mint);
+ assert.equal(
+ resolveToolCallPartId(ids, "call_0", undefined, "", mint),
+ first,
+ );
+ // A confirmation id wins outright: that is the scoped key above.
+ assert.equal(
+ resolveToolCallPartId(ids, "call_0", "sess:thread:tok", "", mint),
+ "sess:thread:tok",
+ );
+});
+
+// The selection guard's effect depends on the set of rendered rows, and its
+// setState bails out on an unchanged selection. React still re-renders once to
+// discover that, so a dependency rebuilt during that render schedules the
+// effect again, without end. React error #185, which took down the whole chat
+// route rather than just the sidebar.
+test("the rows the selection guard reads keep their identity", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ for (const name of [
+ "visibleProjectRecords",
+ "visiblePinnedItems",
+ "visibleRecentItems",
+ "renderedProjectChatItems",
+ "renderedChatIds",
+ ]) {
+ const at = sidebar.indexOf(`const ${name} = `);
+ assert.notEqual(at, -1, `${name} is gone`);
+ assert.match(
+ sidebar.slice(at, at + name.length + 40),
+ /= useMemo\(/,
+ `${name} is rebuilt every render and feeds a selection effect`,
+ );
+ }
+});
+
+// The root of the chain the test above pins. groupThreads returns a fresh
+// array, so calling it during render gives every derived sidebar list a new
+// identity on every render, which is what made the selection guard's effect
+// re-run without end.
+test("the sidebar item lists are built once per change, not per render", async () => {
+ const hook = await readFile(
+ new URL("../src/features/chat/hooks/use-chat-sidebar-items.ts", import.meta.url),
+ "utf8",
+ );
+ for (const name of ["items", "archivedItems"]) {
+ const at = hook.indexOf(`const ${name} = `);
+ assert.notEqual(at, -1, `${name} is gone`);
+ assert.match(
+ hook.slice(at, at + name.length + 30),
+ /= useMemo\(/,
+ `${name} is rebuilt every render and feeds a selection effect`,
+ );
+ }
+});
+
+// Ctrl/Cmd-clicking a project row selects it without selecting any chat. The
+// chat-only chords used to read that as "no selection" and act on the open
+// chat, so Archive archived a chat the user had not pointed at.
+test("the chat-only chords stand aside for a project selection", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ for (const id of ["archiveChat", "markChatUnread", "togglePinChat"]) {
+ const at = sidebar.indexOf(`useShortcut("${id}", () => {`);
+ assert.notEqual(at, -1, `${id} is gone`);
+ const body = sidebar.slice(at, sidebar.indexOf("\n });", at));
+ const stand = body.indexOf("projectsOnlySelected()");
+ assert.notEqual(stand, -1, `${id} acts on the open chat under a project selection`);
+ assert.ok(
+ stand < body.indexOf("withActiveChat("),
+ `${id} checks the project selection too late`,
+ );
+ }
+ // Only when no chat is selected: a mixed selection still has chats to act on.
+ assert.match(
+ sidebar,
+ /const projectsOnlySelected = \(\) =>\n\s*selectionCount === 0 && projectSelectionCount > 0;/,
+ );
+});
+
+// Apple lists Shift-Command-] and Shift-Command-[ as Safari's Show Next Tab
+// and Show Previous Tab, and Chrome carries the same pair on macOS. The chat
+// walk ships on them for the desktop build, so Settings has to say so rather
+// than let a web user rebind into a chord the browser takes first.
+test("the chat walk's bracket pair is reserved on macOS only", () => {
+ for (const value of ["Mod+Shift+BracketLeft", "Mod+Shift+BracketRight"]) {
+ assert.ok(
+ isBrowserReservedBinding(value, true),
+ `${value} warns nobody on the platform that takes it`,
+ );
+ assert.equal(
+ isBrowserReservedBinding(value, false),
+ false,
+ `${value} is not taken off macOS`,
+ );
+ }
+ // Still the shipped default, which is why it is on the deliberate list.
+ const walk = SHORTCUT_DEFS.find((def) => def.id === "nextChat");
+ assert.equal(defaultBindingFor(walk!, "primary", true), "Mod+Shift+BracketRight");
+});
+
+// The desktop signs out through the OS account menu, so the chord's handler
+// returns there and the sidebar hides its own logout item. Offering the row in
+// Settings let a desktop user bind a key that can never fire.
+test("the logout row is not offered on the desktop build", async () => {
+ const logout = SHORTCUT_DEFS.find((def) => def.id === "logOut");
+ assert.equal(logout?.webOnly, true);
+ // Nothing else claims it, or the flag would hide a working action.
+ assert.deepEqual(
+ SHORTCUT_DEFS.filter((def) => def.webOnly).map((def) => def.id),
+ ["logOut"],
+ );
+ const tab = await readFile(
+ new URL(
+ "../src/features/settings/tabs/keyboard-shortcuts-tab.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(tab, /!\(isTauri && def\.webOnly\)/);
+});
diff --git a/studio/frontend/tests/recorded-sandbox-session.test.ts b/studio/frontend/tests/recorded-sandbox-session.test.ts
index f2afc30ee49..2dff315b3d4 100644
--- a/studio/frontend/tests/recorded-sandbox-session.test.ts
+++ b/studio/frontend/tests/recorded-sandbox-session.test.ts
@@ -8,11 +8,11 @@ import { registerBundlerResolver } from "./helpers/kit.ts";
registerBundlerResolver();
-const { recordedSandboxSessionId } = await import(
+const { allRecordedSandboxSessionIds } = await import(
"../src/features/chat/utils/recorded-sandbox-session.ts"
);
-type Message = Parameters<typeof recordedSandboxSessionId>[0][number];
+type Message = Parameters<typeof allRecordedSandboxSessionIds>[0][number];
function toolMessage(sessionId: string): Message {
return {
@@ -40,12 +40,27 @@ function toolMessage(sessionId: string): Message {
test("a chat moved into a project still names the sandbox its files are in", () => {
// Written while the chat was loose, so the id is the thread's, not project-<id>.
const messages = [toolMessage("thread-1")];
- assert.equal(recordedSandboxSessionId(messages), "thread-1");
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), ["thread-1"]);
});
-test("the most recent tool result wins when the scope changed mid-chat", () => {
+test("a scope change mid-chat leaves files in both folders, so both are named", () => {
+ // One thread, two sandboxes: it ran a tool loose, joined a project, and ran
+ // another. Answering with the newest alone would strand the first folder,
+ // and its caller would think the chat had a single session id to hand out.
const messages = [toolMessage("thread-1"), toolMessage("project-p1")];
- assert.equal(recordedSandboxSessionId(messages), "project-p1");
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), [
+ "project-p1",
+ "thread-1",
+ ]);
+});
+
+test("a chat that stayed put names its one sandbox once, however many tools ran", () => {
+ const messages = [
+ toolMessage("project-p1"),
+ toolMessage("project-p1"),
+ toolMessage("project-p1"),
+ ];
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), ["project-p1"]);
});
test("a chat that never ran a tool records nothing, leaving the caller its default", () => {
@@ -58,7 +73,7 @@ test("a chat that never ran a tool records nothing, leaving the caller its defau
content: [{ type: "text", text: "hello" }],
} as unknown as Message,
];
- assert.equal(recordedSandboxSessionId(messages), undefined);
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), []);
});
test("an mcp tool answering with its own session id is not read as a sandbox", () => {
@@ -83,7 +98,7 @@ test("an mcp tool answering with its own session id is not read as a sandbox", (
],
} as unknown as Message,
];
- assert.equal(recordedSandboxSessionId(messages), undefined);
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), []);
});
test("a python result missing the wrapper shape is not read as a sandbox", () => {
@@ -104,7 +119,7 @@ test("a python result missing the wrapper shape is not read as a sandbox", () =>
],
} as unknown as Message,
];
- assert.equal(recordedSandboxSessionId(messages), undefined);
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), []);
});
test("a result without a session id is skipped rather than read as one", () => {
@@ -130,7 +145,7 @@ test("a result without a session id is skipped rather than read as one", () => {
],
} as unknown as Message,
];
- assert.equal(recordedSandboxSessionId(messages), undefined);
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), []);
});
test("a run that created no files still names the sandbox it ran in", () => {
@@ -158,7 +173,7 @@ test("a run that created no files still names the sandbox it ran in", () => {
],
} as unknown as Message,
];
- assert.equal(recordedSandboxSessionId(messages), "project-p1");
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), ["project-p1"]);
});
test("content that is not an array is skipped rather than thrown on", () => {
@@ -169,7 +184,7 @@ test("content that is not an array is skipped rather than thrown on", () => {
{ id: "m2", threadId: "t", role: "assistant", createdAt: 2, content: null },
{ id: "m3", threadId: "t", role: "assistant", createdAt: 3 },
] as unknown as Message[];
- assert.equal(recordedSandboxSessionId(messages), undefined);
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), []);
});
test("a null part inside a real content array does not stop the scan", () => {
@@ -191,7 +206,7 @@ test("a null part inside a real content array does not stop the scan", () => {
],
} as unknown as Message,
];
- assert.equal(recordedSandboxSessionId(messages), "thread-1");
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), ["thread-1"]);
});
test("a tool-result shaped part is not mistaken for a tool call", () => {
@@ -212,12 +227,13 @@ test("a tool-result shaped part is not mistaken for a tool call", () => {
],
} as unknown as Message,
];
- assert.equal(recordedSandboxSessionId(messages), undefined);
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), []);
});
-test("a long history answers from the newest message without walking it all", () => {
- // Runs on a menu click over a chat of thousands of turns. Walking backwards
- // makes it one part when the newest message carries the answer.
+test("a long history is walked in full and still answers inside a menu click", () => {
+ // Naming every folder means the whole history, not an early return on the
+ // newest. Runs on a menu click over a chat of thousands of turns, so the
+ // bound stands: it is one pass over parts already in memory.
const messages: Message[] = [];
for (let i = 0; i < 5000; i += 1) {
messages.push({
@@ -230,9 +246,9 @@ test("a long history answers from the newest message without walking it all", ()
}
messages.push(toolMessage("newest-session"));
const started = performance.now();
- assert.equal(recordedSandboxSessionId(messages), "newest-session");
+ assert.deepEqual(allRecordedSandboxSessionIds(messages), ["newest-session"]);
assert.ok(
performance.now() - started < 50,
- "the newest message must answer it",
+ "a full pass has to stay inside a click",
);
});
diff --git a/studio/frontend/tests/sandbox-reveal-path.test.ts b/studio/frontend/tests/sandbox-reveal-path.test.ts
index b9e0818c118..4f1b4c70d23 100644
--- a/studio/frontend/tests/sandbox-reveal-path.test.ts
+++ b/studio/frontend/tests/sandbox-reveal-path.test.ts
@@ -108,17 +108,36 @@ test("a failed history read is reported, not mistaken for a chat that ran no too
// No React renderer here, so this asserts on source, like ~50 sibling tests.
// A per-pane catch makes a failed read look like "never ran a tool", and the
// fallback is project membership, the answer the recorded id overrides.
- const start = SIDEBAR.indexOf("const recorded: (string | undefined)[] = [];");
- const end = SIDEBAR.indexOf("let distinct = ");
+ // Both "Open chat folder" and "Copy session id" read through this helper.
+ const start = SIDEBAR.indexOf("async function recordedSandboxSessionIds");
+ const end = SIDEBAR.indexOf("\n }", start);
assert.ok(start !== -1 && end > start, "the read block moved");
const block = SIDEBAR.slice(start, end);
- assert.ok(block.includes("recordedSandboxSessionId"), "the read block moved");
+ assert.ok(
+ block.includes("allRecordedSandboxSessionIds"),
+ "the read block moved",
+ );
assert.ok(
!block.includes(".catch("),
"a per-pane catch turns a failed read into a wrong folder",
);
});
+test("one thread that outlived a move counts as two folders, not one", () => {
+ // A chat can name two sandboxes on its own: ran a tool, moved between
+ // projects, ran another. Taking one id per thread would leave the refusal
+ // blind to that and hand out the newer id as though it were the only one.
+ const start = SIDEBAR.indexOf("async function recordedSandboxSessionIds");
+ const end = SIDEBAR.indexOf("\n }", start);
+ const block = SIDEBAR.slice(start, end);
+ assert.match(
+ block,
+ /recorded\.push\(\n\s*\.\.\.allRecordedSandboxSessionIds\(await listStoredChatMessages\(threadId\)\),\n\s*\);/,
+ );
+ // Both actions refuse on more than one, rather than picking a folder.
+ assert.equal(SIDEBAR.split("distinct.length > 1").length - 1, 2);
+});
+
test("a sandbox holding files is told apart from one that was never written", async () => {
// The legacy-folder probe. A missing sandbox lists as 200 with an empty
// array rather than an error, so both cases must read as "not this one".
@@ -154,15 +173,54 @@ test("a probe that could not be answered is reported, not read as an empty folde
});
});
-test("the legacy probe runs only for a chat now inside a project", () => {
- // A chat moved OUT of a project wrote under project-<id>, and nothing retains
- // which one, so there is no candidate to probe in that direction.
- const block = SIDEBAR.slice(
- SIDEBAR.indexOf("let distinct = [...new Set(recorded.filter(Boolean))];"),
- SIDEBAR.indexOf("if (distinct.length > 1)"),
+test("the legacy probe runs whichever project the chat sits in now", () => {
+ // This used to skip a chat outside a project, on the grounds that one moved
+ // OUT wrote under project-<id> and nothing retains which one. A chat can join
+ // a project, record that session, and move back out, and skipping the probe
+ // there reported one folder while its older files stayed hidden. The thread
+ // folder is probed whichever project the chat sits in now; the project
+ // workspace is not, since every chat in the project writes to it.
+ const start = SIDEBAR.indexOf("async function sandboxSessionIdsHolding");
+ assert.notEqual(start, -1, "the legacy probe moved");
+ const block = SIDEBAR.slice(start, SIDEBAR.indexOf("\n }", start));
+ assert.ok(!block.includes("if (!item.projectId) return recorded;"));
+ assert.ok(block.includes("sandboxHasFiles(candidate)"));
+ // Not the project workspace: it is shared by every chat in the project, so
+ // files there say nothing about this one.
+ assert.ok(!block.includes("sandboxSessionIdFor("));
+});
+
+test("a recorded session does not hide a legacy folder beside it", () => {
+ // The mixed history: a tool ran before results carried a session, the chat
+ // moved into a project, another tool ran and recorded one. Treating the
+ // recorded id as proof that nothing else holds files answers for one folder
+ // while the older keeps the rest.
+ const start = SIDEBAR.indexOf("async function sandboxSessionIdsHolding");
+ const block = SIDEBAR.slice(start, SIDEBAR.indexOf("\n }", start));
+ // A union, so a recorded id cannot short-circuit the probe.
+ assert.match(block, /return \[\.\.\.new Set\(\[\.\.\.recorded, \.\.\.held\]\)\];/);
+ assert.ok(
+ !block.includes("recorded.length > 0"),
+ "an early return on any recorded id is what hid the legacy folder",
);
- assert.ok(block.includes("distinct.length === 0 && item.projectId"));
- assert.ok(block.includes("sandboxHasFiles(threadId)"));
+ // Probing an id that is already named would only cost a request.
+ assert.match(block, /if \(recorded\.includes\(candidate\)\) continue;/);
+});
+
+test("both the folder and the session id are answered from the same probe", () => {
+ // They drifted once: only the reveal path fell back to the legacy folder, so
+ // Copy session id answered a legacy chat that had since joined a project with
+ // project-<id>, a folder it had never written to, and called it a success.
+ const callers = SIDEBAR.match(/await sandboxSessionIdsHolding\(/g) ?? [];
+ assert.equal(callers.length, 2);
+ for (const action of ["copyChatSessionId", "Open chat folder"]) {
+ const at = SIDEBAR.indexOf(action);
+ assert.notEqual(at, -1, `${action} moved`);
+ }
+ // Neither may reach past it to the recorded ids alone.
+ const copyAt = SIDEBAR.indexOf("async function copyChatSessionId");
+ const copy = SIDEBAR.slice(copyAt, SIDEBAR.indexOf("\n }\n", copyAt));
+ assert.ok(!copy.includes("await recordedSandboxSessionIds("));
});
test("a sandbox tool result is wrapped even when it carries no envelope", () => {
diff --git a/studio/frontend/tests/shortcut-dispatch-guards.test.ts b/studio/frontend/tests/shortcut-dispatch-guards.test.ts
new file mode 100644
index 00000000000..90593274294
--- /dev/null
+++ b/studio/frontend/tests/shortcut-dispatch-guards.test.ts
@@ -0,0 +1,590 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const {
+ isImeComposing,
+ isSurfaceBackgrounded,
+ isSurfaceInForeground,
+ typesInTextField,
+} = await import(
+ "../src/features/settings/hooks/use-shortcut.ts"
+);
+const { isAcceptableBinding, parseBinding } = await import(
+ "../src/features/settings/lib/keyboard-shortcuts.ts"
+);
+
+/** A keydown the dispatcher would see, with only the fields it reads. */
+function keydown(init: { isComposing?: boolean; keyCode?: number }) {
+ return {
+ isComposing: init.isComposing ?? false,
+ keyCode: init.keyCode ?? 27,
+ } as unknown as KeyboardEvent;
+}
+
+// Escape cancels an IME candidate and Enter commits one, and both ship bare
+// here, so without this a CJK user dismissing a candidate answers the tool
+// call. Two signals because neither is reliable alone: isComposing on WebKit,
+// the legacy 229 on Chromium.
+test("a keydown mid-IME-composition is not a chord", () => {
+ assert.equal(isImeComposing(keydown({ isComposing: true })), true);
+ assert.equal(isImeComposing(keydown({ keyCode: 229 })), true);
+ assert.equal(isImeComposing(keydown({ isComposing: true, keyCode: 229 })), true);
+ assert.equal(isImeComposing(keydown({})), false);
+});
+
+test("the dispatcher checks composition before it matches anything", async () => {
+ const source = await readFile(
+ new URL("../src/features/settings/hooks/use-shortcut.ts", import.meta.url),
+ "utf8",
+ );
+ // Before the match, so no chord is found, and before preventDefault, so the
+ // candidate window keeps its key.
+ assert.match(
+ source,
+ /if \(isImeComposing\(event\)\) return;\n\s*const hit = bindings\.find/,
+ );
+});
+
+// Tab moves focus and a chord consumes what it answers. Bound bare to a tool
+// decision it makes that card's own buttons unreachable by keyboard, which is
+// worse than the chord not existing.
+test("bare Tab is refused even for a prompt-gated action", () => {
+ assert.equal(isAcceptableBinding(parseBinding("Tab")!, true), false);
+ assert.equal(isAcceptableBinding(parseBinding("Shift+Tab")!, true), false);
+ assert.equal(isAcceptableBinding(parseBinding("Tab")!, false), false);
+});
+
+test("Tab held with a modifier is still a chord", () => {
+ // The recently-viewed walk ships on exactly these.
+ assert.equal(isAcceptableBinding(parseBinding("Ctrl+Tab")!, false), true);
+ assert.equal(isAcceptableBinding(parseBinding("Mod+Tab")!, false), true);
+ assert.equal(isAcceptableBinding(parseBinding("Mod+Shift+Tab")!, false), true);
+});
+
+test("refusing Tab does not disturb the other bare-key rules", () => {
+ assert.equal(isAcceptableBinding(parseBinding("Enter")!, true), true);
+ assert.equal(isAcceptableBinding(parseBinding("Escape")!, true), true);
+ assert.equal(isAcceptableBinding(parseBinding("KeyG")!, false), false);
+ assert.equal(isAcceptableBinding(parseBinding("F5")!, false), true);
+ assert.equal(isAcceptableBinding(parseBinding("Shift+Escape")!, false), true);
+});
+
+/** Install a document whose querySelectorAll answers with `els`. */
+function withElements(...els: { closest: (selector: string) => unknown }[]) {
+ (globalThis as { document?: unknown }).document = {
+ querySelectorAll: () => els,
+ };
+}
+const under = { closest: () => ({}) };
+const clear = { closest: () => null };
+
+// A dialog leaves the route mounted, so a chord gated only on the route still
+// fires behind it. Radix marks the rest of the page aria-hidden for the life of
+// a modal, which is the general signal rather than a per-dialog store.
+test("a surface under a modal is not in the foreground", () => {
+ withElements(under);
+ assert.equal(isSurfaceInForeground(".aui-composer-input"), false);
+});
+
+test("a surface with nothing over it is in the foreground", () => {
+ withElements(clear);
+ assert.equal(isSurfaceInForeground(".aui-composer-input"), true);
+});
+
+test("a surface that is not rendered at all is not in the foreground", () => {
+ withElements();
+ assert.equal(isSurfaceInForeground(".aui-composer-input"), false);
+});
+
+// Entering Compare leaves the base view mounted and inert behind the panes, so
+// the first composer in the document is the hidden one. Asking it alone called
+// Compare backgrounded and killed its dictation chord outright.
+test("a hidden earlier match does not mask a visible later one", () => {
+ withElements(under, clear);
+ assert.equal(isSurfaceInForeground(".aui-composer-input"), true);
+});
+
+test("every match under a modal is still not the foreground", () => {
+ withElements(under, under);
+ assert.equal(isSurfaceInForeground(".aui-composer-input"), false);
+});
+
+test("dictation asks at press time, not through enabled", async () => {
+ const source = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ const at = source.indexOf('useShortcut(\n "startDictation"');
+ assert.notEqual(at, -1, "the dictation chord lost its call site");
+ const body = source.slice(at, source.indexOf("\n );", at));
+ // Inside the handler: `enabled` is read at render, and a dialog opening need
+ // not re-render this component.
+ assert.match(
+ body,
+ /\(\) => \{\n\s*\/\/[\s\S]*?if \(!isSurfaceInForeground\(COMPOSER_INPUT_SELECTOR\)\) return;/,
+ );
+});
+
+// A write that fails with a good payload used to report nothing at all, so the
+// chord was indistinguishable from a dead key.
+test("both copy chords report a failed write", async () => {
+ const source = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /} else if \(empty\.value\) \{[\s\S]*?\} else \{[\s\S]*?toast\.error\("Could not copy this chat\."\)/,
+ );
+ assert.match(source, /toast\.error\("Could not copy the session id\."\)/);
+});
+
+// Current membership says nothing about where a chat's older files went: it can
+// join a project, record that session, and move back out.
+test("the sandbox probe does not skip a chat that is out of a project", async () => {
+ const source = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ const at = source.indexOf("async function sandboxSessionIdsHolding");
+ assert.notEqual(at, -1);
+ const body = source.slice(at, source.indexOf("\n }", at));
+ assert.doesNotMatch(body, /if \(!item\.projectId\) return recorded;/);
+ assert.match(
+ body,
+ /if \(await sandboxHasFiles\(candidate\)\) held\.push\(candidate\);/,
+ );
+});
+
+// Both composers register the dictation chord, and only one is on screen at a
+// time, so the foreground check has to be on both or Compare keeps the hole.
+test("both composers gate dictation on the foreground", async () => {
+ for (const path of [
+ "../src/components/assistant-ui/thread.tsx",
+ "../src/features/chat/shared-composer.tsx",
+ ]) {
+ const source = await readFile(new URL(path, import.meta.url), "utf8");
+ const at = source.indexOf('useShortcut(\n "startDictation"');
+ assert.notEqual(at, -1, `${path} lost its dictation chord`);
+ const body = source.slice(at, source.indexOf("\n );", at));
+ assert.match(
+ body,
+ /if \(!isSurfaceInForeground\(COMPOSER_INPUT_SELECTOR\)\) return;/,
+ `${path} starts the microphone behind a modal`,
+ );
+ }
+});
+
+// The sidebar used to hold the unread set in component state, which died with
+// it. A module store does not, so the next account inherits it.
+test("signing out drops the previous account's navigation state", async () => {
+ const store = await readFile(
+ new URL("../src/features/chat/stores/chat-navigation-store.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(store, /resetAccountState: \(\) =>/);
+ // A fresh Set, or every account after the first shares one.
+ assert.match(store, /set\(\{ \.\.\.ACCOUNT_STATE, unreadThreadIds: new Set\(\), unreadRowIds: \{\} \}\)/);
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ // On unmount, which is what the auth routes do to the sidebar.
+ assert.match(
+ sidebar,
+ /useEffect\(\n\s*\(\) => \(\) => useChatNavigationStore\.getState\(\)\.resetAccountState\(\),\n\s*\[\],\n\s*\);/,
+ );
+});
+
+// The latch holds back a repeat of the action that took the selection, not a
+// different command issued straight after it.
+test("the selection latch is keyed by action", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(sidebar, /selectionActedRef = useRef<\{ id: ShortcutId; at: number \} \| null>/);
+ assert.match(sidebar, /last\?\.id === id &&/);
+ assert.doesNotMatch(sidebar, /followsSelectionAction\(\)/);
+});
+
+// One selector has to mean "the composer" whichever of the two is on screen, or
+// Escape stops declining in Compare and the dictation gate reads the wrong one.
+test("both composers answer to the shared selector", async () => {
+ const shared = await readFile(
+ new URL("../src/features/chat/shared-composer.tsx", import.meta.url),
+ "utf8",
+ );
+ const thread = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ const { COMPOSER_INPUT_SELECTOR } = await import(
+ "../src/features/settings/hooks/use-shortcut.ts"
+ );
+ const className = COMPOSER_INPUT_SELECTOR.replace(/^\./, "");
+ for (const [name, source] of [["shared", shared], ["thread", thread]]) {
+ assert.match(
+ source,
+ new RegExp(`className="[^"]*\\b${className}\\b[^"]*"`),
+ `the ${name} composer does not carry ${className}`,
+ );
+ }
+});
+
+// The recording bar replaces the composer input while dictation runs, so the
+// foreground gate asks about an element that is gone for exactly as long as
+// there is a recording to stop. Stopping has to come first.
+test("stopping dictation is reachable once the input is gone", async () => {
+ for (const path of [
+ "../src/components/assistant-ui/thread.tsx",
+ "../src/features/chat/shared-composer.tsx",
+ ]) {
+ const source = await readFile(new URL(path, import.meta.url), "utf8");
+ const at = source.indexOf('useShortcut(\n "startDictation"');
+ const body = source.slice(at, source.indexOf("\n );", at));
+ const stop = body.search(/stopDictation\(\)/);
+ const gate = body.search(/isSurfaceInForeground\(/);
+ assert.notEqual(stop, -1, `${path} lost its stop branch`);
+ assert.notEqual(gate, -1, `${path} lost its foreground gate`);
+ assert.ok(
+ stop < gate,
+ `${path} gates the stop branch on a surface dictation removes`,
+ );
+ }
+});
+
+// Sending is not undoable, and a dialog over Chat leaves the chord registered
+// with the draft behind it still submittable.
+test("both composers refuse to send from behind a modal", async () => {
+ for (const path of [
+ "../src/components/assistant-ui/thread.tsx",
+ "../src/features/chat/shared-composer.tsx",
+ ]) {
+ const source = await readFile(new URL(path, import.meta.url), "utf8");
+ const at = source.indexOf('useShortcut(\n "sendMessage"');
+ assert.notEqual(at, -1, `${path} lost its send chord`);
+ const body = source.slice(at, source.indexOf("\n );", at));
+ assert.match(
+ body,
+ /if \(!isSurfaceInForeground\(COMPOSER_INPUT_SELECTOR\)\) return;/,
+ `${path} sends the hidden draft from behind a dialog`,
+ );
+ }
+});
+
+// A surface that is not rendered is not covered. The mobile sidebar lives in a
+// drawer and is unmounted while it is closed, so reading "no match" as covered
+// would leave every sidebar chord dead on mobile.
+test("an absent surface is not a covered one", () => {
+ const doc = globalThis.document;
+ try {
+ (globalThis as { document?: unknown }).document = {
+ querySelectorAll: () => [],
+ };
+ assert.equal(isSurfaceBackgrounded(".gone"), false);
+ assert.equal(isSurfaceInForeground(".gone"), false);
+ const covered = { closest: () => ({}) };
+ const open = { closest: () => null };
+ (globalThis as { document?: unknown }).document = {
+ querySelectorAll: () => [covered],
+ };
+ assert.equal(isSurfaceBackgrounded(".x"), true);
+ (globalThis as { document?: unknown }).document = {
+ querySelectorAll: () => [covered, open],
+ };
+ // One live match is enough: the base view stays mounted behind Compare.
+ assert.equal(isSurfaceBackgrounded(".x"), false);
+ } finally {
+ (globalThis as { document?: unknown }).document = doc;
+ }
+});
+
+// Window-level chords stay registered under a dialog, so the destructive ones
+// have to ask at press time whether the sidebar is still the foreground.
+test("the sidebar's mutating chords refuse to fire under a dialog", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ for (const id of [
+ "archiveChat",
+ "markChatUnread",
+ "togglePinChat",
+ "deleteSelectedChats",
+ "renameChat",
+ "clearAllUnreads",
+ ]) {
+ const at = sidebar.indexOf(`useShortcut("${id}", () => {`);
+ assert.notEqual(at, -1, `${id} is gone`);
+ const body = sidebar.slice(at, sidebar.indexOf("\n });", at));
+ assert.match(
+ body,
+ /if \(sidebarCovered\(\)\) return;/,
+ `${id} acts on the chat behind an open dialog`,
+ );
+ }
+ // Covered, not "not in the foreground", or the mobile drawer kills them all.
+ assert.match(sidebar, /isSurfaceBackgrounded\(SIDEBAR_SELECTOR\)/);
+ // And with the drawer closed the sidebar is unmounted, so the app root is
+ // what carries the modal signal there.
+ assert.match(
+ sidebar,
+ /document\.querySelector\(SIDEBAR_SELECTOR\) === null &&\n\s*isSurfaceBackgrounded\("#root"\)/,
+ );
+});
+
+// A chat that ran tools before and after joining a project has files in the
+// thread folder and in the project one. Probing only the thread folder
+// answered for one and hid the other.
+test("the sandbox probe leaves the shared project folder alone", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ const at = sidebar.indexOf("async function sandboxSessionIdsHolding(");
+ assert.notEqual(at, -1);
+ const body = sidebar.slice(at, sidebar.indexOf("\n }", at));
+ // The shared project workspace is not probed: every chat in the project
+ // writes there, so its files are no evidence about this one, and counting
+ // them reported a second folder for any chat that joined a used project.
+ assert.doesNotMatch(body, /sandboxSessionIdFor\(/);
+ assert.doesNotMatch(body, /candidates\.add\(/);
+ assert.equal(sidebar.split("sandboxSessionIdsHolding(ids)").length - 1, 2);
+});
+
+// Loading a model that drops the level in force leaves the effort set to one
+// the model does not list, and indexOf then returns -1.
+test("an unlisted reasoning effort steps to the first supported level", async () => {
+ const page = await readFile(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+ const at = page.indexOf("const current = levels.indexOf(state.reasoningEffort);");
+ assert.notEqual(at, -1);
+ const body = page.slice(at, at + 700);
+ assert.match(
+ body,
+ /if \(current === -1\) \{\n\s*state\.setReasoningEffort\(levels\[0\]\);/,
+ "an unlisted effort still counts a step off an index that is not in the list",
+ );
+});
+
+// The composer exception exists for a chord that types nothing there. Decline
+// ships on Escape, but the row takes bare keys, so it can be rebound to one
+// that does type, and the pass would then deny the request mid-sentence.
+test("only a chord that types nothing keeps the composer exception", () => {
+ const bare = (code: string) => ({
+ code,
+ mod: false,
+ ctrl: false,
+ shift: false,
+ alt: false,
+ });
+ assert.equal(typesInTextField(bare("Escape")), false);
+ assert.equal(typesInTextField(bare("F5")), false);
+ assert.equal(typesInTextField(bare("Enter")), true);
+ assert.equal(typesInTextField(bare("KeyA")), true);
+ assert.equal(typesInTextField(bare("Backspace")), true);
+ // A caret key inserts nothing, but a chord on one still has an edit to
+ // stand aside for, so it does not get the pass either.
+ assert.equal(typesInTextField(bare("ArrowUp")), true);
+ // Held with anything but Shift it types nothing, whatever the key is.
+ assert.equal(typesInTextField({ ...bare("KeyA"), mod: true }), false);
+ assert.equal(typesInTextField({ ...bare("KeyA"), shift: true }), true);
+});
+
+test("the dispatcher drops the exception for a typing chord", async () => {
+ const source = await readFile(
+ new URL("../src/features/settings/hooks/use-shortcut.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /const exception = typesInTextField\(hit\) \? undefined : textFieldException;/,
+ );
+ assert.match(source, /isTextEntryFocused\(exception\)/);
+});
+
+// Every keydown is swallowed while recording, and on a bare-key row Escape is
+// a chord rather than a cancel, so a keyboard-only user had no way out.
+test("recording can be left from the keyboard", async () => {
+ const tab = await readFile(
+ new URL(
+ "../src/features/settings/tabs/keyboard-shortcuts-tab.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const at = tab.indexOf("const onKeyDown = (event: KeyboardEvent) => {");
+ assert.notEqual(at, -1);
+ const body = tab.slice(at, at + 900);
+ const exit = body.indexOf('event.code === "Tab"');
+ const swallow = body.indexOf("event.preventDefault();");
+ assert.notEqual(exit, -1, "recording has no keyboard exit");
+ assert.ok(exit < swallow, "the exit is swallowed before it is read");
+});
+
+// The page stays mounted under a dialog, so `enabled` still says yes.
+test("the header pickers do not open behind a dialog", async () => {
+ const page = await readFile(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+ for (const id of ["openModelPicker", "openProjectPicker"]) {
+ const at = page.indexOf(`"${id}",`);
+ assert.notEqual(at, -1, `${id} is gone`);
+ assert.match(
+ page.slice(at, at + 260),
+ /if \(chatCovered\(\)\) return;/,
+ `${id} opens a control on the covered surface`,
+ );
+ }
+ assert.match(
+ page,
+ /isSurfaceBackgrounded\(COMPOSER_INPUT_SELECTOR\)/,
+ );
+});
+
+// The OS file chooser is the least dismissable thing a chord can raise.
+test("both composers refuse to attach from behind a modal", async () => {
+ for (const path of [
+ "../src/components/assistant-ui/thread.tsx",
+ "../src/features/chat/shared-composer.tsx",
+ ]) {
+ const source = await readFile(new URL(path, import.meta.url), "utf8");
+ const at = source.indexOf('useShortcut(\n "attachFiles"');
+ assert.notEqual(at, -1, `${path} lost its attach chord`);
+ const body = source.slice(at, source.indexOf("\n );", at));
+ assert.match(
+ body,
+ /if \(!isSurfaceInForeground\(COMPOSER_INPUT_SELECTOR\)\) return;/,
+ `${path} opens the file chooser behind a dialog`,
+ );
+ }
+});
+
+// Answering a tool call the user cannot see is the one decision here that must
+// not be reachable by accident, and the Chat route stays mounted under a
+// dialog, so `keyboardReady` alone still says yes.
+test("a tool call cannot be answered from behind a dialog", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/components/assistant-ui/tool-confirmation-controls.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ for (const id of ["approveToolRequest", "declineToolRequest"]) {
+ const at = source.indexOf(`"${id}",`);
+ assert.notEqual(at, -1, `${id} is gone`);
+ const body = source.slice(at, at + 200);
+ const guard = body.indexOf("if (chatCovered()) return;");
+ const call = body.indexOf("resolve(");
+ assert.notEqual(guard, -1, `${id} answers from behind a dialog`);
+ assert.ok(guard < call, `${id} resolves before it checks`);
+ }
+ assert.match(source, /isSurfaceBackgrounded\(COMPOSER_INPUT_SELECTOR\)/);
+});
+
+// A selection made behind a dialog is invisible and still what the mutating
+// chords act on afterwards, and the clipboard is outside the app entirely.
+test("selection and clipboard chords stop at a covered sidebar", async () => {
+ const sidebar = await readFile(
+ new URL("../src/components/app-sidebar.tsx", import.meta.url),
+ "utf8",
+ );
+ for (const id of ["selectAllChats", "copyChatAsMarkdown", "copySessionId"]) {
+ const at = sidebar.indexOf(`useShortcut("${id}", () => {`);
+ assert.notEqual(at, -1, `${id} is gone`);
+ const body = sidebar.slice(at, sidebar.indexOf("\n });", at));
+ assert.match(
+ body,
+ /if \(sidebarCovered\(\)\) return;/,
+ `${id} acts behind an open dialog`,
+ );
+ }
+});
+
+// The rows these chords stand in for stay enabled while the hardware verdict is
+// out: resolveNavRowState returns disabled false for a pending row on purpose,
+// so the click lands on a page that shows its own loading state. Gating the
+// chords on the unknown verdict would make them disagree with their own rows.
+test("the workspace chords wait on the same verdict their rows do", async () => {
+ const root = await readFile(
+ new URL("../src/app/routes/__root.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(root, /enabled: !isAuthFlowRoute && !chatOnlyMeasured,/);
+ assert.match(root, /enabled: !isAuthFlowRoute && !videoDisabled,/);
+ const rowState = await readFile(
+ new URL("../src/components/nav-row-state.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ rowState,
+ /if \(row\.pending\) \{\n\s*return \{\n\s*disabled: false,/,
+ "a pending row now blocks the click the chord is allowed to make",
+ );
+});
+
+// The reasoning, Fast mode and fork chords drive controls on the page behind a
+// dialog just as the pickers do.
+test("the remaining chat-page chords stop at a covered surface", async () => {
+ const page = await readFile(
+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),
+ "utf8",
+ );
+ for (const id of [
+ "cycleReasoningEffort",
+ "increaseReasoningEffort",
+ "decreaseReasoningEffort",
+ "toggleFastMode",
+ ]) {
+ const at = page.indexOf(`"${id}",`);
+ assert.notEqual(at, -1, `${id} is gone`);
+ assert.match(
+ page.slice(at, at + 220),
+ /if \(chatCovered\(\)\) return;/,
+ `${id} acts on the covered surface`,
+ );
+ }
+ const thread = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ const at = thread.indexOf('"forkChat",');
+ assert.notEqual(at, -1);
+ assert.match(
+ thread.slice(at, at + 320),
+ /if \(!isSurfaceInForeground\(COMPOSER_INPUT_SELECTOR\)\) return;/,
+ );
+});
+
+// A non-modal popover leaves the composer the foreground, so the press-time
+// check alone does not keep the send chord out of the picker's search box.
+test("the send chords stand aside in any text field but the composer", async () => {
+ for (const path of [
+ "../src/components/assistant-ui/thread.tsx",
+ "../src/features/chat/shared-composer.tsx",
+ ]) {
+ const source = await readFile(new URL(path, import.meta.url), "utf8");
+ const at = source.indexOf('useShortcut(\n "sendMessage"');
+ assert.notEqual(at, -1, `${path} lost its send chord`);
+ const body = source.slice(at, source.indexOf("\n );", at));
+ assert.match(body, /skipInTextFields: true,/, `${path} sends from any field`);
+ assert.match(
+ body,
+ /textFieldException: COMPOSER_INPUT_SELECTOR,/,
+ `${path} can no longer send from the composer itself`,
+ );
+ }
+});
diff --git a/studio/frontend/tests/shortcut-text-field-gate.test.ts b/studio/frontend/tests/shortcut-text-field-gate.test.ts
new file mode 100644
index 00000000000..6d6d0fb8ea2
--- /dev/null
+++ b/studio/frontend/tests/shortcut-text-field-gate.test.ts
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { COMPOSER_INPUT_SELECTOR, isTextEntryFocused } = await import(
+ "../src/features/settings/hooks/use-shortcut.ts"
+);
+
+/** Put an element in the focus the gate reads, with no DOM to do it for us. */
+function focus(el: { tagName?: string; isContentEditable?: boolean } | null) {
+ (globalThis as { document?: unknown }).document = {
+ activeElement: el
+ ? { matches: (selector: string) => selector === el.tagName, ...el }
+ : null,
+ };
+}
+
+/** A focused field that answers `matches` for exactly these selectors. */
+function field(tagName: string, ...selectors: string[]) {
+ return {
+ tagName,
+ matches: (selector: string) => selectors.includes(selector),
+ };
+}
+
+test("the gate holds for every text entry when no exception is named", () => {
+ for (const tagName of ["INPUT", "TEXTAREA"]) {
+ focus(field(tagName));
+ assert.equal(isTextEntryFocused(), true);
+ }
+ focus({ tagName: "DIV", isContentEditable: true });
+ assert.equal(isTextEntryFocused(), true);
+
+ // Everything else is not typing, so the gate has nothing to hold back.
+ focus(field("BUTTON"));
+ assert.equal(isTextEntryFocused(), false);
+ focus(null);
+ assert.equal(isTextEntryFocused(), false);
+});
+
+test("the composer exception frees the composer and nothing else", () => {
+ // The state a tool request arrives in: the prompt that caused it left focus
+ // in the composer, and Escape types nothing there.
+ focus(field("TEXTAREA", COMPOSER_INPUT_SELECTOR));
+ assert.equal(isTextEntryFocused(), true, "the plain gate still holds it");
+ assert.equal(isTextEntryFocused(COMPOSER_INPUT_SELECTOR), false);
+
+ // Every other field keeps its own Escape: the queued-prompt editor, the
+ // settings search, a rename pill.
+ focus(field("TEXTAREA"));
+ assert.equal(isTextEntryFocused(COMPOSER_INPUT_SELECTOR), true);
+ focus(field("INPUT"));
+ assert.equal(isTextEntryFocused(COMPOSER_INPUT_SELECTOR), true);
+ focus({ tagName: "DIV", isContentEditable: true });
+ assert.equal(isTextEntryFocused(COMPOSER_INPUT_SELECTOR), true);
+});
+
+test("the decline chord takes the exception and the approve chord does not", async () => {
+ const controls = await readFile(
+ new URL(
+ "../src/components/assistant-ui/tool-confirmation-controls.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // Escape leaves the text alone. Enter sends, so it stays behind the gate.
+ assert.match(
+ controls,
+ /useShortcut\(\n\s*"declineToolRequest",[\s\S]{0,800}?textFieldException: COMPOSER_INPUT_SELECTOR,/,
+ );
+ const approve = controls.slice(
+ controls.indexOf('"approveToolRequest",'),
+ controls.indexOf('"declineToolRequest",'),
+ );
+ assert.ok(approve.includes("skipInTextFields: true"));
+ assert.ok(!approve.includes("textFieldException"));
+});
+
+test("the selector matches the class the composer actually carries", async () => {
+ const thread = await readFile(
+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.equal(COMPOSER_INPUT_SELECTOR, ".aui-composer-input");
+ // A selector naming a class nothing carries would silently gate everything.
+ assert.match(thread, /className="aui-composer-input /);
+});
diff --git a/studio/frontend/tsconfig.app.json b/studio/frontend/tsconfig.app.json
index bdda66808bb..374932571f8 100644
--- a/studio/frontend/tsconfig.app.json
+++ b/studio/frontend/tsconfig.app.json
@@ -36,6 +36,7 @@
"smoke-heavy-thread-main.tsx",
"smoke-thread-weight-main.tsx",
"smoke-settings-main.tsx",
+ "smoke-shortcuts-main.tsx",
"smoke-stream-pacing-main.tsx",
"smoke-code-block-flicker-main.tsx"
]
diff --git a/tests/studio/playwright_keyboard_shortcuts.py b/tests/studio/playwright_keyboard_shortcuts.py
new file mode 100644
index 00000000000..2765fbb9f50
--- /dev/null
+++ b/tests/studio/playwright_keyboard_shortcuts.py
@@ -0,0 +1,643 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Keyboard shortcut behaviour, in a real browser, on three emulated platforms.
+
+Drives smoke-shortcuts.html: the real registry, the real store and the real
+useShortcut against a browser's own keyboard. The node suite reaches the pure
+functions, but a listener is not a pure function, so what a chord does to a
+focused button, to a text field, on auto-repeat, under AltGr, or to a stored
+binding carried over from another platform is only answerable here.
+
+ SMOKE_ENGINES=chromium,firefox,webkit python3 tests/studio/playwright_keyboard_shortcuts.py
+
+Platform is emulated the way the app reads it, through navigator.platform and
+the user agent, because isMacPlatform() is memoised on first call.
+"""
+
+import json
+import os
+import sys
+import time
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import ( # noqa: E402
+ chromium_launch_args,
+ start_vite,
+ stop_process,
+)
+
+PORT = int(os.environ.get("SMOKE_PORT", "5407"))
+ENGINES = [e for e in os.environ.get("SMOKE_ENGINES", "chromium").split(",") if e]
+URL = f"http://127.0.0.1:{PORT}/smoke-shortcuts.html"
+
+# navigator.platform, and a user agent to match. WebKit reports a Mac agent even
+# on Linux, so nothing here may be left to the engine's own default.
+PLATFORMS = {
+ "macOS": ("MacIntel", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) SmokeUA"),
+ "Windows": ("Win32", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) SmokeUA"),
+ "Linux": ("Linux x86_64", "Mozilla/5.0 (X11; Linux x86_64) SmokeUA"),
+}
+MOD = {"macOS": "Meta", "Windows": "Control", "Linux": "Control"}
+
+failures: list[str] = []
+passed = 0
+
+
+def check(
+ engine: str,
+ platform: str,
+ name: str,
+ ok: bool,
+ detail: str = "",
+) -> None:
+ global passed
+ if ok:
+ passed += 1
+ return
+ failures.append(f"{engine}/{platform}: {name}\n {detail}")
+
+
+def to_press(value: str, platform: str) -> str:
+ """A stored binding, in the key syntax Playwright presses."""
+ parts = value.split("+")
+ mods = [
+ MOD[platform] if token == "Mod" else {"Ctrl": "Control"}.get(token, token)
+ for token in parts[:-1]
+ ]
+ return "+".join([*mods, parts[-1]])
+
+
+def actions(page) -> list[str]:
+ return [e["action"] for e in page.evaluate("window.__shortcutsSmoke.fired()")]
+
+
+def details(page) -> list[str]:
+ return [e.get("detail") for e in page.evaluate("window.__shortcutsSmoke.fired()")]
+
+
+def reset(page) -> None:
+ page.evaluate("window.__shortcutsSmoke.reset()")
+
+
+def reload_with(page, raw: str | None) -> None:
+ """Seed storage the way an install of any age would have, then restart."""
+ page.evaluate(
+ """([raw]) => {
+ if (raw === null) localStorage.removeItem("unsloth_keyboard_shortcuts");
+ else localStorage.setItem("unsloth_keyboard_shortcuts", raw);
+ }""",
+ [raw],
+ )
+ page.goto(URL)
+ page.wait_for_selector("#smoke-ready")
+
+
+def check_defaults(page, engine: str, platform: str) -> None:
+ check(
+ engine,
+ platform,
+ "isMacPlatform follows the emulated platform",
+ page.evaluate("window.__shortcutsSmoke.registry.isMacPlatform()") == (platform == "macOS"),
+ )
+ rows = page.evaluate(
+ """() => {
+ const r = window.__shortcutsSmoke.registry;
+ const mac = r.isMacPlatform();
+ const out = [];
+ for (const def of r.SHORTCUT_DEFS) {
+ for (const slot of r.SHORTCUT_SLOTS) {
+ const value = r.defaultBindingFor(def, slot, mac);
+ if (value == null) continue;
+ const parsed = r.parseBinding(value);
+ out.push({ id: def.id, value, parsed: parsed &&
+ `${parsed.code}|${parsed.mod}|${parsed.ctrl}|${parsed.shift}|${parsed.alt}`,
+ canon: parsed && r.formatBindingValue(parsed) });
+ }
+ }
+ return out;
+ }"""
+ )
+ check(
+ engine,
+ platform,
+ "every shipped default parses and is canonical",
+ all(r["parsed"] and r["canon"] == r["value"] for r in rows),
+ )
+ seen: dict[str, set[str]] = {}
+ for row in rows:
+ seen.setdefault(row["parsed"], set()).add(row["id"])
+ clash = {k: sorted(v) for k, v in seen.items() if len(v) > 1}
+ check(
+ engine,
+ platform,
+ "no two actions claim one physical chord",
+ not clash,
+ json.dumps(clash)[:200],
+ )
+ if platform != "macOS":
+ ctrl = [r["id"] for r in rows if r["parsed"].split("|")[2] == "true"]
+ check(engine, platform, "no unreachable Ctrl default off macOS", not ctrl, str(ctrl))
+
+
+def check_dispatch(page, engine: str, platform: str) -> None:
+ reset(page)
+ page.keyboard.press(to_press("Mod+Comma", platform))
+ check(
+ engine,
+ platform,
+ "a shipped chord fires from a real keypress",
+ "openSettings" in actions(page),
+ str(actions(page)),
+ )
+
+ # Exact match: the chord is this set of modifiers, not at least this set.
+ reset(page)
+ page.keyboard.press(f"{MOD[platform]}+Alt+Comma")
+ check(
+ engine,
+ platform,
+ "an extra modifier does not satisfy a chord",
+ "openSettings" not in actions(page),
+ str(actions(page)),
+ )
+
+ # Both slots answer. newChat is the only action that ships a pair.
+ reset(page)
+ page.keyboard.press(to_press("Mod+Shift+KeyO", platform))
+ page.keyboard.press(to_press("Mod+KeyN", platform))
+ check(
+ engine,
+ platform,
+ "both slots of an action fire",
+ actions(page).count("newChat") == 2,
+ str(actions(page)),
+ )
+
+
+def check_text_fields(page, engine: str, platform: str) -> None:
+ reset(page)
+ page.focus("#smoke-input")
+ page.keyboard.press(to_press("Mod+KeyK", platform))
+ guarded = actions(page)
+ page.evaluate("document.activeElement && document.activeElement.blur()")
+ reset(page)
+ page.keyboard.press(to_press("Mod+KeyK", platform))
+ check(
+ engine,
+ platform,
+ "a text-field chord stands aside while typing",
+ "searchChats" not in guarded and "searchChats" in actions(page),
+ f"in field {guarded}, outside {actions(page)}",
+ )
+
+ reset(page)
+ page.focus("#smoke-editable")
+ page.keyboard.press(to_press("Mod+KeyK", platform))
+ check(
+ engine,
+ platform,
+ "the gate covers contenteditable too",
+ "searchChats" not in actions(page),
+ str(actions(page)),
+ )
+
+ # Escape types nothing in the composer, so declining keeps working there,
+ # and Enter, which sends, does not.
+ reset(page)
+ page.focus("#smoke-composer")
+ page.keyboard.press("Escape")
+ declined = actions(page)
+ reset(page)
+ page.focus("#smoke-composer")
+ page.keyboard.press("Enter")
+ check(
+ engine,
+ platform,
+ "the composer excepts Escape but not Enter",
+ "decline" in declined and "approve" not in actions(page),
+ f"escape {declined}, enter {actions(page)}",
+ )
+
+ reset(page)
+ page.focus("#smoke-input")
+ page.keyboard.press("Escape")
+ check(
+ engine,
+ platform,
+ "an ordinary field keeps its own Escape",
+ "decline" not in actions(page),
+ str(actions(page)),
+ )
+ page.evaluate("document.activeElement && document.activeElement.blur()")
+
+
+def check_bare_keys(page, engine: str, platform: str) -> None:
+ reset(page)
+ page.keyboard.press("Enter")
+ check(
+ engine,
+ platform,
+ "bare Enter answers a waiting request",
+ "approve" in actions(page),
+ str(actions(page)),
+ )
+
+ # The whole reason the stand-aside exists: preventDefault runs before the
+ # handler, so without it Enter on Deny would cancel the click and approve.
+ reset(page)
+ page.focus("#smoke-button")
+ page.keyboard.press("Enter")
+ got = actions(page)
+ check(
+ engine,
+ platform,
+ "Enter on a focused button clicks it and does not approve",
+ "buttonClick" in got and "approve" not in got,
+ str(got),
+ )
+
+ reset(page)
+ page.focus("#smoke-link")
+ page.keyboard.press("Enter")
+ check(
+ engine,
+ platform,
+ "Enter on a focused link does not approve",
+ "approve" not in actions(page),
+ str(actions(page)),
+ )
+
+ # Escape activates nothing, so it is deliberately not stood aside.
+ reset(page)
+ page.focus("#smoke-button")
+ page.keyboard.press("Escape")
+ check(
+ engine,
+ platform,
+ "Escape still declines from a focused button",
+ "decline" in actions(page),
+ str(actions(page)),
+ )
+ page.evaluate("document.activeElement && document.activeElement.blur()")
+
+
+def check_repeat(page, engine: str, platform: str) -> None:
+ for code, key, name, expected, label in (
+ ("BracketRight", "]", "nextChat", 3, "a walking chord runs on auto-repeat"),
+ ("Comma", ",", "openSettings", 1, "a one-shot chord ignores auto-repeat"),
+ ):
+ reset(page)
+ page.evaluate(
+ """([mac, code, key, shift]) => {
+ for (let i = 0; i < 3; i++) {
+ window.dispatchEvent(new KeyboardEvent('keydown', {
+ key, code, bubbles: true, cancelable: true, shiftKey: shift,
+ metaKey: mac, ctrlKey: !mac, repeat: i > 0,
+ }));
+ }
+ }""",
+ [platform == "macOS", code, key, code == "BracketRight"],
+ )
+ check(engine, platform, label, actions(page).count(name) == expected, str(actions(page)))
+
+
+def check_altgr(page, engine: str, platform: str) -> None:
+ # AltGr reports itself as Ctrl+Alt. Off macOS an Alt chord must stand aside
+ # so the character is typed; on macOS Option reports AltGraph and is a plain Alt.
+ reset(page)
+ prevented = page.evaluate(
+ """([mac]) => {
+ const ev = new KeyboardEvent('keydown', {
+ key: 'e', code: 'KeyE', bubbles: true, cancelable: true,
+ metaKey: mac, ctrlKey: !mac, altKey: true,
+ });
+ ev.getModifierState = (m) => m === 'AltGraph';
+ window.dispatchEvent(ev);
+ return ev.defaultPrevented;
+ }""",
+ [platform == "macOS"],
+ )
+ got = actions(page)
+ if platform == "macOS":
+ check(
+ engine,
+ platform,
+ "an Option chord still fires on macOS",
+ "archiveActive" in got or "archiveSelected" in got,
+ str(got),
+ )
+ else:
+ check(
+ engine,
+ platform,
+ "AltGr typing neither fires a chord nor loses the character",
+ not got and not prevented,
+ f"{got} prevented={prevented}",
+ )
+
+
+def check_foreign_binding(page, engine: str, platform: str) -> None:
+ # A binding stored on a Mac must not fire on the bare key elsewhere. Before
+ # the registry grew, matchesBinding ignored the ctrl flag off macOS instead
+ # of rejecting it, and a Mac Ctrl chord fired on the unmodified key.
+ reload_with(page, json.dumps({"copySessionId": {"primary": "Ctrl+KeyG"}}))
+ reset(page)
+ page.evaluate(
+ """() => window.dispatchEvent(new KeyboardEvent('keydown', {
+ key: 'g', code: 'KeyG', bubbles: true, cancelable: true }))"""
+ )
+ bare = actions(page)
+ reset(page)
+ page.keyboard.press("Control+KeyG")
+ held = actions(page)
+ if platform == "macOS":
+ check(
+ engine,
+ platform,
+ "a Ctrl chord fires on Ctrl, not on the bare key",
+ "copySessionId" in held and "copySessionId" not in bare,
+ f"bare {bare}, ctrl {held}",
+ )
+ else:
+ check(
+ engine,
+ platform,
+ "a Mac Ctrl chord is inert off macOS",
+ "copySessionId" not in bare and "copySessionId" not in held,
+ f"bare {bare}, ctrl {held}",
+ )
+ reload_with(page, None)
+
+
+def check_storage(page, engine: str, platform: str) -> None:
+ cases = [
+ (
+ "a pre-alternate rebind becomes a primary override",
+ json.dumps({"newChat": "Mod+KeyJ"}),
+ lambda a: a["newChat"]["primary"] == "Mod+KeyJ"
+ and a["newChat"]["alternate"] == "Mod+KeyN",
+ ),
+ (
+ "an action cleared before alternates existed stays cleared",
+ json.dumps({"newChat": None}),
+ lambda a: a["newChat"]["primary"] is None and a["newChat"]["alternate"] is None,
+ ),
+ (
+ "an id from an older build is dropped",
+ json.dumps({"aRemovedAction": "Mod+KeyJ", "newChat": "Mod+KeyJ"}),
+ lambda a: a["newChat"]["primary"] == "Mod+KeyJ",
+ ),
+ (
+ "the current shape round-trips",
+ json.dumps({"toggleSidebar": {"primary": "Mod+Alt+KeyW"}}),
+ lambda a: a["toggleSidebar"]["primary"] == "Mod+Alt+KeyW",
+ ),
+ (
+ "corrupt JSON falls back to the defaults",
+ "{not json",
+ lambda a: a["openSettings"]["primary"] == "Mod+Comma",
+ ),
+ (
+ "a non-object payload falls back to the defaults",
+ "42",
+ lambda a: a["openSettings"]["primary"] == "Mod+Comma",
+ ),
+ (
+ "an array payload falls back to the defaults",
+ "[1,2]",
+ lambda a: a["openSettings"]["primary"] == "Mod+Comma",
+ ),
+ (
+ "a junk slot type reverts that action",
+ json.dumps({"toggleSidebar": {"primary": 5}}),
+ lambda a: a["toggleSidebar"]["primary"] == "Mod+KeyB",
+ ),
+ (
+ "nothing stored takes the defaults",
+ None,
+ lambda a: a["openSettings"]["primary"] == "Mod+Comma",
+ ),
+ ]
+ for name, raw, predicate in cases:
+ reload_with(page, raw)
+ resolved = page.evaluate(
+ """() => {
+ const s = window.__shortcutsSmoke.store;
+ return s.resolveAllBindings(s.useKeyboardShortcutsStore.getState().overrides);
+ }"""
+ )
+ try:
+ ok, detail = predicate(resolved), ""
+ except Exception as exc: # noqa: BLE001
+ ok, detail = False, f"{type(exc).__name__}: {exc}"
+ check(engine, platform, f"storage: {name}", ok, detail)
+
+ # A rebind has to reach the live listener, and survive a restart.
+ reload_with(page, None)
+ page.evaluate(
+ """() => window.__shortcutsSmoke.store.useKeyboardShortcutsStore
+ .getState().setBinding('toggleSidebar', 'primary', 'Mod+Alt+KeyW')"""
+ )
+ reset(page)
+ page.keyboard.press(to_press("Mod+Alt+KeyW", platform))
+ live = actions(page)
+ page.goto(URL)
+ page.wait_for_selector("#smoke-ready")
+ reset(page)
+ page.keyboard.press(to_press("Mod+Alt+KeyW", platform))
+ check(
+ engine,
+ platform,
+ "a rebind takes effect live and survives a restart",
+ "toggleSidebar" in live and "toggleSidebar" in actions(page),
+ f"live {live}, after restart {actions(page)}",
+ )
+
+ page.evaluate(
+ "() => window.__shortcutsSmoke.store.useKeyboardShortcutsStore.getState().resetAll()"
+ )
+ check(
+ engine,
+ platform,
+ "reset all leaves no storage residue",
+ page.evaluate("localStorage.getItem('unsloth_keyboard_shortcuts')") is None,
+ )
+
+
+def check_selection_latch(page, engine: str, platform: str) -> None:
+ archive = to_press("Mod+Alt+KeyE", platform)
+ pin = to_press("Ctrl+Shift+KeyP" if platform == "macOS" else "Mod+Alt+KeyP", platform)
+
+ def with_selection() -> None:
+ page.click("#smoke-select")
+ page.wait_for_function("document.getElementById('smoke-selection').textContent === '3'")
+ reset(page)
+
+ # A selection chord clears the selection, so an immediate second press would
+ # otherwise land on the open chat, which was never selected.
+ with_selection()
+ page.keyboard.press(archive)
+ page.wait_for_function("document.getElementById('smoke-selection').textContent === '0'")
+ page.keyboard.press(archive)
+ check(
+ engine,
+ platform,
+ "a second fast press does not reach the open chat",
+ actions(page) == ["archiveSelected", "archiveSuppressed"],
+ str(actions(page)),
+ )
+
+ # A different command straight after is not the repeat this guards against,
+ # and swallowing it would trade one silent wrong action for another.
+ with_selection()
+ page.keyboard.press(archive)
+ page.wait_for_function("document.getElementById('smoke-selection').textContent === '0'")
+ page.keyboard.press(pin)
+ check(
+ engine,
+ platform,
+ "a sibling chord inside the window still acts on the open chat",
+ actions(page) == ["archiveSelected", "pinActive"],
+ str(actions(page)),
+ )
+
+ # And a deliberate press afterwards still works, or the latch has traded one
+ # silent wrong action for a silent dead key.
+ with_selection()
+ page.keyboard.press(archive)
+ page.wait_for_function("document.getElementById('smoke-selection').textContent === '0'")
+ page.wait_for_timeout(900)
+ page.keyboard.press(archive)
+ check(
+ engine,
+ platform,
+ "a deliberate press after the window still acts",
+ actions(page) == ["archiveSelected", "archiveActive"],
+ str(actions(page)),
+ )
+
+ # With no selection the latch is never stamped, so nothing is swallowed.
+ reset(page)
+ page.keyboard.press(archive)
+ page.keyboard.press(archive)
+ check(
+ engine,
+ platform,
+ "with no selection nothing is swallowed",
+ actions(page) == ["archiveActive", "archiveActive"],
+ str(actions(page)),
+ )
+
+ # Deleting needs no latch: it has no open-chat branch to fall through to.
+ reset(page)
+ page.evaluate(
+ """() => window.__shortcutsSmoke.store.useKeyboardShortcutsStore
+ .getState().setBinding('deleteSelectedChats', 'primary', 'Mod+Alt+KeyY')"""
+ )
+ page.keyboard.press(to_press("Mod+Alt+KeyY", platform))
+ check(
+ engine,
+ platform,
+ "delete selected does nothing without a selection",
+ actions(page) == [],
+ str(actions(page)),
+ )
+ page.evaluate(
+ "() => window.__shortcutsSmoke.store.useKeyboardShortcutsStore.getState().resetAll()"
+ )
+
+
+def check_unreads(page, engine: str, platform: str) -> None:
+ chord = "Shift+Escape" if platform == "macOS" else to_press("Mod+Alt+Shift+KeyU", platform)
+ for size, expected in (
+ (0, "No unread chats"),
+ (1, "Cleared 1 unread chat"),
+ (3, "Cleared 3 unread chats"),
+ ):
+ reset(page)
+ page.evaluate(
+ """([size]) => window.__shortcutsSmoke.nav.setState({
+ unreadThreadIds: new Set(Array.from({ length: size }, (_, i) => `t${i}`)),
+ })""",
+ [size],
+ )
+ page.keyboard.press(chord)
+ left = page.evaluate("window.__shortcutsSmoke.nav.getState().unreadThreadIds.size")
+ check(
+ engine,
+ platform,
+ f"clearing {size} unread reports it and empties the set",
+ details(page)[:1] == [expected] and left == 0,
+ f"{details(page)} left={left}",
+ )
+
+
+def run_engine(pw, engine: str) -> None:
+ launch = {"args": chromium_launch_args()} if engine == "chromium" else {}
+ browser = getattr(pw, engine).launch(**launch)
+ try:
+ for platform, (nav_platform, agent) in PLATFORMS.items():
+ context = browser.new_context(user_agent = agent)
+ context.add_init_script(
+ "Object.defineProperty(navigator, 'platform', "
+ f"{{ get: () => {json.dumps(nav_platform)} }});"
+ )
+ page = context.new_page()
+ for attempt in range(30):
+ try:
+ page.goto(URL, wait_until = "domcontentloaded", timeout = 30000)
+ break
+ except Exception:
+ if attempt == 29:
+ raise
+ time.sleep(2)
+ page.wait_for_selector("#smoke-ready", timeout = 120000)
+ try:
+ check_defaults(page, engine, platform)
+ check_dispatch(page, engine, platform)
+ check_text_fields(page, engine, platform)
+ check_bare_keys(page, engine, platform)
+ check_repeat(page, engine, platform)
+ check_altgr(page, engine, platform)
+ check_foreign_binding(page, engine, platform)
+ check_storage(page, engine, platform)
+ check_selection_latch(page, engine, platform)
+ check_unreads(page, engine, platform)
+ except Exception as exc: # noqa: BLE001
+ check(
+ engine,
+ platform,
+ "the harness ran to completion",
+ False,
+ f"{type(exc).__name__}: {str(exc)[:300]}",
+ )
+ context.close()
+ finally:
+ browser.close()
+
+
+def main() -> int:
+ server = start_vite(PORT)
+ try:
+ with sync_playwright() as pw:
+ for engine in ENGINES:
+ run_engine(pw, engine)
+ finally:
+ stop_process(server)
+
+ total = passed + len(failures)
+ print(
+ f"[keyboard-shortcuts] {passed}/{total} checks passed "
+ f"across {', '.join(ENGINES)} on {', '.join(PLATFORMS)}"
+ )
+ for failure in failures:
+ print(f"[keyboard-shortcuts] FAIL {failure}")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())