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

keybindings.test.ts

520 lines18.1 KB

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