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 { 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 "@t3tools/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 assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
196 assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
197 assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
198 }),
199 );
200
201 it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
202 Effect.gen(function* () {
203 const fs = yield* FileSystem.FileSystem;
204 const { keybindingsConfigPath } = yield* ServerConfig;
205 yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
206
207 const configState = yield* Effect.gen(function* () {
208 const keybindings = yield* Keybindings;
209 return yield* keybindings.loadConfigState;
210 });
211
212 assert.deepEqual(
213 configState.keybindings,
214 compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS),
215 );
216 assert.deepEqual(configState.issues, [
217 {
218 kind: "keybindings.malformed-config",
219 message: configState.issues[0]?.message ?? "",
220 },
221 ]);
222 assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json");
223 }).pipe(Effect.provide(makeKeybindingsLayer())),
224 );
225
226 it.effect("ignores invalid entries in runtime and reports them as issues", () =>
227 Effect.gen(function* () {
228 const fs = yield* FileSystem.FileSystem;
229 const { keybindingsConfigPath } = yield* ServerConfig;
230 yield* fs.writeFileString(
231 keybindingsConfigPath,
232 JSON.stringify([
233 { key: "mod+j", command: "terminal.toggle" },
234 { key: "mod+shift+d+o", command: "terminal.new" },
235 { key: "mod+x", command: "invalid.command" },
236 ]),
237 );
238
239 const configState = yield* Effect.gen(function* () {
240 const keybindings = yield* Keybindings;
241 return yield* keybindings.loadConfigState;
242 });
243
244 assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
245 assert.isFalse(
246 configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
247 );
248 assert.deepEqual(configState.issues, [
249 {
250 kind: "keybindings.invalid-entry",
251 index: 1,
252 message: configState.issues[0]?.message ?? "",
253 },
254 {
255 kind: "keybindings.invalid-entry",
256 index: 2,
257 message: configState.issues[1]?.message ?? "",
258 },
259 ]);
260 }).pipe(Effect.provide(makeKeybindingsLayer())),
261 );
262
263 it.effect(
264 "upserts missing default keybindings on startup without overriding existing command rules",
265 () =>
266 Effect.gen(function* () {
267 const { keybindingsConfigPath } = yield* ServerConfig;
268 yield* writeKeybindingsConfig(keybindingsConfigPath, [
269 { key: "mod+shift+t", command: "terminal.toggle" },
270 { key: "mod+shift+r", command: "script.run-tests.run" },
271 ]);
272
273 yield* Effect.gen(function* () {
274 const keybindings = yield* Keybindings;
275 yield* keybindings.syncDefaultKeybindingsOnStartup;
276 });
277
278 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
279 const byCommand = new Map(persisted.map((entry) => [entry.command, entry]));
280
281 const persistedToggle = byCommand.get("terminal.toggle");
282 assert.isNotNull(persistedToggle);
283 assert.equal(persistedToggle?.key, "mod+shift+t");
284 assert.isFalse(
285 persisted.some((entry) => entry.command === "terminal.toggle" && entry.key === "mod+j"),
286 );
287
288 for (const defaultRule of DEFAULT_KEYBINDINGS) {
289 assert.isTrue(byCommand.has(defaultRule.command), `expected ${defaultRule.command}`);
290 }
291 assert.isTrue(byCommand.has("script.run-tests.run"));
292 }).pipe(Effect.provide(makeKeybindingsLayer())),
293 );
294
295 it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => {
296 const messages: string[] = [];
297 const logger = Logger.make(({ message }) => {
298 messages.push(String(message));
299 });
300
301 return Effect.gen(function* () {
302 const { keybindingsConfigPath } = yield* ServerConfig;
303 yield* writeKeybindingsConfig(keybindingsConfigPath, [
304 { key: "mod+j", command: "script.custom-action.run" },
305 ]);
306
307 yield* Effect.gen(function* () {
308 const keybindings = yield* Keybindings;
309 yield* keybindings.syncDefaultKeybindingsOnStartup;
310 });
311
312 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
313 assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle"));
314 assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run"));
315
316 assert.isTrue(
317 messages.some((message) =>
318 message.includes("skipping default keybinding due to shortcut conflict"),
319 ),
320 );
321 }).pipe(
322 Effect.provide(
323 Layer.mergeAll(
324 makeKeybindingsLayer(),
325 Logger.layer([logger], { mergeWithExisting: false }),
326 ),
327 ),
328 );
329 });
330
331 it.effect("upserts custom keybindings to configured path", () =>
332 Effect.gen(function* () {
333 const { keybindingsConfigPath } = yield* ServerConfig;
334 yield* writeKeybindingsConfig(keybindingsConfigPath, [
335 { key: "mod+j", command: "terminal.toggle" },
336 ]);
337
338 const resolved = yield* Effect.gen(function* () {
339 const keybindings = yield* Keybindings;
340 return yield* keybindings.upsertKeybindingRule({
341 key: "mod+shift+r",
342 command: "script.run-tests.run",
343 });
344 });
345
346 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
347 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
348
349 assert.deepEqual(persistedView, [
350 { key: "mod+j", command: "terminal.toggle" },
351 { key: "mod+shift+r", command: "script.run-tests.run" },
352 ]);
353 assert.isTrue(resolved.some((entry) => entry.command === "script.run-tests.run"));
354 }).pipe(Effect.provide(makeKeybindingsLayer())),
355 );
356
357 it.effect("replaces existing custom keybinding for the same command", () =>
358 Effect.gen(function* () {
359 const { keybindingsConfigPath } = yield* ServerConfig;
360 yield* writeKeybindingsConfig(keybindingsConfigPath, [
361 { key: "mod+r", command: "script.run-tests.run" },
362 ]);
363 yield* Effect.gen(function* () {
364 const keybindings = yield* Keybindings;
365 return yield* keybindings.upsertKeybindingRule({
366 key: "mod+shift+r",
367 command: "script.run-tests.run",
368 });
369 });
370
371 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
372 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
373 assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
374 }).pipe(Effect.provide(makeKeybindingsLayer())),
375 );
376
377 it.effect("refuses to overwrite malformed keybindings config", () =>
378 Effect.gen(function* () {
379 const fs = yield* FileSystem.FileSystem;
380 const { keybindingsConfigPath } = yield* ServerConfig;
381 yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
382
383 const result = yield* Effect.gen(function* () {
384 const keybindings = yield* Keybindings;
385 return yield* keybindings.upsertKeybindingRule({
386 key: "mod+shift+r",
387 command: "script.run-tests.run",
388 });
389 }).pipe(toDetailResult);
390 assertFailure(result, "expected JSON array");
391
392 const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
393 assert.equal(persistedRaw, "{ not-json");
394 }).pipe(Effect.provide(makeKeybindingsLayer())),
395 );
396
397 it.effect("reports non-array config parse errors without duplicate prefix", () =>
398 Effect.gen(function* () {
399 const fs = yield* FileSystem.FileSystem;
400 const { keybindingsConfigPath } = yield* ServerConfig;
401 yield* fs.writeFileString(
402 keybindingsConfigPath,
403 '{"key":"mod+j","command":"terminal.toggle"}',
404 );
405
406 const firstResult = yield* Effect.gen(function* () {
407 const keybindings = yield* Keybindings;
408 return yield* keybindings.upsertKeybindingRule({
409 key: "mod+shift+r",
410 command: "script.run-tests.run",
411 });
412 }).pipe(toDetailResult);
413 assertFailure(firstResult, "expected JSON array");
414
415 const secondResult = yield* Effect.gen(function* () {
416 const keybindings = yield* Keybindings;
417 return yield* keybindings.upsertKeybindingRule({
418 key: "mod+shift+r",
419 command: "script.run-tests.run",
420 });
421 }).pipe(toDetailResult);
422 assertFailure(secondResult, "expected JSON array");
423 }).pipe(Effect.provide(makeKeybindingsLayer())),
424 );
425
426 it.effect("fails when config directory is not writable", () =>
427 Effect.gen(function* () {
428 const fs = yield* FileSystem.FileSystem;
429 const { keybindingsConfigPath } = yield* ServerConfig;
430 const { dirname } = yield* Path.Path;
431 yield* writeKeybindingsConfig(keybindingsConfigPath, [
432 { key: "mod+j", command: "terminal.toggle" },
433 ]);
434 yield* fs.chmod(dirname(keybindingsConfigPath), 0o500);
435
436 const result = yield* Effect.gen(function* () {
437 const keybindings = yield* Keybindings;
438 return yield* keybindings.upsertKeybindingRule({
439 key: "mod+shift+r",
440 command: "script.run-tests.run",
441 });
442 }).pipe(toDetailResult);
443 assertFailure(result, "failed to write keybindings config");
444
445 yield* fs.chmod(dirname(keybindingsConfigPath), 0o700);
446
447 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
448 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
449 assert.deepEqual(persistedView, [{ key: "mod+j", command: "terminal.toggle" }]);
450 }).pipe(Effect.provide(makeKeybindingsLayer())),
451 );
452
453 it.effect("caches loaded resolved config across repeated reads", () =>
454 Effect.gen(function* () {
455 const { keybindingsConfigPath } = yield* ServerConfig;
456 yield* writeKeybindingsConfig(keybindingsConfigPath, [
457 { key: "mod+j", command: "terminal.toggle" },
458 ]);
459
460 const [first, second] = yield* Effect.gen(function* () {
461 const keybindings = yield* Keybindings;
462 const firstLoad = (yield* keybindings.loadConfigState).keybindings;
463 const secondLoad = (yield* keybindings.loadConfigState).keybindings;
464 return [firstLoad, secondLoad] as const;
465 });
466
467 assert.deepEqual(first, second);
468 assert.isTrue(second.some((entry) => entry.command === "terminal.toggle"));
469 }).pipe(Effect.provide(makeKeybindingsLayer())),
470 );
471
472 it.effect("updates cached resolved config after upsert", () =>
473 Effect.gen(function* () {
474 const { keybindingsConfigPath } = yield* ServerConfig;
475 yield* writeKeybindingsConfig(keybindingsConfigPath, [
476 { key: "mod+j", command: "terminal.toggle" },
477 ]);
478
479 const loadedAfterUpsert = yield* Effect.gen(function* () {
480 const keybindings = yield* Keybindings;
481 yield* keybindings.loadConfigState;
482 yield* keybindings.upsertKeybindingRule({
483 key: "mod+shift+r",
484 command: "script.run-tests.run",
485 });
486 return (yield* keybindings.loadConfigState).keybindings;
487 });
488
489 assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "script.run-tests.run"));
490 assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "terminal.toggle"));
491 }).pipe(Effect.provide(makeKeybindingsLayer())),
492 );
493
494 it.effect("serializes concurrent upserts to avoid lost updates", () =>
495 Effect.gen(function* () {
496 const { keybindingsConfigPath } = yield* ServerConfig;
497 yield* writeKeybindingsConfig(keybindingsConfigPath, []);
498
499 const commands = Array.from(
500 { length: 20 },
501 (_, index): KeybindingCommand => `script.concurrent-${index}.run`,
502 );
503 yield* Effect.gen(function* () {
504 const keybindings = yield* Keybindings;
505 yield* Effect.all(
506 commands.map((command, index) =>
507 keybindings.upsertKeybindingRule({
508 key: `mod+${String.fromCharCode(97 + index)}`,
509 command,
510 }),
511 ),
512 { concurrency: "unbounded", discard: true },
513 );
514 });
515
516 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
517 const persistedCommands = new Set(persisted.map((entry) => entry.command));
518 for (const command of commands) {
519 assert.isTrue(persistedCommands.has(command), `expected persisted command ${command}`);
520 }
521 }).pipe(Effect.provide(makeKeybindingsLayer())),
522 );
523});