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

keybindings.test.ts

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