The best way to control Claude Code, Codex and more from any computer or phone

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