Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.test.ts

855 lines33.8 KB

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