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 DEFAULT_RESOLVED_KEYBINDINGS,
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.transformOrFail({
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
204function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
205 if (custom.length === 0) {
206 return [...DEFAULT_RESOLVED_KEYBINDINGS];
207 }
208
209 const overriddenCommands = new Set(custom.map((binding) => binding.command));
210 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
211 (binding) => !overriddenCommands.has(binding.command),
212 );
213 const merged = [...retainedDefaults, ...custom];
214
215 if (merged.length <= MAX_KEYBINDINGS_COUNT) {
216 return merged;
217 }
218
219 // Keep the latest rules when the config exceeds max size; later rules have higher precedence.
220 return merged.slice(-MAX_KEYBINDINGS_COUNT);
221}
222
223/**
224 * Keybindings - Service tag for keybinding configuration operations.
225 */
226export class Keybindings extends Context.Service<
227 Keybindings,
228 {
229 /**
230 * Start the keybindings runtime and attach file watching.
231 *
232 * Safe to call multiple times. The first successful call establishes the
233 * runtime; later calls await the same startup.
234 */
235 readonly start: Effect.Effect<void, KeybindingsConfigError>;
236
237 /**
238 * Await keybindings runtime readiness.
239 *
240 * Readiness means the config directory exists, the watcher is attached, the
241 * startup sync has completed, and the current snapshot has been loaded.
242 */
243 readonly ready: Effect.Effect<void, KeybindingsConfigError>;
244
245 /**
246 * Ensure the on-disk keybindings file exists and includes all default
247 * commands so newly-added defaults are backfilled on startup.
248 */
249 readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
250
251 /**
252 * Load runtime keybindings state along with non-fatal configuration issues.
253 */
254 readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
255
256 /**
257 * Read the latest keybindings snapshot from cache/disk.
258 */
259 readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
260
261 /**
262 * Stream of keybindings config change events.
263 */
264 readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
265
266 /**
267 * Upsert a keybinding rule and persist the resulting configuration.
268 *
269 * Writes config atomically and enforces the max rule count by truncating
270 * oldest entries when needed.
271 */
272 readonly upsertKeybindingRule: (
273 input: ServerUpsertKeybindingInput,
274 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
275
276 /**
277 * Remove a single persisted keybinding rule by exact key/command/when match.
278 */
279 readonly removeKeybindingRule: (
280 input: ServerRemoveKeybindingInput,
281 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
282 }
283>()("t3/keybindings") {}
284
285const make = Effect.gen(function* () {
286 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
287 const fs = yield* FileSystem.FileSystem;
288 const path = yield* Path.Path;
289 const upsertSemaphore = yield* Semaphore.make(1);
290 const resolvedConfigCacheKey = "resolved" as const;
291 const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
292 const startedRef = yield* Ref.make(false);
293 const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
294 const watcherScope = yield* Scope.make("sequential");
295 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
296 const emitChange = (configState: KeybindingsConfigState) =>
297 PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
298
299 const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
300 Effect.mapError(
301 (cause) =>
302 new KeybindingsConfigError({
303 configPath: keybindingsConfigPath,
304 detail: "failed to access keybindings config",
305 cause,
306 }),
307 ),
308 );
309
310 const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
311 Effect.mapError(
312 (cause) =>
313 new KeybindingsConfigError({
314 configPath: keybindingsConfigPath,
315 detail: "failed to read keybindings config",
316 cause,
317 }),
318 ),
319 );
320
321 const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
322 readonly KeybindingRule[],
323 KeybindingsConfigError
324 > {
325 if (!(yield* readConfigExists)) {
326 return [];
327 }
328
329 const rawConfig = yield* readRawConfig.pipe(
330 Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
331 Effect.mapError(
332 (cause) =>
333 new KeybindingsConfigError({
334 configPath: keybindingsConfigPath,
335 detail: "expected JSON array",
336 cause,
337 }),
338 ),
339 );
340
341 return yield* Effect.forEach(rawConfig, (entry) =>
342 Effect.gen(function* () {
343 const decodedRule = decodeKeybindingRuleExit(entry);
344 if (decodedRule._tag === "Failure") {
345 yield* Effect.logWarning("ignoring invalid keybinding entry", {
346 path: keybindingsConfigPath,
347 entry,
348 error: Cause.pretty(decodedRule.cause),
349 });
350 return null;
351 }
352 const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
353 if (resolved._tag === "Failure") {
354 yield* Effect.logWarning("ignoring invalid keybinding entry", {
355 path: keybindingsConfigPath,
356 entry,
357 error: Cause.pretty(resolved.cause),
358 });
359 return null;
360 }
361 return decodedRule.value;
362 }),
363 ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
364 });
365
366 const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
367 {
368 readonly keybindings: readonly KeybindingRule[];
369 readonly issues: readonly ServerConfigIssue[];
370 },
371 KeybindingsConfigError
372 > {
373 if (!(yield* readConfigExists)) {
374 return { keybindings: [], issues: [] };
375 }
376
377 const rawConfig = yield* readRawConfig;
378 const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
379 if (decodedEntries._tag === "Failure") {
380 const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
381 return {
382 keybindings: [],
383 issues: [malformedConfigIssue(detail)],
384 };
385 }
386
387 const keybindings: KeybindingRule[] = [];
388 const issues: ServerConfigIssue[] = [];
389 for (const [index, entry] of decodedEntries.value.entries()) {
390 const decodedRule = decodeKeybindingRuleExit(entry);
391 if (decodedRule._tag === "Failure") {
392 const detail = Cause.pretty(decodedRule.cause);
393 issues.push(invalidEntryIssue(index, detail));
394 yield* Effect.logWarning("ignoring invalid keybinding entry", {
395 path: keybindingsConfigPath,
396 index,
397 entry,
398 error: detail,
399 });
400 continue;
401 }
402
403 const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
404 if (resolvedRule._tag === "Failure") {
405 const detail = Cause.pretty(resolvedRule.cause);
406 issues.push(invalidEntryIssue(index, detail));
407 yield* Effect.logWarning("ignoring invalid keybinding entry", {
408 path: keybindingsConfigPath,
409 index,
410 entry,
411 error: detail,
412 });
413 continue;
414 }
415 keybindings.push(decodedRule.value);
416 }
417
418 return { keybindings, issues };
419 });
420
421 const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
422 return encodeKeybindingsConfigPrettyJson(rules).pipe(
423 Effect.map((encoded) => `${encoded}\n`),
424 Effect.flatMap((encoded) =>
425 writeFileStringAtomically({
426 filePath: keybindingsConfigPath,
427 contents: encoded,
428 }).pipe(
429 Effect.provideService(FileSystem.FileSystem, fs),
430 Effect.provideService(Path.Path, path),
431 ),
432 ),
433 Effect.mapError(
434 (cause) =>
435 new KeybindingsConfigError({
436 configPath: keybindingsConfigPath,
437 detail: "failed to write keybindings config",
438 cause,
439 }),
440 ),
441 );
442 };
443
444 const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(
445 Effect.map(({ keybindings, issues }) => ({
446 keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
447 issues,
448 })),
449 );
450
451 const resolvedConfigCache = yield* Cache.make<
452 typeof resolvedConfigCacheKey,
453 KeybindingsConfigState,
454 KeybindingsConfigError
455 >({
456 capacity: 1,
457 lookup: () => loadConfigStateFromDisk,
458 });
459
460 const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
461
462 const revalidateAndEmit = upsertSemaphore.withPermits(1)(
463 Effect.gen(function* () {
464 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
465 const configState = yield* loadConfigStateFromCacheOrDisk;
466 yield* emitChange(configState);
467 }),
468 );
469
470 const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
471 Effect.gen(function* () {
472 const configExists = yield* readConfigExists;
473 if (!configExists) {
474 yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
475 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
476 return;
477 }
478
479 const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();
480 if (runtimeConfig.issues.length > 0) {
481 yield* Effect.logWarning(
482 "skipping startup keybindings default sync because config has issues",
483 {
484 path: keybindingsConfigPath,
485 issues: runtimeConfig.issues,
486 },
487 );
488 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
489 return;
490 }
491 const customConfig = runtimeConfig.keybindings;
492 const existingCommands = new Set(customConfig.map((entry) => entry.command));
493 const missingDefaults: KeybindingRule[] = [];
494 const shortcutConflictWarnings: Array<{
495 defaultCommand: KeybindingRule["command"];
496 conflictingCommand: KeybindingRule["command"];
497 key: string;
498 when: string | null;
499 }> = [];
500 for (const defaultRule of DEFAULT_KEYBINDINGS) {
501 if (existingCommands.has(defaultRule.command)) {
502 continue;
503 }
504 const conflictingEntry = customConfig.find((entry) =>
505 hasSameShortcutContext(entry, defaultRule),
506 );
507 if (conflictingEntry) {
508 shortcutConflictWarnings.push({
509 defaultCommand: defaultRule.command,
510 conflictingCommand: conflictingEntry.command,
511 key: defaultRule.key,
512 when: defaultRule.when ?? null,
513 });
514 continue;
515 }
516 missingDefaults.push(defaultRule);
517 }
518 for (const conflict of shortcutConflictWarnings) {
519 yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
520 path: keybindingsConfigPath,
521 defaultCommand: conflict.defaultCommand,
522 conflictingCommand: conflict.conflictingCommand,
523 key: conflict.key,
524 when: conflict.when,
525 reason: "shortcut context already used by existing rule",
526 });
527 }
528 if (missingDefaults.length === 0) {
529 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
530 return;
531 }
532
533 const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
534 customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
535 ? Result.succeed(defaultRule.command)
536 : Result.failVoid,
537 );
538 if (matchingDefaults.length > 0) {
539 yield* Effect.logWarning("default keybinding rule already defined in user config", {
540 path: keybindingsConfigPath,
541 commands: matchingDefaults,
542 });
543 }
544
545 // Startup backfill must never evict persisted user rules: append only
546 // the defaults that fit and skip the rest.
547 const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length);
548 const defaultsToAppend = missingDefaults.slice(0, availableSlots);
549 const skippedDefaults = missingDefaults.slice(availableSlots);
550 if (skippedDefaults.length > 0) {
551 yield* Effect.logWarning("skipping default keybinding backfill at max entries", {
552 path: keybindingsConfigPath,
553 maxEntries: MAX_KEYBINDINGS_COUNT,
554 commands: skippedDefaults.map((rule) => rule.command),
555 });
556 }
557 if (defaultsToAppend.length === 0) {
558 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
559 return;
560 }
561
562 yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]);
563 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
564 }),
565 );
566
567 const startWatcher = Effect.gen(function* () {
568 const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
569 const keybindingsConfigFile = path.basename(keybindingsConfigPath);
570 const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
571
572 yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(
573 Effect.mapError(
574 (cause) =>
575 new KeybindingsConfigError({
576 configPath: keybindingsConfigPath,
577 detail: "failed to prepare keybindings config directory",
578 cause,
579 }),
580 ),
581 );
582
583 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
584
585 // Debounce watch events so the file is fully written before we read it.
586 // Editors emit multiple events per save (truncate, write, rename) and
587 // `fs.watch` can fire before the content has been flushed to disk.
588 const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
589 Stream.filter((event) => {
590 return (
591 event.path === keybindingsConfigFile ||
592 event.path === keybindingsConfigPath ||
593 path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
594 );
595 }),
596 Stream.debounce(Duration.millis(100)),
597 );
598
599 yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
600 Effect.ignoreCause({ log: true }),
601 Effect.forkIn(watcherScope),
602 Effect.asVoid,
603 );
604 });
605
606 const start = Effect.gen(function* () {
607 const alreadyStarted = yield* Ref.get(startedRef);
608 if (alreadyStarted) {
609 return yield* Deferred.await(startedDeferred);
610 }
611
612 yield* Ref.set(startedRef, true);
613 const startup = Effect.gen(function* () {
614 yield* startWatcher;
615 yield* syncDefaultKeybindingsOnStartup;
616 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
617 yield* loadConfigStateFromCacheOrDisk;
618 });
619
620 const startupExit = yield* Effect.exit(startup);
621 if (startupExit._tag === "Failure") {
622 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
623 return yield* Effect.failCause(startupExit.cause);
624 }
625
626 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
627 });
628
629 return {
630 start,
631 ready: Deferred.await(startedDeferred),
632 syncDefaultKeybindingsOnStartup,
633 loadConfigState: loadConfigStateFromCacheOrDisk,
634 getSnapshot: loadConfigStateFromCacheOrDisk,
635 get streamChanges() {
636 return Stream.fromPubSub(changesPubSub);
637 },
638 upsertKeybindingRule: (input) =>
639 upsertSemaphore.withPermits(1)(
640 Effect.gen(function* () {
641 const customConfig = yield* loadWritableCustomKeybindingsConfig();
642 const rule = keybindingRuleFromUpsertInput(input);
643 const replaceTarget = replaceTargetFromUpsertInput(input);
644 const nextConfig = [
645 ...customConfig.filter((entry) => {
646 if (replaceTarget) {
647 return (
648 !isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
649 );
650 }
651 return !isSameKeybindingRule(entry, rule);
652 }),
653 rule,
654 ];
655 const cappedConfig =
656 nextConfig.length > MAX_KEYBINDINGS_COUNT
657 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
658 : nextConfig;
659 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
660 yield* Effect.logWarning("truncating keybindings config to max entries", {
661 path: keybindingsConfigPath,
662 maxEntries: MAX_KEYBINDINGS_COUNT,
663 });
664 }
665 yield* writeConfigAtomically(cappedConfig);
666 const nextResolved = mergeWithDefaultKeybindings(
667 compileResolvedKeybindingsConfig(cappedConfig),
668 );
669 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
670 keybindings: nextResolved,
671 issues: [],
672 });
673 yield* emitChange({
674 keybindings: nextResolved,
675 issues: [],
676 });
677 return nextResolved;
678 }),
679 ),
680 removeKeybindingRule: (input) =>
681 upsertSemaphore.withPermits(1)(
682 Effect.gen(function* () {
683 const customConfig = yield* loadWritableCustomKeybindingsConfig();
684 const target = keybindingRuleFromRemoveInput(input);
685 const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
686 yield* writeConfigAtomically(nextConfig);
687 const nextResolved = mergeWithDefaultKeybindings(
688 compileResolvedKeybindingsConfig(nextConfig),
689 );
690 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
691 keybindings: nextResolved,
692 issues: [],
693 });
694 yield* emitChange({
695 keybindings: nextResolved,
696 issues: [],
697 });
698 return nextResolved;
699 }),
700 ),
701 } satisfies Keybindings["Service"];
702});
703
704export const layer = Layer.effect(Keybindings, make);