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