Open History to see the last commit
1import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/contracts";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import { assertFailure } from "@effect/vitest/utils";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Logger from "effect/Logger";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as ServerConfig from "./config.ts";
12import * as Keybindings from "./keybindings.ts";
13import { KeybindingsConfigError, MAX_KEYBINDINGS_COUNT } from "@t3tools/contracts";
14
15const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
16const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson);
17const decodeKeybindingsConfigJson = Schema.decodeUnknownEffect(KeybindingsConfigJson);
18const layerKeybindings = () => {
19 return Keybindings.layer.pipe(
20 Layer.provideMerge(
21 Layer.fresh(
22 ServerConfig.layerTest(process.cwd(), {
23 prefix: "t3code-keybindings-test-",
24 }),
25 ),
26 ),
27 );
28};
29
30const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
31 effect.pipe(
32 Effect.mapError((error) => error.detail),
33 Effect.result,
34 );
35
36const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
37 Effect.gen(function* () {
38 const fileSystem = yield* FileSystem.FileSystem;
39 const path = yield* Path.Path;
40 const encoded = yield* encodeKeybindingsConfigJson(rules);
41 yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
42 yield* fileSystem.writeFileString(configPath, encoded);
43 });
44
45const readKeybindingsConfig = (configPath: string) =>
46 Effect.gen(function* () {
47 const fileSystem = yield* FileSystem.FileSystem;
48 const rawConfig = yield* fileSystem.readFileString(configPath);
49 return yield* decodeKeybindingsConfigJson(rawConfig);
50 });
51
52it.layer(NodeServices.layer)("keybindings", (it) => {
53 it.effect("parses shortcuts including plus key", () =>
54 Effect.sync(() => {
55 assert.deepEqual(Keybindings.parseKeybindingShortcut("mod+j"), {
56 key: "j",
57 metaKey: false,
58 ctrlKey: false,
59 shiftKey: false,
60 altKey: false,
61 modKey: true,
62 });
63 assert.deepEqual(Keybindings.parseKeybindingShortcut("mod++"), {
64 key: "+",
65 metaKey: false,
66 ctrlKey: false,
67 shiftKey: false,
68 altKey: false,
69 modKey: true,
70 });
71 }),
72 );
73
74 it.effect("compiles valid rule with parsed when AST", () =>
75 Effect.sync(() => {
76 const compiled = Keybindings.compileResolvedKeybindingRule({
77 key: "mod+d",
78 command: "terminal.split",
79 when: "terminalOpen && !terminalFocus",
80 });
81
82 assert.deepEqual(compiled, {
83 command: "terminal.split",
84 shortcut: {
85 key: "d",
86 metaKey: false,
87 ctrlKey: false,
88 shiftKey: false,
89 altKey: false,
90 modKey: true,
91 },
92 whenAst: {
93 type: "and",
94 left: { type: "identifier", name: "terminalOpen" },
95 right: {
96 type: "not",
97 node: { type: "identifier", name: "terminalFocus" },
98 },
99 },
100 });
101 }),
102 );
103
104 it.effect("rejects invalid rules", () =>
105 Effect.sync(() => {
106 assert.isNull(
107 Keybindings.compileResolvedKeybindingRule({
108 key: "mod+shift+d+o",
109 command: "terminal.new",
110 }),
111 );
112
113 assert.isNull(
114 Keybindings.compileResolvedKeybindingRule({
115 key: "mod+d",
116 command: "terminal.split",
117 when: "terminalFocus && (",
118 }),
119 );
120
121 assert.isNull(
122 Keybindings.compileResolvedKeybindingRule({
123 key: "mod+d",
124 command: "terminal.split",
125 when: `${"!".repeat(300)}terminalFocus`,
126 }),
127 );
128 }),
129 );
130
131 it.effect("bootstraps default keybindings when config file is missing", () =>
132 Effect.gen(function* () {
133 const fs = yield* FileSystem.FileSystem;
134 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
135 assert.isFalse(yield* fs.exists(keybindingsConfigPath));
136
137 yield* Effect.gen(function* () {
138 const keybindings = yield* Keybindings.Keybindings;
139 yield* keybindings.syncDefaultKeybindingsOnStartup;
140 });
141
142 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
143 assert.deepEqual(persisted, Keybindings.DEFAULT_KEYBINDINGS);
144 }).pipe(Effect.provide(layerKeybindings())),
145 );
146
147 it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
148 Effect.gen(function* () {
149 const fs = yield* FileSystem.FileSystem;
150 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
151 yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
152
153 const configState = yield* Effect.gen(function* () {
154 const keybindings = yield* Keybindings.Keybindings;
155 return yield* keybindings.loadConfigState;
156 });
157
158 assert.deepEqual(
159 configState.keybindings,
160 Keybindings.compileResolvedKeybindingsConfig(Keybindings.DEFAULT_KEYBINDINGS),
161 );
162 assert.deepEqual(configState.issues, [
163 {
164 kind: "keybindings.malformed-config",
165 message: configState.issues[0]?.message ?? "",
166 },
167 ]);
168 assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json");
169 }).pipe(Effect.provide(layerKeybindings())),
170 );
171
172 it.effect("ignores invalid entries in runtime and reports them as issues", () =>
173 Effect.gen(function* () {
174 const fs = yield* FileSystem.FileSystem;
175 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
176 yield* fs.writeFileString(
177 keybindingsConfigPath,
178 JSON.stringify([
179 { key: "mod+j", command: "terminal.toggle" },
180 { key: "mod+shift+d+o", command: "terminal.new" },
181 { key: "mod+x", command: "invalid.command" },
182 ]),
183 );
184
185 const configState = yield* Effect.gen(function* () {
186 const keybindings = yield* Keybindings.Keybindings;
187 return yield* keybindings.loadConfigState;
188 });
189
190 assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
191 assert.isFalse(
192 configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
193 );
194 assert.deepEqual(configState.issues, [
195 {
196 kind: "keybindings.invalid-entry",
197 index: 1,
198 message: configState.issues[0]?.message ?? "",
199 },
200 {
201 kind: "keybindings.invalid-entry",
202 index: 2,
203 message: configState.issues[1]?.message ?? "",
204 },
205 ]);
206 }).pipe(Effect.provide(layerKeybindings())),
207 );
208
209 it.effect(
210 "upserts missing default keybindings on startup without overriding existing command rules",
211 () =>
212 Effect.gen(function* () {
213 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
214 yield* writeKeybindingsConfig(keybindingsConfigPath, [
215 { key: "mod+shift+y", command: "terminal.toggle" },
216 { key: "mod+shift+r", command: "script.run-tests.run" },
217 { key: "mod+shift+b", command: "script.custom-panel.run" },
218 {
219 key: "mod+shift+b",
220 command: "script.custom-composer.run",
221 when: "composerFocus",
222 },
223 ]);
224
225 const keybindings = yield* Keybindings.Keybindings;
226 yield* keybindings.syncDefaultKeybindingsOnStartup;
227
228 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
229 const byCommand = new Map(persisted.map((entry) => [entry.command, entry]));
230
231 const persistedToggle = byCommand.get("terminal.toggle");
232 assert.isNotNull(persistedToggle);
233 assert.equal(persistedToggle?.key, "mod+shift+y");
234 assert.isFalse(
235 persisted.some((entry) => entry.command === "terminal.toggle" && entry.key === "mod+j"),
236 );
237
238 for (const defaultRule of Keybindings.DEFAULT_KEYBINDINGS) {
239 assert.isTrue(byCommand.has(defaultRule.command), `expected ${defaultRule.command}`);
240 }
241 assert.isTrue(byCommand.has("script.run-tests.run"));
242
243 const configState = yield* keybindings.loadConfigState;
244 assert.deepEqual(
245 configState.keybindings
246 .filter((entry) => entry.shortcut.key === "b" && entry.shortcut.shiftKey)
247 .map((entry) => entry.command),
248 ["threadPanel.toggle", "script.custom-panel.run", "script.custom-composer.run"],
249 );
250 }).pipe(Effect.provide(layerKeybindings())),
251 );
252
253 it.effect("adds a late default to an existing command once", () =>
254 Effect.gen(function* () {
255 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
256 const keybindings = yield* Keybindings.Keybindings;
257 const when = "composerFocus && draftThreadRoute";
258 const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const;
259 const backgroundRules = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) =>
260 rules.filter((entry) => entry.command === "composer.sendBackground"),
261 );
262 yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
263
264 yield* keybindings.syncDefaultKeybindingsOnStartup;
265 assert.deepStrictEqual(yield* backgroundRules, [
266 { key: "mod+enter", command: "composer.sendBackground", when },
267 existing,
268 ]);
269
270 yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
271 yield* keybindings.syncDefaultKeybindingsOnStartup;
272 assert.deepStrictEqual(yield* backgroundRules, [existing]);
273 }).pipe(Effect.provide(layerKeybindings())),
274 );
275
276 it.effect("leaves a customized command without the late default", () =>
277 Effect.gen(function* () {
278 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
279 const keybindings = yield* Keybindings.Keybindings;
280 const custom = {
281 key: "alt+b",
282 command: "composer.sendBackground",
283 when: "composerFocus && draftThreadRoute",
284 } as const;
285 yield* writeKeybindingsConfig(keybindingsConfigPath, [custom]);
286
287 yield* keybindings.syncDefaultKeybindingsOnStartup;
288 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
289 assert.deepStrictEqual(
290 persisted.filter((entry) => entry.command === "composer.sendBackground"),
291 [custom],
292 );
293 }).pipe(Effect.provide(layerKeybindings())),
294 );
295
296 it.effect("keeps a late default pending while the config is full", () =>
297 Effect.gen(function* () {
298 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
299 const keybindings = yield* Keybindings.Keybindings;
300 const when = "composerFocus && draftThreadRoute";
301 const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const;
302 const fillers = Array.from({ length: MAX_KEYBINDINGS_COUNT - 1 }, (_, index) => ({
303 key: "mod+alt+f1",
304 command: `script.filler-${index}.run` as const,
305 }));
306 const hasModEnter = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) =>
307 rules.some(
308 (entry) => entry.command === "composer.sendBackground" && entry.key === "mod+enter",
309 ),
310 );
311
312 yield* writeKeybindingsConfig(keybindingsConfigPath, [existing, ...fillers]);
313 yield* keybindings.syncDefaultKeybindingsOnStartup;
314 assert.isFalse(yield* hasModEnter);
315
316 yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
317 yield* keybindings.syncDefaultKeybindingsOnStartup;
318 assert.isTrue(yield* hasModEnter);
319 }).pipe(Effect.provide(layerKeybindings())),
320 );
321
322 it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => {
323 const messages: string[] = [];
324 const logger = Logger.make(({ message }) => {
325 messages.push(String(message));
326 });
327
328 return Effect.gen(function* () {
329 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
330 yield* writeKeybindingsConfig(keybindingsConfigPath, [
331 { key: "mod+j", command: "script.custom-action.run" },
332 ]);
333
334 yield* Effect.gen(function* () {
335 const keybindings = yield* Keybindings.Keybindings;
336 yield* keybindings.syncDefaultKeybindingsOnStartup;
337 });
338
339 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
340 assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle"));
341 assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run"));
342
343 assert.isTrue(
344 messages.some((message) =>
345 message.includes("skipping default keybinding due to shortcut conflict"),
346 ),
347 );
348 }).pipe(
349 Effect.provide(
350 Layer.mergeAll(layerKeybindings(), Logger.layer([logger], { mergeWithExisting: false })),
351 ),
352 );
353 });
354
355 it.effect("appends additional custom keybindings for the same command", () =>
356 Effect.gen(function* () {
357 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
358 yield* writeKeybindingsConfig(keybindingsConfigPath, [
359 { key: "mod+r", command: "script.run-tests.run" },
360 ]);
361 yield* Effect.gen(function* () {
362 const keybindings = yield* Keybindings.Keybindings;
363 return yield* keybindings.upsertKeybindingRule({
364 key: "mod+shift+r",
365 command: "script.run-tests.run",
366 });
367 });
368
369 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
370 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
371 assert.deepEqual(persistedView, [
372 { key: "mod+r", command: "script.run-tests.run" },
373 { key: "mod+shift+r", command: "script.run-tests.run" },
374 ]);
375 }).pipe(Effect.provide(layerKeybindings())),
376 );
377
378 it.effect("replaces only the targeted custom keybinding", () =>
379 Effect.gen(function* () {
380 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
381 yield* writeKeybindingsConfig(keybindingsConfigPath, [
382 { key: "mod+r", command: "script.run-tests.run" },
383 { key: "mod+shift+r", command: "script.run-tests.run" },
384 ]);
385 yield* Effect.gen(function* () {
386 const keybindings = yield* Keybindings.Keybindings;
387 return yield* keybindings.upsertKeybindingRule({
388 key: "mod+alt+r",
389 command: "script.run-tests.run",
390 replace: { key: "mod+r", command: "script.run-tests.run" },
391 });
392 });
393
394 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
395 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
396 assert.deepEqual(persistedView, [
397 { key: "mod+shift+r", command: "script.run-tests.run" },
398 { key: "mod+alt+r", command: "script.run-tests.run" },
399 ]);
400 }).pipe(Effect.provide(layerKeybindings())),
401 );
402
403 it.effect("replacing with a rule that already exists elsewhere does not duplicate it", () =>
404 Effect.gen(function* () {
405 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
406 yield* writeKeybindingsConfig(keybindingsConfigPath, [
407 { key: "mod+r", command: "script.run-tests.run" },
408 { key: "mod+alt+r", command: "script.run-tests.run" },
409 ]);
410 yield* Effect.gen(function* () {
411 const keybindings = yield* Keybindings.Keybindings;
412 return yield* keybindings.upsertKeybindingRule({
413 key: "mod+alt+r",
414 command: "script.run-tests.run",
415 replace: { key: "mod+r", command: "script.run-tests.run" },
416 });
417 });
418
419 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
420 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
421 assert.deepEqual(persistedView, [{ key: "mod+alt+r", command: "script.run-tests.run" }]);
422 }).pipe(Effect.provide(layerKeybindings())),
423 );
424
425 it.effect("removes only the targeted custom keybinding", () =>
426 Effect.gen(function* () {
427 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
428 yield* writeKeybindingsConfig(keybindingsConfigPath, [
429 { key: "mod+r", command: "script.run-tests.run" },
430 { key: "mod+shift+r", command: "script.run-tests.run" },
431 ]);
432 yield* Effect.gen(function* () {
433 const keybindings = yield* Keybindings.Keybindings;
434 return yield* keybindings.removeKeybindingRule({
435 key: "mod+r",
436 command: "script.run-tests.run",
437 });
438 });
439
440 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
441 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
442 assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
443 }).pipe(Effect.provide(layerKeybindings())),
444 );
445
446 it.effect("refuses to overwrite malformed keybindings config", () =>
447 Effect.gen(function* () {
448 const fs = yield* FileSystem.FileSystem;
449 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
450 yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
451
452 const result = yield* Effect.gen(function* () {
453 const keybindings = yield* Keybindings.Keybindings;
454 return yield* keybindings.upsertKeybindingRule({
455 key: "mod+shift+r",
456 command: "script.run-tests.run",
457 });
458 }).pipe(toDetailResult);
459 assertFailure(result, "expected JSON array");
460
461 const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
462 assert.equal(persistedRaw, "{ not-json");
463 }).pipe(Effect.provide(layerKeybindings())),
464 );
465
466 it.effect("retries a failed config read instead of keeping the failure", () =>
467 Effect.gen(function* () {
468 const fileSystem = yield* FileSystem.FileSystem;
469 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
470 yield* fileSystem.makeDirectory(keybindingsConfigPath, { recursive: true });
471
472 const keybindings = yield* Keybindings.Keybindings;
473 const failed = yield* toDetailResult(keybindings.loadConfigState);
474 assertFailure(failed, "failed to read keybindings config");
475
476 yield* fileSystem.remove(keybindingsConfigPath, { recursive: true });
477 yield* writeKeybindingsConfig(keybindingsConfigPath, [
478 { key: "mod+j", command: "terminal.toggle" },
479 ]);
480
481 const configState = yield* keybindings.loadConfigState;
482 assert.deepEqual(configState.issues, []);
483 assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
484 }).pipe(Effect.provide(layerKeybindings())),
485 );
486
487 it.effect("serializes concurrent upserts to avoid lost updates", () =>
488 Effect.gen(function* () {
489 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
490 yield* writeKeybindingsConfig(keybindingsConfigPath, []);
491
492 const commands = Array.from(
493 { length: 20 },
494 (_, index): KeybindingCommand => `script.concurrent-${index}.run`,
495 );
496 yield* Effect.gen(function* () {
497 const keybindings = yield* Keybindings.Keybindings;
498 yield* Effect.forEach(
499 commands,
500 (command, index) =>
501 keybindings.upsertKeybindingRule({
502 key: `mod+${String.fromCharCode(97 + index)}`,
503 command,
504 }),
505 { concurrency: "unbounded", discard: true },
506 );
507 });
508
509 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
510 const persistedCommands = new Set(persisted.map((entry) => entry.command));
511 for (const command of commands) {
512 assert.isTrue(persistedCommands.has(command), `expected persisted command ${command}`);
513 }
514 }).pipe(Effect.provide(layerKeybindings())),
515 );
516});