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