Open History to see the last commit
1/**
2 * Keybindings - Keybinding configuration service definitions.
3 *
4 * Owns parsing, validation, merge, and persistence of user keybinding
5 * configuration consumed by the server runtime.
6 *
7 * @module Keybindings
8 */
9import {
10 KeybindingRule,
11 KeybindingsConfig,
12 KeybindingsConfigError,
13 KeybindingShortcut,
14 KeybindingWhenNode,
15 MAX_KEYBINDINGS_COUNT,
16 MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
17 MAX_WHEN_EXPRESSION_DEPTH,
18 ResolvedKeybindingRule,
19 ResolvedKeybindingsConfig,
20 THREAD_JUMP_KEYBINDING_COMMANDS,
21 type ServerConfigIssue,
22} from "@t3tools/contracts";
23import type { Mutable } from "effect/Types";
24import {
25 Array,
26 Cache,
27 Cause,
28 Deferred,
29 Duration,
30 Effect,
31 Exit,
32 FileSystem,
33 Path,
34 Layer,
35 Option,
36 Predicate,
37 PubSub,
38 Schema,
39 SchemaGetter,
40 SchemaIssue,
41 SchemaTransformation,
42 Ref,
43 Context,
44 Scope,
45 Stream,
46} from "effect";
47import * as Semaphore from "effect/Semaphore";
48import { ServerConfig } from "./config.ts";
49import { writeFileStringAtomically } from "./atomicWrite.ts";
50import { fromLenientJson } from "@t3tools/shared/schemaJson";
51
52type WhenToken =
53 | { type: "identifier"; value: string }
54 | { type: "not" }
55 | { type: "and" }
56 | { type: "or" }
57 | { type: "lparen" }
58 | { type: "rparen" };
59
60export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
61 { key: "mod+j", command: "terminal.toggle" },
62 { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
63 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
64 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
65 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
66 { key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
67 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
68 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
69 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
70 { key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },
71 { key: "mod+o", command: "editor.openFavorite" },
72 { key: "mod+shift+[", command: "thread.previous" },
73 { key: "mod+shift+]", command: "thread.next" },
74 ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
75 key: `mod+${index + 1}`,
76 command,
77 })),
78 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
79 key: `mod+${index + 1}`,
80 command,
81 when: "modelPickerOpen",
82 })),
83];
84
85function normalizeKeyToken(token: string): string {
86 if (token === "space") return " ";
87 if (token === "esc") return "escape";
88 return token;
89}
90
91/** @internal - Exported for testing */
92export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
93 const rawTokens = value
94 .toLowerCase()
95 .split("+")
96 .map((token) => token.trim());
97 const tokens = [...rawTokens];
98 let trailingEmptyCount = 0;
99 while (tokens[tokens.length - 1] === "") {
100 trailingEmptyCount += 1;
101 tokens.pop();
102 }
103 if (trailingEmptyCount > 0) {
104 tokens.push("+");
105 }
106 if (tokens.some((token) => token.length === 0)) {
107 return null;
108 }
109 if (tokens.length === 0) return null;
110
111 let key: string | null = null;
112 let metaKey = false;
113 let ctrlKey = false;
114 let shiftKey = false;
115 let altKey = false;
116 let modKey = false;
117
118 for (const token of tokens) {
119 switch (token) {
120 case "cmd":
121 case "meta":
122 metaKey = true;
123 break;
124 case "ctrl":
125 case "control":
126 ctrlKey = true;
127 break;
128 case "shift":
129 shiftKey = true;
130 break;
131 case "alt":
132 case "option":
133 altKey = true;
134 break;
135 case "mod":
136 modKey = true;
137 break;
138 default: {
139 if (key !== null) return null;
140 key = normalizeKeyToken(token);
141 }
142 }
143 }
144
145 if (key === null) return null;
146 return {
147 key,
148 metaKey,
149 ctrlKey,
150 shiftKey,
151 altKey,
152 modKey,
153 };
154}
155
156function tokenizeWhenExpression(expression: string): WhenToken[] | null {
157 const tokens: WhenToken[] = [];
158 let index = 0;
159
160 while (index < expression.length) {
161 const current = expression[index];
162 if (!current) break;
163
164 if (/\s/.test(current)) {
165 index += 1;
166 continue;
167 }
168 if (expression.startsWith("&&", index)) {
169 tokens.push({ type: "and" });
170 index += 2;
171 continue;
172 }
173 if (expression.startsWith("||", index)) {
174 tokens.push({ type: "or" });
175 index += 2;
176 continue;
177 }
178 if (current === "!") {
179 tokens.push({ type: "not" });
180 index += 1;
181 continue;
182 }
183 if (current === "(") {
184 tokens.push({ type: "lparen" });
185 index += 1;
186 continue;
187 }
188 if (current === ")") {
189 tokens.push({ type: "rparen" });
190 index += 1;
191 continue;
192 }
193
194 const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
195 if (!identifier) {
196 return null;
197 }
198 tokens.push({ type: "identifier", value: identifier[0] });
199 index += identifier[0].length;
200 }
201
202 return tokens;
203}
204
205function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
206 const tokens = tokenizeWhenExpression(expression);
207 if (!tokens || tokens.length === 0) return null;
208 let index = 0;
209
210 const parsePrimary = (depth: number): KeybindingWhenNode | null => {
211 if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
212 return null;
213 }
214 const token = tokens[index];
215 if (!token) return null;
216
217 if (token.type === "identifier") {
218 index += 1;
219 return { type: "identifier", name: token.value };
220 }
221
222 if (token.type === "lparen") {
223 index += 1;
224 const expressionNode = parseOr(depth + 1);
225 const closeToken = tokens[index];
226 if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
227 return null;
228 }
229 index += 1;
230 return expressionNode;
231 }
232
233 return null;
234 };
235
236 const parseUnary = (depth: number): KeybindingWhenNode | null => {
237 let notCount = 0;
238 while (tokens[index]?.type === "not") {
239 index += 1;
240 notCount += 1;
241 if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
242 return null;
243 }
244 }
245
246 let node = parsePrimary(depth);
247 if (!node) return null;
248
249 while (notCount > 0) {
250 node = { type: "not", node };
251 notCount -= 1;
252 }
253
254 return node;
255 };
256
257 const parseAnd = (depth: number): KeybindingWhenNode | null => {
258 let left = parseUnary(depth);
259 if (!left) return null;
260
261 while (tokens[index]?.type === "and") {
262 index += 1;
263 const right = parseUnary(depth);
264 if (!right) return null;
265 left = { type: "and", left, right };
266 }
267
268 return left;
269 };
270
271 const parseOr = (depth: number): KeybindingWhenNode | null => {
272 let left = parseAnd(depth);
273 if (!left) return null;
274
275 while (tokens[index]?.type === "or") {
276 index += 1;
277 const right = parseAnd(depth);
278 if (!right) return null;
279 left = { type: "or", left, right };
280 }
281
282 return left;
283 };
284
285 const ast = parseOr(0);
286 if (!ast || index !== tokens.length) return null;
287 return ast;
288}
289
290/** @internal - Exported for testing */
291export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
292 const shortcut = parseKeybindingShortcut(rule.key);
293 if (!shortcut) return null;
294
295 if (rule.when !== undefined) {
296 const whenAst = parseKeybindingWhenExpression(rule.when);
297 if (!whenAst) return null;
298 return {
299 command: rule.command,
300 shortcut,
301 whenAst,
302 };
303 }
304
305 return {
306 command: rule.command,
307 shortcut,
308 };
309}
310
311export function compileResolvedKeybindingsConfig(
312 config: KeybindingsConfig,
313): ResolvedKeybindingsConfig {
314 const compiled: Mutable<ResolvedKeybindingsConfig> = [];
315 for (const rule of config) {
316 const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule);
317 if (result._tag === "Success") {
318 compiled.push(result.value);
319 }
320 }
321 return compiled;
322}
323
324export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
325 Schema.decodeTo(
326 Schema.toType(ResolvedKeybindingRule),
327 SchemaTransformation.transformOrFail({
328 decode: (rule) =>
329 Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(
330 Effect.filterOrFail(
331 Predicate.isNotNull,
332 () =>
333 new SchemaIssue.InvalidValue(Option.some(rule), {
334 message: "Invalid keybinding rule",
335 }),
336 ),
337 Effect.map((resolved) => resolved),
338 ),
339
340 encode: (resolved) =>
341 Effect.gen(function* () {
342 const key = encodeShortcut(resolved.shortcut);
343 if (!key) {
344 return yield* Effect.fail(
345 new SchemaIssue.InvalidValue(Option.some(resolved), {
346 message: "Resolved shortcut cannot be encoded to key string",
347 }),
348 );
349 }
350
351 const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
352 return {
353 key,
354 command: resolved.command,
355 when,
356 };
357 }),
358 }),
359 ),
360);
361
362export const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check(
363 Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
364);
365
366function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {
367 return (
368 left.command === right.command &&
369 left.key === right.key &&
370 (left.when ?? undefined) === (right.when ?? undefined)
371 );
372}
373
374function keybindingShortcutContext(rule: KeybindingRule): string | null {
375 const parsed = parseKeybindingShortcut(rule.key);
376 if (!parsed) return null;
377 const encoded = encodeShortcut(parsed);
378 if (!encoded) return null;
379 return `${encoded}\u0000${rule.when ?? ""}`;
380}
381
382function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean {
383 const leftContext = keybindingShortcutContext(left);
384 const rightContext = keybindingShortcutContext(right);
385 if (!leftContext || !rightContext) return false;
386 return leftContext === rightContext;
387}
388
389function encodeShortcut(shortcut: KeybindingShortcut): string | null {
390 const modifiers: string[] = [];
391 if (shortcut.modKey) modifiers.push("mod");
392 if (shortcut.metaKey) modifiers.push("meta");
393 if (shortcut.ctrlKey) modifiers.push("ctrl");
394 if (shortcut.altKey) modifiers.push("alt");
395 if (shortcut.shiftKey) modifiers.push("shift");
396 if (!shortcut.key) return null;
397 if (shortcut.key !== "+" && shortcut.key.includes("+")) return null;
398 const key = shortcut.key === " " ? "space" : shortcut.key;
399 return [...modifiers, key].join("+");
400}
401
402function encodeWhenAst(node: KeybindingWhenNode): string {
403 switch (node.type) {
404 case "identifier":
405 return node.name;
406 case "not":
407 return `!(${encodeWhenAst(node.node)})`;
408 case "and":
409 return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;
410 case "or":
411 return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;
412 }
413}
414
415const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
416
417const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
418const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
419const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
420 SchemaGetter.stringifyJson({ space: 2 }),
421);
422const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
423 Schema.encode({
424 decode: PrettyJsonString,
425 encode: PrettyJsonString,
426 }),
427);
428
429export interface KeybindingsConfigState {
430 readonly keybindings: ResolvedKeybindingsConfig;
431 readonly issues: readonly ServerConfigIssue[];
432}
433
434export interface KeybindingsChangeEvent {
435 readonly keybindings: ResolvedKeybindingsConfig;
436 readonly issues: readonly ServerConfigIssue[];
437}
438
439function trimIssueMessage(message: string): string {
440 const trimmed = message.trim();
441 return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
442}
443
444function malformedConfigIssue(detail: string): ServerConfigIssue {
445 return {
446 kind: "keybindings.malformed-config",
447 message: trimIssueMessage(detail),
448 };
449}
450
451function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
452 return {
453 kind: "keybindings.invalid-entry",
454 index,
455 message: trimIssueMessage(detail),
456 };
457}
458
459function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
460 if (custom.length === 0) {
461 return [...DEFAULT_RESOLVED_KEYBINDINGS];
462 }
463
464 const overriddenCommands = new Set(custom.map((binding) => binding.command));
465 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
466 (binding) => !overriddenCommands.has(binding.command),
467 );
468 const merged = [...retainedDefaults, ...custom];
469
470 if (merged.length <= MAX_KEYBINDINGS_COUNT) {
471 return merged;
472 }
473
474 // Keep the latest rules when the config exceeds max size; later rules have higher precedence.
475 return merged.slice(-MAX_KEYBINDINGS_COUNT);
476}
477
478/**
479 * KeybindingsShape - Service API for keybinding configuration operations.
480 */
481export interface KeybindingsShape {
482 /**
483 * Start the keybindings runtime and attach file watching.
484 *
485 * Safe to call multiple times. The first successful call establishes the
486 * runtime; later calls await the same startup.
487 */
488 readonly start: Effect.Effect<void, KeybindingsConfigError>;
489
490 /**
491 * Await keybindings runtime readiness.
492 *
493 * Readiness means the config directory exists, the watcher is attached, the
494 * startup sync has completed, and the current snapshot has been loaded.
495 */
496 readonly ready: Effect.Effect<void, KeybindingsConfigError>;
497
498 /**
499 * Ensure the on-disk keybindings file exists and includes all default
500 * commands so newly-added defaults are backfilled on startup.
501 */
502 readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
503
504 /**
505 * Load runtime keybindings state along with non-fatal configuration issues.
506 */
507 readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
508
509 /**
510 * Read the latest keybindings snapshot from cache/disk.
511 */
512 readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
513
514 /**
515 * Stream of keybindings config change events.
516 */
517 readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
518
519 /**
520 * Upsert a keybinding rule and persist the resulting configuration.
521 *
522 * Writes config atomically and enforces the max rule count by truncating
523 * oldest entries when needed.
524 */
525 readonly upsertKeybindingRule: (
526 rule: KeybindingRule,
527 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
528}
529
530/**
531 * Keybindings - Service tag for keybinding configuration operations.
532 */
533export class Keybindings extends Context.Service<Keybindings, KeybindingsShape>()(
534 "t3/keybindings",
535) {}
536
537const makeKeybindings = Effect.gen(function* () {
538 const { keybindingsConfigPath } = yield* ServerConfig;
539 const fs = yield* FileSystem.FileSystem;
540 const path = yield* Path.Path;
541 const upsertSemaphore = yield* Semaphore.make(1);
542 const resolvedConfigCacheKey = "resolved" as const;
543 const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
544 const startedRef = yield* Ref.make(false);
545 const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
546 const watcherScope = yield* Scope.make("sequential");
547 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
548 const emitChange = (configState: KeybindingsConfigState) =>
549 PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
550
551 const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
552 Effect.mapError(
553 (cause) =>
554 new KeybindingsConfigError({
555 configPath: keybindingsConfigPath,
556 detail: "failed to access keybindings config",
557 cause,
558 }),
559 ),
560 );
561
562 const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
563 Effect.mapError(
564 (cause) =>
565 new KeybindingsConfigError({
566 configPath: keybindingsConfigPath,
567 detail: "failed to read keybindings config",
568 cause,
569 }),
570 ),
571 );
572
573 const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
574 readonly KeybindingRule[],
575 KeybindingsConfigError
576 > {
577 if (!(yield* readConfigExists)) {
578 return [];
579 }
580
581 const rawConfig = yield* readRawConfig.pipe(
582 Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
583 Effect.mapError(
584 (cause) =>
585 new KeybindingsConfigError({
586 configPath: keybindingsConfigPath,
587 detail: "expected JSON array",
588 cause,
589 }),
590 ),
591 );
592
593 return yield* Effect.forEach(rawConfig, (entry) =>
594 Effect.gen(function* () {
595 const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
596 if (decodedRule._tag === "Failure") {
597 yield* Effect.logWarning("ignoring invalid keybinding entry", {
598 path: keybindingsConfigPath,
599 entry,
600 error: Cause.pretty(decodedRule.cause),
601 });
602 return null;
603 }
604 const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
605 if (resolved._tag === "Failure") {
606 yield* Effect.logWarning("ignoring invalid keybinding entry", {
607 path: keybindingsConfigPath,
608 entry,
609 error: Cause.pretty(resolved.cause),
610 });
611 return null;
612 }
613 return decodedRule.value;
614 }),
615 ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
616 });
617
618 const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
619 {
620 readonly keybindings: readonly KeybindingRule[];
621 readonly issues: readonly ServerConfigIssue[];
622 },
623 KeybindingsConfigError
624 > {
625 if (!(yield* readConfigExists)) {
626 return { keybindings: [], issues: [] };
627 }
628
629 const rawConfig = yield* readRawConfig;
630 const decodedEntries = Schema.decodeUnknownExit(RawKeybindingsEntries)(rawConfig);
631 if (decodedEntries._tag === "Failure") {
632 const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
633 return {
634 keybindings: [],
635 issues: [malformedConfigIssue(detail)],
636 };
637 }
638
639 const keybindings: KeybindingRule[] = [];
640 const issues: ServerConfigIssue[] = [];
641 for (const [index, entry] of decodedEntries.value.entries()) {
642 const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
643 if (decodedRule._tag === "Failure") {
644 const detail = Cause.pretty(decodedRule.cause);
645 issues.push(invalidEntryIssue(index, detail));
646 yield* Effect.logWarning("ignoring invalid keybinding entry", {
647 path: keybindingsConfigPath,
648 index,
649 entry,
650 error: detail,
651 });
652 continue;
653 }
654
655 const resolvedRule = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
656 if (resolvedRule._tag === "Failure") {
657 const detail = Cause.pretty(resolvedRule.cause);
658 issues.push(invalidEntryIssue(index, detail));
659 yield* Effect.logWarning("ignoring invalid keybinding entry", {
660 path: keybindingsConfigPath,
661 index,
662 entry,
663 error: detail,
664 });
665 continue;
666 }
667 keybindings.push(decodedRule.value);
668 }
669
670 return { keybindings, issues };
671 });
672
673 const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
674 return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
675 Effect.map((encoded) => `${encoded}\n`),
676 Effect.flatMap((encoded) =>
677 writeFileStringAtomically({
678 filePath: keybindingsConfigPath,
679 contents: encoded,
680 }).pipe(
681 Effect.provideService(FileSystem.FileSystem, fs),
682 Effect.provideService(Path.Path, path),
683 ),
684 ),
685 Effect.mapError(
686 (cause) =>
687 new KeybindingsConfigError({
688 configPath: keybindingsConfigPath,
689 detail: "failed to write keybindings config",
690 cause,
691 }),
692 ),
693 );
694 };
695
696 const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(
697 Effect.map(({ keybindings, issues }) => ({
698 keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
699 issues,
700 })),
701 );
702
703 const resolvedConfigCache = yield* Cache.make<
704 typeof resolvedConfigCacheKey,
705 KeybindingsConfigState,
706 KeybindingsConfigError
707 >({
708 capacity: 1,
709 lookup: () => loadConfigStateFromDisk,
710 });
711
712 const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
713
714 const revalidateAndEmit = upsertSemaphore.withPermits(1)(
715 Effect.gen(function* () {
716 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
717 const configState = yield* loadConfigStateFromCacheOrDisk;
718 yield* emitChange(configState);
719 }),
720 );
721
722 const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
723 Effect.gen(function* () {
724 const configExists = yield* readConfigExists;
725 if (!configExists) {
726 yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
727 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
728 return;
729 }
730
731 const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();
732 if (runtimeConfig.issues.length > 0) {
733 yield* Effect.logWarning(
734 "skipping startup keybindings default sync because config has issues",
735 {
736 path: keybindingsConfigPath,
737 issues: runtimeConfig.issues,
738 },
739 );
740 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
741 return;
742 }
743 const customConfig = runtimeConfig.keybindings;
744 const existingCommands = new Set(customConfig.map((entry) => entry.command));
745 const missingDefaults: KeybindingRule[] = [];
746 const shortcutConflictWarnings: Array<{
747 defaultCommand: KeybindingRule["command"];
748 conflictingCommand: KeybindingRule["command"];
749 key: string;
750 when: string | null;
751 }> = [];
752 for (const defaultRule of DEFAULT_KEYBINDINGS) {
753 if (existingCommands.has(defaultRule.command)) {
754 continue;
755 }
756 const conflictingEntry = customConfig.find((entry) =>
757 hasSameShortcutContext(entry, defaultRule),
758 );
759 if (conflictingEntry) {
760 shortcutConflictWarnings.push({
761 defaultCommand: defaultRule.command,
762 conflictingCommand: conflictingEntry.command,
763 key: defaultRule.key,
764 when: defaultRule.when ?? null,
765 });
766 continue;
767 }
768 missingDefaults.push(defaultRule);
769 }
770 for (const conflict of shortcutConflictWarnings) {
771 yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
772 path: keybindingsConfigPath,
773 defaultCommand: conflict.defaultCommand,
774 conflictingCommand: conflict.conflictingCommand,
775 key: conflict.key,
776 when: conflict.when,
777 reason: "shortcut context already used by existing rule",
778 });
779 }
780 if (missingDefaults.length === 0) {
781 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
782 return;
783 }
784
785 const matchingDefaults = DEFAULT_KEYBINDINGS.filter((defaultRule) =>
786 customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)),
787 ).map((rule) => rule.command);
788 if (matchingDefaults.length > 0) {
789 yield* Effect.logWarning("default keybinding rule already defined in user config", {
790 path: keybindingsConfigPath,
791 commands: matchingDefaults,
792 });
793 }
794
795 const nextConfig = [...customConfig, ...missingDefaults];
796 const cappedConfig =
797 nextConfig.length > MAX_KEYBINDINGS_COUNT
798 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
799 : nextConfig;
800 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
801 yield* Effect.logWarning("truncating keybindings config to max entries", {
802 path: keybindingsConfigPath,
803 maxEntries: MAX_KEYBINDINGS_COUNT,
804 });
805 }
806
807 yield* writeConfigAtomically(cappedConfig);
808 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
809 }),
810 );
811
812 const startWatcher = Effect.gen(function* () {
813 const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
814 const keybindingsConfigFile = path.basename(keybindingsConfigPath);
815 const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
816
817 yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(
818 Effect.mapError(
819 (cause) =>
820 new KeybindingsConfigError({
821 configPath: keybindingsConfigPath,
822 detail: "failed to prepare keybindings config directory",
823 cause,
824 }),
825 ),
826 );
827
828 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
829
830 // Debounce watch events so the file is fully written before we read it.
831 // Editors emit multiple events per save (truncate, write, rename) and
832 // `fs.watch` can fire before the content has been flushed to disk.
833 const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
834 Stream.filter((event) => {
835 return (
836 event.path === keybindingsConfigFile ||
837 event.path === keybindingsConfigPath ||
838 path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
839 );
840 }),
841 Stream.debounce(Duration.millis(100)),
842 );
843
844 yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
845 Effect.ignoreCause({ log: true }),
846 Effect.forkIn(watcherScope),
847 Effect.asVoid,
848 );
849 });
850
851 const start = Effect.gen(function* () {
852 const alreadyStarted = yield* Ref.get(startedRef);
853 if (alreadyStarted) {
854 return yield* Deferred.await(startedDeferred);
855 }
856
857 yield* Ref.set(startedRef, true);
858 const startup = Effect.gen(function* () {
859 yield* startWatcher;
860 yield* syncDefaultKeybindingsOnStartup;
861 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
862 yield* loadConfigStateFromCacheOrDisk;
863 });
864
865 const startupExit = yield* Effect.exit(startup);
866 if (startupExit._tag === "Failure") {
867 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
868 return yield* Effect.failCause(startupExit.cause);
869 }
870
871 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
872 });
873
874 return {
875 start,
876 ready: Deferred.await(startedDeferred),
877 syncDefaultKeybindingsOnStartup,
878 loadConfigState: loadConfigStateFromCacheOrDisk,
879 getSnapshot: loadConfigStateFromCacheOrDisk,
880 get streamChanges() {
881 return Stream.fromPubSub(changesPubSub);
882 },
883 upsertKeybindingRule: (rule) =>
884 upsertSemaphore.withPermits(1)(
885 Effect.gen(function* () {
886 const customConfig = yield* loadWritableCustomKeybindingsConfig();
887 const nextConfig = [
888 ...customConfig.filter((entry) => entry.command !== rule.command),
889 rule,
890 ];
891 const cappedConfig =
892 nextConfig.length > MAX_KEYBINDINGS_COUNT
893 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
894 : nextConfig;
895 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
896 yield* Effect.logWarning("truncating keybindings config to max entries", {
897 path: keybindingsConfigPath,
898 maxEntries: MAX_KEYBINDINGS_COUNT,
899 });
900 }
901 yield* writeConfigAtomically(cappedConfig);
902 const nextResolved = mergeWithDefaultKeybindings(
903 compileResolvedKeybindingsConfig(cappedConfig),
904 );
905 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
906 keybindings: nextResolved,
907 issues: [],
908 });
909 yield* emitChange({
910 keybindings: nextResolved,
911 issues: [],
912 });
913 return nextResolved;
914 }),
915 ),
916 } satisfies KeybindingsShape;
917});
918
919export const KeybindingsLive = Layer.effect(Keybindings, makeKeybindings);