From d6673a2127671c6732f7d943226662cba18e6d33 Mon Sep 17 00:00:00 2001 From: Dylan McCavitt Date: Wed, 8 Jul 2026 12:13:48 -0400 Subject: [PATCH 1/3] =?UTF-8?q?AGE-692=20=E2=80=94=20User-configurable=20k?= =?UTF-8?q?eybindings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- e2e/demo/scenarios/keybindings.mjs | 53 ++++++ src/main/services/settings-service.ts | 41 ++++- src/renderer/src/lib/keybindings.ts | 194 +++++++++++++++++++++ src/renderer/src/lib/useShortcuts.test.tsx | 27 +++ src/renderer/src/lib/useShortcuts.ts | 86 +++++---- src/renderer/src/views/Settings.test.tsx | 50 +++++- src/renderer/src/views/Settings.tsx | 169 ++++++++++++++++++ src/shared/ipc.ts | 35 ++++ test/settings-service.test.ts | 36 ++++ 9 files changed, 642 insertions(+), 49 deletions(-) create mode 100644 e2e/demo/scenarios/keybindings.mjs create mode 100644 src/renderer/src/lib/keybindings.ts diff --git a/e2e/demo/scenarios/keybindings.mjs b/e2e/demo/scenarios/keybindings.mjs new file mode 100644 index 0000000000..997bed58a5 --- /dev/null +++ b/e2e/demo/scenarios/keybindings.mjs @@ -0,0 +1,53 @@ +// Demo: user-configurable keybindings (AGE-692). +// Opens Settings, records a new New chat binding, shows conflict blocking, then +// proves the remapped shortcut starts a chat. +import { seedDemoFixtures } from "../fixtures.mjs"; + +export function seed(baseDir) { + return seedDemoFixtures(baseDir, { + messageCount: 8, + title: "Keybindings demo", + }); +} + +export async function run({ page, pause, shot }) { + const steps = []; + const step = (name, ok = true) => + steps.push(`${ok ? "PASS" : "FAIL"} ${name}`); + + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await page.getByRole("heading", { name: "Settings" }).waitFor(); + await page + .locator('[data-keybinding-action="newChat"]') + .scrollIntoViewIfNeeded(); + await shot("settings-keybindings"); + step("open Settings keybindings section"); + + const newChatRow = page.locator('[data-keybinding-action="newChat"]'); + await newChatRow + .getByRole("button", { name: "Record New chat shortcut" }) + .click(); + await page.keyboard.press("Control+J"); + await page.getByText("New chat set to Cmd/Ctrl+J.").waitFor(); + await shot("new-chat-captured"); + step("capture Cmd/Ctrl+J for New chat"); + + await newChatRow + .getByRole("button", { name: "Record New chat shortcut" }) + .click(); + await page.keyboard.press("Control+K"); + await page + .getByText("Cmd/Ctrl+K is already assigned to Command palette.") + .waitFor(); + await shot("conflict-warning"); + step("conflict warning blocks Cmd/Ctrl+K"); + + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await pause(500); + await page.keyboard.press("Control+J"); + await page.getByLabel("Message").waitFor({ timeout: 15000 }); + await shot("rebound-shortcut-fired"); + step("rebound shortcut starts a chat"); + + return steps; +} diff --git a/src/main/services/settings-service.ts b/src/main/services/settings-service.ts index a2bef47351..b958e72f91 100644 --- a/src/main/services/settings-service.ts +++ b/src/main/services/settings-service.ts @@ -15,6 +15,7 @@ import type { BrowserBookmark, BrowserHistoryEntry, ExternalTerminalProfile, + KeybindingChord, LayoutSettings, OpenSessionDescriptor, RecentProject, @@ -24,7 +25,7 @@ import type { UiPrefs, Workspace, } from "@shared/ipc"; -import { WORKSPACE_COLOR_KEYS } from "@shared/ipc"; +import { KEYBINDING_ACTION_IDS, WORKSPACE_COLOR_KEYS } from "@shared/ipc"; import type { ApprovalMode, ApprovalPolicy, ThinkingLevel } from "@shared/rpc"; import { scoped } from "../logger"; @@ -109,6 +110,7 @@ export function defaultSettings(): StudioSettings { recentProjects: [], openSessions: [], linear: { writesEnabled: false }, + keybindings: {}, terminal: { enabled: false, maxConcurrent: DEFAULT_TERMINAL_MAX_CONCURRENT, @@ -395,6 +397,41 @@ function coerceUiPrefs(value: unknown): UiPrefs | undefined { return Object.keys(out).length === 0 ? undefined : out; } +function coerceKeybindingChord(value: unknown): KeybindingChord | undefined { + if (!isRecord(value)) return undefined; + const key = + typeof value.key === "string" ? value.key.trim().toLowerCase() : ""; + const normalizedKey = key === "escape" ? "Escape" : key; + const mod = value.mod === true; + const shift = value.shift === true; + if (value.mod !== undefined && typeof value.mod !== "boolean") return; + if (value.shift !== undefined && typeof value.shift !== "boolean") return; + if (normalizedKey === "Escape") { + return mod || shift ? undefined : { key: "Escape" }; + } + if (!mod) return undefined; + if (!/^[a-z0-9]$/.test(normalizedKey)) return undefined; + return { + key: normalizedKey, + mod: true, + ...(shift ? { shift: true } : {}), + }; +} + +function coerceKeybindings( + value: unknown, +): StudioSettings["keybindings"] | undefined { + if (!isRecord(value)) return undefined; + const out: NonNullable = {}; + for (const actionId of KEYBINDING_ACTION_IDS) { + const chord = coerceKeybindingChord(value[actionId]); + if (chord) out[actionId] = chord; + } + return Object.keys(out).length > 0 || Object.keys(value).length === 0 + ? out + : undefined; +} + /** * NON-SECRET Linear metadata only. The API key lives in the OS keychain and * MUST never be persisted here, so we copy `writesEnabled`/`defaultTeamId` @@ -646,6 +683,8 @@ function mergeKnown( if (layout) next.layout = layout; const ui = coerceUiPrefs(patch.ui); if (ui) next.ui = ui; + const keybindings = coerceKeybindings(patch.keybindings); + if (keybindings) next.keybindings = keybindings; const linear = coerceLinearMeta(patch.linear); if (linear) next.linear = linear; const terminal = coerceTerminal(patch.terminal); diff --git a/src/renderer/src/lib/keybindings.ts b/src/renderer/src/lib/keybindings.ts new file mode 100644 index 0000000000..7acaae87c6 --- /dev/null +++ b/src/renderer/src/lib/keybindings.ts @@ -0,0 +1,194 @@ +import type { + KeybindingActionId, + KeybindingChord, + KeybindingSettings, +} from "@shared/ipc"; + +export interface ShortcutAction { + id: KeybindingActionId; + label: string; + description: string; + defaultChords: KeybindingChord[]; +} + +export const SHORTCUT_ACTIONS: ShortcutAction[] = [ + { + id: "newChat", + label: "New chat", + description: "Start a new chat session.", + defaultChords: [ + { key: "t", mod: true }, + { key: "n", mod: true }, + ], + }, + { + id: "closeSession", + label: "Close active session", + description: "Close the active chat session.", + defaultChords: [{ key: "w", mod: true }], + }, + { + id: "toggleSidebar", + label: "Toggle sidebar", + description: "Collapse or expand the left sidebar.", + defaultChords: [{ key: "b", mod: true }], + }, + { + id: "toggleNavPalette", + label: "Command palette", + description: "Open or close the navigation palette.", + defaultChords: [{ key: "k", mod: true }], + }, + { + id: "toggleSearch", + label: "Global search", + description: "Open or close full-text search.", + defaultChords: [{ key: "f", mod: true, shift: true }], + }, + { + id: "toggleSlashPalette", + label: "Slash command palette", + description: "Toggle slash commands in the active composer.", + defaultChords: [{ key: "p", mod: true, shift: true }], + }, + { + id: "closeOverlay", + label: "Close overlay", + description: "Close the topmost soft overlay.", + defaultChords: [{ key: "Escape" }], + }, + ...Array.from({ length: 9 }, (_, index) => { + const slot = index + 1; + return { + id: `openSession${slot}` as KeybindingActionId, + label: `Open session ${slot}`, + description: `Switch to open session ${slot}.`, + defaultChords: [{ key: String(slot), mod: true }], + }; + }), +]; + +const ACTION_BY_ID = new Map( + SHORTCUT_ACTIONS.map((action) => [action.id, action]), +); + +export function chordKey(chord: KeybindingChord): string { + return [chord.mod ? "mod" : "", chord.shift ? "shift" : "", chord.key] + .filter(Boolean) + .join("+") + .toLowerCase(); +} + +export function chordsEqual( + left: KeybindingChord, + right: KeybindingChord, +): boolean { + return chordKey(left) === chordKey(right); +} + +export function displayChord(chord: KeybindingChord): string { + const parts: string[] = []; + if (chord.mod) parts.push("Cmd/Ctrl"); + if (chord.shift) parts.push("Shift"); + parts.push(chord.key === "Escape" ? "Esc" : chord.key.toUpperCase()); + return parts.join("+"); +} + +export function displayActionBinding( + action: ShortcutAction, + custom: KeybindingSettings | undefined, +): string { + const chord = custom?.[action.id]; + if (chord) return displayChord(chord); + return action.defaultChords.map(displayChord).join(" / "); +} + +export function effectiveChords( + action: ShortcutAction, + custom: KeybindingSettings | undefined, +): KeybindingChord[] { + const chord = custom?.[action.id]; + return chord ? [chord] : action.defaultChords; +} + +export function resolveShortcutAction( + event: KeyboardEvent, + custom: KeybindingSettings | undefined, +): KeybindingActionId | undefined { + const chord = chordFromKeyboardEvent(event); + if (!chord) return undefined; + for (const action of SHORTCUT_ACTIONS) { + if ( + effectiveChords(action, custom).some((item) => chordsEqual(item, chord)) + ) { + return action.id; + } + } + return undefined; +} + +export interface KeybindingConflict { + action: ShortcutAction; + chord: KeybindingChord; +} + +export function findKeybindingConflict( + actionId: KeybindingActionId, + chord: KeybindingChord, + custom: KeybindingSettings | undefined, +): KeybindingConflict | undefined { + for (const action of SHORTCUT_ACTIONS) { + if (action.id === actionId) continue; + const conflict = effectiveChords(action, custom).find((item) => + chordsEqual(item, chord), + ); + if (conflict) return { action, chord: conflict }; + } + return undefined; +} + +export function canAssignChord( + actionId: KeybindingActionId, + chord: KeybindingChord, +): boolean { + if (chord.key === "Escape") return actionId === "closeOverlay"; + return chord.mod === true; +} + +export function chordFromKeyboardEvent( + event: KeyboardEvent, +): KeybindingChord | undefined { + if (event.altKey) return undefined; + if ( + event.key === "Meta" || + event.key === "Control" || + event.key === "Shift" + ) { + return undefined; + } + if (event.key === "Escape") return { key: "Escape" }; + if (!(event.metaKey || event.ctrlKey)) return undefined; + const key = event.key.toLowerCase(); + if (!/^[a-z0-9]$/.test(key)) return undefined; + return { + key, + mod: true, + ...(event.shiftKey ? { shift: true } : {}), + }; +} + +export function invalidChordMessage( + actionId: KeybindingActionId, + chord: KeybindingChord | undefined, +): string { + if (chord?.key === "Escape" && actionId !== "closeOverlay") { + return "Escape is reserved for closing overlays."; + } + return "Use Cmd/Ctrl with a letter or digit."; +} + +export function shortcutActionById( + id: KeybindingActionId, +): ShortcutAction | undefined { + return ACTION_BY_ID.get(id); +} diff --git a/src/renderer/src/lib/useShortcuts.test.tsx b/src/renderer/src/lib/useShortcuts.test.tsx index 8d5784ee77..4e2b900406 100644 --- a/src/renderer/src/lib/useShortcuts.test.tsx +++ b/src/renderer/src/lib/useShortcuts.test.tsx @@ -9,6 +9,7 @@ import { useShortcuts } from "@/lib/useShortcuts"; import { useAppStore } from "@/store/app"; import { useChatStore } from "@/store/chat"; import { createSession } from "@/store/session-reducer"; +import { useSettingsStore } from "@/store/settings"; import { useShellStore } from "@/store/shell"; import { useUiStore } from "@/store/ui"; @@ -40,6 +41,7 @@ beforeEach(() => { slashPaletteToggle: 0, }); useAppStore.setState({ route: "dashboard" }); + useSettingsStore.setState({ settings: null }); useShellStore.getState().setSidebarToggleHandler(null); }); @@ -52,6 +54,31 @@ describe("useShortcuts", () => { expect(newChat).toHaveBeenCalledTimes(2); }); + it("reads custom bindings from settings without reloading the listener", () => { + useSettingsStore.setState({ + settings: { + keybindings: { newChat: { key: "j", mod: true } }, + } as never, + }); + const newChat = vi.spyOn(useChatStore.getState(), "newChat"); + render(); + + press("t", { metaKey: true }); + expect(newChat).not.toHaveBeenCalled(); + press("j", { metaKey: true }); + expect(newChat).toHaveBeenCalledTimes(1); + + useSettingsStore.setState({ + settings: { + keybindings: { newChat: { key: "l", mod: true } }, + } as never, + }); + press("j", { metaKey: true }); + expect(newChat).toHaveBeenCalledTimes(1); + press("l", { metaKey: true }); + expect(newChat).toHaveBeenCalledTimes(2); + }); + it("Cmd+K toggles the navigation palette", () => { render(); press("k", { metaKey: true }); diff --git a/src/renderer/src/lib/useShortcuts.ts b/src/renderer/src/lib/useShortcuts.ts index 65c3334910..34b34c8730 100644 --- a/src/renderer/src/lib/useShortcuts.ts +++ b/src/renderer/src/lib/useShortcuts.ts @@ -1,10 +1,9 @@ // The single global keyboard-shortcut manager (G2). Wired once from App so there -// is exactly ONE window keydown listener for studio chords — the per-component -// listeners that used to own Cmd+K (GlobalSearch), Cmd+W (ChatWorkspace), and -// Cmd+Shift+P (PromptComposer) were removed and routed through here + the ui -// store so nothing double-fires. +// is exactly ONE window keydown listener for studio chords. Defaults live in +// lib/keybindings; user overrides are read from settings on each keydown so +// remaps apply immediately without remounting this listener. // -// Shortcut map: +// Default shortcut map: // Cmd/Ctrl+T or N new chat // Cmd/Ctrl+W close the active session (confirm if streaming) // Cmd/Ctrl+1..9 switch to the Nth open session @@ -23,7 +22,9 @@ import { useEffect } from "react"; import { closeSessionWithConfirm } from "@/components/chat/SessionList"; +import { resolveShortcutAction } from "@/lib/keybindings"; import { useChatStore } from "@/store/chat"; +import { useSettingsStore } from "@/store/settings"; import { useShellStore } from "@/store/shell"; import { useUiStore } from "@/store/ui"; @@ -54,9 +55,15 @@ function isEditableTarget(el: EventTarget | null): boolean { export function useShortcuts(): void { useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { - // Esc closes the topmost soft overlay we own (nav palette first, then - // global search). Blocking dialogs and the slash palette handle their own. - if (e.key === "Escape") { + const action = resolveShortcutAction( + e, + useSettingsStore.getState().settings?.keybindings, + ); + if (!action) return; + + // Close the topmost soft overlay we own (nav palette first, then global + // search). Blocking dialogs and the slash palette handle their own. + if (action === "closeOverlay") { const ui = useUiStore.getState(); if (ui.navPaletteOpen) { e.preventDefault(); @@ -68,63 +75,48 @@ export function useShortcuts(): void { return; } - if (!(e.metaKey || e.ctrlKey)) return; // bare keys are typing, not chords if (isEditableTarget(document.activeElement)) return; // typing — only Esc if (blockingModalOpen()) return; // the modal owns the keyboard const chat = useChatStore.getState(); const ui = useUiStore.getState(); - // Cmd/Ctrl+Shift+P — slash-command palette (consumed by the active composer). - if (e.shiftKey && (e.key === "p" || e.key === "P")) { - e.preventDefault(); - ui.requestSlashPalette(); - return; - } - // Cmd/Ctrl+Shift+F — global full-text search overlay. - if (e.shiftKey && (e.key === "f" || e.key === "F")) { - e.preventDefault(); - ui.toggleSearch(); - return; - } - if (e.shiftKey) return; // no other Shift chords are bound - - // Cmd/Ctrl+B — collapse/expand the left sidebar. - if (e.key === "b" || e.key === "B") { - e.preventDefault(); - useShellStore.getState().toggleSidebar(); - return; - } - - switch (e.key) { - case "t": - case "T": - case "n": - case "N": + switch (action) { + case "newChat": e.preventDefault(); chat.newChat(); return; - case "w": - case "W": { + case "closeSession": { const id = chat.activeSessionId; if (!id) return; e.preventDefault(); closeSessionWithConfirm(id); return; } - case "k": - case "K": + case "toggleSidebar": + e.preventDefault(); + useShellStore.getState().toggleSidebar(); + return; + case "toggleNavPalette": e.preventDefault(); ui.toggleNavPalette(); return; - default: - // Cmd/Ctrl+1..9 — switch to the Nth open (live) session. - if (e.key >= "1" && e.key <= "9") { - const target = Object.keys(chat.openSessions)[Number(e.key) - 1]; - if (!target) return; - e.preventDefault(); - chat.openChat(target); - } + case "toggleSearch": + e.preventDefault(); + ui.toggleSearch(); + return; + case "toggleSlashPalette": + e.preventDefault(); + ui.requestSlashPalette(); + return; + default: { + if (!action.startsWith("openSession")) return; + const slot = Number(action.replace("openSession", "")); + const target = Object.keys(chat.openSessions)[slot - 1]; + if (!target) return; + e.preventDefault(); + chat.openChat(target); + } } }; diff --git a/src/renderer/src/views/Settings.test.tsx b/src/renderer/src/views/Settings.test.tsx index fb5cdd0eb0..cf0f64203b 100644 --- a/src/renderer/src/views/Settings.test.tsx +++ b/src/renderer/src/views/Settings.test.tsx @@ -1,6 +1,12 @@ import type { ModelInfo } from "@shared/domain"; import type { OmpApi, StudioSettings } from "@shared/ipc"; -import { render, screen, waitFor, within } from "@testing-library/react"; +import { + fireEvent, + render, + screen, + waitFor, + within, +} from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { useSettingsStore } from "@/store/settings"; import Settings from "./Settings"; @@ -113,6 +119,48 @@ it("persists terminal target/profile without enabling the shell", async () => { }); }); +it("captures and persists a custom keybinding", async () => { + const user = userEvent.setup(); + const update = seedSettings(); + + render(); + + await user.click( + screen.getByRole("button", { name: "Record New chat shortcut" }), + ); + const capture = screen.getByRole("button", { + name: "Press shortcut for New chat", + }); + fireEvent.keyDown(capture, { key: "j", metaKey: true }); + + await waitFor(() => + expect(update).toHaveBeenCalledWith({ + keybindings: { newChat: { key: "j", mod: true } }, + }), + ); + expect(screen.getByText("New chat set to Cmd/Ctrl+J.")).toBeInTheDocument(); +}); + +it("blocks conflicting custom keybindings", async () => { + const user = userEvent.setup(); + const update = seedSettings(); + + render(); + + await user.click( + screen.getByRole("button", { name: "Record New chat shortcut" }), + ); + fireEvent.keyDown( + screen.getByRole("button", { name: "Press shortcut for New chat" }), + { key: "k", metaKey: true }, + ); + + expect(update).not.toHaveBeenCalled(); + expect(await screen.findByRole("alert")).toHaveTextContent( + "Cmd/Ctrl+K is already assigned to Command palette.", + ); +}); + it("gates enabling the built-in shell and preserves target/profile", async () => { const user = userEvent.setup(); const update = seedSettings({ diff --git a/src/renderer/src/views/Settings.tsx b/src/renderer/src/views/Settings.tsx index 9dc1215689..e2fbdf8e6d 100644 --- a/src/renderer/src/views/Settings.tsx +++ b/src/renderer/src/views/Settings.tsx @@ -5,6 +5,8 @@ import type { } from "@shared/domain"; import type { ExternalTerminalProfile, + KeybindingActionId, + KeybindingChord, TerminalDefaultTarget, TerminalSettings, ThemeMode, @@ -57,6 +59,16 @@ import { } from "@/components/workspace/WorkspaceColor"; import { cn } from "@/lib/cn"; import { formatNumber } from "@/lib/format"; +import { + canAssignChord, + chordFromKeyboardEvent, + displayActionBinding, + displayChord, + findKeybindingConflict, + invalidChordMessage, + SHORTCUT_ACTIONS, + shortcutActionById, +} from "@/lib/keybindings"; import { modelComboboxOptions } from "@/lib/model-options"; import { type AsyncState, useAsync } from "@/lib/useAsync"; import { sortWorkspaces } from "@/lib/workspaces"; @@ -172,6 +184,7 @@ export default function Settings() { /> + @@ -546,6 +559,162 @@ function AppearancePanel() { ); } +// --------------------------------------------------------------------------- +// Keybindings +// --------------------------------------------------------------------------- + +function KeybindingsPanel() { + const settings = useSettingsStore((s) => s.settings); + const update = useSettingsStore((s) => s.update); + const [capturing, setCapturing] = useState(null); + const [notice, setNotice] = useState<{ + kind: "info" | "warn"; + message: string; + } | null>(null); + + const title = ( + + + Keybindings + + ); + + if (!settings) { + return ( + +
+ +
+
+ ); + } + + const keybindings = settings.keybindings ?? {}; + const updateKeybinding = ( + actionId: KeybindingActionId, + chord: KeybindingChord, + ) => { + const action = shortcutActionById(actionId); + if (!action) return; + if (!canAssignChord(actionId, chord)) { + setNotice({ + kind: "warn", + message: invalidChordMessage(actionId, chord), + }); + return; + } + const conflict = findKeybindingConflict(actionId, chord, keybindings); + if (conflict) { + setNotice({ + kind: "warn", + message: `${displayChord(chord)} is already assigned to ${conflict.action.label}.`, + }); + return; + } + void update({ keybindings: { ...keybindings, [actionId]: chord } }); + setCapturing(null); + setNotice({ + kind: "info", + message: `${action.label} set to ${displayChord(chord)}.`, + }); + }; + + const resetKeybinding = (actionId: KeybindingActionId) => { + const { [actionId]: _removed, ...next } = keybindings; + void update({ keybindings: next }); + const action = shortcutActionById(actionId); + setNotice( + action + ? { kind: "info", message: `${action.label} reset to default.` } + : null, + ); + }; + + return ( + + {notice && ( +
+ {notice.message} +
+ )} + +
+ {SHORTCUT_ACTIONS.map((action) => ( +
+
+
{action.label}
+

+ {action.description} +

+
+
+ + resetKeybinding(action.id)} + > + + +
+
+ ))} +
+
+ ); +} + // --------------------------------------------------------------------------- // Workspaces (first-class projects: pin / set-default / edit label / re-point / remove) // --------------------------------------------------------------------------- diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts index 8addb82e07..5211c2351b 100644 --- a/src/shared/ipc.ts +++ b/src/shared/ipc.ts @@ -306,6 +306,39 @@ export interface UiPrefs { pinnedCommands?: string[]; } +export const KEYBINDING_ACTION_IDS = [ + "newChat", + "closeSession", + "toggleSidebar", + "toggleNavPalette", + "toggleSearch", + "toggleSlashPalette", + "closeOverlay", + "openSession1", + "openSession2", + "openSession3", + "openSession4", + "openSession5", + "openSession6", + "openSession7", + "openSession8", + "openSession9", +] as const; + +export type KeybindingActionId = (typeof KEYBINDING_ACTION_IDS)[number]; + +export interface KeybindingChord { + /** Lowercase letter/digit, or "Escape". */ + key: string; + /** Platform command modifier: Cmd on macOS, Ctrl elsewhere. */ + mod?: boolean; + shift?: boolean; +} + +export type KeybindingSettings = Partial< + Record +>; + export type TerminalDefaultTarget = "built-in" | "external"; export type ExternalTerminalProfile = | "system" @@ -366,6 +399,8 @@ export interface StudioSettingsV2 extends Omit { layout?: LayoutSettings; /** Features 3 & 6 — collapse state + pinned commands. */ ui?: UiPrefs; + /** User overrides for renderer-local keyboard shortcuts. */ + keybindings?: KeybindingSettings; /** Feature 2 — NON-SECRET Linear metadata only (key lives in the OS keychain). */ linear?: { writesEnabled: boolean; defaultTeamId?: string | null }; terminal?: TerminalSettings; diff --git a/test/settings-service.test.ts b/test/settings-service.test.ts index faecced27b..6dbf7de149 100644 --- a/test/settings-service.test.ts +++ b/test/settings-service.test.ts @@ -121,6 +121,42 @@ test("updateSettings merges known keys and drops unknown ones", async () => { expect(onDisk.theme).toBe("dark"); }); +test("updateSettings persists valid keybindings and drops invalid chords", async () => { + const updated = await updateSettings({ + keybindings: { + newChat: { key: "j", mod: true }, + toggleSearch: { key: "f", mod: true, shift: true }, + closeOverlay: { key: "Escape" }, + closeSession: { key: "q" }, + nope: { key: "x", mod: true }, + }, + } as unknown as Partial); + + expect(updated.keybindings).toEqual({ + newChat: { key: "j", mod: true }, + toggleSearch: { key: "f", mod: true, shift: true }, + closeOverlay: { key: "Escape" }, + }); + + const loaded = await loadSettings(); + expect(loaded.keybindings).toEqual(updated.keybindings); +}); + +test("malformed keybinding patches preserve the prior bindings; empty clears", async () => { + await updateSettings({ + keybindings: { newChat: { key: "j", mod: true } }, + }); + await updateSettings({ + keybindings: { closeSession: { key: "q" } }, + } as unknown as Partial); + expect((await loadSettings()).keybindings).toEqual({ + newChat: { key: "j", mod: true }, + }); + + await updateSettings({ keybindings: {} }); + expect((await loadSettings()).keybindings).toEqual({}); +}); + test("updateSettings coerces invalid values back to the current value", async () => { const updated = await updateSettings({ theme: "neon" as unknown as StudioSettings["theme"], From 1bb9a8b2e8892384874892ce806eecbf39eb388c Mon Sep 17 00:00:00 2001 From: Dylan McCavitt Date: Wed, 8 Jul 2026 13:03:03 -0400 Subject: [PATCH 2/3] =?UTF-8?q?AGE-692=20=E2=80=94=20review=20fixes:=20Esc?= =?UTF-8?q?ape=20reservation=20in=20main=20coercion,=20capture=20cancel/bl?= =?UTF-8?q?ur,=20bare-modifier=20ignore,=20conflict=20drop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- src/main/services/settings-service.ts | 22 ++++++-- src/renderer/src/views/Settings.test.tsx | 67 ++++++++++++++++++++++++ src/renderer/src/views/Settings.tsx | 15 ++++++ test/settings-service.test.ts | 33 ++++++++++++ 4 files changed, 134 insertions(+), 3 deletions(-) diff --git a/src/main/services/settings-service.ts b/src/main/services/settings-service.ts index b958e72f91..eda74cc35f 100644 --- a/src/main/services/settings-service.ts +++ b/src/main/services/settings-service.ts @@ -397,7 +397,10 @@ function coerceUiPrefs(value: unknown): UiPrefs | undefined { return Object.keys(out).length === 0 ? undefined : out; } -function coerceKeybindingChord(value: unknown): KeybindingChord | undefined { +function coerceKeybindingChord( + actionId: string, + value: unknown, +): KeybindingChord | undefined { if (!isRecord(value)) return undefined; const key = typeof value.key === "string" ? value.key.trim().toLowerCase() : ""; @@ -407,6 +410,7 @@ function coerceKeybindingChord(value: unknown): KeybindingChord | undefined { if (value.mod !== undefined && typeof value.mod !== "boolean") return; if (value.shift !== undefined && typeof value.shift !== "boolean") return; if (normalizedKey === "Escape") { + if (actionId !== "closeOverlay") return undefined; return mod || shift ? undefined : { key: "Escape" }; } if (!mod) return undefined; @@ -418,14 +422,26 @@ function coerceKeybindingChord(value: unknown): KeybindingChord | undefined { }; } +function keybindingChordKey(chord: KeybindingChord): string { + return [chord.mod ? "mod" : "", chord.shift ? "shift" : "", chord.key] + .filter(Boolean) + .join("+") + .toLowerCase(); +} + function coerceKeybindings( value: unknown, ): StudioSettings["keybindings"] | undefined { if (!isRecord(value)) return undefined; const out: NonNullable = {}; + const seen = new Set(); for (const actionId of KEYBINDING_ACTION_IDS) { - const chord = coerceKeybindingChord(value[actionId]); - if (chord) out[actionId] = chord; + const chord = coerceKeybindingChord(actionId, value[actionId]); + if (!chord) continue; + const key = keybindingChordKey(chord); + if (seen.has(key)) continue; + seen.add(key); + out[actionId] = chord; } return Object.keys(out).length > 0 || Object.keys(value).length === 0 ? out diff --git a/src/renderer/src/views/Settings.test.tsx b/src/renderer/src/views/Settings.test.tsx index cf0f64203b..e678b499b1 100644 --- a/src/renderer/src/views/Settings.test.tsx +++ b/src/renderer/src/views/Settings.test.tsx @@ -161,6 +161,73 @@ it("blocks conflicting custom keybindings", async () => { ); }); +it("cancels keybinding capture with Escape", async () => { + const user = userEvent.setup(); + const update = seedSettings(); + + render(); + + await user.click( + screen.getByRole("button", { name: "Record New chat shortcut" }), + ); + fireEvent.keyDown( + screen.getByRole("button", { name: "Press shortcut for New chat" }), + { key: "Escape" }, + ); + + expect(update).not.toHaveBeenCalled(); + expect( + screen.getByRole("button", { name: "Record New chat shortcut" }), + ).toBeInTheDocument(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); +}); + +it("clears keybinding capture on blur", async () => { + const user = userEvent.setup(); + seedSettings(); + + render(); + + await user.click( + screen.getByRole("button", { name: "Record New chat shortcut" }), + ); + fireEvent.blur( + screen.getByRole("button", { name: "Press shortcut for New chat" }), + ); + + expect( + screen.getByRole("button", { name: "Record New chat shortcut" }), + ).toBeInTheDocument(); +}); + +it("ignores bare modifier keydown while capturing a keybinding", async () => { + const user = userEvent.setup(); + const update = seedSettings(); + + render(); + + await user.click( + screen.getByRole("button", { name: "Record New chat shortcut" }), + ); + const capture = screen.getByRole("button", { + name: "Press shortcut for New chat", + }); + fireEvent.keyDown(capture, { key: "Control", ctrlKey: true }); + + expect(update).not.toHaveBeenCalled(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + expect( + screen.getByRole("button", { name: "Press shortcut for New chat" }), + ).toBeInTheDocument(); + + fireEvent.keyDown(capture, { key: "j", metaKey: true }); + await waitFor(() => + expect(update).toHaveBeenCalledWith({ + keybindings: { newChat: { key: "j", mod: true } }, + }), + ); +}); + it("gates enabling the built-in shell and preserves target/profile", async () => { const user = userEvent.setup(); const update = seedSettings({ diff --git a/src/renderer/src/views/Settings.tsx b/src/renderer/src/views/Settings.tsx index e2fbdf8e6d..6895b2a1de 100644 --- a/src/renderer/src/views/Settings.tsx +++ b/src/renderer/src/views/Settings.tsx @@ -685,6 +685,12 @@ function KeybindingsPanel() { if (capturing !== action.id) return; event.preventDefault(); event.stopPropagation(); + if (event.key === "Escape") { + setCapturing(null); + setNotice(null); + return; + } + if (isBareModifierKey(event.key)) return; const chord = chordFromKeyboardEvent(event.nativeEvent); if (!chord) { setNotice({ @@ -695,6 +701,9 @@ function KeybindingsPanel() { } updateKeybinding(action.id, chord); }} + onBlur={() => { + if (capturing === action.id) setCapturing(null); + }} > {capturing === action.id ? "Press shortcut" @@ -715,6 +724,12 @@ function KeybindingsPanel() { ); } +function isBareModifierKey(key: string): boolean { + return ( + key === "Meta" || key === "Control" || key === "Shift" || key === "Alt" + ); +} + // --------------------------------------------------------------------------- // Workspaces (first-class projects: pin / set-default / edit label / re-point / remove) // --------------------------------------------------------------------------- diff --git a/test/settings-service.test.ts b/test/settings-service.test.ts index 6dbf7de149..e57e3f912c 100644 --- a/test/settings-service.test.ts +++ b/test/settings-service.test.ts @@ -142,6 +142,39 @@ test("updateSettings persists valid keybindings and drops invalid chords", async expect(loaded.keybindings).toEqual(updated.keybindings); }); +test("loadSettings reserves Escape for the close-overlay keybinding", async () => { + writeFileSync( + settingsFile(), + `${JSON.stringify({ + ...defaultSettings(), + keybindings: { + newChat: { key: "Escape" }, + closeOverlay: { key: "Escape" }, + }, + })}\n`, + "utf8", + ); + + expect((await loadSettings()).keybindings).toEqual({ + closeOverlay: { key: "Escape" }, + }); +}); + +test("updateSettings drops conflicting direct keybinding patches after the first action", async () => { + const updated = await updateSettings({ + keybindings: { + newChat: { key: "j", mod: true }, + closeSession: { key: "j", mod: true }, + toggleSearch: { key: "f", mod: true, shift: true }, + }, + }); + + expect(updated.keybindings).toEqual({ + newChat: { key: "j", mod: true }, + toggleSearch: { key: "f", mod: true, shift: true }, + }); +}); + test("malformed keybinding patches preserve the prior bindings; empty clears", async () => { await updateSettings({ keybindings: { newChat: { key: "j", mod: true } }, From cb4234978722feaa86895f51cf59a5e48118b8bf Mon Sep 17 00:00:00 2001 From: Dylan McCavitt Date: Wed, 8 Jul 2026 13:08:25 -0400 Subject: [PATCH 3/3] =?UTF-8?q?AGE-692=20=E2=80=94=20make=20keybindings=20?= =?UTF-8?q?demo=20dismiss=20Settings=20robustly=20across=20docked=20view?= =?UTF-8?q?=20and=20AGE-690=20modal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- e2e/demo/scenarios/keybindings.mjs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/e2e/demo/scenarios/keybindings.mjs b/e2e/demo/scenarios/keybindings.mjs index 997bed58a5..1e7a5cc38e 100644 --- a/e2e/demo/scenarios/keybindings.mjs +++ b/e2e/demo/scenarios/keybindings.mjs @@ -42,7 +42,18 @@ export async function run({ page, pause, shot }) { await shot("conflict-warning"); step("conflict warning blocks Cmd/Ctrl+K"); - await page.getByRole("button", { name: "Settings", exact: true }).click(); + // Leave Settings. Escape may first cancel an armed capture, and with + // AGE-690's floating modal a further Escape dismisses the dialog; on the + // pre-modal docked layout Escape is a no-op and the rail button closes it. + const settingsHeading = page.getByRole("heading", { name: "Settings" }); + for (let i = 0; i < 3; i++) { + if (!(await settingsHeading.isVisible().catch(() => false))) break; + await page.keyboard.press("Escape"); + await pause(300); + } + if (await settingsHeading.isVisible().catch(() => false)) { + await page.getByRole("button", { name: "Settings", exact: true }).click(); + } await pause(500); await page.keyboard.press("Control+J"); await page.getByLabel("Message").waitFor({ timeout: 15000 });