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

keybindings.test.ts

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