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