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