Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions e2e/demo/scenarios/keybindings.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// 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");

// 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 });
await shot("rebound-shortcut-fired");
step("rebound shortcut starts a chat");

return steps;
}
57 changes: 56 additions & 1 deletion src/main/services/settings-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
BrowserBookmark,
BrowserHistoryEntry,
ExternalTerminalProfile,
KeybindingChord,
LayoutSettings,
OpenSessionDescriptor,
RecentProject,
Expand All @@ -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";

Expand Down Expand Up @@ -109,6 +110,7 @@ export function defaultSettings(): StudioSettings {
recentProjects: [],
openSessions: [],
linear: { writesEnabled: false },
keybindings: {},
terminal: {
enabled: false,
maxConcurrent: DEFAULT_TERMINAL_MAX_CONCURRENT,
Expand Down Expand Up @@ -395,6 +397,57 @@ function coerceUiPrefs(value: unknown): UiPrefs | undefined {
return Object.keys(out).length === 0 ? undefined : out;
}

function coerceKeybindingChord(
actionId: string,
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") {
if (actionId !== "closeOverlay") return undefined;
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 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<StudioSettings["keybindings"]> = {};
const seen = new Set<string>();
for (const actionId of KEYBINDING_ACTION_IDS) {
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
: 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`
Expand Down Expand Up @@ -646,6 +699,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);
Expand Down
194 changes: 194 additions & 0 deletions src/renderer/src/lib/keybindings.ts
Original file line number Diff line number Diff line change
@@ -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);
}
27 changes: 27 additions & 0 deletions src/renderer/src/lib/useShortcuts.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -40,6 +41,7 @@ beforeEach(() => {
slashPaletteToggle: 0,
});
useAppStore.setState({ route: "dashboard" });
useSettingsStore.setState({ settings: null });
useShellStore.getState().setSidebarToggleHandler(null);
});

Expand All @@ -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(<Harness />);

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(<Harness />);
press("k", { metaKey: true });
Expand Down
Loading
Loading