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 * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Logger from "effect/Logger";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import * as ServerConfig from "./config.ts";
14import * as Keybindings from "./keybindings.ts";
15import * as SharedKeybindings from "@t3tools/shared/keybindings";
16import { KeybindingsConfigError, MAX_KEYBINDINGS_COUNT } from "@t3tools/contracts";
17
18const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
19const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson);
20const decodeKeybindingsConfigJson = Schema.decodeUnknownEffect(KeybindingsConfigJson);
21const layerKeybindings = () => {
22 return Keybindings.layer.pipe(
23 Layer.provideMerge(
24 Layer.fresh(
25 ServerConfig.layerTest(process.cwd(), {
26 prefix: "t3code-keybindings-test-",
27 }),
28 ),
29 ),
30 );
31};
32
33const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
34 effect.pipe(
35 Effect.mapError((error) => error.detail),
36 Effect.result,
37 );
38
39const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
40 Effect.gen(function* () {
41 const fileSystem = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43 const encoded = yield* encodeKeybindingsConfigJson(rules);
44 yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
45 yield* fileSystem.writeFileString(configPath, encoded);
46 });
47
48const readKeybindingsConfig = (configPath: string) =>
49 Effect.gen(function* () {
50 const fileSystem = yield* FileSystem.FileSystem;
51 const rawConfig = yield* fileSystem.readFileString(configPath);
52 return yield* decodeKeybindingsConfigJson(rawConfig);
53 });
54
55it.layer(NodeServices.layer)("keybindings", (it) => {
56 it.effect("parses shortcuts including plus key", () =>
57 Effect.sync(() => {
58 assert.deepEqual(SharedKeybindings.parseKeybindingShortcut("mod+j"), {
59 key: "j",
60 metaKey: false,
61 ctrlKey: false,
62 shiftKey: false,
63 altKey: false,
64 modKey: true,
65 });
66 assert.deepEqual(SharedKeybindings.parseKeybindingShortcut("mod++"), {
67 key: "+",
68 metaKey: false,
69 ctrlKey: false,
70 shiftKey: false,
71 altKey: false,
72 modKey: true,
73 });
74 }),
75 );
76
77 it.effect("compiles valid rule with parsed when AST", () =>
78 Effect.sync(() => {
79 const compiled = SharedKeybindings.compileResolvedKeybindingRule({
80 key: "mod+d",
81 command: "terminal.split",
82 when: "terminalOpen && !terminalFocus",
83 });
84
85 assert.deepEqual(compiled, {
86 command: "terminal.split",
87 shortcut: {
88 key: "d",
89 metaKey: false,
90 ctrlKey: false,
91 shiftKey: false,
92 altKey: false,
93 modKey: true,
94 },
95 whenAst: {
96 type: "and",
97 left: { type: "identifier", name: "terminalOpen" },
98 right: {
99 type: "not",
100 node: { type: "identifier", name: "terminalFocus" },
101 },
102 },
103 });
104 }),
105 );
106
107 it.effect("rejects invalid rules", () =>
108 Effect.sync(() => {
109 assert.isNull(
110 SharedKeybindings.compileResolvedKeybindingRule({
111 key: "mod+shift+d+o",
112 command: "terminal.new",
113 }),
114 );
115
116 assert.isNull(
117 SharedKeybindings.compileResolvedKeybindingRule({
118 key: "mod+d",
119 command: "terminal.split",
120 when: "terminalFocus && (",
121 }),
122 );
123
124 assert.isNull(
125 SharedKeybindings.compileResolvedKeybindingRule({
126 key: "mod+d",
127 command: "terminal.split",
128 when: `${"!".repeat(300)}terminalFocus`,
129 }),
130 );
131 }),
132 );
133
134 it.effect("bootstraps default keybindings when config file is missing", () =>
135 Effect.gen(function* () {
136 const fs = yield* FileSystem.FileSystem;
137 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
138 assert.isFalse(yield* fs.exists(keybindingsConfigPath));
139
140 yield* Effect.gen(function* () {
141 const keybindings = yield* Keybindings.Keybindings;
142 yield* keybindings.syncDefaultKeybindingsOnStartup;
143 });
144
145 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
146 assert.deepEqual(persisted, SharedKeybindings.DEFAULT_KEYBINDINGS);
147 }).pipe(Effect.provide(layerKeybindings())),
148 );
149
150 it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
151 Effect.gen(function* () {
152 const fs = yield* FileSystem.FileSystem;
153 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
154 yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
155
156 const configState = yield* Effect.gen(function* () {
157 const keybindings = yield* Keybindings.Keybindings;
158 return yield* keybindings.loadConfigState;
159 });
160
161 assert.deepEqual(
162 configState.keybindings,
163 SharedKeybindings.compileResolvedKeybindingsConfig(SharedKeybindings.DEFAULT_KEYBINDINGS),
164 );
165 assert.deepEqual(configState.issues, [
166 {
167 kind: "keybindings.malformed-config",
168 message: configState.issues[0]?.message ?? "",
169 },
170 ]);
171 assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json");
172 }).pipe(Effect.provide(layerKeybindings())),
173 );
174
175 it.effect("ignores invalid entries in runtime and reports them as issues", () =>
176 Effect.gen(function* () {
177 const fs = yield* FileSystem.FileSystem;
178 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
179 yield* fs.writeFileString(
180 keybindingsConfigPath,
181 JSON.stringify([
182 { key: "mod+j", command: "terminal.toggle" },
183 { key: "mod+shift+d+o", command: "terminal.new" },
184 { key: "mod+x", command: "invalid.command" },
185 { key: "mod+", command: "sidebar.toggle" },
186 { key: "mod+a+++", command: "sidebar.toggle" },
187 ]),
188 );
189
190 const configState = yield* Effect.gen(function* () {
191 const keybindings = yield* Keybindings.Keybindings;
192 return yield* keybindings.loadConfigState;
193 });
194
195 assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
196 assert.isFalse(
197 configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),
198 );
199 assert.deepEqual(configState.issues, [
200 {
201 kind: "keybindings.invalid-entry",
202 index: 1,
203 message: configState.issues[0]?.message ?? "",
204 },
205 {
206 kind: "keybindings.invalid-entry",
207 index: 2,
208 message: configState.issues[1]?.message ?? "",
209 },
210 {
211 kind: "keybindings.invalid-entry",
212 index: 3,
213 message: configState.issues[2]?.message ?? "",
214 },
215 {
216 kind: "keybindings.invalid-entry",
217 index: 4,
218 message: configState.issues[3]?.message ?? "",
219 },
220 ]);
221 }).pipe(Effect.provide(layerKeybindings())),
222 );
223
224 it.effect(
225 "upserts missing default keybindings on startup without overriding existing command rules",
226 () =>
227 Effect.gen(function* () {
228 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
229 yield* writeKeybindingsConfig(keybindingsConfigPath, [
230 { key: "mod+shift+y", command: "terminal.toggle" },
231 { key: "mod+shift+r", command: "script.run-tests.run" },
232 { key: "mod+shift+b", command: "script.custom-panel.run" },
233 {
234 key: "mod+shift+b",
235 command: "script.custom-composer.run",
236 when: "composerFocus",
237 },
238 ]);
239
240 const keybindings = yield* Keybindings.Keybindings;
241 yield* keybindings.syncDefaultKeybindingsOnStartup;
242
243 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
244 const byCommand = new Map(persisted.map((entry) => [entry.command, entry]));
245
246 const persistedToggle = byCommand.get("terminal.toggle");
247 assert.isNotNull(persistedToggle);
248 assert.equal(persistedToggle?.key, "mod+shift+y");
249 assert.isFalse(
250 persisted.some((entry) => entry.command === "terminal.toggle" && entry.key === "mod+j"),
251 );
252
253 for (const defaultRule of SharedKeybindings.DEFAULT_KEYBINDINGS) {
254 assert.isTrue(byCommand.has(defaultRule.command), `expected ${defaultRule.command}`);
255 }
256 assert.isTrue(byCommand.has("script.run-tests.run"));
257
258 const configState = yield* keybindings.loadConfigState;
259 assert.deepEqual(
260 configState.keybindings
261 .filter((entry) => entry.shortcut.key === "b" && entry.shortcut.shiftKey)
262 .map((entry) => entry.command),
263 ["threadPanel.toggle", "script.custom-panel.run", "script.custom-composer.run"],
264 );
265 }).pipe(Effect.provide(layerKeybindings())),
266 );
267
268 it.effect("adds a late default to an existing command once", () =>
269 Effect.gen(function* () {
270 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
271 const keybindings = yield* Keybindings.Keybindings;
272 const when = "composerFocus && draftThreadRoute";
273 const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const;
274 const backgroundRules = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) =>
275 rules.filter((entry) => entry.command === "composer.sendBackground"),
276 );
277 yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
278
279 yield* keybindings.syncDefaultKeybindingsOnStartup;
280 assert.deepStrictEqual(yield* backgroundRules, [
281 { key: "mod+enter", command: "composer.sendBackground", when },
282 existing,
283 ]);
284
285 yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
286 yield* keybindings.syncDefaultKeybindingsOnStartup;
287 assert.deepStrictEqual(yield* backgroundRules, [existing]);
288 }).pipe(Effect.provide(layerKeybindings())),
289 );
290
291 it.effect("leaves a customized command without the late default", () =>
292 Effect.gen(function* () {
293 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
294 const keybindings = yield* Keybindings.Keybindings;
295 const custom = {
296 key: "alt+b",
297 command: "composer.sendBackground",
298 when: "composerFocus && draftThreadRoute",
299 } as const;
300 yield* writeKeybindingsConfig(keybindingsConfigPath, [custom]);
301
302 yield* keybindings.syncDefaultKeybindingsOnStartup;
303 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
304 assert.deepStrictEqual(
305 persisted.filter((entry) => entry.command === "composer.sendBackground"),
306 [custom],
307 );
308 }).pipe(Effect.provide(layerKeybindings())),
309 );
310
311 it.effect("keeps a late default pending while the config is full", () =>
312 Effect.gen(function* () {
313 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
314 const keybindings = yield* Keybindings.Keybindings;
315 const when = "composerFocus && draftThreadRoute";
316 const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const;
317 const fillers = Array.from({ length: MAX_KEYBINDINGS_COUNT - 1 }, (_, index) => ({
318 key: "mod+alt+f1",
319 command: `script.filler-${index}.run` as const,
320 }));
321 const hasModEnter = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) =>
322 rules.some(
323 (entry) => entry.command === "composer.sendBackground" && entry.key === "mod+enter",
324 ),
325 );
326
327 yield* writeKeybindingsConfig(keybindingsConfigPath, [existing, ...fillers]);
328 yield* keybindings.syncDefaultKeybindingsOnStartup;
329 assert.isFalse(yield* hasModEnter);
330
331 yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
332 yield* keybindings.syncDefaultKeybindingsOnStartup;
333 assert.isTrue(yield* hasModEnter);
334 }).pipe(Effect.provide(layerKeybindings())),
335 );
336
337 it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => {
338 const messages: string[] = [];
339 const logger = Logger.make(({ message }) => {
340 messages.push(String(message));
341 });
342
343 return Effect.gen(function* () {
344 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
345 yield* writeKeybindingsConfig(keybindingsConfigPath, [
346 { key: "mod+j", command: "script.custom-action.run" },
347 ]);
348
349 yield* Effect.gen(function* () {
350 const keybindings = yield* Keybindings.Keybindings;
351 yield* keybindings.syncDefaultKeybindingsOnStartup;
352 });
353
354 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
355 assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle"));
356 assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run"));
357
358 assert.isTrue(
359 messages.some((message) =>
360 message.includes("skipping default keybinding due to shortcut conflict"),
361 ),
362 );
363 }).pipe(
364 Effect.provide(
365 Layer.mergeAll(layerKeybindings(), Logger.layer([logger], { mergeWithExisting: false })),
366 ),
367 );
368 });
369
370 it.effect("appends additional custom keybindings for the same command", () =>
371 Effect.gen(function* () {
372 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
373 yield* writeKeybindingsConfig(keybindingsConfigPath, [
374 { key: "mod+r", command: "script.run-tests.run" },
375 ]);
376 yield* Effect.gen(function* () {
377 const keybindings = yield* Keybindings.Keybindings;
378 return yield* keybindings.upsertKeybindingRule({
379 key: "mod+shift+r",
380 command: "script.run-tests.run",
381 });
382 });
383
384 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
385 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
386 assert.deepEqual(persistedView, [
387 { key: "mod+r", command: "script.run-tests.run" },
388 { key: "mod+shift+r", command: "script.run-tests.run" },
389 ]);
390 }).pipe(Effect.provide(layerKeybindings())),
391 );
392
393 it.effect("replaces only the targeted custom keybinding", () =>
394 Effect.gen(function* () {
395 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
396 yield* writeKeybindingsConfig(keybindingsConfigPath, [
397 { key: "mod+r", command: "script.run-tests.run" },
398 { key: "mod+shift+r", command: "script.run-tests.run" },
399 ]);
400 yield* Effect.gen(function* () {
401 const keybindings = yield* Keybindings.Keybindings;
402 return yield* keybindings.upsertKeybindingRule({
403 key: "mod+alt+r",
404 command: "script.run-tests.run",
405 replace: { key: "mod+r", command: "script.run-tests.run" },
406 });
407 });
408
409 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
410 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
411 assert.deepEqual(persistedView, [
412 { key: "mod+shift+r", command: "script.run-tests.run" },
413 { key: "mod+alt+r", command: "script.run-tests.run" },
414 ]);
415 }).pipe(Effect.provide(layerKeybindings())),
416 );
417
418 it.effect("replacing with a rule that already exists elsewhere does not duplicate it", () =>
419 Effect.gen(function* () {
420 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
421 yield* writeKeybindingsConfig(keybindingsConfigPath, [
422 { key: "mod+r", command: "script.run-tests.run" },
423 { key: "mod+alt+r", command: "script.run-tests.run" },
424 ]);
425 yield* Effect.gen(function* () {
426 const keybindings = yield* Keybindings.Keybindings;
427 return yield* keybindings.upsertKeybindingRule({
428 key: "mod+alt+r",
429 command: "script.run-tests.run",
430 replace: { key: "mod+r", command: "script.run-tests.run" },
431 });
432 });
433
434 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
435 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
436 assert.deepEqual(persistedView, [{ key: "mod+alt+r", command: "script.run-tests.run" }]);
437 }).pipe(Effect.provide(layerKeybindings())),
438 );
439
440 it.effect("removes only the targeted custom keybinding", () =>
441 Effect.gen(function* () {
442 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
443 yield* writeKeybindingsConfig(keybindingsConfigPath, [
444 { key: "mod+r", command: "script.run-tests.run" },
445 { key: "mod+shift+r", command: "script.run-tests.run" },
446 ]);
447 yield* Effect.gen(function* () {
448 const keybindings = yield* Keybindings.Keybindings;
449 return yield* keybindings.removeKeybindingRule({
450 key: "mod+r",
451 command: "script.run-tests.run",
452 });
453 });
454
455 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
456 const persistedView = persisted.map(({ key, command }) => ({ key, command }));
457 assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
458 }).pipe(Effect.provide(layerKeybindings())),
459 );
460
461 it.effect("preserves sibling shortcuts when editing an inherited shortcut", () =>
462 Effect.gen(function* () {
463 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
464 const keybindings = yield* Keybindings.Keybindings;
465 const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const;
466 const sibling = { ...target, key: "mod+n" };
467 const unrelated = { ...sibling, command: "threadPanel.toggle" } as const;
468 yield* writeKeybindingsConfig(keybindingsConfigPath, [unrelated]);
469
470 const replacement = { ...target, key: "f8" };
471 const saved = yield* keybindings.upsertKeybindingRule({
472 ...replacement,
473 replace: { ...target, key: "Shift+Mod+O", when: "!(terminalFocus)" },
474 });
475 const relevant = (rule: (typeof saved.keybindings)[number]) =>
476 rule.command === target.command || rule.command === unrelated.command;
477 const expected = SharedKeybindings.compileResolvedKeybindingsConfig([
478 sibling,
479 unrelated,
480 replacement,
481 ]);
482 assert.deepEqual(saved.keybindings.filter(relevant), expected);
483
484 yield* keybindings.syncDefaultKeybindingsOnStartup;
485 const snapshot = yield* keybindings.getSnapshot;
486 assert.deepEqual(snapshot.keybindings.filter(relevant), expected);
487 }).pipe(Effect.provide(layerKeybindings())),
488 );
489
490 it.effect("preserves sibling shortcuts when adding to an inherited command", () =>
491 Effect.gen(function* () {
492 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
493 const keybindings = yield* Keybindings.Keybindings;
494 yield* writeKeybindingsConfig(keybindingsConfigPath, []);
495
496 const added = { key: "f9", command: "chat.new" } as const;
497 const saved = yield* keybindings.upsertKeybindingRule(added);
498 assert.deepEqual(
499 saved.keybindings.filter((rule) => rule.command === added.command),
500 SharedKeybindings.compileResolvedKeybindingsConfig([
501 { key: "mod+n", command: added.command, when: "!terminalFocus" },
502 { key: "mod+shift+o", command: added.command, when: "!terminalFocus" },
503 added,
504 ]),
505 );
506 }).pipe(Effect.provide(layerKeybindings())),
507 );
508
509 it.effect("preserves sibling shortcuts by rejecting an edit that would evict saved rules", () =>
510 Effect.gen(function* () {
511 const fs = yield* FileSystem.FileSystem;
512 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
513 const keybindings = yield* Keybindings.Keybindings;
514 const original = JSON.stringify([
515 { key: "f7", command: "terminal.new" },
516 ...Array.from({ length: MAX_KEYBINDINGS_COUNT - 2 }, (_, index) => ({
517 key: "f1",
518 command: `future.command-${index}`,
519 })),
520 ]);
521 yield* fs.writeFileString(keybindingsConfigPath, original);
522
523 const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const;
524 const result = yield* toDetailResult(
525 keybindings.upsertKeybindingRule({ ...target, key: "f8", replace: target }),
526 );
527 assertFailure(result, "Not enough room to save this shortcut and its inherited shortcuts.");
528 assert.equal(yield* fs.readFileString(keybindingsConfigPath), original);
529 }).pipe(Effect.provide(layerKeybindings())),
530 );
531
532 it.effect("preserves sibling shortcuts only if visible within the binding limit", () =>
533 Effect.gen(function* () {
534 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
535 const keybindings = yield* Keybindings.Keybindings;
536 yield* writeKeybindingsConfig(
537 keybindingsConfigPath,
538 Array.from({ length: 210 }, (_, index) => ({
539 key: "mod+alt+f1",
540 command: `script.filler-${index}.run` as const,
541 })),
542 );
543
544 const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const;
545 const local = { ...target, key: "mod+shift+n", command: "chat.newLocal" } as const;
546 const relevant = (rule: { readonly command: KeybindingCommand }) =>
547 rule.command === target.command || rule.command === local.command;
548 const before = yield* keybindings.getSnapshot;
549 assert.deepEqual(
550 before.keybindings.filter(relevant),
551 SharedKeybindings.compileResolvedKeybindingsConfig([target, local]),
552 );
553
554 const replacement = { ...target, key: "f8" };
555 const saved = yield* keybindings.upsertKeybindingRule({ ...replacement, replace: target });
556 assert.deepEqual(
557 saved.keybindings.filter(relevant),
558 SharedKeybindings.compileResolvedKeybindingsConfig([local, replacement]),
559 );
560 }).pipe(Effect.provide(layerKeybindings())),
561 );
562
563 it.effect(
564 "preserves sibling shortcuts when an inherited edit target has since become hidden",
565 () =>
566 Effect.gen(function* () {
567 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
568 const keybindings = yield* Keybindings.Keybindings;
569 yield* writeKeybindingsConfig(
570 keybindingsConfigPath,
571 Array.from({ length: 209 }, (_, index) => ({
572 key: "mod+alt+f1",
573 command: `script.filler-${index}.run` as const,
574 })),
575 );
576
577 const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const;
578 const sibling = { ...target, key: "mod+shift+o" };
579 const isChatNew = (binding: { readonly command: KeybindingCommand }) =>
580 binding.command === target.command;
581 const before = yield* keybindings.getSnapshot;
582 assert.deepEqual(
583 before.keybindings.filter(isChatNew),
584 SharedKeybindings.compileResolvedKeybindingsConfig([target, sibling]),
585 );
586
587 const afterUnrelatedSave = yield* keybindings.upsertKeybindingRule({
588 key: "mod+alt+f1",
589 command: "script.extra.run",
590 });
591 assert.deepEqual(
592 afterUnrelatedSave.keybindings.filter(isChatNew),
593 SharedKeybindings.compileResolvedKeybindingsConfig([sibling]),
594 );
595
596 const replacement = { ...target, key: "f8" };
597 const saved = yield* keybindings.upsertKeybindingRule({ ...replacement, replace: target });
598 assert.deepEqual(
599 saved.keybindings.filter(isChatNew),
600 SharedKeybindings.compileResolvedKeybindingsConfig([sibling, replacement]),
601 );
602 }).pipe(Effect.provide(layerKeybindings())),
603 );
604
605 it.effect("unassigns a shortcut without restoring it on startup and can reassign it", () =>
606 Effect.gen(function* () {
607 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
608 yield* writeKeybindingsConfig(keybindingsConfigPath, []);
609 const keybindings = yield* Keybindings.Keybindings;
610 const target = SharedKeybindings.DEFAULT_KEYBINDINGS.find(
611 (rule) => rule.command === "composer.sendBackground",
612 )!;
613 const siblings = SharedKeybindings.DEFAULT_KEYBINDINGS.filter(
614 (rule) => rule.command === target.command && rule !== target,
615 );
616 const removed = yield* keybindings.upsertKeybindingRule({
617 ...target,
618 when: "false",
619 replace: target,
620 });
621 const expected = SharedKeybindings.compileResolvedKeybindingsConfig([
622 ...siblings,
623 { ...target, when: "false" },
624 ]);
625 assert.deepEqual(
626 removed.keybindings.filter((rule) => rule.command === target.command),
627 expected,
628 );
629 yield* keybindings.syncDefaultKeybindingsOnStartup;
630 const snapshot = yield* keybindings.getSnapshot;
631 assert.deepEqual(
632 snapshot.keybindings.filter((rule) => rule.command === target.command),
633 expected,
634 );
635 const restored = yield* keybindings.upsertKeybindingRule({
636 ...target,
637 replace: { ...target, when: "false" },
638 });
639 assert.deepEqual(
640 restored.keybindings.filter((rule) => rule.command === target.command),
641 SharedKeybindings.compileResolvedKeybindingsConfig([...siblings, target]),
642 );
643 }).pipe(Effect.provide(layerKeybindings())),
644 );
645
646 it.effect("keeps entries it cannot decode when editing other keybindings", () =>
647 Effect.gen(function* () {
648 const fs = yield* FileSystem.FileSystem;
649 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
650 const futureCommand = { key: "mod+shift+k", command: "command.from-a-newer-build" };
651 const badShortcut = { key: "mod+shift+d+o", command: "terminal.new" };
652 yield* fs.writeFileString(
653 keybindingsConfigPath,
654 JSON.stringify([
655 { key: "mod+r", command: "script.run-tests.run" },
656 futureCommand,
657 badShortcut,
658 ]),
659 );
660 const keybindings = yield* Keybindings.Keybindings;
661 const persisted = Effect.map(fs.readFileString(keybindingsConfigPath), JSON.parse);
662
663 const saved = yield* keybindings.upsertKeybindingRule({
664 key: "mod+shift+r",
665 command: "script.run-tests.run",
666 });
667 assert.equal(saved.issues.length, 2);
668 assert.deepEqual(yield* persisted, [
669 { key: "mod+r", command: "script.run-tests.run" },
670 futureCommand,
671 badShortcut,
672 { key: "mod+shift+r", command: "script.run-tests.run" },
673 ]);
674
675 const removed = yield* keybindings.removeKeybindingRule({
676 key: "mod+r",
677 command: "script.run-tests.run",
678 });
679 assert.deepEqual(yield* persisted, [
680 futureCommand,
681 badShortcut,
682 { key: "mod+shift+r", command: "script.run-tests.run" },
683 ]);
684 const { issues } = yield* keybindings.loadConfigState;
685 assert.deepEqual(removed.issues, issues);
686 assert.deepEqual(
687 issues.map((issue) => issue.kind === "keybindings.invalid-entry" && issue.index),
688 [0, 1],
689 );
690 }).pipe(Effect.provide(layerKeybindings())),
691 );
692
693 it.effect("removes a hand-written keybinding targeted by its settings spelling", () =>
694 Effect.gen(function* () {
695 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
696 yield* writeKeybindingsConfig(keybindingsConfigPath, [
697 {
698 key: "Shift+Cmd+R",
699 command: "script.run-tests.run",
700 when: "terminalFocus&&!previewFocus",
701 },
702 { key: "mod+shift+r", command: "script.run-tests.run" },
703 { key: "x\u0000true", command: "script.run-tests.run" },
704 { key: "x", command: "script.run-tests.run", when: "true" },
705 ]);
706 yield* Effect.gen(function* () {
707 const keybindings = yield* Keybindings.Keybindings;
708 yield* keybindings.removeKeybindingRule({
709 key: "meta+shift+r",
710 command: "script.run-tests.run",
711 when: "terminalFocus && !previewFocus",
712 });
713 yield* keybindings.removeKeybindingRule({
714 key: "x",
715 command: "script.run-tests.run",
716 when: "true",
717 });
718 });
719
720 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
721 assert.deepEqual(persisted, [
722 { key: "mod+shift+r", command: "script.run-tests.run" },
723 { key: "x\u0000true", command: "script.run-tests.run" },
724 ]);
725 }).pipe(Effect.provide(layerKeybindings())),
726 );
727
728 it.effect("replaces a hand-written keybinding targeted by its settings spelling", () =>
729 Effect.gen(function* () {
730 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
731 yield* writeKeybindingsConfig(keybindingsConfigPath, [
732 { key: "escape", command: "script.run-tests.run", when: "a && b && c" },
733 ]);
734 yield* Effect.gen(function* () {
735 const keybindings = yield* Keybindings.Keybindings;
736 return yield* keybindings.upsertKeybindingRule({
737 key: "mod+alt+r",
738 command: "script.run-tests.run",
739 replace: { key: "esc", command: "script.run-tests.run", when: "(a && b) && c" },
740 });
741 });
742
743 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
744 assert.deepEqual(persisted, [{ key: "mod+alt+r", command: "script.run-tests.run" }]);
745 }).pipe(Effect.provide(layerKeybindings())),
746 );
747
748 it.effect("refuses to overwrite malformed keybindings config", () =>
749 Effect.gen(function* () {
750 const fs = yield* FileSystem.FileSystem;
751 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
752 yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
753
754 const result = yield* Effect.gen(function* () {
755 const keybindings = yield* Keybindings.Keybindings;
756 return yield* keybindings.upsertKeybindingRule({
757 key: "mod+shift+r",
758 command: "script.run-tests.run",
759 });
760 }).pipe(toDetailResult);
761 assertFailure(result, "expected JSON array");
762
763 const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
764 assert.equal(persistedRaw, "{ not-json");
765 }).pipe(Effect.provide(layerKeybindings())),
766 );
767
768 it.effect("retries a failed config read instead of keeping the failure", () =>
769 Effect.gen(function* () {
770 const fileSystem = yield* FileSystem.FileSystem;
771 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
772 yield* fileSystem.makeDirectory(keybindingsConfigPath, { recursive: true });
773
774 const keybindings = yield* Keybindings.Keybindings;
775 const failed = yield* toDetailResult(keybindings.loadConfigState);
776 assertFailure(failed, "failed to read keybindings config");
777
778 yield* fileSystem.remove(keybindingsConfigPath, { recursive: true });
779 yield* writeKeybindingsConfig(keybindingsConfigPath, [
780 { key: "mod+j", command: "terminal.toggle" },
781 ]);
782
783 const configState = yield* keybindings.loadConfigState;
784 assert.deepEqual(configState.issues, []);
785 assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
786 }).pipe(Effect.provide(layerKeybindings())),
787 );
788
789 it.effect("serializes concurrent upserts to avoid lost updates", () =>
790 Effect.gen(function* () {
791 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
792 yield* writeKeybindingsConfig(keybindingsConfigPath, []);
793
794 const commands = Array.from(
795 { length: 20 },
796 (_, index): KeybindingCommand => `script.concurrent-${index}.run`,
797 );
798 yield* Effect.gen(function* () {
799 const keybindings = yield* Keybindings.Keybindings;
800 yield* Effect.forEach(
801 commands,
802 (command, index) =>
803 keybindings.upsertKeybindingRule({
804 key: `mod+${String.fromCharCode(97 + index)}`,
805 command,
806 }),
807 { concurrency: "unbounded", discard: true },
808 );
809 });
810
811 const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
812 const persistedCommands = new Set(persisted.map((entry) => entry.command));
813 for (const command of commands) {
814 assert.isTrue(persistedCommands.has(command), `expected persisted command ${command}`);
815 }
816 }).pipe(Effect.provide(layerKeybindings())),
817 );
818
819 it.effect(
820 "suppresses change emission when revalidating unchanged keybindings configuration",
821 () =>
822 Effect.gen(function* () {
823 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
824 yield* writeKeybindingsConfig(keybindingsConfigPath, [
825 { key: "mod+j", command: "terminal.toggle" },
826 ]);
827
828 const keybindings = yield* Keybindings.Keybindings;
829 yield* keybindings.start;
830
831 const changes = yield* keybindings.subscribeChanges;
832
833 // Revalidate when config on disk has not changed (e.g. atime bump on Windows).
834 // `revalidate` publishes before it returns, so a wrongly emitted event would be
835 // buffered in the subscription ahead of the real change observed below.
836 yield* keybindings.revalidate;
837
838 yield* writeKeybindingsConfig(keybindingsConfigPath, [
839 { key: "mod+j", command: "terminal.toggle" },
840 { key: "mod+k", command: "threadPanel.toggle" },
841 ]);
842 yield* keybindings.revalidate;
843
844 // The first buffered event must be the real change, not the unchanged state.
845 const change = Option.getOrThrow(yield* Stream.runHead(changes));
846 assert.isTrue(
847 change.keybindings.some(
848 (rule) =>
849 rule.command === "threadPanel.toggle" &&
850 rule.shortcut.key === "k" &&
851 rule.shortcut.modKey,
852 ),
853 );
854 }).pipe(Effect.scoped, Effect.provide(layerKeybindings())),
855 );
856});