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