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