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