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