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