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