Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.ts

907 lines27.5 KB

1/**
2 * Keybindings - Keybinding configuration service definitions.
3 *
4 * Owns parsing, validation, merge, and persistence of user keybinding
5 * configuration consumed by the server runtime.
6 *
7 * @module Keybindings
8 */
9import {
10 KeybindingRule,
11 KeybindingsConfig,
12 KeybindingsConfigError,
13 KeybindingShortcut,
14 KeybindingWhenNode,
15 MAX_KEYBINDINGS_COUNT,
16 MAX_WHEN_EXPRESSION_DEPTH,
17 ResolvedKeybindingRule,
18 ResolvedKeybindingsConfig,
19 THREAD_JUMP_KEYBINDING_COMMANDS,
20 type ServerConfigIssue,
21} from "@t3tools/contracts";
22import { Mutable } from "effect/Types";
23import {
24 Array,
25 Cache,
26 Cause,
27 Deferred,
28 Duration,
29 Effect,
30 Exit,
31 FileSystem,
32 Path,
33 Layer,
34 Option,
35 Predicate,
36 PubSub,
37 Schema,
38 SchemaGetter,
39 SchemaIssue,
40 SchemaTransformation,
41 Ref,
42 ServiceMap,
43 Scope,
44 Stream,
45} from "effect";
46import * as Semaphore from "effect/Semaphore";
47import { ServerConfig } from "./config";
48import { fromLenientJson } from "@t3tools/shared/schemaJson";
49​
50type WhenToken =
51 | { type: "identifier"; value: string }
52 | { type: "not" }
53 | { type: "and" }
54 | { type: "or" }
55 | { type: "lparen" }
56 | { type: "rparen" };
57​
58export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
59 { key: "mod+j", command: "terminal.toggle" },
60 { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
61 { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
62 { key: "mod+w", command: "terminal.close", when: "terminalFocus" },
63 { key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
64 { key: "mod+n", command: "chat.new", when: "!terminalFocus" },
65 { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
66 { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
67 { key: "mod+o", command: "editor.openFavorite" },
68 { key: "mod+shift+[", command: "thread.previous" },
69 { key: "mod+shift+]", command: "thread.next" },
70 ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({
71 key: `mod+${index + 1}`,
72 command,
73 })),
74];
75​
76function normalizeKeyToken(token: string): string {
77 if (token === "space") return " ";
78 if (token === "esc") return "escape";
79 return token;
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 };
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;
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;
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 };
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;
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 );
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 ?? ""}`;
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;
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("+");
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 }
405​
406const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
407​
408const RawKeybindingsEntries = fromLenientJson(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[];
424​
425export interface KeybindingsChangeEvent {
426 readonly keybindings: ResolvedKeybindingsConfig;
427 readonly issues: readonly ServerConfigIssue[];
429​
430function trimIssueMessage(message: string): string {
431 const trimmed = message.trim();
432 return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
434​
435function malformedConfigIssue(detail: string): ServerConfigIssue {
436 return {
437 kind: "keybindings.malformed-config",
438 message: trimIssueMessage(detail),
439 };
441​
442function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
443 return {
444 kind: "keybindings.invalid-entry",
445 index,
446 message: trimIssueMessage(detail),
447 };
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);
468​
469/**
470 * KeybindingsShape - Service API for keybinding configuration operations.
471 */
472export interface KeybindingsShape {
473 /**
474 * Start the keybindings runtime and attach file watching.
475 *
476 * Safe to call multiple times. The first successful call establishes the
477 * runtime; later calls await the same startup.
478 */
479 readonly start: Effect.Effect<void, KeybindingsConfigError>;
480​
481 /**
482 * Await keybindings runtime readiness.
483 *
484 * Readiness means the config directory exists, the watcher is attached, the
485 * startup sync has completed, and the current snapshot has been loaded.
486 */
487 readonly ready: Effect.Effect<void, KeybindingsConfigError>;
488​
489 /**
490 * Ensure the on-disk keybindings file exists and includes all default
491 * commands so newly-added defaults are backfilled on startup.
492 */
493 readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
494​
495 /**
496 * Load runtime keybindings state along with non-fatal configuration issues.
497 */
498 readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
499​
500 /**
501 * Read the latest keybindings snapshot from cache/disk.
502 */
503 readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
504​
505 /**
506 * Stream of keybindings config change events.
507 */
508 readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
509​
510 /**
511 * Upsert a keybinding rule and persist the resulting configuration.
512 *
513 * Writes config atomically and enforces the max rule count by truncating
514 * oldest entries when needed.
515 */
516 readonly upsertKeybindingRule: (
517 rule: KeybindingRule,
518 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
520​
521/**
522 * Keybindings - Service tag for keybinding configuration operations.
523 */
524export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
525 "t3/keybindings",
526) {}
527​
528const makeKeybindings = Effect.gen(function* () {
529 const { keybindingsConfigPath } = yield* ServerConfig;
530 const fs = yield* FileSystem.FileSystem;
531 const path = yield* Path.Path;
532 const upsertSemaphore = yield* Semaphore.make(1);
533 const resolvedConfigCacheKey = "resolved" as const;
534 const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
535 const startedRef = yield* Ref.make(false);
536 const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
537 const watcherScope = yield* Scope.make("sequential");
538 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
539 const emitChange = (configState: KeybindingsConfigState) =>
540 PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
541​
542 const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
543 Effect.mapError(
544 (cause) =>
545 new KeybindingsConfigError({
546 configPath: keybindingsConfigPath,
547 detail: "failed to access keybindings config",
548 cause,
549 }),
550 ),
551 );
552​
553 const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
554 Effect.mapError(
555 (cause) =>
556 new KeybindingsConfigError({
557 configPath: keybindingsConfigPath,
558 detail: "failed to read keybindings config",
559 cause,
560 }),
561 ),
562 );
563​
564 const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
565 readonly KeybindingRule[],
566 KeybindingsConfigError
567 > {
568 if (!(yield* readConfigExists)) {
569 return [];
570 }
571​
572 const rawConfig = yield* readRawConfig.pipe(
573 Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
574 Effect.mapError(
575 (cause) =>
576 new KeybindingsConfigError({
577 configPath: keybindingsConfigPath,
578 detail: "expected JSON array",
579 cause,
580 }),
581 ),
582 );
583​
584 return yield* Effect.forEach(rawConfig, (entry) =>
585 Effect.gen(function* () {
586 const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
587 if (decodedRule._tag === "Failure") {
588 yield* Effect.logWarning("ignoring invalid keybinding entry", {
589 path: keybindingsConfigPath,
590 entry,
591 error: Cause.pretty(decodedRule.cause),
592 });
593 return null;
594 }
595 const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
596 if (resolved._tag === "Failure") {
597 yield* Effect.logWarning("ignoring invalid keybinding entry", {
598 path: keybindingsConfigPath,
599 entry,
600 error: Cause.pretty(resolved.cause),
601 });
602 return null;
603 }
604 return decodedRule.value;
605 }),
606 ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
607 });
608​
609 const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
610 {
611 readonly keybindings: readonly KeybindingRule[];
612 readonly issues: readonly ServerConfigIssue[];
613 },
614 KeybindingsConfigError
615 > {
616 if (!(yield* readConfigExists)) {
617 return { keybindings: [], issues: [] };
618 }
619​
620 const rawConfig = yield* readRawConfig;
621 const decodedEntries = Schema.decodeUnknownExit(RawKeybindingsEntries)(rawConfig);
622 if (decodedEntries._tag === "Failure") {
623 const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
624 return {
625 keybindings: [],
626 issues: [malformedConfigIssue(detail)],
627 };
628 }
629​
630 const keybindings: KeybindingRule[] = [];
631 const issues: ServerConfigIssue[] = [];
632 for (const [index, entry] of decodedEntries.value.entries()) {
633 const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
634 if (decodedRule._tag === "Failure") {
635 const detail = Cause.pretty(decodedRule.cause);
636 issues.push(invalidEntryIssue(index, detail));
637 yield* Effect.logWarning("ignoring invalid keybinding entry", {
638 path: keybindingsConfigPath,
639 index,
640 entry,
641 error: detail,
642 });
643 continue;
644 }
645​
646 const resolvedRule = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
647 if (resolvedRule._tag === "Failure") {
648 const detail = Cause.pretty(resolvedRule.cause);
649 issues.push(invalidEntryIssue(index, detail));
650 yield* Effect.logWarning("ignoring invalid keybinding entry", {
651 path: keybindingsConfigPath,
652 index,
653 entry,
654 error: detail,
655 });
656 continue;
657 }
658 keybindings.push(decodedRule.value);
659 }
660​
661 return { keybindings, issues };
662 });
663​
664 const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
665 const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
666​
667 return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
668 Effect.map((encoded) => `${encoded}\n`),
669 Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
670 Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
671 Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
672 Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
673 Effect.mapError(
674 (cause) =>
675 new KeybindingsConfigError({
676 configPath: keybindingsConfigPath,
677 detail: "failed to write keybindings config",
678 cause,
679 }),
680 ),
681 );
682 };
683​
684 const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(
685 Effect.map(({ keybindings, issues }) => ({
686 keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
687 issues,
688 })),
689 );
690​
691 const resolvedConfigCache = yield* Cache.make<
692 typeof resolvedConfigCacheKey,
693 KeybindingsConfigState,
694 KeybindingsConfigError
695 >({
696 capacity: 1,
697 lookup: () => loadConfigStateFromDisk,
698 });
699​
700 const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
701​
702 const revalidateAndEmit = upsertSemaphore.withPermits(1)(
703 Effect.gen(function* () {
704 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
705 const configState = yield* loadConfigStateFromCacheOrDisk;
706 yield* emitChange(configState);
707 }),
708 );
709​
710 const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
711 Effect.gen(function* () {
712 const configExists = yield* readConfigExists;
713 if (!configExists) {
714 yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
715 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
716 return;
717 }
718​
719 const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();
720 if (runtimeConfig.issues.length > 0) {
721 yield* Effect.logWarning(
722 "skipping startup keybindings default sync because config has issues",
723 {
724 path: keybindingsConfigPath,
725 issues: runtimeConfig.issues,
726 },
727 );
728 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
729 return;
730 }
731 const customConfig = runtimeConfig.keybindings;
732 const existingCommands = new Set(customConfig.map((entry) => entry.command));
733 const missingDefaults: KeybindingRule[] = [];
734 const shortcutConflictWarnings: Array<{
735 defaultCommand: KeybindingRule["command"];
736 conflictingCommand: KeybindingRule["command"];
737 key: string;
738 when: string | null;
739 }> = [];
740 for (const defaultRule of DEFAULT_KEYBINDINGS) {
741 if (existingCommands.has(defaultRule.command)) {
742 continue;
743 }
744 const conflictingEntry = customConfig.find((entry) =>
745 hasSameShortcutContext(entry, defaultRule),
746 );
747 if (conflictingEntry) {
748 shortcutConflictWarnings.push({
749 defaultCommand: defaultRule.command,
750 conflictingCommand: conflictingEntry.command,
751 key: defaultRule.key,
752 when: defaultRule.when ?? null,
753 });
754 continue;
755 }
756 missingDefaults.push(defaultRule);
757 }
758 for (const conflict of shortcutConflictWarnings) {
759 yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
760 path: keybindingsConfigPath,
761 defaultCommand: conflict.defaultCommand,
762 conflictingCommand: conflict.conflictingCommand,
763 key: conflict.key,
764 when: conflict.when,
765 reason: "shortcut context already used by existing rule",
766 });
767 }
768 if (missingDefaults.length === 0) {
769 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
770 return;
771 }
772​
773 const matchingDefaults = DEFAULT_KEYBINDINGS.filter((defaultRule) =>
774 customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)),
775 ).map((rule) => rule.command);
776 if (matchingDefaults.length > 0) {
777 yield* Effect.logWarning("default keybinding rule already defined in user config", {
778 path: keybindingsConfigPath,
779 commands: matchingDefaults,
780 });
781 }
782​
783 const nextConfig = [...customConfig, ...missingDefaults];
784 const cappedConfig =
785 nextConfig.length > MAX_KEYBINDINGS_COUNT
786 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
787 : nextConfig;
788 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
789 yield* Effect.logWarning("truncating keybindings config to max entries", {
790 path: keybindingsConfigPath,
791 maxEntries: MAX_KEYBINDINGS_COUNT,
792 });
793 }
794​
795 yield* writeConfigAtomically(cappedConfig);
796 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
797 }),
798 );
799​
800 const startWatcher = Effect.gen(function* () {
801 const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
802 const keybindingsConfigFile = path.basename(keybindingsConfigPath);
803 const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
804​
805 yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(
806 Effect.mapError(
807 (cause) =>
808 new KeybindingsConfigError({
809 configPath: keybindingsConfigPath,
810 detail: "failed to prepare keybindings config directory",
811 cause,
812 }),
813 ),
814 );
815​
816 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
817​
818 // Debounce watch events so the file is fully written before we read it.
819 // Editors emit multiple events per save (truncate, write, rename) and
820 // `fs.watch` can fire before the content has been flushed to disk.
821 const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
822 Stream.filter((event) => {
823 return (
824 event.path === keybindingsConfigFile ||
825 event.path === keybindingsConfigPath ||
826 path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
827 );
828 }),
829 Stream.debounce(Duration.millis(100)),
830 );
831​
832 yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
833 Effect.ignoreCause({ log: true }),
834 Effect.forkIn(watcherScope),
835 Effect.asVoid,
836 );
837 });
838​
839 const start = Effect.gen(function* () {
840 const alreadyStarted = yield* Ref.get(startedRef);
841 if (alreadyStarted) {
842 return yield* Deferred.await(startedDeferred);
843 }
844​
845 yield* Ref.set(startedRef, true);
846 const startup = Effect.gen(function* () {
847 yield* startWatcher;
848 yield* syncDefaultKeybindingsOnStartup;
849 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
850 yield* loadConfigStateFromCacheOrDisk;
851 });
852​
853 const startupExit = yield* Effect.exit(startup);
854 if (startupExit._tag === "Failure") {
855 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
856 return yield* Effect.failCause(startupExit.cause);
857 }
858​
859 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
860 });
861​
862 return {
863 start,
864 ready: Deferred.await(startedDeferred),
865 syncDefaultKeybindingsOnStartup,
866 loadConfigState: loadConfigStateFromCacheOrDisk,
867 getSnapshot: loadConfigStateFromCacheOrDisk,
868 get streamChanges() {
869 return Stream.fromPubSub(changesPubSub);
870 },
871 upsertKeybindingRule: (rule) =>
872 upsertSemaphore.withPermits(1)(
873 Effect.gen(function* () {
874 const customConfig = yield* loadWritableCustomKeybindingsConfig();
875 const nextConfig = [
876 ...customConfig.filter((entry) => entry.command !== rule.command),
877 rule,
878 ];
879 const cappedConfig =
880 nextConfig.length > MAX_KEYBINDINGS_COUNT
881 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
882 : nextConfig;
883 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
884 yield* Effect.logWarning("truncating keybindings config to max entries", {
885 path: keybindingsConfigPath,
886 maxEntries: MAX_KEYBINDINGS_COUNT,
887 });
888 }
889 yield* writeConfigAtomically(cappedConfig);
890 const nextResolved = mergeWithDefaultKeybindings(
891 compileResolvedKeybindingsConfig(cappedConfig),
892 );
893 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
894 keybindings: nextResolved,
895 issues: [],
896 });
897 yield* emitChange({
898 keybindings: nextResolved,
899 issues: [],
900 });
901 return nextResolved;
902 }),
903 ),
904 } satisfies KeybindingsShape;
905});
906​
907export const KeybindingsLive = Layer.effect(Keybindings, makeKeybindings);