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

keybindings.ts

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