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 KeybindingsConfigError,
12 KeybindingsLive,
13 ResolvedKeybindingFromConfig,
14 compileResolvedKeybindingRule,
15 compileResolvedKeybindingsConfig,
16 parseKeybindingShortcut,
17} from "./keybindings";
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("uses defaults in runtime when config is malformed without overriding file", () =>
169 Effect.gen(function* () {
170 const fs = yield* FileSystem.FileSystem;
171 const { keybindingsConfigPath } = yield* ServerConfig;
172 yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
173
174 const configState = yield* Effect.gen(function* () {
175 const keybindings = yield* Keybindings;
176 return yield* keybindings.loadConfigState;
177 });
178
179 assert.deepEqual(
180 configState.keybindings,
181 compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS),
182 );
183 assert.deepEqual(configState.issues, [
184 {
185 kind: "keybindings.malformed-config",
186 message: configState.issues[0]?.message ?? "",
187 },
188 ]);
189 assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json");
190 }).pipe(Effect.provide(makeKeybindingsLayer())),
191 );
192
193 it.effect("ignores invalid entries in runtime and reports them as issues", () =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
196 const { keybindingsConfigPath } = yield* ServerConfig;
197 yield* fs.writeFileString(
198 keybindingsConfigPath,
199 JSON.stringify([
200 { key: "mod+j", command: "terminal.toggle" },
201 { key: "mod+shift+d+o", command: "terminal.new" },
202 { key: "mod+x", command: "invalid.command" },
203 ]),
204 );
205
206 const configState = yield* Effect.gen(function* () {
207 const keybindings = yield* Keybindings;
208 return yield* keybindings.loadConfigState;
209 });
210
211 assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
212 assert.isFalse(
213 configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
214 );
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});