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

keybindings.ts

702 lines24.1 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 "@v12/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 * as ServerConfig from "./config.ts";
45import { writeFileStringAtomically } from "./atomicWrite.ts";
46import { fromJsonStringPretty, fromLenientJson } from "@v12/shared/schemaJson";
47import {
48 DEFAULT_KEYBINDINGS,
49 DEFAULT_RESOLVED_KEYBINDINGS,
50 compileResolvedKeybindingRule,
51 compileResolvedKeybindingsConfig,
52 parseKeybindingShortcut,
53} from "@v12/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 );
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 ?? ""}`;
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;
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 };
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 };
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 };
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("+");
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 }
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[];
183​
184export interface KeybindingsChangeEvent {
185 readonly keybindings: ResolvedKeybindingsConfig;
186 readonly issues: readonly ServerConfigIssue[];
188​
189function trimIssueMessage(message: string): string {
190 const trimmed = message.trim();
191 return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
193​
194function malformedConfigIssue(detail: string): ServerConfigIssue {
195 return {
196 kind: "keybindings.malformed-config",
197 message: trimIssueMessage(detail),
198 };
200​
201function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
202 return {
203 kind: "keybindings.invalid-entry",
204 index,
205 message: trimIssueMessage(detail),
206 };
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);
227​
228/**
229 * Keybindings - Service tag for keybinding configuration operations.
230 */
231export class Keybindings extends Context.Service<
232 Keybindings,
233 {
234 /**
235 * Start the keybindings runtime and attach file watching.
236 *
237 * Safe to call multiple times. The first successful call establishes the
238 * runtime; later calls await the same startup.
239 */
240 readonly start: Effect.Effect<void, KeybindingsConfigError>;
241​
242 /**
243 * Await keybindings runtime readiness.
244 *
245 * Readiness means the config directory exists, the watcher is attached, the
246 * startup sync has completed, and the current snapshot has been loaded.
247 */
248 readonly ready: Effect.Effect<void, KeybindingsConfigError>;
249​
250 /**
251 * Ensure the on-disk keybindings file exists and includes all default
252 * commands so newly-added defaults are backfilled on startup.
253 */
254 readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
255​
256 /**
257 * Load runtime keybindings state along with non-fatal configuration issues.
258 */
259 readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
260​
261 /**
262 * Read the latest keybindings snapshot from cache/disk.
263 */
264 readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
265​
266 /**
267 * Stream of keybindings config change events.
268 */
269 readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
270​
271 /**
272 * Upsert a keybinding rule and persist the resulting configuration.
273 *
274 * Writes config atomically and enforces the max rule count by truncating
275 * oldest entries when needed.
276 */
277 readonly upsertKeybindingRule: (
278 input: ServerUpsertKeybindingInput,
279 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
280​
281 /**
282 * Remove a single persisted keybinding rule by exact key/command/when match.
283 */
284 readonly removeKeybindingRule: (
285 input: ServerRemoveKeybindingInput,
286 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
287 }
288>()("v12/keybindings") {}
289​
290const make = Effect.gen(function* () {
291 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
292 const fs = yield* FileSystem.FileSystem;
293 const path = yield* Path.Path;
294 const upsertSemaphore = yield* Semaphore.make(1);
295 const resolvedConfigCacheKey = "resolved" as const;
296 const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
297 const startedRef = yield* Ref.make(false);
298 const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
299 const watcherScope = yield* Scope.make("sequential");
300 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
301 const emitChange = (configState: KeybindingsConfigState) =>
302 PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
303​
304 const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
305 Effect.mapError(
306 (cause) =>
307 new KeybindingsConfigError({
308 configPath: keybindingsConfigPath,
309 detail: "failed to access keybindings config",
310 cause,
311 }),
312 ),
313 );
314​
315 const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
316 Effect.mapError(
317 (cause) =>
318 new KeybindingsConfigError({
319 configPath: keybindingsConfigPath,
320 detail: "failed to read keybindings config",
321 cause,
322 }),
323 ),
324 );
325​
326 const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
327 readonly KeybindingRule[],
328 KeybindingsConfigError
329 > {
330 if (!(yield* readConfigExists)) {
331 return [];
332 }
333​
334 const rawConfig = yield* readRawConfig.pipe(
335 Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
336 Effect.mapError(
337 (cause) =>
338 new KeybindingsConfigError({
339 configPath: keybindingsConfigPath,
340 detail: "expected JSON array",
341 cause,
342 }),
343 ),
344 );
345​
346 return yield* Effect.forEach(rawConfig, (entry) =>
347 Effect.gen(function* () {
348 const decodedRule = decodeKeybindingRuleExit(entry);
349 if (decodedRule._tag === "Failure") {
350 yield* Effect.logWarning("ignoring invalid keybinding entry", {
351 path: keybindingsConfigPath,
352 entry,
353 error: Cause.pretty(decodedRule.cause),
354 });
355 return null;
356 }
357 const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
358 if (resolved._tag === "Failure") {
359 yield* Effect.logWarning("ignoring invalid keybinding entry", {
360 path: keybindingsConfigPath,
361 entry,
362 error: Cause.pretty(resolved.cause),
363 });
364 return null;
365 }
366 return decodedRule.value;
367 }),
368 ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
369 });
370​
371 const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
372 {
373 readonly keybindings: readonly KeybindingRule[];
374 readonly issues: readonly ServerConfigIssue[];
375 },
376 KeybindingsConfigError
377 > {
378 if (!(yield* readConfigExists)) {
379 return { keybindings: [], issues: [] };
380 }
381​
382 const rawConfig = yield* readRawConfig;
383 const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
384 if (decodedEntries._tag === "Failure") {
385 const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
386 return {
387 keybindings: [],
388 issues: [malformedConfigIssue(detail)],
389 };
390 }
391​
392 const keybindings: KeybindingRule[] = [];
393 const issues: ServerConfigIssue[] = [];
394 for (const [index, entry] of decodedEntries.value.entries()) {
395 const decodedRule = decodeKeybindingRuleExit(entry);
396 if (decodedRule._tag === "Failure") {
397 const detail = Cause.pretty(decodedRule.cause);
398 issues.push(invalidEntryIssue(index, detail));
399 yield* Effect.logWarning("ignoring invalid keybinding entry", {
400 path: keybindingsConfigPath,
401 index,
402 entry,
403 error: detail,
404 });
405 continue;
406 }
407​
408 const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
409 if (resolvedRule._tag === "Failure") {
410 const detail = Cause.pretty(resolvedRule.cause);
411 issues.push(invalidEntryIssue(index, detail));
412 yield* Effect.logWarning("ignoring invalid keybinding entry", {
413 path: keybindingsConfigPath,
414 index,
415 entry,
416 error: detail,
417 });
418 continue;
419 }
420 keybindings.push(decodedRule.value);
421 }
422​
423 return { keybindings, issues };
424 });
425​
426 const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
427 return encodeKeybindingsConfigPrettyJson(rules).pipe(
428 Effect.map((encoded) => `${encoded}\n`),
429 Effect.flatMap((encoded) =>
430 writeFileStringAtomically({
431 filePath: keybindingsConfigPath,
432 contents: encoded,
433 }).pipe(
434 Effect.provideService(FileSystem.FileSystem, fs),
435 Effect.provideService(Path.Path, path),
436 ),
437 ),
438 Effect.mapError(
439 (cause) =>
440 new KeybindingsConfigError({
441 configPath: keybindingsConfigPath,
442 detail: "failed to write keybindings config",
443 cause,
444 }),
445 ),
446 );
447 };
448​
449 const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(
450 Effect.map(({ keybindings, issues }) => ({
451 keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
452 issues,
453 })),
454 );
455​
456 const resolvedConfigCache = yield* Cache.make<
457 typeof resolvedConfigCacheKey,
458 KeybindingsConfigState,
459 KeybindingsConfigError
460 >({
461 capacity: 1,
462 lookup: () => loadConfigStateFromDisk,
463 });
464​
465 const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
466​
467 const revalidateAndEmit = upsertSemaphore.withPermits(1)(
468 Effect.gen(function* () {
469 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
470 const configState = yield* loadConfigStateFromCacheOrDisk;
471 yield* emitChange(configState);
472 }),
473 );
474​
475 const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
476 Effect.gen(function* () {
477 const configExists = yield* readConfigExists;
478 if (!configExists) {
479 yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
480 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
481 return;
482 }
483​
484 const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();
485 if (runtimeConfig.issues.length > 0) {
486 yield* Effect.logWarning(
487 "skipping startup keybindings default sync because config has issues",
488 {
489 path: keybindingsConfigPath,
490 issues: runtimeConfig.issues,
491 },
492 );
493 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
494 return;
495 }
496 const customConfig = runtimeConfig.keybindings;
497 const existingCommands = new Set(customConfig.map((entry) => entry.command));
498 const missingDefaults: KeybindingRule[] = [];
499 const shortcutConflictWarnings: Array<{
500 defaultCommand: KeybindingRule["command"];
501 conflictingCommand: KeybindingRule["command"];
502 key: string;
503 when: string | null;
504 }> = [];
505 for (const defaultRule of DEFAULT_KEYBINDINGS) {
506 if (existingCommands.has(defaultRule.command)) {
507 continue;
508 }
509 const conflictingEntry = customConfig.find((entry) =>
510 hasSameShortcutContext(entry, defaultRule),
511 );
512 if (conflictingEntry) {
513 shortcutConflictWarnings.push({
514 defaultCommand: defaultRule.command,
515 conflictingCommand: conflictingEntry.command,
516 key: defaultRule.key,
517 when: defaultRule.when ?? null,
518 });
519 continue;
520 }
521 missingDefaults.push(defaultRule);
522 }
523 for (const conflict of shortcutConflictWarnings) {
524 yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
525 path: keybindingsConfigPath,
526 defaultCommand: conflict.defaultCommand,
527 conflictingCommand: conflict.conflictingCommand,
528 key: conflict.key,
529 when: conflict.when,
530 reason: "shortcut context already used by existing rule",
531 });
532 }
533 if (missingDefaults.length === 0) {
534 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
535 return;
536 }
537​
538 const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
539 customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
540 ? Result.succeed(defaultRule.command)
541 : Result.failVoid,
542 );
543 if (matchingDefaults.length > 0) {
544 yield* Effect.logWarning("default keybinding rule already defined in user config", {
545 path: keybindingsConfigPath,
546 commands: matchingDefaults,
547 });
548 }
549​
550 const nextConfig = [...customConfig, ...missingDefaults];
551 const cappedConfig =
552 nextConfig.length > MAX_KEYBINDINGS_COUNT
553 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
554 : nextConfig;
555 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
556 yield* Effect.logWarning("truncating keybindings config to max entries", {
557 path: keybindingsConfigPath,
558 maxEntries: MAX_KEYBINDINGS_COUNT,
559 });
560 }
561​
562 yield* writeConfigAtomically(cappedConfig);
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 !isSameKeybindingRule(entry, replaceTarget);
648 }
649 return !isSameKeybindingRule(entry, rule);
650 }),
651 rule,
652 ];
653 const cappedConfig =
654 nextConfig.length > MAX_KEYBINDINGS_COUNT
655 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
656 : nextConfig;
657 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
658 yield* Effect.logWarning("truncating keybindings config to max entries", {
659 path: keybindingsConfigPath,
660 maxEntries: MAX_KEYBINDINGS_COUNT,
661 });
662 }
663 yield* writeConfigAtomically(cappedConfig);
664 const nextResolved = mergeWithDefaultKeybindings(
665 compileResolvedKeybindingsConfig(cappedConfig),
666 );
667 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
668 keybindings: nextResolved,
669 issues: [],
670 });
671 yield* emitChange({
672 keybindings: nextResolved,
673 issues: [],
674 });
675 return nextResolved;
676 }),
677 ),
678 removeKeybindingRule: (input) =>
679 upsertSemaphore.withPermits(1)(
680 Effect.gen(function* () {
681 const customConfig = yield* loadWritableCustomKeybindingsConfig();
682 const target = keybindingRuleFromRemoveInput(input);
683 const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
684 yield* writeConfigAtomically(nextConfig);
685 const nextResolved = mergeWithDefaultKeybindings(
686 compileResolvedKeybindingsConfig(nextConfig),
687 );
688 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
689 keybindings: nextResolved,
690 issues: [],
691 });
692 yield* emitChange({
693 keybindings: nextResolved,
694 issues: [],
695 });
696 return nextResolved;
697 }),
698 ),
699 } satisfies Keybindings["Service"];
700});
701​
702export const layer = Layer.effect(Keybindings, make);