The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 25, 18:30 UTC
Resolve and validate keybindings on server before sending to web
- add server keybinding compiler for shortcuts and `when` AST parsing - switch websocket/server config payload to resolved keybinding rules - update web keybinding logic/types to consume resolved payload directly - add/adjust contract, server, and web tests (including plus-key parsing) and docs
Julius Marminge committed
Feb 15, 2026 at 13:48 UTC
370127760ac980eb790f347c172c2b51f6d3c501
14 files changed
+813
-433
KEYBINDINGS.md
+13
-2
@@ -9,8 +9,9 @@ Schema source of truth:
9
- [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
10
- [`packages/contracts/src/server.ts`](packages/contracts/src/server.ts)
11
12
-Server-side default resolution/merging:
12
+Server-side parsing/default resolution/merging:
13
14
+- [`apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
15
- [`apps/server/src/wsServer.ts`](apps/server/src/wsServer.ts)
16
17
The file must be a JSON array of rules:
@@ -94,8 +95,18 @@ Built-in defaults are resolved on the server and sent to the web client via `ser
95
96
If you define any rules for a command, the default rule for that command is removed on the server.
97
98
+## Server-Resolved Payload
99
+
100
+`~/.t3/keybindings.json` is parsed and compiled on the server. The web client receives resolved rules (including parsed shortcut/when fields) and does not parse raw keybinding strings.
101
+
102
+See:
103
+
104
+- [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
105
+- [`apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
106
+- [`apps/server/src/wsServer.ts`](apps/server/src/wsServer.ts)
107
+
108
## Precedence
109
110
- Rules are evaluated in array order.
100
-- For a key event, the server/client resolves the last rule where both `key` matches and `when` evaluates to `true`.
111
+- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
112
- That means precedence is across commands, not only within the same command.
apps/server/src/keybindings.test.ts
new
+71
@@ -0,0 +1,71 @@
1
+import { describe, expect, it } from "vitest";
2
+
3
+import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings";
4
+
5
+describe("server keybindings", () => {
6
+ it("parses shortcuts including plus key", () => {
7
+ expect(parseKeybindingShortcut("mod+j")).toEqual({
8
+ key: "j",
9
+ metaKey: false,
10
+ ctrlKey: false,
11
+ shiftKey: false,
12
+ altKey: false,
13
+ modKey: true,
14
+ });
15
+ expect(parseKeybindingShortcut("mod++")).toEqual({
16
+ key: "+",
17
+ metaKey: false,
18
+ ctrlKey: false,
19
+ shiftKey: false,
20
+ altKey: false,
21
+ modKey: true,
22
+ });
23
+ });
24
+
25
+ it("compiles valid rule with parsed when AST", () => {
26
+ const compiled = compileResolvedKeybindingRule({
27
+ key: "mod+d",
28
+ command: "terminal.split",
29
+ when: "terminalOpen && !terminalFocus",
30
+ });
31
+
32
+ expect(compiled).toEqual({
33
+ key: "mod+d",
34
+ command: "terminal.split",
35
+ when: "terminalOpen && !terminalFocus",
36
+ shortcut: {
37
+ key: "d",
38
+ metaKey: false,
39
+ ctrlKey: false,
40
+ shiftKey: false,
41
+ altKey: false,
42
+ modKey: true,
43
+ },
44
+ whenAst: {
45
+ type: "and",
46
+ left: { type: "identifier", name: "terminalOpen" },
47
+ right: {
48
+ type: "not",
49
+ node: { type: "identifier", name: "terminalFocus" },
50
+ },
51
+ },
52
+ });
53
+ });
54
+
55
+ it("rejects invalid rules", () => {
56
+ expect(
57
+ compileResolvedKeybindingRule({
58
+ key: "mod+shift+d+o",
59
+ command: "terminal.new",
60
+ }),
61
+ ).toBeNull();
62
+
63
+ expect(
64
+ compileResolvedKeybindingRule({
65
+ key: "mod+d",
66
+ command: "terminal.split",
67
+ when: "terminalFocus && (",
68
+ }),
69
+ ).toBeNull();
70
+ });
71
+});
apps/server/src/keybindings.ts
new
+244
@@ -0,0 +1,244 @@
1
+import type {
2
+ KeybindingRule,
3
+ KeybindingsConfig,
4
+ KeybindingShortcut,
5
+ KeybindingWhenNode,
6
+ ResolvedKeybindingRule,
7
+ ResolvedKeybindingsConfig,
8
+} from "@t3tools/contracts";
9
+
10
+type WhenToken =
11
+ | { type: "identifier"; value: string }
12
+ | { type: "not" }
13
+ | { type: "and" }
14
+ | { type: "or" }
15
+ | { type: "lparen" }
16
+ | { type: "rparen" };
17
+
18
+function normalizeKeyToken(token: string): string {
19
+ if (token === "space") return " ";
20
+ if (token === "esc") return "escape";
21
+ return token;
22
+}
23
+
24
+export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
25
+ const rawTokens = value.toLowerCase().split("+").map((token) => token.trim());
26
+ const tokens = [...rawTokens];
27
+ let trailingEmptyCount = 0;
28
+ while (tokens[tokens.length - 1] === "") {
29
+ trailingEmptyCount += 1;
30
+ tokens.pop();
31
+ }
32
+ if (trailingEmptyCount > 0) {
33
+ tokens.push("+");
34
+ }
35
+ if (tokens.some((token) => token.length === 0)) {
36
+ return null;
37
+ }
38
+ if (tokens.length === 0) return null;
39
+
40
+ let key: string | null = null;
41
+ let metaKey = false;
42
+ let ctrlKey = false;
43
+ let shiftKey = false;
44
+ let altKey = false;
45
+ let modKey = false;
46
+
47
+ for (const token of tokens) {
48
+ switch (token) {
49
+ case "cmd":
50
+ case "meta":
51
+ metaKey = true;
52
+ break;
53
+ case "ctrl":
54
+ case "control":
55
+ ctrlKey = true;
56
+ break;
57
+ case "shift":
58
+ shiftKey = true;
59
+ break;
60
+ case "alt":
61
+ case "option":
62
+ altKey = true;
63
+ break;
64
+ case "mod":
65
+ modKey = true;
66
+ break;
67
+ default: {
68
+ if (key !== null) return null;
69
+ key = normalizeKeyToken(token);
70
+ }
71
+ }
72
+ }
73
+
74
+ if (key === null) return null;
75
+ return {
76
+ key,
77
+ metaKey,
78
+ ctrlKey,
79
+ shiftKey,
80
+ altKey,
81
+ modKey,
82
+ };
83
+}
84
+
85
+function tokenizeWhenExpression(expression: string): WhenToken[] | null {
86
+ const tokens: WhenToken[] = [];
87
+ let index = 0;
88
+
89
+ while (index < expression.length) {
90
+ const current = expression[index];
91
+ if (!current) break;
92
+
93
+ if (/\s/.test(current)) {
94
+ index += 1;
95
+ continue;
96
+ }
97
+ if (expression.startsWith("&&", index)) {
98
+ tokens.push({ type: "and" });
99
+ index += 2;
100
+ continue;
101
+ }
102
+ if (expression.startsWith("||", index)) {
103
+ tokens.push({ type: "or" });
104
+ index += 2;
105
+ continue;
106
+ }
107
+ if (current === "!") {
108
+ tokens.push({ type: "not" });
109
+ index += 1;
110
+ continue;
111
+ }
112
+ if (current === "(") {
113
+ tokens.push({ type: "lparen" });
114
+ index += 1;
115
+ continue;
116
+ }
117
+ if (current === ")") {
118
+ tokens.push({ type: "rparen" });
119
+ index += 1;
120
+ continue;
121
+ }
122
+
123
+ const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
124
+ if (!identifier) {
125
+ return null;
126
+ }
127
+ tokens.push({ type: "identifier", value: identifier[0] });
128
+ index += identifier[0].length;
129
+ }
130
+
131
+ return tokens;
132
+}
133
+
134
+export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
135
+ const tokens = tokenizeWhenExpression(expression);
136
+ if (!tokens || tokens.length === 0) return null;
137
+ let index = 0;
138
+
139
+ const parsePrimary = (): KeybindingWhenNode | null => {
140
+ const token = tokens[index];
141
+ if (!token) return null;
142
+
143
+ if (token.type === "identifier") {
144
+ index += 1;
145
+ return { type: "identifier", name: token.value };
146
+ }
147
+
148
+ if (token.type === "lparen") {
149
+ index += 1;
150
+ const expressionNode = parseOr();
151
+ const closeToken = tokens[index];
152
+ if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
153
+ return null;
154
+ }
155
+ index += 1;
156
+ return expressionNode;
157
+ }
158
+
159
+ return null;
160
+ };
161
+
162
+ const parseUnary = (): KeybindingWhenNode | null => {
163
+ const token = tokens[index];
164
+ if (token?.type === "not") {
165
+ index += 1;
166
+ const node = parseUnary();
167
+ if (!node) return null;
168
+ return { type: "not", node };
169
+ }
170
+ return parsePrimary();
171
+ };
172
+
173
+ const parseAnd = (): KeybindingWhenNode | null => {
174
+ let left = parseUnary();
175
+ if (!left) return null;
176
+
177
+ while (tokens[index]?.type === "and") {
178
+ index += 1;
179
+ const right = parseUnary();
180
+ if (!right) return null;
181
+ left = { type: "and", left, right };
182
+ }
183
+
184
+ return left;
185
+ };
186
+
187
+ const parseOr = (): KeybindingWhenNode | null => {
188
+ let left = parseAnd();
189
+ if (!left) return null;
190
+
191
+ while (tokens[index]?.type === "or") {
192
+ index += 1;
193
+ const right = parseAnd();
194
+ if (!right) return null;
195
+ left = { type: "or", left, right };
196
+ }
197
+
198
+ return left;
199
+ };
200
+
201
+ const ast = parseOr();
202
+ if (!ast || index !== tokens.length) return null;
203
+ return ast;
204
+}
205
+
206
+export function compileResolvedKeybindingRule(
207
+ rule: KeybindingRule,
208
+): ResolvedKeybindingRule | null {
209
+ const key = rule.key.trim();
210
+ if (key.length === 0) return null;
211
+ const shortcut = parseKeybindingShortcut(key);
212
+ if (!shortcut) return null;
213
+
214
+ const when = rule.when?.trim();
215
+ if (when && when.length > 0) {
216
+ const whenAst = parseKeybindingWhenExpression(when);
217
+ if (!whenAst) return null;
218
+ return {
219
+ key,
220
+ command: rule.command,
221
+ when,
222
+ shortcut,
223
+ whenAst,
224
+ };
225
+ }
226
+
227
+ return {
228
+ key,
229
+ command: rule.command,
230
+ shortcut,
231
+ };
232
+}
233
+
234
+export function compileResolvedKeybindingsConfig(
235
+ config: KeybindingsConfig,
236
+): ResolvedKeybindingsConfig {
237
+ const compiled: ResolvedKeybindingsConfig = [];
238
+ for (const rule of config) {
239
+ const resolved = compileResolvedKeybindingRule(rule);
240
+ if (!resolved) continue;
241
+ compiled.push(resolved);
242
+ }
243
+ return compiled;
244
+}
apps/server/src/wsServer.test.ts
+29
-14
@@ -11,10 +11,13 @@ import {
11
DEFAULT_TERMINAL_ID,
12
WS_CHANNELS,
13
WS_METHODS,
14
+ type KeybindingsConfig,
15
+ type ResolvedKeybindingsConfig,
16
type WsPush,
17
type WsResponse,
18
} from "@t3tools/contracts";
19
import { ProjectRegistry } from "./projectRegistry";
20
+import { compileResolvedKeybindingRule } from "./keybindings";
21
import type {
22
TerminalClearInput,
23
TerminalCloseInput,
@@ -192,6 +195,18 @@ async function sendRequest(ws: WebSocket, method: string, params?: unknown): Pro
195
}
196
}
197
198
+function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
199
+ const resolved: ResolvedKeybindingsConfig = [];
200
+ for (const binding of bindings) {
201
+ const compiled = compileResolvedKeybindingRule(binding);
202
+ if (!compiled) {
203
+ throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`);
204
+ }
205
+ resolved.push(compiled);
206
+ }
207
+ return resolved;
208
+}
209
+
210
describe("WebSocket Server", () => {
211
let server: ReturnType<typeof createServer> | null = null;
212
const connections: WebSocket[] = [];
@@ -309,13 +324,13 @@ describe("WebSocket Server", () => {
324
expect(response.error).toBeUndefined();
325
expect(response.result).toEqual({
326
cwd: "/my/workspace",
312
- keybindings: [
327
+ keybindings: compileKeybindings([
328
{ key: "mod+j", command: "terminal.toggle" },
329
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
330
{ key: "mod+shift+d", command: "terminal.new", when: "terminalFocus" },
331
{ key: "mod+shift+o", command: "chat.new" },
332
{ key: "mod+o", command: "editor.openFavorite" },
318
- ],
333
+ ]),
334
});
335
});
336
@@ -348,13 +363,13 @@ describe("WebSocket Server", () => {
363
expect(response.error).toBeUndefined();
364
expect(response.result).toEqual({
365
cwd: "/my/workspace",
351
- keybindings: [
366
+ keybindings: compileKeybindings([
367
{ key: "mod+shift+o", command: "chat.new" },
368
{ key: "mod+o", command: "editor.openFavorite" },
369
{ key: "cmd+j", command: "terminal.toggle" },
370
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
371
{ key: "mod+shift+d", command: "terminal.new", when: "terminalFocus" },
357
- ],
372
+ ]),
373
});
374
});
375
@@ -387,13 +402,13 @@ describe("WebSocket Server", () => {
402
expect(response.error).toBeUndefined();
403
expect(response.result).toEqual({
404
cwd: "/my/workspace",
390
- keybindings: [
405
+ keybindings: compileKeybindings([
406
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
407
{ key: "mod+shift+d", command: "terminal.new", when: "terminalFocus" },
408
{ key: "mod+shift+o", command: "chat.new" },
409
{ key: "mod+o", command: "editor.openFavorite" },
410
{ key: "mod+j", command: "terminal.toggle" },
396
- ],
411
+ ]),
412
});
413
expect(
414
warnSpy.mock.calls.some(([message]) =>
@@ -428,13 +443,13 @@ describe("WebSocket Server", () => {
443
expect(response.error).toBeUndefined();
444
expect(response.result).toEqual({
445
cwd: "/my/workspace",
431
- keybindings: [
446
+ keybindings: compileKeybindings([
447
{ key: "mod+j", command: "terminal.toggle" },
448
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
449
{ key: "mod+shift+d", command: "terminal.new", when: "terminalFocus" },
450
{ key: "mod+shift+o", command: "chat.new" },
451
{ key: "mod+o", command: "editor.openFavorite" },
437
- ],
452
+ ]),
453
});
454
expect(
455
warnSpy.mock.calls.some(([message]) =>
@@ -468,13 +483,13 @@ describe("WebSocket Server", () => {
483
expect(firstResponse.error).toBeUndefined();
484
expect(firstResponse.result).toEqual({
485
cwd: "/my/workspace",
471
- keybindings: [
486
+ keybindings: compileKeybindings([
487
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
488
{ key: "mod+shift+d", command: "terminal.new", when: "terminalFocus" },
489
{ key: "mod+shift+o", command: "chat.new" },
490
{ key: "mod+o", command: "editor.openFavorite" },
491
{ key: "cmd+j", command: "terminal.toggle" },
477
- ],
492
+ ]),
493
});
494
495
fs.writeFileSync(
@@ -514,13 +529,13 @@ describe("WebSocket Server", () => {
529
expect(response.error).toBeUndefined();
530
expect(response.result).toEqual({
531
cwd: "/my/workspace",
517
- keybindings: [
532
+ keybindings: compileKeybindings([
533
{ key: "mod+j", command: "terminal.toggle" },
534
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
535
{ key: "mod+shift+d", command: "terminal.new", when: "terminalFocus" },
536
{ key: "mod+shift+o", command: "chat.new" },
537
{ key: "mod+o", command: "editor.openFavorite" },
523
- ],
538
+ ]),
539
});
540
expect(
541
warnSpy.mock.calls.some(([message]) =>
@@ -551,13 +566,13 @@ describe("WebSocket Server", () => {
566
expect(response.error).toBeUndefined();
567
expect(response.result).toEqual({
568
cwd: "/my/workspace",
554
- keybindings: [
569
+ keybindings: compileKeybindings([
570
{ key: "mod+j", command: "terminal.toggle" },
571
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
572
{ key: "mod+shift+d", command: "terminal.new", when: "terminalFocus" },
573
{ key: "mod+shift+o", command: "chat.new" },
574
{ key: "mod+o", command: "editor.openFavorite" },
560
- ],
575
+ ]),
576
});
577
expect(
578
warnSpy.mock.calls.some(([message]) =>
apps/server/src/wsServer.ts
+31
-128
@@ -11,6 +11,7 @@ import {
11
WS_METHODS,
12
keybindingRuleSchema,
13
type KeybindingsConfig,
14
+ type ResolvedKeybindingsConfig,
15
type TerminalEvent,
16
type WsPush,
17
type WsRequest,
@@ -33,6 +34,7 @@ import {
34
removeGitWorktree,
35
} from "./git";
36
import { TerminalManager } from "./terminalManager";
37
+import { compileResolvedKeybindingRule } from "./keybindings";
38
39
const MIME_TYPES: Record<string, string> = {
40
".html": "text/html; charset=utf-8",
@@ -78,129 +80,29 @@ const DEFAULT_KEYBINDINGS: KeybindingsConfig = [
80
{ key: "mod+o", command: "editor.openFavorite" },
81
];
82
81
-type WhenTokenType = "identifier" | "not" | "and" | "or" | "lparen" | "rparen";
82
-
83
-interface WhenToken {
84
- type: WhenTokenType;
85
-}
86
-
87
-function tokenizeWhenExpression(expression: string): WhenToken[] | null {
88
- const tokens: WhenToken[] = [];
89
- let index = 0;
90
-
91
- while (index < expression.length) {
92
- const current = expression[index];
93
- if (!current) break;
94
-
95
- if (/\s/.test(current)) {
96
- index += 1;
97
- continue;
98
- }
99
- if (expression.startsWith("&&", index)) {
100
- tokens.push({ type: "and" });
101
- index += 2;
102
- continue;
103
- }
104
- if (expression.startsWith("||", index)) {
105
- tokens.push({ type: "or" });
106
- index += 2;
107
- continue;
108
- }
109
- if (current === "!") {
110
- tokens.push({ type: "not" });
111
- index += 1;
112
- continue;
113
- }
114
- if (current === "(") {
115
- tokens.push({ type: "lparen" });
116
- index += 1;
117
- continue;
83
+function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
84
+ const resolved: ResolvedKeybindingsConfig = [];
85
+ for (const rule of DEFAULT_KEYBINDINGS) {
86
+ const compiled = compileResolvedKeybindingRule(rule);
87
+ if (!compiled) {
88
+ throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
89
}
119
- if (current === ")") {
120
- tokens.push({ type: "rparen" });
121
- index += 1;
122
- continue;
123
- }
124
-
125
- const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
126
- if (!identifier) {
127
- return null;
128
- }
129
- tokens.push({ type: "identifier" });
130
- index += identifier[0].length;
90
+ resolved.push(compiled);
91
}
132
-
133
- return tokens;
92
+ return resolved;
93
}
94
136
-function isValidWhenExpression(when: string): boolean {
137
- const tokens = tokenizeWhenExpression(when);
138
- if (!tokens || tokens.length === 0) return false;
139
- let index = 0;
140
-
141
- const parsePrimary = (): boolean => {
142
- const token = tokens[index];
143
- if (!token) return false;
144
-
145
- if (token.type === "identifier") {
146
- index += 1;
147
- return true;
148
- }
149
-
150
- if (token.type === "lparen") {
151
- index += 1;
152
- const parsed = parseOr();
153
- const close = tokens[index];
154
- if (!parsed || !close || close.type !== "rparen") return false;
155
- index += 1;
156
- return true;
157
- }
158
-
159
- return false;
160
- };
161
-
162
- const parseUnary = (): boolean => {
163
- const token = tokens[index];
164
- if (token?.type === "not") {
165
- index += 1;
166
- return parseUnary();
167
- }
168
- return parsePrimary();
169
- };
170
-
171
- const parseAnd = (): boolean => {
172
- if (!parseUnary()) return false;
173
-
174
- while (tokens[index]?.type === "and") {
175
- index += 1;
176
- if (!parseUnary()) return false;
177
- }
178
-
179
- return true;
180
- };
181
-
182
- const parseOr = (): boolean => {
183
- if (!parseAnd()) return false;
184
-
185
- while (tokens[index]?.type === "or") {
186
- index += 1;
187
- if (!parseAnd()) return false;
188
- }
189
-
190
- return true;
191
- };
192
-
193
- if (!parseOr()) return false;
194
- return index === tokens.length;
195
-}
95
+const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
96
197
-function mergeWithDefaultKeybindings(custom: KeybindingsConfig): KeybindingsConfig {
97
+function mergeWithDefaultKeybindings(
98
+ custom: ResolvedKeybindingsConfig,
99
+): ResolvedKeybindingsConfig {
100
if (custom.length === 0) {
199
- return [...DEFAULT_KEYBINDINGS];
101
+ return [...DEFAULT_RESOLVED_KEYBINDINGS];
102
}
103
104
const overriddenCommands = new Set(custom.map((binding) => binding.command));
203
- const retainedDefaults = DEFAULT_KEYBINDINGS.filter(
105
+ const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
106
(binding) => !overriddenCommands.has(binding.command),
107
);
108
const merged = [...retainedDefaults, ...custom];
@@ -213,7 +115,9 @@ function mergeWithDefaultKeybindings(custom: KeybindingsConfig): KeybindingsConf
115
return merged.slice(-256);
116
}
117
216
-function readKeybindingsConfig(logger: ReturnType<typeof createLogger>): KeybindingsConfig {
118
+function readKeybindingsConfig(
119
+ logger: ReturnType<typeof createLogger>,
120
+): ResolvedKeybindingsConfig {
121
const configPath = path.join(os.homedir(), ".t3", "keybindings.json");
122
try {
123
const raw = fs.readFileSync(configPath, "utf8");
@@ -222,19 +126,20 @@ function readKeybindingsConfig(logger: ReturnType<typeof createLogger>): Keybind
126
logger.warn("ignoring keybindings config with unsupported format; expected array", {
127
path: configPath,
128
});
225
- return [...DEFAULT_KEYBINDINGS];
129
+ return [...DEFAULT_RESOLVED_KEYBINDINGS];
130
}
131
228
- const sanitized: KeybindingsConfig = [];
132
+ const sanitized: ResolvedKeybindingsConfig = [];
133
let invalidEntries = 0;
134
for (const entry of parsed) {
135
const result = keybindingRuleSchema.safeParse(entry);
136
if (result.success) {
233
- if (result.data.when && !isValidWhenExpression(result.data.when)) {
137
+ const compiled = compileResolvedKeybindingRule(result.data);
138
+ if (!compiled) {
139
invalidEntries += 1;
140
continue;
141
}
237
- sanitized.push(result.data);
142
+ sanitized.push(compiled);
143
continue;
144
}
145
invalidEntries += 1;
@@ -246,14 +151,12 @@ function readKeybindingsConfig(logger: ReturnType<typeof createLogger>): Keybind
151
totalEntries: parsed.length,
152
});
153
}
249
- const mergedBeforeCap = [
250
- ...DEFAULT_KEYBINDINGS.filter(
251
- (binding) => !new Set(sanitized.map((entry) => entry.command)).has(binding.command),
252
- ),
253
- ...sanitized,
254
- ];
154
+ const overriddenCommands = new Set(sanitized.map((entry) => entry.command));
155
+ const mergedBeforeCapLength =
156
+ DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
157
+ .length + sanitized.length;
158
const merged = mergeWithDefaultKeybindings(sanitized);
256
- if (mergedBeforeCap.length > 256) {
159
+ if (mergedBeforeCapLength > 256) {
160
logger.warn("truncating merged keybindings config to max entries", {
161
path: configPath,
162
maxEntries: 256,
@@ -262,14 +165,14 @@ function readKeybindingsConfig(logger: ReturnType<typeof createLogger>): Keybind
165
return merged;
166
} catch (error) {
167
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
265
- return [...DEFAULT_KEYBINDINGS];
168
+ return [...DEFAULT_RESOLVED_KEYBINDINGS];
169
}
170
logger.warn("ignoring malformed keybindings config", {
171
path: configPath,
172
error: error instanceof Error ? error.message : String(error),
173
});
174
}
272
- return [...DEFAULT_KEYBINDINGS];
175
+ return [...DEFAULT_RESOLVED_KEYBINDINGS];
176
}
177
178
export function createServer(options: ServerOptions) {
apps/web/src/components/ChatView.tsx
+3
-3
@@ -5,9 +5,9 @@ import {
5
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
6
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
7
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
8
+ type ResolvedKeybindingsConfig,
9
type ProviderApprovalDecision,
10
type ProviderSendTurnAttachmentInput,
10
- type KeybindingsConfig,
11
} from "@t3tools/contracts";
12
import {
13
type ClipboardEvent,
@@ -92,7 +92,7 @@ const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
92
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
93
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
94
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
95
-const EMPTY_KEYBINDINGS: KeybindingsConfig = [];
95
+const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
96
97
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
98
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
@@ -1520,7 +1520,7 @@ function ReasoningEffortPicker(props: {
1520
);
1521
}
1522
1523
-function OpenInPicker({ keybindings }: { keybindings: KeybindingsConfig }) {
1523
+function OpenInPicker({ keybindings }: { keybindings: ResolvedKeybindingsConfig }) {
1524
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
1525
const stored = localStorage.getItem(LAST_EDITOR_KEY);
1526
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
apps/web/src/components/Sidebar.tsx
+3
-1
@@ -1,5 +1,6 @@
1
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
2
import { useCallback, useEffect, useMemo, useState } from "react";
3
+import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
4
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
5
import { isElectron } from "../env";
6
import { useTheme } from "../hooks/useTheme";
@@ -19,6 +20,7 @@ import { serverConfigQueryOptions } from "../lib/serverReactQuery";
20
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
21
22
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
23
+const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
24
25
function formatRelativeTime(iso: string): string {
26
const diff = Date.now() - new Date(iso).getTime();
@@ -115,7 +117,7 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
117
export default function Sidebar() {
118
const { state, dispatch } = useStore();
119
const api = useNativeApi();
118
- const { data: keybindings = [] } = useQuery({
120
+ const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
121
...serverConfigQueryOptions(api),
122
select: (config) => config.keybindings,
123
});
apps/web/src/keybindings.test.ts
+250
-18
@@ -1,6 +1,11 @@
1
import { assert, describe, it } from "vitest";
2
3
-import type { KeybindingsConfig } from "@t3tools/contracts";
3
+import {
4
+ type KeybindingShortcut,
5
+ type KeybindingsConfig,
6
+ type KeybindingWhenNode,
7
+ type ResolvedKeybindingsConfig,
8
+} from "@t3tools/contracts";
9
import {
10
formatShortcutLabel,
11
isChatNewShortcut,
@@ -13,6 +18,14 @@ import {
18
type ShortcutEventLike,
19
} from "./keybindings";
20
21
+type WhenToken =
22
+ | { type: "identifier"; value: string }
23
+ | { type: "not" }
24
+ | { type: "and" }
25
+ | { type: "or" }
26
+ | { type: "lparen" }
27
+ | { type: "rparen" };
28
+
29
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
30
return {
31
key: "j",
@@ -24,13 +37,232 @@ function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
37
};
38
}
39
27
-const DEFAULT_BINDINGS: KeybindingsConfig = [
40
+function parseShortcut(value: string): KeybindingShortcut | null {
41
+ const rawTokens = value.toLowerCase().split("+").map((token) => token.trim());
42
+ const tokens = [...rawTokens];
43
+ let trailingEmptyCount = 0;
44
+ while (tokens[tokens.length - 1] === "") {
45
+ trailingEmptyCount += 1;
46
+ tokens.pop();
47
+ }
48
+ if (trailingEmptyCount > 0) {
49
+ tokens.push("+");
50
+ }
51
+ if (tokens.some((token) => token.length === 0)) {
52
+ return null;
53
+ }
54
+ if (tokens.length === 0) return null;
55
+
56
+ let key: string | null = null;
57
+ let metaKey = false;
58
+ let ctrlKey = false;
59
+ let shiftKey = false;
60
+ let altKey = false;
61
+ let modKey = false;
62
+
63
+ for (const token of tokens) {
64
+ switch (token) {
65
+ case "cmd":
66
+ case "meta":
67
+ metaKey = true;
68
+ break;
69
+ case "ctrl":
70
+ case "control":
71
+ ctrlKey = true;
72
+ break;
73
+ case "shift":
74
+ shiftKey = true;
75
+ break;
76
+ case "alt":
77
+ case "option":
78
+ altKey = true;
79
+ break;
80
+ case "mod":
81
+ modKey = true;
82
+ break;
83
+ default: {
84
+ if (key !== null) return null;
85
+ key = token;
86
+ }
87
+ }
88
+ }
89
+
90
+ if (key === null) return null;
91
+ return {
92
+ key,
93
+ metaKey,
94
+ ctrlKey,
95
+ shiftKey,
96
+ altKey,
97
+ modKey,
98
+ };
99
+}
100
+
101
+function shortcut(value: string): KeybindingShortcut {
102
+ const parsed = parseShortcut(value);
103
+ if (!parsed) {
104
+ throw new Error(`invalid shortcut in test fixture: ${value}`);
105
+ }
106
+ return parsed;
107
+}
108
+
109
+function tokenizeWhenExpression(expression: string): WhenToken[] | null {
110
+ const tokens: WhenToken[] = [];
111
+ let index = 0;
112
+
113
+ while (index < expression.length) {
114
+ const current = expression[index];
115
+ if (!current) break;
116
+
117
+ if (/\s/.test(current)) {
118
+ index += 1;
119
+ continue;
120
+ }
121
+ if (expression.startsWith("&&", index)) {
122
+ tokens.push({ type: "and" });
123
+ index += 2;
124
+ continue;
125
+ }
126
+ if (expression.startsWith("||", index)) {
127
+ tokens.push({ type: "or" });
128
+ index += 2;
129
+ continue;
130
+ }
131
+ if (current === "!") {
132
+ tokens.push({ type: "not" });
133
+ index += 1;
134
+ continue;
135
+ }
136
+ if (current === "(") {
137
+ tokens.push({ type: "lparen" });
138
+ index += 1;
139
+ continue;
140
+ }
141
+ if (current === ")") {
142
+ tokens.push({ type: "rparen" });
143
+ index += 1;
144
+ continue;
145
+ }
146
+
147
+ const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
148
+ if (!identifier) return null;
149
+ tokens.push({ type: "identifier", value: identifier[0] });
150
+ index += identifier[0].length;
151
+ }
152
+
153
+ return tokens;
154
+}
155
+
156
+function parseWhenExpression(expression: string): KeybindingWhenNode | null {
157
+ const tokens = tokenizeWhenExpression(expression);
158
+ if (!tokens || tokens.length === 0) return null;
159
+ let index = 0;
160
+
161
+ const parsePrimary = (): KeybindingWhenNode | null => {
162
+ const token = tokens[index];
163
+ if (!token) return null;
164
+
165
+ if (token.type === "identifier") {
166
+ index += 1;
167
+ return { type: "identifier", name: token.value };
168
+ }
169
+
170
+ if (token.type === "lparen") {
171
+ index += 1;
172
+ const expressionNode = parseOr();
173
+ const closeToken = tokens[index];
174
+ if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
175
+ return null;
176
+ }
177
+ index += 1;
178
+ return expressionNode;
179
+ }
180
+
181
+ return null;
182
+ };
183
+
184
+ const parseUnary = (): KeybindingWhenNode | null => {
185
+ const token = tokens[index];
186
+ if (token?.type === "not") {
187
+ index += 1;
188
+ const node = parseUnary();
189
+ if (!node) return null;
190
+ return { type: "not", node };
191
+ }
192
+ return parsePrimary();
193
+ };
194
+
195
+ const parseAnd = (): KeybindingWhenNode | null => {
196
+ let left = parseUnary();
197
+ if (!left) return null;
198
+
199
+ while (tokens[index]?.type === "and") {
200
+ index += 1;
201
+ const right = parseUnary();
202
+ if (!right) return null;
203
+ left = { type: "and", left, right };
204
+ }
205
+
206
+ return left;
207
+ };
208
+
209
+ const parseOr = (): KeybindingWhenNode | null => {
210
+ let left = parseAnd();
211
+ if (!left) return null;
212
+
213
+ while (tokens[index]?.type === "or") {
214
+ index += 1;
215
+ const right = parseAnd();
216
+ if (!right) return null;
217
+ left = { type: "or", left, right };
218
+ }
219
+
220
+ return left;
221
+ };
222
+
223
+ const ast = parseOr();
224
+ if (!ast || index !== tokens.length) return null;
225
+ return ast;
226
+}
227
+
228
+function compile(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
229
+ const resolved: ResolvedKeybindingsConfig = [];
230
+ for (const binding of bindings) {
231
+ const parsedShortcut = parseShortcut(binding.key);
232
+ if (!parsedShortcut) {
233
+ throw new Error(`invalid shortcut in test fixture: ${binding.key}`);
234
+ }
235
+ const when = binding.when?.trim();
236
+ if (when && when.length > 0) {
237
+ const whenAst = parseWhenExpression(when);
238
+ if (!whenAst) {
239
+ throw new Error(`invalid when expression in test fixture: ${when}`);
240
+ }
241
+ resolved.push({
242
+ key: binding.key.trim(),
243
+ command: binding.command,
244
+ when,
245
+ shortcut: parsedShortcut,
246
+ whenAst,
247
+ });
248
+ continue;
249
+ }
250
+ resolved.push({
251
+ key: binding.key.trim(),
252
+ command: binding.command,
253
+ shortcut: parsedShortcut,
254
+ });
255
+ }
256
+ return resolved;
257
+}
258
+
259
+const DEFAULT_BINDINGS = compile([
260
{ key: "mod+j", command: "terminal.toggle" },
261
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
262
{ key: "mod+shift+d", command: "terminal.new", when: "terminalFocus" },
263
{ key: "mod+shift+o", command: "chat.new" },
264
{ key: "mod+o", command: "editor.openFavorite" },
33
-];
265
+]);
266
267
describe("isTerminalToggleShortcut", () => {
268
it("matches Cmd+J on macOS", () => {
@@ -78,7 +310,7 @@ describe("split/new terminal shortcuts", () => {
310
});
311
312
it("supports when expressions", () => {
81
- const keybindings: KeybindingsConfig = [
313
+ const keybindings = compile([
314
{
315
key: "mod+\\",
316
command: "terminal.split",
@@ -90,7 +322,7 @@ describe("split/new terminal shortcuts", () => {
322
when: "terminalOpen && !terminalFocus",
323
},
324
{ key: "mod+j", command: "terminal.toggle" },
93
- ];
325
+ ]);
326
assert.isTrue(
327
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
328
platform: "Win32",
@@ -112,10 +344,10 @@ describe("split/new terminal shortcuts", () => {
344
});
345
346
it("supports when boolean literals", () => {
115
- const keybindings: KeybindingsConfig = [
347
+ const keybindings = compile([
348
{ key: "mod+n", command: "terminal.new", when: "true" },
349
{ key: "mod+m", command: "terminal.new", when: "false" },
118
- ];
350
+ ]);
351
352
assert.isTrue(
353
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
@@ -132,10 +364,10 @@ describe("split/new terminal shortcuts", () => {
364
365
describe("shortcutLabelForCommand", () => {
366
it("returns the most recent binding label", () => {
135
- const bindings: KeybindingsConfig = [
367
+ const bindings = compile([
368
{ key: "mod+\\", command: "terminal.split", when: "terminalFocus" },
369
{ key: "mod+shift+\\", command: "terminal.split", when: "!terminalFocus" },
138
- ];
370
+ ]);
371
assert.strictEqual(shortcutLabelForCommand(bindings, "terminal.split", "Linux"), "Ctrl+Shift+\\");
372
});
373
@@ -178,10 +410,10 @@ describe("chat/editor shortcuts", () => {
410
411
describe("cross-command precedence", () => {
412
it("uses when + order so a later focused rule overrides a global rule", () => {
181
- const keybindings: KeybindingsConfig = [
413
+ const keybindings = compile([
414
{ key: "mod+n", command: "chat.new" },
415
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
184
- ];
416
+ ]);
417
418
assert.isTrue(
419
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
@@ -210,10 +442,10 @@ describe("cross-command precedence", () => {
442
});
443
444
it("still lets a later global rule win when both rules match", () => {
213
- const keybindings: KeybindingsConfig = [
445
+ const keybindings = compile([
446
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
447
{ key: "mod+n", command: "chat.new" },
216
- ];
448
+ ]);
449
450
assert.isFalse(
451
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
@@ -232,16 +464,16 @@ describe("cross-command precedence", () => {
464
465
describe("formatShortcutLabel", () => {
466
it("formats labels for macOS", () => {
235
- assert.strictEqual(formatShortcutLabel("mod+shift+d", "MacIntel"), "⇧⌘D");
467
+ assert.strictEqual(formatShortcutLabel(shortcut("mod+shift+d"), "MacIntel"), "⇧⌘D");
468
});
469
470
it("formats labels for non-macOS", () => {
239
- assert.strictEqual(formatShortcutLabel("mod+shift+d", "Linux"), "Ctrl+Shift+D");
471
+ assert.strictEqual(formatShortcutLabel(shortcut("mod+shift+d"), "Linux"), "Ctrl+Shift+D");
472
});
473
474
it("formats labels for plus key", () => {
243
- assert.strictEqual(formatShortcutLabel("mod++", "MacIntel"), "⌘+");
244
- assert.strictEqual(formatShortcutLabel("mod++", "Linux"), "Ctrl++");
475
+ assert.strictEqual(formatShortcutLabel(shortcut("mod++"), "MacIntel"), "⌘+");
476
+ assert.strictEqual(formatShortcutLabel(shortcut("mod++"), "Linux"), "Ctrl++");
477
});
478
});
479
@@ -258,7 +490,7 @@ describe("isTerminalClearShortcut", () => {
490
491
describe("plus key parsing", () => {
492
it("matches the plus key shortcut", () => {
261
- const plusBindings: KeybindingsConfig = [{ key: "mod++", command: "terminal.toggle" }];
493
+ const plusBindings = compile([{ key: "mod++", command: "terminal.toggle" }]);
494
assert.isTrue(
495
isTerminalToggleShortcut(event({ key: "+", metaKey: true }), plusBindings, {
496
platform: "MacIntel",
apps/web/src/keybindings.ts
+37
-265
@@ -1,5 +1,9 @@
1
-import type { KeybindingCommand, KeybindingsConfig } from "@t3tools/contracts";
2
-import { LruCache } from "./lib/lru";
1
+import {
2
+ type KeybindingCommand,
3
+ type KeybindingShortcut,
4
+ type KeybindingWhenNode,
5
+ type ResolvedKeybindingsConfig,
6
+} from "@t3tools/contracts";
7
8
export interface ShortcutEventLike {
9
key: string;
@@ -15,262 +19,55 @@ export interface ShortcutMatchContext {
19
[key: string]: boolean;
20
}
21
18
-export type ResolvedKeybindings = KeybindingsConfig;
19
-
20
-interface ParsedShortcut {
21
- key: string;
22
- metaKey: boolean;
23
- ctrlKey: boolean;
24
- shiftKey: boolean;
25
- altKey: boolean;
26
- modKey: boolean;
27
-}
22
+export type ResolvedKeybindings = ResolvedKeybindingsConfig;
23
24
interface ShortcutMatchOptions {
25
platform?: string;
26
context?: Partial<ShortcutMatchContext>;
27
}
28
34
-type WhenNode =
35
- | { type: "identifier"; name: string }
36
- | { type: "not"; node: WhenNode }
37
- | { type: "and"; left: WhenNode; right: WhenNode }
38
- | { type: "or"; left: WhenNode; right: WhenNode };
39
-
40
-type WhenToken =
41
- | { type: "identifier"; value: string }
42
- | { type: "not" }
43
- | { type: "and" }
44
- | { type: "or" }
45
- | { type: "lparen" }
46
- | { type: "rparen" };
47
-
48
-const WHEN_AST_CACHE = new LruCache<string, WhenNode | null>(512);
49
-
29
function isMacPlatform(platform: string): boolean {
30
return /mac|iphone|ipad|ipod/i.test(platform);
31
}
32
54
-function normalizeKeyToken(token: string): string {
55
- if (token === "space") return " ";
56
- if (token === "esc") return "escape";
57
- return token;
58
-}
59
-
60
-function parseShortcutValue(value: string): ParsedShortcut | null {
61
- const rawTokens = value.toLowerCase().split("+").map((token) => token.trim());
62
- const tokens = [...rawTokens];
63
- let trailingEmptyCount = 0;
64
- while (tokens[tokens.length - 1] === "") {
65
- trailingEmptyCount += 1;
66
- tokens.pop();
67
- }
68
- if (trailingEmptyCount > 0) {
69
- tokens.push("+");
70
- }
71
- if (tokens.some((token) => token.length === 0)) {
72
- return null;
73
- }
74
- if (tokens.length === 0) return null;
75
-
76
- let key: string | null = null;
77
- let metaKey = false;
78
- let ctrlKey = false;
79
- let shiftKey = false;
80
- let altKey = false;
81
- let modKey = false;
82
-
83
- for (const token of tokens) {
84
- switch (token) {
85
- case "cmd":
86
- case "meta":
87
- metaKey = true;
88
- break;
89
- case "ctrl":
90
- case "control":
91
- ctrlKey = true;
92
- break;
93
- case "shift":
94
- shiftKey = true;
95
- break;
96
- case "alt":
97
- case "option":
98
- altKey = true;
99
- break;
100
- case "mod":
101
- modKey = true;
102
- break;
103
- default: {
104
- if (key !== null) {
105
- return null;
106
- }
107
- key = normalizeKeyToken(token);
108
- }
109
- }
110
- }
111
-
112
- if (key === null) return null;
113
-
114
- return {
115
- key,
116
- metaKey,
117
- ctrlKey,
118
- shiftKey,
119
- altKey,
120
- modKey,
121
- };
122
-}
123
-
33
function normalizeEventKey(key: string): string {
34
const normalized = key.toLowerCase();
35
if (normalized === "esc") return "escape";
36
return normalized;
37
}
38
130
-function matchesShortcutValue(
39
+function matchesShortcut(
40
event: ShortcutEventLike,
132
- shortcutValue: string,
41
+ shortcut: KeybindingShortcut,
42
platform = navigator.platform,
43
): boolean {
135
- const parsed = parseShortcutValue(shortcutValue);
136
- if (!parsed) return false;
137
-
44
const key = normalizeEventKey(event.key);
139
- if (key !== parsed.key) return false;
45
+ if (key !== shortcut.key) return false;
46
47
const useMetaForMod = isMacPlatform(platform);
142
- const expectedMeta = parsed.metaKey || (parsed.modKey && useMetaForMod);
143
- const expectedCtrl = parsed.ctrlKey || (parsed.modKey && !useMetaForMod);
48
+ const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
49
+ const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
50
return (
51
event.metaKey === expectedMeta &&
52
event.ctrlKey === expectedCtrl &&
147
- event.shiftKey === parsed.shiftKey &&
148
- event.altKey === parsed.altKey
53
+ event.shiftKey === shortcut.shiftKey &&
54
+ event.altKey === shortcut.altKey
55
);
56
}
57
152
-function tokenizeWhenExpression(expression: string): WhenToken[] | null {
153
- const tokens: WhenToken[] = [];
154
- let index = 0;
155
-
156
- while (index < expression.length) {
157
- const current = expression[index];
158
- if (!current) break;
159
-
160
- if (/\s/.test(current)) {
161
- index += 1;
162
- continue;
163
- }
164
- if (expression.startsWith("&&", index)) {
165
- tokens.push({ type: "and" });
166
- index += 2;
167
- continue;
168
- }
169
- if (expression.startsWith("||", index)) {
170
- tokens.push({ type: "or" });
171
- index += 2;
172
- continue;
173
- }
174
- if (current === "!") {
175
- tokens.push({ type: "not" });
176
- index += 1;
177
- continue;
178
- }
179
- if (current === "(") {
180
- tokens.push({ type: "lparen" });
181
- index += 1;
182
- continue;
183
- }
184
- if (current === ")") {
185
- tokens.push({ type: "rparen" });
186
- index += 1;
187
- continue;
188
- }
189
-
190
- const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
191
- if (!identifier) {
192
- return null;
193
- }
194
- tokens.push({ type: "identifier", value: identifier[0] });
195
- index += identifier[0].length;
196
- }
197
-
198
- return tokens;
58
+function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
59
+ return options?.platform ?? navigator.platform;
60
}
61
201
-function parseWhenExpression(expression: string): WhenNode | null {
202
- const tokens = tokenizeWhenExpression(expression);
203
- if (!tokens || tokens.length === 0) return null;
204
- let index = 0;
205
-
206
- const parsePrimary = (): WhenNode | null => {
207
- const token = tokens[index];
208
- if (!token) return null;
209
-
210
- if (token.type === "identifier") {
211
- index += 1;
212
- return { type: "identifier", name: token.value };
213
- }
214
-
215
- if (token.type === "lparen") {
216
- index += 1;
217
- const expressionNode = parseOr();
218
- const closeToken = tokens[index];
219
- if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
220
- return null;
221
- }
222
- index += 1;
223
- return expressionNode;
224
- }
225
-
226
- return null;
227
- };
228
-
229
- const parseUnary = (): WhenNode | null => {
230
- const token = tokens[index];
231
- if (token?.type === "not") {
232
- index += 1;
233
- const node = parseUnary();
234
- if (!node) return null;
235
- return { type: "not", node };
236
- }
237
- return parsePrimary();
238
- };
239
-
240
- const parseAnd = (): WhenNode | null => {
241
- let left = parseUnary();
242
- if (!left) return null;
243
-
244
- while (tokens[index]?.type === "and") {
245
- index += 1;
246
- const right = parseUnary();
247
- if (!right) return null;
248
- left = { type: "and", left, right };
249
- }
250
-
251
- return left;
252
- };
253
-
254
- const parseOr = (): WhenNode | null => {
255
- let left = parseAnd();
256
- if (!left) return null;
257
-
258
- while (tokens[index]?.type === "or") {
259
- index += 1;
260
- const right = parseAnd();
261
- if (!right) return null;
262
- left = { type: "or", left, right };
263
- }
264
-
265
- return left;
62
+function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
63
+ return {
64
+ terminalFocus: false,
65
+ terminalOpen: false,
66
+ ...options?.context,
67
};
267
-
268
- const ast = parseOr();
269
- if (!ast || index !== tokens.length) return null;
270
- return ast;
68
}
69
273
-function evaluateWhenNode(node: WhenNode, context: ShortcutMatchContext): boolean {
70
+function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
71
switch (node.type) {
72
case "identifier":
73
if (node.name === "true") return true;
@@ -285,32 +82,12 @@ function evaluateWhenNode(node: WhenNode, context: ShortcutMatchContext): boolea
82
}
83
}
84
288
-function matchesWhenExpression(when: string | undefined, context: ShortcutMatchContext): boolean {
289
- if (!when) return true;
290
- const normalized = when.trim();
291
- if (normalized.length === 0) return true;
292
-
293
- const cached = WHEN_AST_CACHE.get(normalized);
294
- if (cached === undefined) {
295
- const parsed = parseWhenExpression(normalized);
296
- WHEN_AST_CACHE.set(normalized, parsed);
297
- if (!parsed) return false;
298
- return evaluateWhenNode(parsed, context);
299
- }
300
- if (!cached) return false;
301
- return evaluateWhenNode(cached, context);
302
-}
303
-
304
-function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
305
- return options?.platform ?? navigator.platform;
306
-}
307
-
308
-function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
309
- return {
310
- terminalFocus: false,
311
- terminalOpen: false,
312
- ...options?.context,
313
- };
85
+function matchesWhenClause(
86
+ whenAst: ResolvedKeybindings[number]["whenAst"],
87
+ context: ShortcutMatchContext,
88
+): boolean {
89
+ if (!whenAst) return true;
90
+ return evaluateWhenNode(whenAst, context);
91
}
92
93
function matchesCommandShortcut(
@@ -333,8 +110,8 @@ function resolveShortcutCommand(
110
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
111
const binding = keybindings[index];
112
if (!binding) continue;
336
- if (!matchesWhenExpression(binding.when, context)) continue;
337
- if (!matchesShortcutValue(event, binding.key, platform)) continue;
113
+ if (!matchesWhenClause(binding.whenAst, context)) continue;
114
+ if (!matchesShortcut(event, binding.shortcut, platform)) continue;
115
return binding.command;
116
}
117
return null;
@@ -351,18 +128,13 @@ function formatShortcutKeyLabel(key: string): string {
128
return key.slice(0, 1).toUpperCase() + key.slice(1);
129
}
130
354
-export function formatShortcutLabel(shortcutValue: string, platform = navigator.platform): string {
355
- const parsed = parseShortcutValue(shortcutValue);
356
- if (!parsed) {
357
- return shortcutValue;
358
- }
359
-
360
- const keyLabel = formatShortcutKeyLabel(parsed.key);
131
+export function formatShortcutLabel(shortcut: KeybindingShortcut, platform = navigator.platform): string {
132
+ const keyLabel = formatShortcutKeyLabel(shortcut.key);
133
const useMetaForMod = isMacPlatform(platform);
362
- const showMeta = parsed.metaKey || (parsed.modKey && useMetaForMod);
363
- const showCtrl = parsed.ctrlKey || (parsed.modKey && !useMetaForMod);
364
- const showAlt = parsed.altKey;
365
- const showShift = parsed.shiftKey;
134
+ const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
135
+ const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
136
+ const showAlt = shortcut.altKey;
137
+ const showShift = shortcut.shiftKey;
138
139
if (useMetaForMod) {
140
return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
@@ -385,7 +157,7 @@ export function shortcutLabelForCommand(
157
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
158
const binding = keybindings[index];
159
if (!binding || binding.command !== command) continue;
388
- return formatShortcutLabel(binding.key, platform);
160
+ return formatShortcutLabel(binding.shortcut, platform);
161
}
162
return null;
163
}
packages/contracts/src/index.ts
+1
@@ -6,6 +6,7 @@ export * from "./provider";
6
export * from "./model";
7
export * from "./ws";
8
export * from "./keybindings";
9
+export * from "./keybindingsWhen";
10
export * from "./server";
11
export * from "./project";
12
export * from "./git";
packages/contracts/src/keybindings.test.ts
new
+78
@@ -0,0 +1,78 @@
1
+import { describe, expect, it } from "vitest";
2
+
3
+import {
4
+ keybindingRuleSchema,
5
+ keybindingsConfigSchema,
6
+ resolvedKeybindingRuleSchema,
7
+ resolvedKeybindingsConfigSchema,
8
+} from "./keybindings";
9
+
10
+describe("keybindings contracts", () => {
11
+ it("parses keybinding rules", () => {
12
+ const parsed = keybindingRuleSchema.parse({
13
+ key: "mod+j",
14
+ command: "terminal.toggle",
15
+ });
16
+ expect(parsed.command).toBe("terminal.toggle");
17
+ });
18
+
19
+ it("rejects invalid command values", () => {
20
+ expect(() =>
21
+ keybindingRuleSchema.parse({
22
+ key: "mod+j",
23
+ command: "invalid.command" as unknown as "terminal.toggle",
24
+ }),
25
+ ).toThrow();
26
+ });
27
+
28
+ it("parses keybindings array payload", () => {
29
+ const parsed = keybindingsConfigSchema.parse([
30
+ { key: "mod+j", command: "terminal.toggle" },
31
+ { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
32
+ ]);
33
+ expect(parsed).toHaveLength(2);
34
+ });
35
+
36
+ it("parses resolved keybinding rules", () => {
37
+ const parsed = resolvedKeybindingRuleSchema.parse({
38
+ key: "mod+d",
39
+ command: "terminal.split",
40
+ when: "terminalOpen && !terminalFocus",
41
+ shortcut: {
42
+ key: "d",
43
+ metaKey: false,
44
+ ctrlKey: false,
45
+ shiftKey: false,
46
+ altKey: false,
47
+ modKey: true,
48
+ },
49
+ whenAst: {
50
+ type: "and",
51
+ left: { type: "identifier", name: "terminalOpen" },
52
+ right: {
53
+ type: "not",
54
+ node: { type: "identifier", name: "terminalFocus" },
55
+ },
56
+ },
57
+ });
58
+ expect(parsed.shortcut.key).toBe("d");
59
+ });
60
+
61
+ it("parses resolved keybindings arrays", () => {
62
+ const parsed = resolvedKeybindingsConfigSchema.parse([
63
+ {
64
+ key: "mod+j",
65
+ command: "terminal.toggle",
66
+ shortcut: {
67
+ key: "j",
68
+ metaKey: false,
69
+ ctrlKey: false,
70
+ shiftKey: false,
71
+ altKey: false,
72
+ modKey: true,
73
+ },
74
+ },
75
+ ]);
76
+ expect(parsed).toHaveLength(1);
77
+ });
78
+});
packages/contracts/src/keybindings.ts
+46
@@ -1,4 +1,5 @@
1
import { z } from "zod";
2
+import type { KeybindingWhenNode } from "./keybindingsWhen";
3
4
export const keybindingCommandSchema = z.enum([
5
"terminal.toggle",
@@ -19,6 +20,51 @@ export const keybindingRuleSchema = z.object({
20
21
export const keybindingsConfigSchema = z.array(keybindingRuleSchema).max(256);
22
23
+export const keybindingShortcutSchema = z.object({
24
+ key: z.string().trim().min(1).max(32),
25
+ metaKey: z.boolean(),
26
+ ctrlKey: z.boolean(),
27
+ shiftKey: z.boolean(),
28
+ altKey: z.boolean(),
29
+ modKey: z.boolean(),
30
+});
31
+
32
+export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(() =>
33
+ z.union([
34
+ z.object({
35
+ type: z.literal("identifier"),
36
+ name: z.string().min(1),
37
+ }),
38
+ z.object({
39
+ type: z.literal("not"),
40
+ node: keybindingWhenNodeSchema,
41
+ }),
42
+ z.object({
43
+ type: z.literal("and"),
44
+ left: keybindingWhenNodeSchema,
45
+ right: keybindingWhenNodeSchema,
46
+ }),
47
+ z.object({
48
+ type: z.literal("or"),
49
+ left: keybindingWhenNodeSchema,
50
+ right: keybindingWhenNodeSchema,
51
+ }),
52
+ ]),
53
+);
54
+
55
+export const resolvedKeybindingRuleSchema = z.object({
56
+ key: keybindingValueSchema,
57
+ command: keybindingCommandSchema,
58
+ when: keybindingWhenSchema.optional(),
59
+ shortcut: keybindingShortcutSchema,
60
+ whenAst: keybindingWhenNodeSchema.optional(),
61
+});
62
+
63
+export const resolvedKeybindingsConfigSchema = z.array(resolvedKeybindingRuleSchema).max(256);
64
+
65
export type KeybindingCommand = z.infer<typeof keybindingCommandSchema>;
66
export type KeybindingRule = z.infer<typeof keybindingRuleSchema>;
67
export type KeybindingsConfig = z.infer<typeof keybindingsConfigSchema>;
68
+export type KeybindingShortcut = z.infer<typeof keybindingShortcutSchema>;
69
+export type ResolvedKeybindingRule = z.infer<typeof resolvedKeybindingRuleSchema>;
70
+export type ResolvedKeybindingsConfig = z.infer<typeof resolvedKeybindingsConfigSchema>;
packages/contracts/src/keybindingsWhen.ts
new
+5
@@ -0,0 +1,5 @@
1
+export type KeybindingWhenNode =
2
+ | { type: "identifier"; name: string }
3
+ | { type: "not"; node: KeybindingWhenNode }
4
+ | { type: "and"; left: KeybindingWhenNode; right: KeybindingWhenNode }
5
+ | { type: "or"; left: KeybindingWhenNode; right: KeybindingWhenNode };
packages/contracts/src/server.ts
+2
-2
@@ -1,9 +1,9 @@
1
import { z } from "zod";
2
-import { keybindingsConfigSchema } from "./keybindings";
2
+import { resolvedKeybindingsConfigSchema } from "./keybindings";
3
4
export const serverConfigSchema = z.object({
5
cwd: z.string().min(1),
6
- keybindings: keybindingsConfigSchema.default([]),
6
+ keybindings: resolvedKeybindingsConfigSchema.default([]),
7
});
8
9
export type ServerConfig = z.infer<typeof serverConfigSchema>;