Add keybindings settings editor (#2533)

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and GitHub committed 2026-05-06 00:08:52 +00:00
1 parent 9b604bcae1
commit 0e38870647
24 files changed
+2142 -111

No files matched your search

+50 -1
View File
@@ -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" }]);
+59 -3
View File
@@ -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;
});
+36
View File
@@ -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;
+9
View File
@@ -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,
@@ -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();
}
@@ -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);
};
@@ -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"]);
});
});
@@ -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("+");
}
File diff suppressed because it is too large. Load diff
@@ -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 />
@@ -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 },
@@ -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>
);
}
+4 -1
View File
@@ -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]",
+11 -1
View File
@@ -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"
+4
View File
@@ -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) =>
+21
View File
@@ -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,
}
+6
View File
@@ -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",
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { KeybindingsSettingsPanel } from "../components/settings/KeybindingsSettings";
export const Route = createFileRoute("/settings/keybindings")({
component: KeybindingsSettingsPanel,
});
+3
View File
@@ -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 })),
+3 -1
View File
@@ -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>;
+3 -3
View File
@@ -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),
);
+10
View File
@@ -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,
+24 -2
View File
@@ -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,
+1 -1
View File
@@ -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;