Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.test.ts

588 lines21.8 KB

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