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 KeybindingShortcut,
13 KeybindingWhenNode,
14 MAX_KEYBINDINGS_COUNT,
15 MAX_WHEN_EXPRESSION_DEPTH,
16 ResolvedKeybindingRule,
17 ResolvedKeybindingsConfig,
18 THREAD_JUMP_KEYBINDING_COMMANDS,
19 type ServerConfigIssue,
20} from "@t3tools/contracts";
21import { Mutable } from "effect/Types";
22import {
23 Array,
24 Cache,
25 Cause,
26 Deferred,
27 Duration,
28 Effect,
29 Exit,
30 FileSystem,
31 Path,
32 Layer,
33 Option,
34 Predicate,
35 PubSub,
36 Schema,
37 SchemaGetter,
38 SchemaIssue,
39 SchemaTransformation,
40 Ref,
41 ServiceMap,
42 Scope,
43 Stream,
44} from "effect";
45import * as Semaphore from "effect/Semaphore";
46import { ServerConfig } from "./config";
47import { fromLenientJson } from "@t3tools/shared/schemaJson";
48
49export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
50 "KeybindingsConfigParseError",
51 {
52 configPath: Schema.String,
53 detail: Schema.String,
54 cause: Schema.optional(Schema.Defect),
55 },
56) {
57 override get message(): string {
58 return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;
59 }
60}
61
62type WhenToken =
63 | { type: "identifier"; value: string }
64 | { type: "not" }
65 | { type: "and" }
66 | { type: "or" }
67 | { type: "lparen" }
68 | { type: "rparen" };
69
70export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
71 { key: "mod+j", command: "terminal.toggle" },
72 { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
73 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
74 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
75 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
76 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
77 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
78 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
79 { key: "mod+o", command: "editor.openFavorite" },
80 { key: "mod+shift+[", command: "thread.previous" },
81 { key: "mod+shift+]", command: "thread.next" },
82 ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
83 key: `mod+${index + 1}`,
84 command,
85 })),
86];
87
88function normalizeKeyToken(token: string): string {
89 if (token === "space") return " ";
90 if (token === "esc") return "escape";
91 return token;
92}
93
94/** @internal - Exported for testing */
95export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
96 const rawTokens = value
97 .toLowerCase()
98 .split("+")
99 .map((token) => token.trim());
100 const tokens = [...rawTokens];
101 let trailingEmptyCount = 0;
102 while (tokens[tokens.length - 1] === "") {
103 trailingEmptyCount += 1;
104 tokens.pop();
105 }
106 if (trailingEmptyCount > 0) {
107 tokens.push("+");
108 }
109 if (tokens.some((token) => token.length === 0)) {
110 return null;
111 }
112 if (tokens.length === 0) return null;
113
114 let key: string | null = null;
115 let metaKey = false;
116 let ctrlKey = false;
117 let shiftKey = false;
118 let altKey = false;
119 let modKey = false;
120
121 for (const token of tokens) {
122 switch (token) {
123 case "cmd":
124 case "meta":
125 metaKey = true;
126 break;
127 case "ctrl":
128 case "control":
129 ctrlKey = true;
130 break;
131 case "shift":
132 shiftKey = true;
133 break;
134 case "alt":
135 case "option":
136 altKey = true;
137 break;
138 case "mod":
139 modKey = true;
140 break;
141 default: {
142 if (key !== null) return null;
143 key = normalizeKeyToken(token);
144 }
145 }
146 }
147
148 if (key === null) return null;
149 return {
150 key,
151 metaKey,
152 ctrlKey,
153 shiftKey,
154 altKey,
155 modKey,
156 };
157}
158
159function tokenizeWhenExpression(expression: string): WhenToken[] | null {
160 const tokens: WhenToken[] = [];
161 let index = 0;
162
163 while (index < expression.length) {
164 const current = expression[index];
165 if (!current) break;
166
167 if (/\s/.test(current)) {
168 index += 1;
169 continue;
170 }
171 if (expression.startsWith("&&", index)) {
172 tokens.push({ type: "and" });
173 index += 2;
174 continue;
175 }
176 if (expression.startsWith("||", index)) {
177 tokens.push({ type: "or" });
178 index += 2;
179 continue;
180 }
181 if (current === "!") {
182 tokens.push({ type: "not" });
183 index += 1;
184 continue;
185 }
186 if (current === "(") {
187 tokens.push({ type: "lparen" });
188 index += 1;
189 continue;
190 }
191 if (current === ")") {
192 tokens.push({ type: "rparen" });
193 index += 1;
194 continue;
195 }
196
197 const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
198 if (!identifier) {
199 return null;
200 }
201 tokens.push({ type: "identifier", value: identifier[0] });
202 index += identifier[0].length;
203 }
204
205 return tokens;
206}
207
208function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
209 const tokens = tokenizeWhenExpression(expression);
210 if (!tokens || tokens.length === 0) return null;
211 let index = 0;
212
213 const parsePrimary = (depth: number): KeybindingWhenNode | null => {
214 if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
215 return null;
216 }
217 const token = tokens[index];
218 if (!token) return null;
219
220 if (token.type === "identifier") {
221 index += 1;
222 return { type: "identifier", name: token.value };
223 }
224
225 if (token.type === "lparen") {
226 index += 1;
227 const expressionNode = parseOr(depth + 1);
228 const closeToken = tokens[index];
229 if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
230 return null;
231 }
232 index += 1;
233 return expressionNode;
234 }
235
236 return null;
237 };
238
239 const parseUnary = (depth: number): KeybindingWhenNode | null => {
240 let notCount = 0;
241 while (tokens[index]?.type === "not") {
242 index += 1;
243 notCount += 1;
244 if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
245 return null;
246 }
247 }
248
249 let node = parsePrimary(depth);
250 if (!node) return null;
251
252 while (notCount > 0) {
253 node = { type: "not", node };
254 notCount -= 1;
255 }
256
257 return node;
258 };
259
260 const parseAnd = (depth: number): KeybindingWhenNode | null => {
261 let left = parseUnary(depth);
262 if (!left) return null;
263
264 while (tokens[index]?.type === "and") {
265 index += 1;
266 const right = parseUnary(depth);
267 if (!right) return null;
268 left = { type: "and", left, right };
269 }
270
271 return left;
272 };
273
274 const parseOr = (depth: number): KeybindingWhenNode | null => {
275 let left = parseAnd(depth);
276 if (!left) return null;
277
278 while (tokens[index]?.type === "or") {
279 index += 1;
280 const right = parseAnd(depth);
281 if (!right) return null;
282 left = { type: "or", left, right };
283 }
284
285 return left;
286 };
287
288 const ast = parseOr(0);
289 if (!ast || index !== tokens.length) return null;
290 return ast;
291}
292
293/** @internal - Exported for testing */
294export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
295 const shortcut = parseKeybindingShortcut(rule.key);
296 if (!shortcut) return null;
297
298 if (rule.when !== undefined) {
299 const whenAst = parseKeybindingWhenExpression(rule.when);
300 if (!whenAst) return null;
301 return {
302 command: rule.command,
303 shortcut,
304 whenAst,
305 };
306 }
307
308 return {
309 command: rule.command,
310 shortcut,
311 };
312}
313
314export function compileResolvedKeybindingsConfig(
315 config: KeybindingsConfig,
316): ResolvedKeybindingsConfig {
317 const compiled: Mutable<ResolvedKeybindingsConfig> = [];
318 for (const rule of config) {
319 const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule);
320 if (result._tag === "Success") {
321 compiled.push(result.value);
322 }
323 }
324 return compiled;
325}
326
327export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
328 Schema.decodeTo(
329 Schema.toType(ResolvedKeybindingRule),
330 SchemaTransformation.transformOrFail({
331 decode: (rule) =>
332 Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(
333 Effect.filterOrFail(
334 Predicate.isNotNull,
335 () =>
336 new SchemaIssue.InvalidValue(Option.some(rule), {
337 title: "Invalid keybinding rule",
338 }),
339 ),
340 Effect.map((resolved) => resolved),
341 ),
342
343 encode: (resolved) =>
344 Effect.gen(function* () {
345 const key = encodeShortcut(resolved.shortcut);
346 if (!key) {
347 return yield* Effect.fail(
348 new SchemaIssue.InvalidValue(Option.some(resolved), {
349 title: "Resolved shortcut cannot be encoded to key string",
350 }),
351 );
352 }
353
354 const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
355 return {
356 key,
357 command: resolved.command,
358 when,
359 };
360 }),
361 }),
362 ),
363);
364
365export const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check(
366 Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
367);
368
369function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {
370 return (
371 left.command === right.command &&
372 left.key === right.key &&
373 (left.when ?? undefined) === (right.when ?? undefined)
374 );
375}
376
377function keybindingShortcutContext(rule: KeybindingRule): string | null {
378 const parsed = parseKeybindingShortcut(rule.key);
379 if (!parsed) return null;
380 const encoded = encodeShortcut(parsed);
381 if (!encoded) return null;
382 return `${encoded}\u0000${rule.when ?? ""}`;
383}
384
385function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean {
386 const leftContext = keybindingShortcutContext(left);
387 const rightContext = keybindingShortcutContext(right);
388 if (!leftContext || !rightContext) return false;
389 return leftContext === rightContext;
390}
391
392function encodeShortcut(shortcut: KeybindingShortcut): string | null {
393 const modifiers: string[] = [];
394 if (shortcut.modKey) modifiers.push("mod");
395 if (shortcut.metaKey) modifiers.push("meta");
396 if (shortcut.ctrlKey) modifiers.push("ctrl");
397 if (shortcut.altKey) modifiers.push("alt");
398 if (shortcut.shiftKey) modifiers.push("shift");
399 if (!shortcut.key) return null;
400 if (shortcut.key !== "+" && shortcut.key.includes("+")) return null;
401 const key = shortcut.key === " " ? "space" : shortcut.key;
402 return [...modifiers, key].join("+");
403}
404
405function encodeWhenAst(node: KeybindingWhenNode): string {
406 switch (node.type) {
407 case "identifier":
408 return node.name;
409 case "not":
410 return `!(${encodeWhenAst(node.node)})`;
411 case "and":
412 return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;
413 case "or":
414 return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;
415 }
416}
417
418const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
419
420const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
421const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
422const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
423 SchemaGetter.stringifyJson({ space: 2 }),
424);
425const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
426 Schema.encode({
427 decode: PrettyJsonString,
428 encode: PrettyJsonString,
429 }),
430);
431
432export interface KeybindingsConfigState {
433 readonly keybindings: ResolvedKeybindingsConfig;
434 readonly issues: readonly ServerConfigIssue[];
435}
436
437export interface KeybindingsChangeEvent {
438 readonly keybindings: ResolvedKeybindingsConfig;
439 readonly issues: readonly ServerConfigIssue[];
440}
441
442function trimIssueMessage(message: string): string {
443 const trimmed = message.trim();
444 return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
445}
446
447function malformedConfigIssue(detail: string): ServerConfigIssue {
448 return {
449 kind: "keybindings.malformed-config",
450 message: trimIssueMessage(detail),
451 };
452}
453
454function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
455 return {
456 kind: "keybindings.invalid-entry",
457 index,
458 message: trimIssueMessage(detail),
459 };
460}
461
462function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
463 if (custom.length === 0) {
464 return [...DEFAULT_RESOLVED_KEYBINDINGS];
465 }
466
467 const overriddenCommands = new Set(custom.map((binding) => binding.command));
468 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
469 (binding) => !overriddenCommands.has(binding.command),
470 );
471 const merged = [...retainedDefaults, ...custom];
472
473 if (merged.length <= MAX_KEYBINDINGS_COUNT) {
474 return merged;
475 }
476
477 // Keep the latest rules when the config exceeds max size; later rules have higher precedence.
478 return merged.slice(-MAX_KEYBINDINGS_COUNT);
479}
480
481/**
482 * KeybindingsShape - Service API for keybinding configuration operations.
483 */
484export interface KeybindingsShape {
485 /**
486 * Start the keybindings runtime and attach file watching.
487 *
488 * Safe to call multiple times. The first successful call establishes the
489 * runtime; later calls await the same startup.
490 */
491 readonly start: Effect.Effect<void, KeybindingsConfigError>;
492
493 /**
494 * Await keybindings runtime readiness.
495 *
496 * Readiness means the config directory exists, the watcher is attached, the
497 * startup sync has completed, and the current snapshot has been loaded.
498 */
499 readonly ready: Effect.Effect<void, KeybindingsConfigError>;
500
501 /**
502 * Ensure the on-disk keybindings file exists and includes all default
503 * commands so newly-added defaults are backfilled on startup.
504 */
505 readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
506
507 /**
508 * Load runtime keybindings state along with non-fatal configuration issues.
509 */
510 readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
511
512 /**
513 * Read the latest keybindings snapshot from cache/disk.
514 */
515 readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
516
517 /**
518 * Stream of keybindings config change events.
519 */
520 readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
521
522 /**
523 * Upsert a keybinding rule and persist the resulting configuration.
524 *
525 * Writes config atomically and enforces the max rule count by truncating
526 * oldest entries when needed.
527 */
528 readonly upsertKeybindingRule: (
529 rule: KeybindingRule,
530 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
531}
532
533/**
534 * Keybindings - Service tag for keybinding configuration operations.
535 */
536export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
537 "t3/keybindings",
538) {}
539
540const makeKeybindings = Effect.gen(function* () {
541 const { keybindingsConfigPath } = yield* ServerConfig;
542 const fs = yield* FileSystem.FileSystem;
543 const path = yield* Path.Path;
544 const upsertSemaphore = yield* Semaphore.make(1);
545 const resolvedConfigCacheKey = "resolved" as const;
546 const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
547 const startedRef = yield* Ref.make(false);
548 const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
549 const watcherScope = yield* Scope.make("sequential");
550 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
551 const emitChange = (configState: KeybindingsConfigState) =>
552 PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
553
554 const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
555 Effect.mapError(
556 (cause) =>
557 new KeybindingsConfigError({
558 configPath: keybindingsConfigPath,
559 detail: "failed to access keybindings config",
560 cause,
561 }),
562 ),
563 );
564
565 const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
566 Effect.mapError(
567 (cause) =>
568 new KeybindingsConfigError({
569 configPath: keybindingsConfigPath,
570 detail: "failed to read keybindings config",
571 cause,
572 }),
573 ),
574 );
575
576 const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
577 readonly KeybindingRule[],
578 KeybindingsConfigError
579 > {
580 if (!(yield* readConfigExists)) {
581 return [];
582 }
583
584 const rawConfig = yield* readRawConfig.pipe(
585 Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
586 Effect.mapError(
587 (cause) =>
588 new KeybindingsConfigError({
589 configPath: keybindingsConfigPath,
590 detail: "expected JSON array",
591 cause,
592 }),
593 ),
594 );
595
596 return yield* Effect.forEach(rawConfig, (entry) =>
597 Effect.gen(function* () {
598 const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
599 if (decodedRule._tag === "Failure") {
600 yield* Effect.logWarning("ignoring invalid keybinding entry", {
601 path: keybindingsConfigPath,
602 entry,
603 error: Cause.pretty(decodedRule.cause),
604 });
605 return null;
606 }
607 const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
608 if (resolved._tag === "Failure") {
609 yield* Effect.logWarning("ignoring invalid keybinding entry", {
610 path: keybindingsConfigPath,
611 entry,
612 error: Cause.pretty(resolved.cause),
613 });
614 return null;
615 }
616 return decodedRule.value;
617 }),
618 ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
619 });
620
621 const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
622 {
623 readonly keybindings: readonly KeybindingRule[];
624 readonly issues: readonly ServerConfigIssue[];
625 },
626 KeybindingsConfigError
627 > {
628 if (!(yield* readConfigExists)) {
629 return { keybindings: [], issues: [] };
630 }
631
632 const rawConfig = yield* readRawConfig;
633 const decodedEntries = Schema.decodeUnknownExit(RawKeybindingsEntries)(rawConfig);
634 if (decodedEntries._tag === "Failure") {
635 const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
636 return {
637 keybindings: [],
638 issues: [malformedConfigIssue(detail)],
639 };
640 }
641
642 const keybindings: KeybindingRule[] = [];
643 const issues: ServerConfigIssue[] = [];
644 for (const [index, entry] of decodedEntries.value.entries()) {
645 const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
646 if (decodedRule._tag === "Failure") {
647 const detail = Cause.pretty(decodedRule.cause);
648 issues.push(invalidEntryIssue(index, detail));
649 yield* Effect.logWarning("ignoring invalid keybinding entry", {
650 path: keybindingsConfigPath,
651 index,
652 entry,
653 error: detail,
654 });
655 continue;
656 }
657
658 const resolvedRule = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
659 if (resolvedRule._tag === "Failure") {
660 const detail = Cause.pretty(resolvedRule.cause);
661 issues.push(invalidEntryIssue(index, detail));
662 yield* Effect.logWarning("ignoring invalid keybinding entry", {
663 path: keybindingsConfigPath,
664 index,
665 entry,
666 error: detail,
667 });
668 continue;
669 }
670 keybindings.push(decodedRule.value);
671 }
672
673 return { keybindings, issues };
674 });
675
676 const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
677 const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
678
679 return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
680 Effect.map((encoded) => `${encoded}\n`),
681 Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
682 Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
683 Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
684 Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
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);