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