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

keybindings.ts

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