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