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