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

keybindings.test.ts

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