Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

Add keybindings settings editor (#2533)

Julius Marminge0e388706470f
diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts
index bbb7e1b43..efada98bf 100644
--- a/apps/server/src/keybindings.test.ts
+++ b/apps/server/src/keybindings.test.ts
@@ -354,7 +354,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
- it.effect("replaces existing custom keybinding for the same command", () =>
+ it.effect("appends additional custom keybindings for the same command", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
@@ -368,6 +368,55 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
});
});
+ const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
+ const persistedView = persisted.map(({ key, command }) => ({ key, command }));
+ assert.deepEqual(persistedView, [
+ { key: "mod+r", command: "script.run-tests.run" },
+ { key: "mod+shift+r", command: "script.run-tests.run" },
+ ]);
+ }).pipe(Effect.provide(makeKeybindingsLayer())),
+ );
+
+ it.effect("replaces only the targeted custom keybinding", () =>
+ Effect.gen(function* () {
+ const { keybindingsConfigPath } = yield* ServerConfig;
+ yield* writeKeybindingsConfig(keybindingsConfigPath, [
+ { key: "mod+r", command: "script.run-tests.run" },
+ { key: "mod+shift+r", command: "script.run-tests.run" },
+ ]);
+ yield* Effect.gen(function* () {
+ const keybindings = yield* Keybindings;
+ return yield* keybindings.upsertKeybindingRule({
+ key: "mod+alt+r",
+ command: "script.run-tests.run",
+ replace: { key: "mod+r", command: "script.run-tests.run" },
+ });
+ });
+
+ const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
+ const persistedView = persisted.map(({ key, command }) => ({ key, command }));
+ assert.deepEqual(persistedView, [
+ { key: "mod+shift+r", command: "script.run-tests.run" },
+ { key: "mod+alt+r", command: "script.run-tests.run" },
+ ]);
+ }).pipe(Effect.provide(makeKeybindingsLayer())),
+ );
+
+ it.effect("removes only the targeted custom keybinding", () =>
+ Effect.gen(function* () {
+ const { keybindingsConfigPath } = yield* ServerConfig;
+ yield* writeKeybindingsConfig(keybindingsConfigPath, [
+ { key: "mod+r", command: "script.run-tests.run" },
+ { key: "mod+shift+r", command: "script.run-tests.run" },
+ ]);
+ yield* Effect.gen(function* () {
+ const keybindings = yield* Keybindings;
+ return yield* keybindings.removeKeybindingRule({
+ key: "mod+r",
+ command: "script.run-tests.run",
+ });
+ });
+
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts
index 4d7ee887a..95bf5c3d9 100644
--- a/apps/server/src/keybindings.ts
+++ b/apps/server/src/keybindings.ts
@@ -15,6 +15,8 @@ import {
MAX_KEYBINDINGS_COUNT,
ResolvedKeybindingRule,
ResolvedKeybindingsConfig,
+ type ServerRemoveKeybindingInput,
+ type ServerUpsertKeybindingInput,
type ServerConfigIssue,
} from "@t3tools/contracts";
import {
@@ -124,6 +126,25 @@ function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): bo
return leftContext === rightContext;
}
+function keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {
+ return input.when === undefined
+ ? { key: input.key, command: input.command }
+ : { key: input.key, command: input.command, when: input.when };
+}
+
+function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
+ if (!input.replace) return null;
+ return input.replace.when === undefined
+ ? { key: input.replace.key, command: input.replace.command }
+ : { key: input.replace.key, command: input.replace.command, when: input.replace.when };
+}
+
+function keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {
+ return input.when === undefined
+ ? { key: input.key, command: input.command }
+ : { key: input.key, command: input.command, when: input.when };
+}
+
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
const modifiers: string[] = [];
if (shortcut.modKey) modifiers.push("mod");
@@ -259,7 +280,14 @@ export interface KeybindingsShape {
* oldest entries when needed.
*/
readonly upsertKeybindingRule: (
- rule: KeybindingRule,
+ input: ServerUpsertKeybindingInput,
+ ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
+
+ /**
+ * Remove a single persisted keybinding rule by exact key/command/when match.
+ */
+ readonly removeKeybindingRule: (
+ input: ServerRemoveKeybindingInput,
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
}
@@ -616,12 +644,19 @@ const makeKeybindings = Effect.gen(function* () {
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
- upsertKeybindingRule: (rule) =>
+ upsertKeybindingRule: (input) =>
upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
const customConfig = yield* loadWritableCustomKeybindingsConfig();
+ const rule = keybindingRuleFromUpsertInput(input);
+ const replaceTarget = replaceTargetFromUpsertInput(input);
const nextConfig = [
- ...customConfig.filter((entry) => entry.command !== rule.command),
+ ...customConfig.filter((entry) => {
+ if (replaceTarget) {
+ return !isSameKeybindingRule(entry, replaceTarget);
+ }
+ return !isSameKeybindingRule(entry, rule);
+ }),
rule,
];
const cappedConfig =
@@ -649,6 +684,27 @@ const makeKeybindings = Effect.gen(function* () {
return nextResolved;
}),
),
+ removeKeybindingRule: (input) =>
+ upsertSemaphore.withPermits(1)(
+ Effect.gen(function* () {
+ const customConfig = yield* loadWritableCustomKeybindingsConfig();
+ const target = keybindingRuleFromRemoveInput(input);
+ const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
+ yield* writeConfigAtomically(nextConfig);
+ const nextResolved = mergeWithDefaultKeybindings(
+ compileResolvedKeybindingsConfig(nextConfig),
+ );
+ yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
+ keybindings: nextResolved,
+ issues: [],
+ });
+ yield* emitChange({
+ keybindings: nextResolved,
+ issues: [],
+ });
+ return nextResolved;
+ }),
+ ),
} satisfies KeybindingsShape;
});
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 195667693..655eec783 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -1918,6 +1918,42 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+ it.effect("routes websocket rpc server.removeKeybinding", () =>
+ Effect.gen(function* () {
+ const rule: KeybindingRule = {
+ command: "terminal.toggle",
+ key: "ctrl+k",
+ };
+ const resolved: ResolvedKeybindingRule = {
+ command: "terminal.toggle",
+ shortcut: {
+ key: "j",
+ metaKey: false,
+ ctrlKey: false,
+ shiftKey: false,
+ altKey: false,
+ modKey: true,
+ },
+ };
+
+ yield* buildAppUnderTest({
+ layers: {
+ keybindings: {
+ removeKeybindingRule: () => Effect.succeed([resolved]),
+ },
+ },
+ });
+
+ const wsUrl = yield* getWsServerUrl("/ws");
+ const response = yield* Effect.scoped(
+ withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverRemoveKeybinding](rule)),
+ );
+
+ assert.deepEqual(response.issues, []);
+ assert.deepEqual(response.keybindings, [resolved]);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
it.effect("rejects websocket rpc handshake when session authentication is missing", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index f25392268..f32953abf 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -804,6 +804,15 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
}),
{ "rpc.aggregate": "server" },
),
+ [WS_METHODS.serverRemoveKeybinding]: (rule) =>
+ observeRpcEffect(
+ WS_METHODS.serverRemoveKeybinding,
+ Effect.gen(function* () {
+ const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);
+ return { keybindings: keybindingsConfig, issues: [] };
+ }),
+ { "rpc.aggregate": "server" },
+ ),
[WS_METHODS.serverGetSettings]: (_input) =>
observeRpcEffect(
WS_METHODS.serverGetSettings,
diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx
index b6df9712b..6bb8be2c2 100644
--- a/apps/web/src/components/KeybindingsToast.browser.tsx
+++ b/apps/web/src/components/KeybindingsToast.browser.tsx
@@ -532,16 +532,20 @@ describe("Keybindings update toast", () => {
document.body.innerHTML = "";
});
- it("shows a toast for each consecutive keybinding update with no issues", async () => {
+ it("coalesces rapid consecutive keybinding update toasts with no issues", async () => {
const mounted = await mountApp();
try {
sendServerConfigUpdatedPush([]);
await waitForToast("Keybindings updated", 1);
- // Each server push represents a distinct file change, so it should produce its own toast.
+ // A single edit can produce several reload notifications as the direct update and
+ // filesystem watcher settle, so avoid stacking identical success toasts.
sendServerConfigUpdatedPush([]);
- await waitForToast("Keybindings updated", 2);
+ await new Promise((resolve) => setTimeout(resolve, 250));
+
+ const titles = queryToastTitles();
+ expect(titles.filter((title) => title === "Keybindings updated")).toHaveLength(1);
} finally {
await mounted.cleanup();
}
diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx
index 11b08cc2c..4a9cda19d 100644
--- a/apps/web/src/components/ProjectScriptsControl.tsx
+++ b/apps/web/src/components/ProjectScriptsControl.tsx
@@ -20,13 +20,13 @@ import {
keybindingValueForCommand,
decodeProjectScriptKeybindingRule,
} from "~/lib/projectScriptKeybindings";
+import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
import {
commandForProjectScript,
nextProjectScriptId,
primaryProjectScript,
} from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
-import { isMacPlatform } from "~/lib/utils";
import {
AlertDialog,
AlertDialogClose,
@@ -96,57 +96,6 @@ interface ProjectScriptsControlProps {
onDeleteScript: (scriptId: string) => Promise<void> | void;
}
-function normalizeShortcutKeyToken(key: string): string | null {
- const normalized = key.toLowerCase();
- if (
- normalized === "meta" ||
- normalized === "control" ||
- normalized === "ctrl" ||
- normalized === "shift" ||
- normalized === "alt" ||
- normalized === "option"
- ) {
- return null;
- }
- if (normalized === " ") return "space";
- if (normalized === "escape") return "esc";
- if (normalized === "arrowup") return "arrowup";
- if (normalized === "arrowdown") return "arrowdown";
- if (normalized === "arrowleft") return "arrowleft";
- if (normalized === "arrowright") return "arrowright";
- if (normalized.length === 1) return normalized;
- if (normalized.startsWith("f") && normalized.length <= 3) return normalized;
- if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
- return normalized;
- }
- if (normalized === "delete" || normalized === "home" || normalized === "end") {
- return normalized;
- }
- if (normalized === "pageup" || normalized === "pagedown") return normalized;
- return null;
-}
-
-function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | null {
- const keyToken = normalizeShortcutKeyToken(event.key);
- if (!keyToken) return null;
-
- const parts: string[] = [];
- if (isMacPlatform(navigator.platform)) {
- if (event.metaKey) parts.push("mod");
- if (event.ctrlKey) parts.push("ctrl");
- } else {
- if (event.ctrlKey) parts.push("mod");
- if (event.metaKey) parts.push("meta");
- }
- if (event.altKey) parts.push("alt");
- if (event.shiftKey) parts.push("shift");
- if (parts.length === 0) {
- return null;
- }
- parts.push(keyToken);
- return parts.join("+");
-}
-
export default function ProjectScriptsControl({
scripts,
keybindings,
@@ -186,7 +135,7 @@ export default function ProjectScriptsControl({
setKeybinding("");
return;
}
- const next = keybindingFromEvent(event);
+ const next = keybindingFromKeyboardEvent(event, navigator.platform);
if (!next) return;
setKeybinding(next);
};
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
new file mode 100644
index 000000000..6c52b9579
--- /dev/null
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
@@ -0,0 +1,248 @@
+import { describe, expect, it } from "vitest";
+import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
+
+import {
+ buildKeybindingRows,
+ buildKeybindingCommandOptions,
+ buildWhenVariableOptions,
+ commandLabel,
+ keybindingConflictLabels,
+ keybindingFromKeyboardEvent,
+ parseWhenExpressionDraft,
+ shortcutToKeybindingInput,
+ unknownWhenVariables,
+ whenAstToExpression,
+} from "./KeybindingsSettings.logic";
+
+describe("KeybindingsSettings.logic", () => {
+ it("builds searchable rows with readable key and when values", () => {
+ const rows = buildKeybindingRows(
+ [
+ {
+ command: "terminal.toggle",
+ shortcut: {
+ key: "j",
+ modKey: true,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ },
+ whenAst: {
+ type: "not",
+ node: { type: "identifier", name: "terminalFocus" },
+ },
+ },
+ ] satisfies ResolvedKeybindingsConfig,
+ "terminal",
+ );
+
+ expect(rows).toEqual([
+ expect.objectContaining({
+ command: "terminal.toggle",
+ key: "mod+j",
+ when: "!terminalFocus",
+ defaultKey: "mod+j",
+ defaultWhen: "",
+ source: "Custom",
+ }),
+ ]);
+ });
+
+ it("captures platform-specific mod shortcuts", () => {
+ expect(
+ keybindingFromKeyboardEvent(
+ { key: "K", metaKey: true, ctrlKey: false, altKey: false, shiftKey: true },
+ "MacIntel",
+ ),
+ ).toBe("mod+shift+k");
+ expect(
+ keybindingFromKeyboardEvent(
+ { key: "K", metaKey: false, ctrlKey: true, altKey: false, shiftKey: true },
+ "Win32",
+ ),
+ ).toBe("mod+shift+k");
+ });
+
+ it("serializes shortcuts and when expressions for upserts", () => {
+ expect(
+ shortcutToKeybindingInput({
+ key: " ",
+ modKey: true,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: true,
+ shiftKey: false,
+ }),
+ ).toBe("mod+alt+space");
+
+ expect(
+ whenAstToExpression({
+ type: "and",
+ left: { type: "identifier", name: "editorFocus" },
+ right: {
+ type: "not",
+ node: { type: "identifier", name: "terminalFocus" },
+ },
+ }),
+ ).toBe("editorFocus && !terminalFocus");
+
+ expect(parseWhenExpressionDraft("editorFocus && (!terminalFocus || modelPickerOpen)")).toEqual({
+ ok: true,
+ value: {
+ type: "and",
+ left: { type: "identifier", name: "editorFocus" },
+ right: {
+ type: "or",
+ left: {
+ type: "not",
+ node: { type: "identifier", name: "terminalFocus" },
+ },
+ right: { type: "identifier", name: "modelPickerOpen" },
+ },
+ },
+ });
+ expect(parseWhenExpressionDraft("editorFocus &&")).toEqual({
+ ok: false,
+ message: "Use variables with !, &&, ||, and parentheses.",
+ });
+
+ expect(parseWhenExpressionDraft("!(terminalFocus || modelPickerOpen)")).toEqual({
+ ok: true,
+ value: {
+ type: "not",
+ node: {
+ type: "or",
+ left: { type: "identifier", name: "terminalFocus" },
+ right: { type: "identifier", name: "modelPickerOpen" },
+ },
+ },
+ });
+ });
+
+ it("formats static and project script command labels", () => {
+ expect(commandLabel("commandPalette.toggle")).toBe("Command Palette: Toggle");
+ expect(commandLabel("script.setup-db.run")).toBe("Run Script: Setup Db");
+ });
+
+ it("builds known when variable options from defaults without frontend labels", () => {
+ const options = buildWhenVariableOptions();
+
+ expect(options).toEqual(
+ expect.arrayContaining(["terminalFocus", "terminalOpen", "modelPickerOpen", "true", "false"]),
+ );
+ expect(options).not.toContain("customModeActive");
+ });
+
+ it("builds command options from defaults and resolved project bindings", () => {
+ const options = buildKeybindingCommandOptions([
+ {
+ command: "script.setup-db.run",
+ shortcut: {
+ key: "r",
+ modKey: true,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ },
+ },
+ ] satisfies ResolvedKeybindingsConfig);
+
+ expect(options).toEqual(expect.arrayContaining(["chat.new", "script.setup-db.run"]));
+ });
+
+ it("reports unknown when variables without rejecting parseable expressions", () => {
+ const parsed = parseWhenExpressionDraft("!terminalFocus && terminalFoc");
+
+ expect(parsed.ok).toBe(true);
+ expect(unknownWhenVariables(parsed.ok ? parsed.value : undefined)).toEqual(["terminalFoc"]);
+ });
+
+ it("marks each default shortcut for multi-binding commands as default", () => {
+ const rows = buildKeybindingRows(
+ [
+ {
+ command: "chat.new",
+ shortcut: {
+ key: "n",
+ modKey: true,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ },
+ whenAst: {
+ type: "not",
+ node: { type: "identifier", name: "terminalFocus" },
+ },
+ },
+ {
+ command: "chat.new",
+ shortcut: {
+ key: "o",
+ modKey: true,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: true,
+ },
+ whenAst: {
+ type: "not",
+ node: { type: "identifier", name: "terminalFocus" },
+ },
+ },
+ ] satisfies ResolvedKeybindingsConfig,
+ "",
+ );
+
+ expect(rows.map((row) => row.source)).toEqual(["Default", "Default"]);
+ });
+
+ it("reports conflicting shortcuts that share an active when context", () => {
+ const rows = buildKeybindingRows(
+ [
+ {
+ command: "chat.new",
+ shortcut: {
+ key: "n",
+ modKey: true,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ },
+ whenAst: {
+ type: "not",
+ node: { type: "identifier", name: "terminalFocus" },
+ },
+ },
+ {
+ command: "chat.newLocal",
+ shortcut: {
+ key: "n",
+ modKey: true,
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ },
+ whenAst: {
+ type: "not",
+ node: { type: "identifier", name: "terminalFocus" },
+ },
+ },
+ ] satisfies ResolvedKeybindingsConfig,
+ "",
+ );
+
+ expect(rows[0]?.conflicts).toEqual(["Chat: New Local"]);
+ expect(
+ keybindingConflictLabels(rows, {
+ rowId: rows[0]?.id ?? "",
+ key: "mod+n",
+ when: "",
+ }),
+ ).toEqual(["Chat: New Local"]);
+ });
+});
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
new file mode 100644
index 000000000..bb6b92048
--- /dev/null
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
@@ -0,0 +1,337 @@
+import {
+ type KeybindingCommand,
+ type KeybindingShortcut,
+ type KeybindingWhenNode,
+ type ResolvedKeybindingRule,
+ type ResolvedKeybindingsConfig,
+} from "@t3tools/contracts";
+import {
+ DEFAULT_RESOLVED_KEYBINDINGS,
+ parseKeybindingWhenExpression,
+} from "@t3tools/shared/keybindings";
+
+import { isMacPlatform } from "../../lib/utils";
+
+export type KeybindingSource = "Default" | "Custom" | "Project";
+
+export interface KeybindingRow {
+ readonly id: string;
+ readonly command: KeybindingCommand;
+ readonly key: string;
+ readonly when: string;
+ readonly source: KeybindingSource;
+ readonly defaultKey: string | null;
+ readonly defaultWhen: string;
+ readonly binding: ResolvedKeybindingRule;
+ readonly conflicts: ReadonlyArray<string>;
+}
+
+export type WhenVariableOption = string;
+export type KeybindingCommandOption = KeybindingCommand;
+
+const CORE_WHEN_VARIABLES = ["terminalFocus", "terminalOpen", "true", "false"] as const;
+
+const DEFAULT_WHEN_VARIABLES = new Set<string>(CORE_WHEN_VARIABLES);
+for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
+ collectWhenIdentifiersFromNode(binding.whenAst, DEFAULT_WHEN_VARIABLES);
+}
+
+export const DEFAULT_WHEN_VARIABLE =
+ [...DEFAULT_WHEN_VARIABLES].find(
+ (identifier) => identifier !== "true" && identifier !== "false",
+ ) ?? "terminalFocus";
+const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES);
+
+export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string {
+ const parts: string[] = [];
+ if (shortcut.modKey) parts.push("mod");
+ if (shortcut.metaKey) parts.push("meta");
+ if (shortcut.ctrlKey) parts.push("ctrl");
+ if (shortcut.altKey) parts.push("alt");
+ if (shortcut.shiftKey) parts.push("shift");
+ parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key);
+ return parts.join("+");
+}
+
+export function whenAstToExpression(node: KeybindingWhenNode | undefined): string {
+ if (!node) return "";
+ switch (node.type) {
+ case "identifier":
+ return node.name;
+ case "not":
+ return `!${wrapWhenExpression(node.node)}`;
+ case "and":
+ return `${wrapWhenExpression(node.left)} && ${wrapWhenExpression(node.right)}`;
+ case "or":
+ return `${wrapWhenExpression(node.left)} || ${wrapWhenExpression(node.right)}`;
+ }
+}
+
+function wrapWhenExpression(node: KeybindingWhenNode): string {
+ if (node.type === "identifier" || node.type === "not") return whenAstToExpression(node);
+ return `(${whenAstToExpression(node)})`;
+}
+
+export function parseWhenExpressionDraft(
+ expression: string,
+): { ok: true; value: KeybindingWhenNode | undefined } | { ok: false; message: string } {
+ const trimmed = expression.trim();
+ if (trimmed.length === 0) return { ok: true, value: undefined };
+
+ const ast = parseKeybindingWhenExpression(trimmed);
+ if (!ast) {
+ return {
+ ok: false,
+ message: "Use variables with !, &&, ||, and parentheses.",
+ };
+ }
+
+ return { ok: true, value: ast };
+}
+
+function sourceForBinding(binding: ResolvedKeybindingRule): KeybindingSource {
+ if (String(binding.command).startsWith("script.")) {
+ return "Project";
+ }
+
+ const bindingKey = shortcutToKeybindingInput(binding.shortcut);
+ const bindingWhen = whenAstToExpression(binding.whenAst);
+ const isDefault = DEFAULT_RESOLVED_KEYBINDINGS.some(
+ (entry) =>
+ entry.command === binding.command &&
+ shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
+ whenAstToExpression(entry.whenAst) === bindingWhen,
+ );
+
+ return isDefault ? "Default" : "Custom";
+}
+
+function defaultBindingForBinding(
+ binding: ResolvedKeybindingRule,
+): ResolvedKeybindingRule | undefined {
+ const bindingKey = shortcutToKeybindingInput(binding.shortcut);
+ const bindingWhen = whenAstToExpression(binding.whenAst);
+
+ return (
+ DEFAULT_RESOLVED_KEYBINDINGS.find(
+ (entry) =>
+ entry.command === binding.command &&
+ shortcutToKeybindingInput(entry.shortcut) === bindingKey &&
+ whenAstToExpression(entry.whenAst) === bindingWhen,
+ ) ??
+ DEFAULT_RESOLVED_KEYBINDINGS.find(
+ (entry) =>
+ entry.command === binding.command && whenAstToExpression(entry.whenAst) === bindingWhen,
+ ) ??
+ DEFAULT_RESOLVED_KEYBINDINGS.find((entry) => entry.command === binding.command)
+ );
+}
+
+function keybindingRowId(command: KeybindingCommand, key: string, when: string): string {
+ return `${command}\u0000${key}\u0000${when}`;
+}
+
+function conflictsWithWhen(leftWhen: string, rightWhen: string): boolean {
+ return leftWhen.length === 0 || rightWhen.length === 0 || leftWhen === rightWhen;
+}
+
+export function keybindingConflictLabels(
+ rows: ReadonlyArray<KeybindingRow>,
+ input: { readonly rowId: string; readonly key: string; readonly when: string },
+): ReadonlyArray<string> {
+ if (input.key.trim().length === 0) return [];
+ const conflicts = rows
+ .filter(
+ (candidate) =>
+ candidate.id !== input.rowId &&
+ candidate.key === input.key &&
+ conflictsWithWhen(candidate.when, input.when),
+ )
+ .map((candidate) => commandLabel(candidate.command));
+ return [...new Set(conflicts)].toSorted();
+}
+
+export function buildKeybindingRows(
+ keybindings: ResolvedKeybindingsConfig,
+ query: string,
+): ReadonlyArray<KeybindingRow> {
+ const normalizedQuery = query.trim().toLowerCase();
+ const rows = keybindings.map((binding, index) => {
+ const defaultBinding = defaultBindingForBinding(binding);
+ const key = shortcutToKeybindingInput(binding.shortcut);
+ const when = whenAstToExpression(binding.whenAst);
+ return {
+ id: `${keybindingRowId(binding.command, key, when)}\u0000${index}`,
+ command: binding.command,
+ key,
+ when,
+ source: sourceForBinding(binding),
+ defaultKey: defaultBinding ? shortcutToKeybindingInput(defaultBinding.shortcut) : null,
+ defaultWhen: whenAstToExpression(defaultBinding?.whenAst),
+ binding,
+ conflicts: [],
+ } satisfies KeybindingRow;
+ });
+
+ const rowsWithConflicts = rows.map((row) => {
+ const conflicts = keybindingConflictLabels(rows, {
+ rowId: row.id,
+ key: row.key,
+ when: row.when,
+ });
+ return conflicts.length > 0
+ ? Object.assign({}, row, { conflicts: [...new Set(conflicts)].toSorted() })
+ : row;
+ });
+
+ rowsWithConflicts.sort((left, right) => {
+ const commandCompare = left.command.localeCompare(right.command);
+ if (commandCompare !== 0) return commandCompare;
+ return left.key.localeCompare(right.key);
+ });
+
+ if (normalizedQuery.length === 0) {
+ return rowsWithConflicts;
+ }
+
+ return rowsWithConflicts.filter((row) => {
+ return (
+ row.command.toLowerCase().includes(normalizedQuery) ||
+ row.key.toLowerCase().includes(normalizedQuery) ||
+ row.when.toLowerCase().includes(normalizedQuery) ||
+ row.source.toLowerCase().includes(normalizedQuery)
+ );
+ });
+}
+
+function collectWhenIdentifiersFromNode(
+ node: KeybindingWhenNode | undefined,
+ identifiers: Set<string>,
+): void {
+ if (!node) return;
+ switch (node.type) {
+ case "identifier":
+ identifiers.add(node.name);
+ return;
+ case "not":
+ collectWhenIdentifiersFromNode(node.node, identifiers);
+ return;
+ case "and":
+ case "or":
+ collectWhenIdentifiersFromNode(node.left, identifiers);
+ collectWhenIdentifiersFromNode(node.right, identifiers);
+ return;
+ }
+}
+
+export function isKnownWhenVariable(identifier: string): boolean {
+ return KNOWN_WHEN_VARIABLES.has(identifier);
+}
+
+export function unknownWhenVariables(node: KeybindingWhenNode | undefined): ReadonlyArray<string> {
+ const identifiers = new Set<string>();
+ collectWhenIdentifiersFromNode(node, identifiers);
+ return [...identifiers].filter((identifier) => !isKnownWhenVariable(identifier)).toSorted();
+}
+
+export function buildWhenVariableOptions(): ReadonlyArray<WhenVariableOption> {
+ return [...KNOWN_WHEN_VARIABLES].toSorted((left, right) => {
+ const leftCoreIndex = CORE_WHEN_VARIABLES.indexOf(left as (typeof CORE_WHEN_VARIABLES)[number]);
+ const rightCoreIndex = CORE_WHEN_VARIABLES.indexOf(
+ right as (typeof CORE_WHEN_VARIABLES)[number],
+ );
+ if (leftCoreIndex !== -1 || rightCoreIndex !== -1) {
+ return (
+ (leftCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : leftCoreIndex) -
+ (rightCoreIndex === -1 ? Number.MAX_SAFE_INTEGER : rightCoreIndex)
+ );
+ }
+ return left.localeCompare(right);
+ });
+}
+
+export function buildKeybindingCommandOptions(
+ keybindings: ResolvedKeybindingsConfig,
+): ReadonlyArray<KeybindingCommandOption> {
+ const commands = new Set<KeybindingCommand>();
+ for (const binding of DEFAULT_RESOLVED_KEYBINDINGS) {
+ commands.add(binding.command);
+ }
+ for (const binding of keybindings) {
+ commands.add(binding.command);
+ }
+ return [...commands].toSorted((left, right) =>
+ commandLabel(left).localeCompare(commandLabel(right)),
+ );
+}
+
+export function commandLabel(command: KeybindingCommand): string {
+ const raw = String(command);
+ if (raw.startsWith("script.") && raw.endsWith(".run")) {
+ return `Run Script: ${titleCaseCommandSegment(raw.slice("script.".length, -".run".length))}`;
+ }
+ return raw.split(".").map(titleCaseCommandSegment).join(": ");
+}
+
+function titleCaseCommandSegment(segment: string): string {
+ return segment
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
+ .split(/[-_\s]+/)
+ .filter(Boolean)
+ .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))
+ .join(" ");
+}
+
+export function normalizeShortcutKeyToken(key: string): string | null {
+ const normalized = key.toLowerCase();
+ if (
+ normalized === "meta" ||
+ normalized === "control" ||
+ normalized === "ctrl" ||
+ normalized === "shift" ||
+ normalized === "alt" ||
+ normalized === "option"
+ ) {
+ return null;
+ }
+ if (normalized === " ") return "space";
+ if (normalized === "escape") return "esc";
+ if (normalized === "arrowup") return "arrowup";
+ if (normalized === "arrowdown") return "arrowdown";
+ if (normalized === "arrowleft") return "arrowleft";
+ if (normalized === "arrowright") return "arrowright";
+ if (normalized.length === 1) return normalized;
+ if (/^f\d{1,2}$/.test(normalized)) return normalized;
+ if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
+ return normalized;
+ }
+ if (normalized === "delete" || normalized === "home" || normalized === "end") {
+ return normalized;
+ }
+ if (normalized === "pageup" || normalized === "pagedown") return normalized;
+ return null;
+}
+
+export function keybindingFromKeyboardEvent(
+ event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
+ platform: string,
+): string | null {
+ const keyToken = normalizeShortcutKeyToken(event.key);
+ if (!keyToken) return null;
+
+ const parts: string[] = [];
+ if (isMacPlatform(platform)) {
+ if (event.metaKey) parts.push("mod");
+ if (event.ctrlKey) parts.push("ctrl");
+ } else {
+ if (event.ctrlKey) parts.push("mod");
+ if (event.metaKey) parts.push("meta");
+ }
+ if (event.altKey) parts.push("alt");
+ if (event.shiftKey) parts.push("shift");
+ if (parts.length === 0) {
+ return null;
+ }
+ parts.push(keyToken);
+ return parts.join("+");
+}
diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx
new file mode 100644
index 000000000..89b070c93
--- /dev/null
+++ b/apps/web/src/components/settings/KeybindingsSettings.tsx
@@ -0,0 +1,1282 @@
+import {
+ ChevronDownIcon,
+ CircleXIcon,
+ EllipsisIcon,
+ FileJsonIcon,
+ InfoIcon,
+ MinusIcon,
+ PlusIcon,
+ SearchIcon,
+ TriangleAlertIcon,
+ XIcon,
+} from "lucide-react";
+import {
+ type KeyboardEvent,
+ type ReactNode,
+ type RefObject,
+ useCallback,
+ useEffect,
+ useMemo,
+ useReducer,
+ useRef,
+ useState,
+} from "react";
+import {
+ type KeybindingCommand,
+ type KeybindingWhenNode,
+ type ServerRemoveKeybindingInput,
+ type ServerUpsertKeybindingInput,
+} from "@t3tools/contracts";
+
+import { isElectron } from "../../env";
+import { openInPreferredEditor } from "../../editorPreferences";
+import { formatShortcutLabel } from "../../keybindings";
+import { cn } from "../../lib/utils";
+import { ensureLocalApi } from "../../localApi";
+import { useServerKeybindings, useServerKeybindingsConfigPath } from "../../rpc/serverState";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { Kbd, KbdGroup } from "../ui/kbd";
+import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
+import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
+import { ScrollArea } from "../ui/scroll-area";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
+import { Toggle } from "../ui/toggle";
+import { toastManager } from "../ui/toast";
+import {
+ buildKeybindingRows,
+ buildKeybindingCommandOptions,
+ buildWhenVariableOptions,
+ commandLabel,
+ DEFAULT_WHEN_VARIABLE,
+ isKnownWhenVariable,
+ keybindingConflictLabels,
+ keybindingFromKeyboardEvent,
+ parseWhenExpressionDraft,
+ type KeybindingCommandOption,
+ type KeybindingRow,
+ type WhenVariableOption,
+ unknownWhenVariables,
+ whenAstToExpression,
+} from "./KeybindingsSettings.logic";
+import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+
+function KeybindingPill({ value }: { value: string }) {
+ const parts = value.split("+");
+ return (
+ <KbdGroup className="bg-transparent p-0 shadow-none">
+ {parts.map((part) => (
+ <Kbd key={part} className="min-w-6 justify-center px-1.5">
+ {part === "mod"
+ ? navigator.platform.toLowerCase().includes("mac")
+ ? "⌘"
+ : "Ctrl"
+ : part === "shift"
+ ? "⇧"
+ : part === "alt"
+ ? navigator.platform.toLowerCase().includes("mac")
+ ? "⌥"
+ : "Alt"
+ : part === "ctrl"
+ ? "⌃"
+ : part.length === 1
+ ? part.toUpperCase()
+ : part}
+ </Kbd>
+ ))}
+ </KbdGroup>
+ );
+}
+
+function ExpandableHeaderSearch({
+ query,
+ onChange,
+ isOpen,
+ onOpenChange,
+ inputRef,
+ collapsedAccessory,
+}: {
+ query: string;
+ onChange: (next: string) => void;
+ isOpen: boolean;
+ onOpenChange: (next: boolean) => void;
+ inputRef?: RefObject<HTMLInputElement | null>;
+ collapsedAccessory?: ReactNode;
+}) {
+ if (!isOpen) {
+ return (
+ <>
+ {collapsedAccessory}
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
+ onClick={() => onOpenChange(true)}
+ aria-label="Search keybindings"
+ >
+ <SearchIcon className="size-3" />
+ </Button>
+ }
+ />
+ <TooltipPopup side="top">Search keybindings</TooltipPopup>
+ </Tooltip>
+ </>
+ );
+ }
+
+ return (
+ <div className="relative">
+ <SearchIcon className="pointer-events-none absolute top-1/2 left-2 size-3 -translate-y-1/2 text-muted-foreground" />
+ <input
+ ref={inputRef}
+ autoFocus
+ type="text"
+ value={query}
+ onChange={(event) => onChange(event.currentTarget.value)}
+ onBlur={() => {
+ if (query.length === 0) onOpenChange(false);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ onChange("");
+ onOpenChange(false);
+ }
+ }}
+ placeholder="Search keybindings"
+ aria-label="Search keybindings"
+ className="h-6 w-44 rounded-md border border-input bg-background pl-7 pr-2 text-[11px] text-foreground outline-none placeholder:text-muted-foreground/72 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24"
+ />
+ </div>
+ );
+}
+
+type BooleanOperator = "and" | "or";
+
+function flattenWhenChildren(
+ node: KeybindingWhenNode,
+ operator: BooleanOperator,
+): KeybindingWhenNode[] {
+ if (node.type !== operator) return [node];
+ return [
+ ...flattenWhenChildren(node.left, operator),
+ ...flattenWhenChildren(node.right, operator),
+ ];
+}
+
+function buildWhenExpressionGroup(
+ children: readonly KeybindingWhenNode[],
+ operator: BooleanOperator,
+): KeybindingWhenNode | undefined {
+ const first = children[0];
+ if (!first) return undefined;
+ return children.slice(1).reduce<KeybindingWhenNode>(
+ (left, right) => ({
+ type: operator,
+ left,
+ right,
+ }),
+ first,
+ );
+}
+
+function conditionParts(node: KeybindingWhenNode): { identifier: string; negated: boolean } | null {
+ if (node.type === "identifier") return { identifier: node.name, negated: false };
+ if (node.type === "not" && node.node.type === "identifier") {
+ return { identifier: node.node.name, negated: true };
+ }
+ return null;
+}
+
+function setConditionIdentifier(node: KeybindingWhenNode, identifier: string): KeybindingWhenNode {
+ const parts = conditionParts(node);
+ if (!parts) return node;
+ const next: KeybindingWhenNode = { type: "identifier", name: identifier };
+ return parts.negated ? { type: "not", node: next } : next;
+}
+
+function setConditionNegated(node: KeybindingWhenNode, negated: boolean): KeybindingWhenNode {
+ const parts = conditionParts(node);
+ if (!parts) return negated ? { type: "not", node } : node;
+ const identifier: KeybindingWhenNode = { type: "identifier", name: parts.identifier };
+ return negated ? { type: "not", node: identifier } : identifier;
+}
+
+function defaultWhenCondition(): KeybindingWhenNode {
+ return { type: "identifier", name: DEFAULT_WHEN_VARIABLE };
+}
+
+function defaultWhenGroup(operator: BooleanOperator = "and"): KeybindingWhenNode {
+ return {
+ type: operator,
+ left: defaultWhenCondition(),
+ right: { type: "not", node: defaultWhenCondition() },
+ };
+}
+
+function UnknownWhenVariableWarning({
+ identifiers,
+ focusable = true,
+}: {
+ identifiers: ReadonlyArray<string>;
+ focusable?: boolean;
+}) {
+ if (identifiers.length === 0) return null;
+ const label =
+ identifiers.length === 1
+ ? `Unknown condition: ${identifiers[0]}`
+ : `Unknown conditions: ${identifiers.join(", ")}`;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ tabIndex={focusable ? 0 : undefined}
+ aria-label={label}
+ className="inline-flex size-4.5 shrink-0 items-center justify-center rounded-sm text-warning outline-none transition-colors hover:bg-warning/10 focus-visible:ring-[3px] focus-visible:ring-warning/25"
+ >
+ <TriangleAlertIcon className="size-3.5" />
+ </span>
+ }
+ />
+ <TooltipPopup side="top" className="max-w-72 whitespace-normal leading-relaxed">
+ T3 Code does not recognize this condition yet. It can still be saved, but it may not match
+ unless the runtime provides it.
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
+
+function KeybindingConflictWarning({ labels }: { labels: ReadonlyArray<string> }) {
+ if (labels.length === 0) return null;
+ const description =
+ labels.length === 1
+ ? `Conflicts with ${labels[0]}.`
+ : `Conflicts with ${labels.slice(0, 3).join(", ")}${labels.length > 3 ? ", and more" : ""}.`;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ tabIndex={0}
+ aria-label={description}
+ className="inline-flex size-5 shrink-0 items-center justify-center rounded-sm text-warning outline-none transition-colors hover:bg-warning/10 focus-visible:ring-[3px] focus-visible:ring-warning/25"
+ >
+ <TriangleAlertIcon className="size-3.5" />
+ </span>
+ }
+ />
+ <TooltipPopup side="top" className="max-w-72 whitespace-normal leading-relaxed">
+ {description} The most recent matching binding wins when both conditions can apply.
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
+
+function WhenVariableSelect({
+ value,
+ variables,
+ unknownIdentifiers,
+ onChange,
+}: {
+ value: string;
+ variables: ReadonlyArray<WhenVariableOption>;
+ unknownIdentifiers?: ReadonlyArray<string>;
+ onChange: (value: string) => void;
+}) {
+ const selected = variables.find((option) => option === value);
+ const options =
+ selected || variables.some((option) => option === value) ? variables : [value, ...variables];
+
+ return (
+ <Select value={value} onValueChange={(nextValue) => nextValue && onChange(nextValue)}>
+ <SelectTrigger
+ size="xs"
+ className="h-7 min-h-7 min-w-0 flex-1 rounded-md font-mono text-xs sm:h-7"
+ >
+ <SelectValue placeholder="Condition" className="leading-7" />
+ {unknownIdentifiers && unknownIdentifiers.length > 0 ? (
+ <UnknownWhenVariableWarning identifiers={unknownIdentifiers} focusable={false} />
+ ) : null}
+ </SelectTrigger>
+ <SelectContent
+ alignItemWithTrigger={false}
+ matchTriggerWidth={false}
+ popupClassName="w-fit"
+ className="max-h-72 w-fit min-w-44"
+ >
+ {options.map((option) => (
+ <SelectItem
+ key={option}
+ value={option}
+ className="min-h-7 w-full py-1 font-mono text-[12px]"
+ >
+ <span className="truncate">{option}</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+function WhenExpressionNodeEditor({
+ node,
+ variables,
+ depth = 0,
+ onChange,
+ onRemove,
+}: {
+ node: KeybindingWhenNode;
+ variables: ReadonlyArray<WhenVariableOption>;
+ depth?: number;
+ onChange: (node: KeybindingWhenNode) => void;
+ onRemove?: () => void;
+}) {
+ const condition = conditionParts(node);
+
+ if (condition) {
+ const unknownIdentifiers = isKnownWhenVariable(condition.identifier)
+ ? []
+ : [condition.identifier];
+
+ return (
+ <div className="flex items-center gap-2 rounded-md border border-border/70 bg-background/60 px-2 py-2">
+ <Toggle
+ pressed={condition.negated}
+ onPressedChange={(pressed) => onChange(setConditionNegated(node, pressed))}
+ aria-label={`Negate ${condition.identifier}`}
+ variant="outline"
+ size="xs"
+ className="h-7 min-w-10 px-2 text-[11px] sm:h-7"
+ >
+ Not
+ </Toggle>
+ <WhenVariableSelect
+ value={condition.identifier}
+ variables={variables}
+ unknownIdentifiers={unknownIdentifiers}
+ onChange={(value) => onChange(setConditionIdentifier(node, value))}
+ />
+ {onRemove ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 sm:size-7"
+ aria-label="Remove condition"
+ onClick={onRemove}
+ >
+ <MinusIcon className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
+ );
+ }
+
+ if (node.type === "not") {
+ return (
+ <div
+ className={cn(
+ "space-y-2 rounded-lg border border-border/70 bg-muted/20 p-2",
+ depth > 0 && "border-border/50 bg-background/50",
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <Toggle
+ pressed
+ onPressedChange={(pressed) => onChange(pressed ? node : node.node)}
+ aria-label="Negate group"
+ variant="outline"
+ size="xs"
+ className="h-7 min-w-10 px-2 text-[11px] sm:h-7"
+ >
+ Not
+ </Toggle>
+ {onRemove ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="ml-auto size-7 sm:size-7"
+ aria-label="Remove negated group"
+ onClick={onRemove}
+ >
+ <MinusIcon className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
+ <div className="relative pl-4">
+ <span className="absolute top-0 bottom-0 left-1.5 w-px bg-border/70" aria-hidden />
+ <span className="absolute top-4 left-1.5 h-px w-2.5 bg-border/70" aria-hidden />
+ <WhenExpressionNodeEditor
+ node={node.node}
+ variables={variables}
+ depth={depth + 1}
+ onChange={(next) => onChange({ type: "not", node: next })}
+ />
+ </div>
+ </div>
+ );
+ }
+
+ const operator: BooleanOperator = node.type === "or" ? "or" : "and";
+ const children = flattenWhenChildren(node, operator);
+ const childKeyCounts = new Map<string, number>();
+ const childEntries = children.map((child) => {
+ const baseKey = `${child.type}-${whenAstToExpression(child)}`;
+ const count = childKeyCounts.get(baseKey) ?? 0;
+ childKeyCounts.set(baseKey, count + 1);
+ return { child, key: count === 0 ? baseKey : `${baseKey}-${count}` };
+ });
+
+ const updateChild = (target: KeybindingWhenNode, next: KeybindingWhenNode) => {
+ let didUpdate = false;
+ const nextChildren = children.map((child) => {
+ if (!didUpdate && child === target) {
+ didUpdate = true;
+ return next;
+ }
+ return child;
+ });
+ const nextNode = buildWhenExpressionGroup(nextChildren, operator);
+ if (nextNode) onChange(nextNode);
+ };
+
+ const removeChild = (target: KeybindingWhenNode) => {
+ let didRemove = false;
+ const nextChildren = children.filter((child) => {
+ if (!didRemove && child === target) {
+ didRemove = true;
+ return false;
+ }
+ return true;
+ });
+ const nextNode = buildWhenExpressionGroup(nextChildren, operator);
+ if (nextNode) {
+ onChange(nextNode);
+ } else {
+ onChange(defaultWhenCondition());
+ }
+ };
+
+ const setOperator = (nextOperator: BooleanOperator) => {
+ if (nextOperator === operator) return;
+ const nextNode = buildWhenExpressionGroup(children, nextOperator);
+ if (nextNode) onChange(nextNode);
+ };
+
+ const addCondition = () => {
+ const nextNode = buildWhenExpressionGroup([...children, defaultWhenCondition()], operator);
+ if (nextNode) onChange(nextNode);
+ };
+
+ const addGroup = () => {
+ const nestedOperator: BooleanOperator = operator === "and" ? "or" : "and";
+ const group: KeybindingWhenNode = {
+ type: nestedOperator,
+ left: defaultWhenCondition(),
+ right: { type: "not", node: defaultWhenCondition() },
+ };
+ const nextNode = buildWhenExpressionGroup([...children, group], operator);
+ if (nextNode) onChange(nextNode);
+ };
+
+ return (
+ <div
+ className={cn(
+ "space-y-2 rounded-lg border border-border/60 bg-muted/10 p-2",
+ depth > 0 && "border-border/70 bg-background/55",
+ )}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <Select value={operator} onValueChange={(value) => setOperator(value as BooleanOperator)}>
+ <SelectTrigger size="xs" className="h-7 min-h-7 w-24 rounded-md text-xs sm:h-7">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent
+ alignItemWithTrigger={false}
+ matchTriggerWidth={false}
+ popupClassName="w-fit"
+ className="w-fit min-w-24"
+ >
+ <SelectItem value="and" className="min-h-7 py-1 font-mono text-[12px]">
+ and
+ </SelectItem>
+ <SelectItem value="or" className="min-h-7 py-1 font-mono text-[12px]">
+ or
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ className="h-7 sm:h-7"
+ onClick={addCondition}
+ >
+ <PlusIcon className="size-3.5" />
+ Condition
+ </Button>
+ <Button type="button" variant="outline" size="xs" className="h-7 sm:h-7" onClick={addGroup}>
+ <PlusIcon className="size-3.5" />
+ Group
+ </Button>
+ {onRemove ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="ml-auto size-7 sm:size-7"
+ aria-label="Remove group"
+ onClick={onRemove}
+ >
+ <MinusIcon className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
+ <div className="space-y-2">
+ {childEntries.map(({ child, key }) => (
+ <div key={key} className="relative pl-4">
+ <span
+ className={cn(
+ "absolute top-0 bottom-0 left-1.5 w-px",
+ depth === 0 ? "bg-border" : "bg-border/70",
+ )}
+ aria-hidden
+ />
+ <span
+ className={cn(
+ "absolute top-4 left-1.5 h-px w-2.5",
+ depth === 0 ? "bg-border" : "bg-border/70",
+ )}
+ aria-hidden
+ />
+ <WhenExpressionNodeEditor
+ node={child}
+ variables={variables}
+ depth={depth + 1}
+ onChange={(next) => updateChild(child, next)}
+ onRemove={() => removeChild(child)}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function WhenExpressionBuilder({
+ value,
+ variables,
+ onChange,
+ onValidityChange,
+}: {
+ value: KeybindingWhenNode | undefined;
+ variables: ReadonlyArray<WhenVariableOption>;
+ onChange: (value: KeybindingWhenNode | undefined) => void;
+ onValidityChange?: (valid: boolean) => void;
+}) {
+ const expression = whenAstToExpression(value);
+ const [expressionDraft, setExpressionDraft] = useState(expression);
+ const parseResult = useMemo(() => parseWhenExpressionDraft(expressionDraft), [expressionDraft]);
+ const parseError = parseResult.ok ? null : parseResult.message;
+ const unknownIdentifiers = parseResult.ok ? unknownWhenVariables(parseResult.value) : [];
+
+ const updateExpressionDraft = (nextExpression: string) => {
+ setExpressionDraft(nextExpression);
+ const nextResult = parseWhenExpressionDraft(nextExpression);
+ onValidityChange?.(nextResult.ok);
+ if (nextResult.ok) {
+ onChange(nextResult.value);
+ }
+ };
+
+ const updateExpressionValue = (nextValue: KeybindingWhenNode | undefined) => {
+ setExpressionDraft(whenAstToExpression(nextValue));
+ onValidityChange?.(true);
+ onChange(nextValue);
+ };
+
+ const addRootCondition = () => {
+ if (!value) {
+ updateExpressionValue(defaultWhenCondition());
+ return;
+ }
+ updateExpressionValue({ type: "and", left: value, right: defaultWhenCondition() });
+ };
+
+ const addRootGroup = () => {
+ const group = defaultWhenGroup("or");
+ if (!value) {
+ updateExpressionValue(group);
+ return;
+ }
+ updateExpressionValue({ type: "and", left: value, right: group });
+ };
+
+ return (
+ <div className="w-[min(34rem,calc(100vw-2rem))] space-y-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-foreground">When</div>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ className="h-7 sm:h-7"
+ onClick={addRootCondition}
+ >
+ <PlusIcon className="size-3.5" />
+ Condition
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ className="h-7 sm:h-7"
+ onClick={addRootGroup}
+ >
+ <PlusIcon className="size-3.5" />
+ Group
+ </Button>
+ </div>
+ </div>
+
+ <div className="space-y-1.5">
+ <div className="relative">
+ <Input
+ value={expressionDraft}
+ onChange={(event) => updateExpressionDraft(event.currentTarget.value)}
+ placeholder="Always"
+ aria-invalid={Boolean(parseError)}
+ aria-label="When expression"
+ className={cn(
+ "h-7 rounded-md font-mono text-[12px] leading-7 sm:h-7 sm:leading-7",
+ unknownIdentifiers.length > 0 && "pr-9",
+ parseError && "border-destructive/70 focus-visible:border-destructive",
+ )}
+ />
+ {unknownIdentifiers.length > 0 ? (
+ <span className="absolute inset-y-0 right-2 flex items-center">
+ <UnknownWhenVariableWarning identifiers={unknownIdentifiers} />
+ </span>
+ ) : null}
+ </div>
+ {parseError ? (
+ <div className="flex items-center gap-1.5 text-[11px] text-destructive">
+ <CircleXIcon className="size-3.5" />
+ {parseError}
+ </div>
+ ) : null}
+ </div>
+
+ <div className="relative">
+ {value ? (
+ <WhenExpressionNodeEditor
+ node={value}
+ variables={variables}
+ onChange={updateExpressionValue}
+ onRemove={() => updateExpressionValue(undefined)}
+ />
+ ) : (
+ <div className="rounded-md border border-dashed border-border/80 bg-muted/15 p-3">
+ <div className="flex flex-wrap gap-2">
+ <Button type="button" size="xs" className="h-7 sm:h-7" onClick={addRootCondition}>
+ <PlusIcon className="size-3.5" />
+ Condition
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ className="h-7 sm:h-7"
+ onClick={addRootGroup}
+ >
+ <PlusIcon className="size-3.5" />
+ Group
+ </Button>
+ </div>
+ </div>
+ )}
+ {parseError ? (
+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center rounded-lg border border-destructive/30 bg-background/75 p-4 text-center text-xs text-destructive backdrop-blur-[1px]">
+ Fix the expression above to continue editing visually.
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+type KeybindingRowDraftState = {
+ keyDraft: string;
+ whenDraft: KeybindingWhenNode | undefined;
+ isRecording: boolean;
+ isWhenDraftValid: boolean;
+};
+
+function createKeybindingRowDraft(row: KeybindingRow): KeybindingRowDraftState {
+ return {
+ keyDraft: row.key,
+ whenDraft: row.binding.whenAst,
+ isRecording: false,
+ isWhenDraftValid: true,
+ };
+}
+
+function keybindingRowDraftReducer(
+ state: KeybindingRowDraftState,
+ patch: Partial<KeybindingRowDraftState>,
+): KeybindingRowDraftState {
+ return { ...state, ...patch };
+}
+
+function rowKeybindingTarget(row: KeybindingRow): ServerRemoveKeybindingInput {
+ return {
+ command: row.command,
+ key: row.key,
+ ...(row.when.trim().length > 0 ? { when: row.when } : {}),
+ };
+}
+
+function KeybindingTableRow({
+ row,
+ allRows,
+ variables,
+ isSaving,
+ onSave,
+ onReset,
+ onRemove,
+}: {
+ row: KeybindingRow;
+ allRows: ReadonlyArray<KeybindingRow>;
+ variables: ReadonlyArray<WhenVariableOption>;
+ isSaving: boolean;
+ onSave: (input: ServerUpsertKeybindingInput) => void;
+ onReset: (row: KeybindingRow) => void;
+ onRemove: (row: KeybindingRow) => void;
+}) {
+ const [draft, setDraft] = useReducer(keybindingRowDraftReducer, row, createKeybindingRowDraft);
+ const { keyDraft, whenDraft, isRecording, isWhenDraftValid } = draft;
+ const whenDraftExpression = whenAstToExpression(whenDraft);
+ const isDirty = keyDraft !== row.key || whenDraftExpression !== row.when;
+ const displayShortcut = formatShortcutLabel(row.binding.shortcut);
+ const canReset = row.source === "Custom" && row.defaultKey !== null;
+ const canRemove = row.source !== "Default";
+ const hasRowActions = canReset || canRemove;
+ const showPill = !isRecording && keyDraft === row.key && row.key.length > 0 && !isDirty;
+ const conflictLabels = keybindingConflictLabels(allRows, {
+ rowId: row.id,
+ key: keyDraft,
+ when: whenDraftExpression,
+ });
+
+ const save = () => {
+ onSave({
+ command: row.command,
+ key: keyDraft,
+ when: whenDraftExpression.trim().length > 0 ? whenDraftExpression : undefined,
+ replace: rowKeybindingTarget(row),
+ });
+ };
+
+ const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === "Tab") return;
+ event.preventDefault();
+ if (event.key === "Escape") {
+ setDraft({ keyDraft: row.key, isRecording: false });
+ return;
+ }
+ const next = keybindingFromKeyboardEvent(event.nativeEvent, navigator.platform);
+ if (!next) return;
+ setDraft({ keyDraft: next, isRecording: false });
+ };
+
+ return (
+ <div className="grid grid-cols-[minmax(190px,1.1fr)_minmax(220px,0.85fr)_minmax(210px,1fr)_60px] items-center px-4 py-1.5 text-sm even:bg-muted/15 hover:bg-accent/40">
+ <div className="min-w-0 pr-4">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <div className="truncate text-[13px] font-medium text-foreground" title={row.command}>
+ {commandLabel(row.command)}
+ </div>
+ </div>
+ </div>
+ <div className="flex min-w-0 items-center gap-2 pr-4">
+ {showPill ? (
+ <button
+ type="button"
+ onClick={() => setDraft({ isRecording: true })}
+ aria-label={`Edit shortcut for ${commandLabel(row.command)}`}
+ className="group inline-flex h-7 items-center gap-1.5 rounded-md border border-transparent px-1.5 outline-none transition-colors hover:border-border/70 hover:bg-background focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24"
+ >
+ <KeybindingPill value={row.key} />
+ <span className="text-[10px] uppercase tracking-[0.08em] text-muted-foreground/0 transition-opacity group-hover:text-muted-foreground/70 group-focus-visible:text-muted-foreground/70">
+ Edit
+ </span>
+ </button>
+ ) : (
+ <Input
+ autoFocus={isRecording}
+ aria-label={`Keybinding for ${commandLabel(row.command)}`}
+ value={isRecording ? "" : keyDraft}
+ placeholder={isRecording ? "Press shortcut" : "Unassigned"}
+ className={cn(
+ "h-7 w-44 rounded-md font-mono text-[12px] sm:h-7",
+ isRecording && "border-primary/70 bg-primary/5",
+ )}
+ onFocus={() => setDraft({ isRecording: true })}
+ onBlur={() => setDraft({ isRecording: false })}
+ onChange={(event) => setDraft({ keyDraft: event.currentTarget.value })}
+ onKeyDown={captureKeybinding}
+ />
+ )}
+ {isDirty ? (
+ <Button
+ size="xs"
+ className="h-7 sm:h-7"
+ disabled={isSaving || keyDraft.trim().length === 0 || !isWhenDraftValid}
+ onClick={save}
+ >
+ {isSaving ? "Saving" : "Save"}
+ </Button>
+ ) : null}
+ </div>
+ <div className="pr-4">
+ <Popover>
+ <PopoverTrigger
+ className={cn(
+ "inline-flex h-7 w-full items-center justify-between gap-2 rounded-md border border-input bg-background px-2.5 text-left font-mono text-[12px] text-foreground shadow-xs/5 outline-none transition-colors hover:bg-accent focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24",
+ !whenDraftExpression && "text-muted-foreground",
+ )}
+ aria-label={`Edit when clause for ${commandLabel(row.command)}`}
+ >
+ <span className="truncate">{whenDraftExpression || "Always"}</span>
+ <ChevronDownIcon className="size-3.5 shrink-0 opacity-60" />
+ </PopoverTrigger>
+ <PopoverContent align="start" sideOffset={6}>
+ <WhenExpressionBuilder
+ value={whenDraft}
+ variables={variables}
+ onChange={(nextWhenDraft) => setDraft({ whenDraft: nextWhenDraft })}
+ onValidityChange={(nextIsValid) => setDraft({ isWhenDraftValid: nextIsValid })}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ <div className="flex items-center justify-end gap-1">
+ <KeybindingConflictWarning labels={conflictLabels} />
+ {hasRowActions ? (
+ <Menu>
+ <MenuTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 text-muted-foreground hover:text-foreground sm:size-7"
+ disabled={isSaving}
+ aria-label={`Actions for ${commandLabel(row.command)}`}
+ />
+ }
+ >
+ <EllipsisIcon className="size-3.5" />
+ </MenuTrigger>
+ <MenuPopup align="end" className="min-w-36">
+ {canReset ? (
+ <MenuItem disabled={isSaving} onClick={() => onReset(row)}>
+ Reset to default
+ </MenuItem>
+ ) : null}
+ {canRemove ? (
+ <MenuItem variant="destructive" disabled={isSaving} onClick={() => onRemove(row)}>
+ Remove
+ </MenuItem>
+ ) : null}
+ </MenuPopup>
+ </Menu>
+ ) : null}
+ <span className="sr-only">{displayShortcut}</span>
+ </div>
+ </div>
+ );
+}
+
+function NewKeybindingTableRow({
+ commandOptions,
+ allRows,
+ variables,
+ isSaving,
+ onSave,
+ onCancel,
+}: {
+ commandOptions: ReadonlyArray<KeybindingCommandOption>;
+ allRows: ReadonlyArray<KeybindingRow>;
+ variables: ReadonlyArray<WhenVariableOption>;
+ isSaving: boolean;
+ onSave: (input: ServerUpsertKeybindingInput) => void;
+ onCancel: () => void;
+}) {
+ const [commandDraft, setCommandDraft] = useState<KeybindingCommand | "">("");
+ const [draft, setDraft] = useReducer(keybindingRowDraftReducer, {
+ keyDraft: "",
+ whenDraft: undefined,
+ isRecording: false,
+ isWhenDraftValid: true,
+ });
+ const { keyDraft, whenDraft, isRecording, isWhenDraftValid } = draft;
+ const whenDraftExpression = whenAstToExpression(whenDraft);
+ const conflictLabels = keybindingConflictLabels(allRows, {
+ rowId: "new",
+ key: keyDraft,
+ when: whenDraftExpression,
+ });
+ const commandLabelText = commandDraft ? commandLabel(commandDraft) : "new keybinding";
+
+ const save = () => {
+ if (!commandDraft) return;
+ onSave({
+ command: commandDraft,
+ key: keyDraft,
+ ...(whenDraftExpression.trim().length > 0 ? { when: whenDraftExpression } : {}),
+ });
+ };
+
+ const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === "Tab") return;
+ event.preventDefault();
+ if (event.key === "Escape") {
+ setDraft({ keyDraft: "", isRecording: false });
+ return;
+ }
+ const next = keybindingFromKeyboardEvent(event.nativeEvent, navigator.platform);
+ if (!next) return;
+ setDraft({ keyDraft: next, isRecording: false });
+ };
+
+ return (
+ <div className="grid grid-cols-[minmax(190px,1.1fr)_minmax(220px,0.85fr)_minmax(210px,1fr)_60px] items-center px-4 py-1.5 text-sm even:bg-muted/15 hover:bg-accent/40">
+ <div className="min-w-0 pr-4">
+ <Select
+ value={commandDraft}
+ onValueChange={(value) => setCommandDraft(value as KeybindingCommand)}
+ >
+ <SelectTrigger
+ size="xs"
+ className="h-7 min-h-7 w-full max-w-60 rounded-md text-xs sm:h-7"
+ >
+ <SelectValue placeholder="Command" />
+ </SelectTrigger>
+ <SelectContent
+ alignItemWithTrigger={false}
+ matchTriggerWidth={false}
+ className="max-h-72 w-fit min-w-56"
+ >
+ {commandOptions.map((command) => (
+ <SelectItem key={command} value={command} className="min-h-7 w-full py-1 text-[12px]">
+ <span className="truncate">{commandLabel(command)}</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="flex min-w-0 items-center gap-2 pr-4">
+ <Input
+ aria-label={`Keybinding for ${commandLabelText}`}
+ value={isRecording ? "" : keyDraft}
+ placeholder={isRecording ? "Press shortcut" : "Unassigned"}
+ className={cn(
+ "h-7 w-44 rounded-md font-mono text-[12px] sm:h-7",
+ isRecording && "border-primary/70 bg-primary/5",
+ )}
+ onFocus={() => setDraft({ isRecording: true })}
+ onBlur={() => setDraft({ isRecording: false })}
+ onChange={(event) => setDraft({ keyDraft: event.currentTarget.value })}
+ onKeyDown={captureKeybinding}
+ />
+ <Button
+ size="xs"
+ className="h-7 sm:h-7"
+ disabled={isSaving || !commandDraft || keyDraft.trim().length === 0 || !isWhenDraftValid}
+ onClick={save}
+ >
+ {isSaving ? "Saving" : "Save"}
+ </Button>
+ </div>
+ <div className="pr-4">
+ <Popover>
+ <PopoverTrigger
+ className={cn(
+ "inline-flex h-7 w-full items-center justify-between gap-2 rounded-md border border-input bg-background px-2.5 text-left font-mono text-[12px] text-foreground shadow-xs/5 outline-none transition-colors hover:bg-accent focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/24",
+ !whenDraftExpression && "text-muted-foreground",
+ )}
+ aria-label={`Edit when clause for ${commandLabelText}`}
+ >
+ <span className="truncate">{whenDraftExpression || "Always"}</span>
+ <ChevronDownIcon className="size-3.5 shrink-0 opacity-60" />
+ </PopoverTrigger>
+ <PopoverContent align="start" sideOffset={6}>
+ <WhenExpressionBuilder
+ value={whenDraft}
+ variables={variables}
+ onChange={(nextWhenDraft) => setDraft({ whenDraft: nextWhenDraft })}
+ onValidityChange={(nextIsValid) => setDraft({ isWhenDraftValid: nextIsValid })}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ <div className="flex items-center justify-end gap-1">
+ <KeybindingConflictWarning labels={conflictLabels} />
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 text-muted-foreground hover:text-foreground sm:size-7"
+ disabled={isSaving}
+ aria-label="Cancel new keybinding"
+ onClick={onCancel}
+ />
+ }
+ >
+ <XIcon className="size-3.5" />
+ </TooltipTrigger>
+ <TooltipPopup side="top">Cancel</TooltipPopup>
+ </Tooltip>
+ </div>
+ </div>
+ );
+}
+
+export function KeybindingsSettingsPanel() {
+ const keybindings = useServerKeybindings();
+ const keybindingsConfigPath = useServerKeybindingsConfigPath();
+ const [query, setQuery] = useState("");
+ const [isSearchOpen, setIsSearchOpen] = useState(false);
+ const searchInputRef = useRef<HTMLInputElement>(null);
+ const [savingCommand, setSavingCommand] = useState<KeybindingCommand | null>(null);
+ const [isAddingBinding, setIsAddingBinding] = useState(false);
+ const rows = useMemo(() => buildKeybindingRows(keybindings, query), [keybindings, query]);
+ const commandOptions = useMemo(() => buildKeybindingCommandOptions(keybindings), [keybindings]);
+ const whenVariables = useMemo(() => buildWhenVariableOptions(), []);
+
+ useEffect(() => {
+ const handleKeyDown = (event: globalThis.KeyboardEvent) => {
+ const isMod = event.metaKey || event.ctrlKey;
+ if (!isMod || event.altKey || event.key.toLowerCase() !== "f") return;
+
+ const target = event.target;
+ if (
+ target !== searchInputRef.current &&
+ target instanceof HTMLElement &&
+ (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ setIsSearchOpen(true);
+ requestAnimationFrame(() => {
+ searchInputRef.current?.focus();
+ searchInputRef.current?.select();
+ });
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, []);
+
+ const openKeybindingsFile = useCallback(() => {
+ if (!keybindingsConfigPath) return;
+ void openInPreferredEditor(ensureLocalApi(), keybindingsConfigPath).catch((error: unknown) => {
+ toastManager.add({
+ title: "Unable to open keybindings file",
+ description:
+ error instanceof Error ? error.message : "The keybindings file was not opened.",
+ type: "error",
+ });
+ });
+ }, [keybindingsConfigPath]);
+
+ const saveKeybinding = useCallback((input: ServerUpsertKeybindingInput) => {
+ setSavingCommand(input.command);
+ const payload: ServerUpsertKeybindingInput = {
+ command: input.command,
+ key: input.key.trim(),
+ ...(input.when?.trim() ? { when: input.when.trim() } : {}),
+ ...(input.replace ? { replace: input.replace } : {}),
+ };
+ void ensureLocalApi()
+ .server.upsertKeybinding(payload)
+ .then(() => {
+ setIsAddingBinding(false);
+ })
+ .catch((error: unknown) => {
+ toastManager.add({
+ title: "Unable to save keybinding",
+ description: error instanceof Error ? error.message : "The keybinding was not saved.",
+ type: "error",
+ });
+ })
+ .finally(() => {
+ setSavingCommand(null);
+ });
+ }, []);
+
+ const removeKeybinding = useCallback((row: KeybindingRow) => {
+ setSavingCommand(row.command);
+ void ensureLocalApi()
+ .server.removeKeybinding(rowKeybindingTarget(row))
+ .catch((error: unknown) => {
+ toastManager.add({
+ title: "Unable to remove keybinding",
+ description: error instanceof Error ? error.message : "The keybinding was not removed.",
+ type: "error",
+ });
+ })
+ .finally(() => {
+ setSavingCommand(null);
+ });
+ }, []);
+
+ const resetKeybinding = useCallback(
+ (row: KeybindingRow) => {
+ if (!row.defaultKey) return;
+ saveKeybinding({
+ command: row.command,
+ key: row.defaultKey,
+ when: row.defaultWhen.trim().length > 0 ? row.defaultWhen : undefined,
+ replace: {
+ command: row.command,
+ key: row.key,
+ ...(row.when.trim().length > 0 ? { when: row.when } : {}),
+ },
+ });
+ },
+ [saveKeybinding],
+ );
+
+ const bindingsCount = (
+ <span className="text-[11px] text-muted-foreground">
+ {rows.length + (isAddingBinding ? 1 : 0)}{" "}
+ {rows.length + (isAddingBinding ? 1 : 0) === 1 ? "binding" : "bindings"}
+ </span>
+ );
+
+ return (
+ <SettingsPageContainer className="max-w-5xl">
+ <SettingsSection
+ title="Keybindings"
+ headerAction={
+ <div className="flex items-center gap-1.5">
+ <ExpandableHeaderSearch
+ query={query}
+ onChange={setQuery}
+ isOpen={isSearchOpen}
+ onOpenChange={setIsSearchOpen}
+ inputRef={searchInputRef}
+ collapsedAccessory={bindingsCount}
+ />
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
+ onClick={() => setIsAddingBinding(true)}
+ aria-label="Add keybinding"
+ >
+ <PlusIcon className="size-3" />
+ </Button>
+ }
+ />
+ <TooltipPopup side="top">Add keybinding</TooltipPopup>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
+ disabled={!keybindingsConfigPath}
+ onClick={openKeybindingsFile}
+ aria-label="Open keybindings.json"
+ >
+ <FileJsonIcon className="size-3" />
+ </Button>
+ }
+ />
+ <TooltipPopup side="top">Open keybindings.json</TooltipPopup>
+ </Tooltip>
+ </div>
+ }
+ >
+ {!isElectron ? (
+ <div className="flex items-start gap-2 border-b border-warning/20 bg-warning/5 px-3 py-2.5 text-[12px] leading-relaxed text-muted-foreground sm:px-4">
+ <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
+ <p>
+ Some shortcuts may be claimed by the browser before T3 Code sees them. Use the desktop
+ app for better keybinding support.
+ </p>
+ </div>
+ ) : null}
+
+ <ScrollArea
+ chainVerticalScroll
+ scrollFade
+ hideScrollbars
+ className="w-full max-w-full rounded-none"
+ >
+ <div className="grid min-w-[680px] grid-cols-[minmax(190px,1.1fr)_minmax(220px,0.85fr)_minmax(210px,1fr)_60px] border-b border-border/70 bg-muted/25 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.07em] text-muted-foreground">
+ <div>Command</div>
+ <div>Keybinding</div>
+ <div>When</div>
+ <div>Status</div>
+ </div>
+ <div className="min-w-[680px] divide-y divide-border/60">
+ {isAddingBinding ? (
+ <NewKeybindingTableRow
+ commandOptions={commandOptions}
+ allRows={rows}
+ variables={whenVariables}
+ isSaving={savingCommand !== null}
+ onSave={saveKeybinding}
+ onCancel={() => setIsAddingBinding(false)}
+ />
+ ) : null}
+ {rows.map((row) => (
+ <KeybindingTableRow
+ key={row.id}
+ row={row}
+ allRows={rows}
+ variables={whenVariables}
+ isSaving={savingCommand === row.command}
+ onSave={saveKeybinding}
+ onReset={resetKeybinding}
+ onRemove={removeKeybinding}
+ />
+ ))}
+ {rows.length === 0 && !isAddingBinding ? (
+ <div className="px-4 py-12 text-center text-sm text-muted-foreground">
+ No keybindings match your search.
+ </div>
+ ) : null}
+ </div>
+ </ScrollArea>
+ </SettingsSection>
+ </SettingsPageContainer>
+ );
+}
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 89816ae47..d8eca942c 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -77,7 +77,6 @@ import {
import { ProjectFavicon } from "../ProjectFavicon";
import {
useServerAvailableEditors,
- useServerKeybindingsConfigPath,
useServerObservability,
useServerProviders,
} from "../../rpc/serverState";
@@ -444,13 +443,11 @@ export function GeneralSettingsPanel() {
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const [openingPathByTarget, setOpeningPathByTarget] = useState({
- keybindings: false,
logsDirectory: false,
});
const [openPathErrorByTarget, setOpenPathErrorByTarget] = useState<
- Partial<Record<"keybindings" | "logsDirectory", string | null>>
+ Partial<Record<"logsDirectory", string | null>>
>({});
- const keybindingsConfigPath = useServerKeybindingsConfigPath();
const availableEditors = useServerAvailableEditors();
const observability = useServerObservability();
const serverProviders = useServerProviders();
@@ -491,7 +488,7 @@ export function GeneralSettingsPanel() {
);
const openInPreferredEditor = useCallback(
- (target: "keybindings" | "logsDirectory", path: string | null, failureMessage: string) => {
+ (target: "logsDirectory", path: string | null, failureMessage: string) => {
if (!path) return;
setOpenPathErrorByTarget((existing) => ({ ...existing, [target]: null }));
setOpeningPathByTarget((existing) => ({ ...existing, [target]: true }));
@@ -521,17 +518,11 @@ export function GeneralSettingsPanel() {
[availableEditors],
);
- const openKeybindingsFile = useCallback(() => {
- openInPreferredEditor("keybindings", keybindingsConfigPath, "Unable to open keybindings file.");
- }, [keybindingsConfigPath, openInPreferredEditor]);
-
const openLogsDirectory = useCallback(() => {
openInPreferredEditor("logsDirectory", logsDirectoryPath, "Unable to open logs folder.");
}, [logsDirectoryPath, openInPreferredEditor]);
- const openKeybindingsError = openPathErrorByTarget.keybindings ?? null;
const openDiagnosticsError = openPathErrorByTarget.logsDirectory ?? null;
- const isOpeningKeybindings = openingPathByTarget.keybindings;
const isOpeningLogsDirectory = openingPathByTarget.logsDirectory;
return (
@@ -911,35 +902,6 @@ export function GeneralSettingsPanel() {
/>
</SettingsSection>
- <SettingsSection title="Advanced">
- <SettingsRow
- title="Keybindings"
- description="Open the persisted `keybindings.json` file to edit advanced bindings directly."
- status={
- <>
- <span className="block break-all font-mono text-[11px] text-foreground">
- {keybindingsConfigPath ?? "Resolving keybindings path..."}
- </span>
- {openKeybindingsError ? (
- <span className="mt-1 block text-destructive">{openKeybindingsError}</span>
- ) : (
- <span className="mt-1 block">Opens in your preferred editor.</span>
- )}
- </>
- }
- control={
- <Button
- size="xs"
- variant="outline"
- disabled={!keybindingsConfigPath || isOpeningKeybindings}
- onClick={openKeybindingsFile}
- >
- {isOpeningKeybindings ? "Opening..." : "Open file"}
- </Button>
- }
- />
- </SettingsSection>
-
<SettingsSection title="About">
{isElectron ? (
<AboutVersionSection />
diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx
index fc0e5a2b4..bec960638 100644
--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx
+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx
@@ -4,6 +4,7 @@ import {
ArrowLeftIcon,
BotIcon,
GitBranchIcon,
+ KeyboardIcon,
Link2Icon,
Settings2Icon,
} from "lucide-react";
@@ -22,6 +23,7 @@ import {
export type SettingsSectionPath =
| "/settings/general"
+ | "/settings/keybindings"
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
@@ -33,6 +35,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
icon: ComponentType<{ className?: string }>;
}> = [
{ label: "General", to: "/settings/general", icon: Settings2Icon },
+ { label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx
index 34197e8d8..54c2c99b8 100644
--- a/apps/web/src/components/settings/settingsLayout.tsx
+++ b/apps/web/src/components/settings/settingsLayout.tsx
@@ -115,10 +115,18 @@ export function SettingResetButton({ label, onClick }: { label: string; onClick:
);
}
-export function SettingsPageContainer({ children }: { children: ReactNode }) {
+export function SettingsPageContainer({
+ children,
+ className,
+}: {
+ children: ReactNode;
+ className?: string;
+}) {
return (
<div className="flex-1 overflow-y-auto p-6 sm:p-8">
- <div className="mx-auto flex w-full max-w-3xl flex-col gap-8">{children}</div>
+ <div className={cn("mx-auto flex w-full max-w-3xl flex-col gap-8", className)}>
+ {children}
+ </div>
</div>
);
}
diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/web/src/components/ui/scroll-area.tsx
index 37ffbb185..f9a363867 100644
--- a/apps/web/src/components/ui/scroll-area.tsx
+++ b/apps/web/src/components/ui/scroll-area.tsx
@@ -10,11 +10,13 @@ function ScrollArea({
scrollFade = false,
scrollbarGutter = false,
hideScrollbars = false,
+ chainVerticalScroll = false,
...props
}: ScrollAreaPrimitive.Root.Props & {
scrollFade?: boolean;
scrollbarGutter?: boolean;
hideScrollbars?: boolean;
+ chainVerticalScroll?: boolean;
}) {
return (
<ScrollAreaPrimitive.Root
@@ -23,7 +25,8 @@ function ScrollArea({
>
<ScrollAreaPrimitive.Viewport
className={cn(
- "h-full max-h-[inherit] overflow-y-auto overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
+ "h-full max-h-[inherit] overflow-auto overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
+ chainVerticalScroll && "overscroll-y-auto",
scrollFade &&
"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]",
scrollbarGutter && "[scrollbar-gutter:stable]",
diff --git a/apps/web/src/components/ui/select.tsx b/apps/web/src/components/ui/select.tsx
index 245fa6dd7..3649a567f 100644
--- a/apps/web/src/components/ui/select.tsx
+++ b/apps/web/src/components/ui/select.tsx
@@ -105,20 +105,24 @@ function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
function SelectPopup({
className,
+ popupClassName,
children,
side = "bottom",
sideOffset = 4,
align = "start",
alignOffset = 0,
alignItemWithTrigger = true,
+ matchTriggerWidth = true,
anchor,
...props
}: SelectPrimitive.Popup.Props & {
+ popupClassName?: string;
side?: SelectPrimitive.Positioner.Props["side"];
sideOffset?: SelectPrimitive.Positioner.Props["sideOffset"];
align?: SelectPrimitive.Positioner.Props["align"];
alignOffset?: SelectPrimitive.Positioner.Props["alignOffset"];
alignItemWithTrigger?: SelectPrimitive.Positioner.Props["alignItemWithTrigger"];
+ matchTriggerWidth?: boolean;
anchor?: SelectPrimitive.Positioner.Props["anchor"];
}) {
return (
@@ -144,7 +148,13 @@ function SelectPopup({
>
<ChevronUpIcon className="relative size-4.5 sm:size-4" />
</SelectPrimitive.ScrollUpArrow>
- <div className="relative h-full min-w-(--anchor-width) rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">
+ <div
+ className={cn(
+ "relative h-full rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
+ matchTriggerWidth && "min-w-(--anchor-width)",
+ popupClassName,
+ )}
+ >
<SelectPrimitive.List
className={cn("max-h-(--available-height) overflow-y-auto p-1", className)}
data-slot="select-list"
diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts
index 2dc140eac..a4ba19051 100644
--- a/apps/web/src/localApi.ts
+++ b/apps/web/src/localApi.ts
@@ -133,6 +133,10 @@ function createBrowserLocalApi(rpcClient?: WsRpcClient): LocalApi {
rpcClient
? rpcClient.server.upsertKeybinding(input)
: Promise.reject(unavailableLocalBackendError()),
+ removeKeybinding: (input) =>
+ rpcClient
+ ? rpcClient.server.removeKeybinding(input)
+ : Promise.reject(unavailableLocalBackendError()),
getSettings: () =>
rpcClient ? rpcClient.server.getSettings() : Promise.reject(unavailableLocalBackendError()),
updateSettings: (patch) =>
diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts
index 1f711ac7d..85a2f9ef8 100644
--- a/apps/web/src/routeTree.gen.ts
+++ b/apps/web/src/routeTree.gen.ts
@@ -15,6 +15,7 @@ import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
+import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
@@ -50,6 +51,11 @@ const SettingsProvidersRoute = SettingsProvidersRouteImport.update({
path: '/providers',
getParentRoute: () => SettingsRoute,
} as any)
+const SettingsKeybindingsRoute = SettingsKeybindingsRouteImport.update({
+ id: '/keybindings',
+ path: '/keybindings',
+ getParentRoute: () => SettingsRoute,
+} as any)
const SettingsGeneralRoute = SettingsGeneralRouteImport.update({
id: '/general',
path: '/general',
@@ -84,6 +90,7 @@ export interface FileRoutesByFullPath {
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/general': typeof SettingsGeneralRoute
+ '/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
@@ -95,6 +102,7 @@ export interface FileRoutesByTo {
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/general': typeof SettingsGeneralRoute
+ '/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/': typeof ChatIndexRoute
@@ -109,6 +117,7 @@ export interface FileRoutesById {
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/general': typeof SettingsGeneralRoute
+ '/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/_chat/': typeof ChatIndexRoute
@@ -124,6 +133,7 @@ export interface FileRouteTypes {
| '/settings/archived'
| '/settings/connections'
| '/settings/general'
+ | '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/$environmentId/$threadId'
@@ -135,6 +145,7 @@ export interface FileRouteTypes {
| '/settings/archived'
| '/settings/connections'
| '/settings/general'
+ | '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/'
@@ -148,6 +159,7 @@ export interface FileRouteTypes {
| '/settings/archived'
| '/settings/connections'
| '/settings/general'
+ | '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/_chat/'
@@ -205,6 +217,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsProvidersRouteImport
parentRoute: typeof SettingsRoute
}
+ '/settings/keybindings': {
+ id: '/settings/keybindings'
+ path: '/keybindings'
+ fullPath: '/settings/keybindings'
+ preLoaderRoute: typeof SettingsKeybindingsRouteImport
+ parentRoute: typeof SettingsRoute
+ }
'/settings/general': {
id: '/settings/general'
path: '/general'
@@ -261,6 +280,7 @@ interface SettingsRouteChildren {
SettingsArchivedRoute: typeof SettingsArchivedRoute
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
+ SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
SettingsProvidersRoute: typeof SettingsProvidersRoute
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
}
@@ -269,6 +289,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsArchivedRoute: SettingsArchivedRoute,
SettingsConnectionsRoute: SettingsConnectionsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
+ SettingsKeybindingsRoute: SettingsKeybindingsRoute,
SettingsProvidersRoute: SettingsProvidersRoute,
SettingsSourceControlRoute: SettingsSourceControlRoute,
}
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index e848b4f05..8c63003cd 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -288,6 +288,7 @@ function EventRouter() {
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);
+ const lastKeybindingsSuccessToastAtRef = useRef(0);
const disposedRef = useRef(false);
const serverConfig = useServerConfig();
@@ -354,6 +355,11 @@ function EventRouter() {
const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
if (!issue) {
+ const now = Date.now();
+ if (now - lastKeybindingsSuccessToastAtRef.current < 2_000) {
+ return;
+ }
+ lastKeybindingsSuccessToastAtRef.current = now;
toastManager.add({
type: "success",
title: "Keybindings updated",
diff --git a/apps/web/src/routes/settings.keybindings.tsx b/apps/web/src/routes/settings.keybindings.tsx
new file mode 100644
index 000000000..f44784078
--- /dev/null
+++ b/apps/web/src/routes/settings.keybindings.tsx
@@ -0,0 +1,7 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { KeybindingsSettingsPanel } from "../components/settings/KeybindingsSettings";
+
+export const Route = createFileRoute("/settings/keybindings")({
+ component: KeybindingsSettingsPanel,
+});
diff --git a/apps/web/src/rpc/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts
index 21c6089ef..a13f2173c 100644
--- a/apps/web/src/rpc/wsRpcClient.ts
+++ b/apps/web/src/rpc/wsRpcClient.ts
@@ -121,6 +121,7 @@ export interface WsRpcClient {
) => ReturnType<RpcUnaryMethod<typeof WS_METHODS.serverRefreshProviders>>;
readonly updateProvider: RpcUnaryMethod<typeof WS_METHODS.serverUpdateProvider>;
readonly upsertKeybinding: RpcUnaryMethod<typeof WS_METHODS.serverUpsertKeybinding>;
+ readonly removeKeybinding: RpcUnaryMethod<typeof WS_METHODS.serverRemoveKeybinding>;
readonly getSettings: RpcUnaryNoArgMethod<typeof WS_METHODS.serverGetSettings>;
readonly updateSettings: (
patch: ServerSettingsPatch,
@@ -239,6 +240,8 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
transport.request((client) => client[WS_METHODS.serverUpdateProvider](input)),
upsertKeybinding: (input) =>
transport.request((client) => client[WS_METHODS.serverUpsertKeybinding](input)),
+ removeKeybinding: (input) =>
+ transport.request((client) => client[WS_METHODS.serverRemoveKeybinding](input)),
getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})),
updateSettings: (patch) =>
transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })),
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index ec8125926..f2c7a28e7 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -30,6 +30,7 @@ import type {
ServerConfig,
ServerProviderUpdateInput,
ServerProviderUpdatedPayload,
+ ServerRemoveKeybindingResult,
ServerUpsertKeybindingResult,
} from "./server.ts";
import type {
@@ -42,7 +43,7 @@ import type {
TerminalSessionSnapshot,
TerminalWriteInput,
} from "./terminal.ts";
-import type { ServerUpsertKeybindingInput } from "./server.ts";
+import type { ServerRemoveKeybindingInput, ServerUpsertKeybindingInput } from "./server.ts";
import type {
ClientOrchestrationCommand,
OrchestrationGetFullThreadDiffInput,
@@ -299,6 +300,7 @@ export interface LocalApi {
}) => Promise<ServerProviderUpdatedPayload>;
updateProvider: (input: ServerProviderUpdateInput) => Promise<ServerProviderUpdatedPayload>;
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
+ removeKeybinding: (input: ServerRemoveKeybindingInput) => Promise<ServerRemoveKeybindingResult>;
getSettings: () => Promise<ServerSettings>;
updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
discoverSourceControl: () => Promise<SourceControlDiscoveryResult>;
diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts
index d3b85d1cd..01587c2a6 100644
--- a/packages/contracts/src/keybindings.ts
+++ b/packages/contracts/src/keybindings.ts
@@ -2,7 +2,7 @@ import { Schema } from "effect";
import { TrimmedString } from "./baseSchemas.ts";
export const MAX_KEYBINDING_VALUE_LENGTH = 64;
-const MAX_KEYBINDING_WHEN_LENGTH = 256;
+export const MAX_KEYBINDING_WHEN_LENGTH = 256;
export const MAX_WHEN_EXPRESSION_DEPTH = 64;
export const MAX_SCRIPT_ID_LENGTH = 24;
export const MAX_KEYBINDINGS_COUNT = 256;
@@ -76,12 +76,12 @@ export const KeybindingCommand = Schema.Union([
]);
export type KeybindingCommand = typeof KeybindingCommand.Type;
-const KeybindingValue = TrimmedString.check(
+export const KeybindingValue = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),
);
-const KeybindingWhen = TrimmedString.check(
+export const KeybindingWhen = TrimmedString.check(
Schema.isMinLength(1),
Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),
);
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index fef6790ae..33cddc98a 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -74,6 +74,8 @@ import {
ServerProviderUpdateError,
ServerProviderUpdateInput,
ServerLifecycleStreamEvent,
+ ServerRemoveKeybindingInput,
+ ServerRemoveKeybindingResult,
ServerProviderUpdatedPayload,
ServerUpsertKeybindingInput,
ServerUpsertKeybindingResult,
@@ -133,6 +135,7 @@ export const WS_METHODS = {
serverRefreshProviders: "server.refreshProviders",
serverUpdateProvider: "server.updateProvider",
serverUpsertKeybinding: "server.upsertKeybinding",
+ serverRemoveKeybinding: "server.removeKeybinding",
serverGetSettings: "server.getSettings",
serverUpdateSettings: "server.updateSettings",
serverDiscoverSourceControl: "server.discoverSourceControl",
@@ -156,6 +159,12 @@ export const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybi
error: KeybindingsConfigError,
});
+export const WsServerRemoveKeybindingRpc = Rpc.make(WS_METHODS.serverRemoveKeybinding, {
+ payload: ServerRemoveKeybindingInput,
+ success: ServerRemoveKeybindingResult,
+ error: KeybindingsConfigError,
+});
+
export const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {
payload: Schema.Struct({}),
success: ServerConfig,
@@ -426,6 +435,7 @@ export const WsRpcGroup = RpcGroup.make(
WsServerRefreshProvidersRpc,
WsServerUpdateProviderRpc,
WsServerUpsertKeybindingRpc,
+ WsServerRemoveKeybindingRpc,
WsServerGetSettingsRpc,
WsServerUpdateSettingsRpc,
WsServerDiscoverSourceControlRpc,
diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts
index d2b034b20..ec6840d80 100644
--- a/packages/contracts/src/server.ts
+++ b/packages/contracts/src/server.ts
@@ -8,7 +8,12 @@ import {
ThreadId,
TrimmedNonEmptyString,
} from "./baseSchemas.ts";
-import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings.ts";
+import {
+ KeybindingCommand,
+ KeybindingValue,
+ KeybindingWhen,
+ ResolvedKeybindingsConfig,
+} from "./keybindings.ts";
import { EditorId } from "./editor.ts";
import { ModelCapabilities } from "./model.ts";
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
@@ -220,15 +225,32 @@ export const ServerConfig = Schema.Struct({
});
export type ServerConfig = typeof ServerConfig.Type;
-export const ServerUpsertKeybindingInput = KeybindingRule;
+const ServerUpsertKeybindingReplaceTarget = Schema.Struct({
+ key: KeybindingValue,
+ command: KeybindingCommand,
+ when: Schema.optional(KeybindingWhen),
+});
+
+export const ServerUpsertKeybindingInput = Schema.Struct({
+ key: KeybindingValue,
+ command: KeybindingCommand,
+ when: Schema.optional(KeybindingWhen),
+ replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),
+});
export type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;
+export const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;
+export type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;
+
export const ServerUpsertKeybindingResult = Schema.Struct({
keybindings: ResolvedKeybindingsConfig,
issues: ServerConfigIssues,
});
export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;
+export const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;
+export type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;
+
export const ServerConfigUpdatedPayload = Schema.Struct({
issues: ServerConfigIssues,
providers: ServerProviders,
diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts
index c67ad784f..3cc2e9136 100644
--- a/packages/shared/src/keybindings.ts
+++ b/packages/shared/src/keybindings.ts
@@ -162,7 +162,7 @@ function tokenizeWhenExpression(expression: string): WhenToken[] | null {
return tokens;
}
-function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
+export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
const tokens = tokenizeWhenExpression(expression);
if (!tokens || tokens.length === 0) return null;
let index = 0;