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