Open History to see the last commit
1import {
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";
13import * as Array from "effect/Array";
14import * as Cache from "effect/Cache";
15import * as Cause from "effect/Cause";
16import * as Deferred from "effect/Deferred";
17import * as Duration from "effect/Duration";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as FileSystem from "effect/FileSystem";
21import * as Path from "effect/Path";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Predicate from "effect/Predicate";
25import * as PubSub from "effect/PubSub";
26import * as Result from "effect/Result";
27import * as Schedule from "effect/Schedule";
28import * as Schema from "effect/Schema";
29import * as SchemaIssue from "effect/SchemaIssue";
30import * as SchemaTransformation from "effect/SchemaTransformation";
31import * as Ref from "effect/Ref";
32import * as Context from "effect/Context";
33import * as Scope from "effect/Scope";
34import * as Stream from "effect/Stream";
35import * as Semaphore from "effect/Semaphore";
36import * as ServerConfig from "./config.ts";
37import { watchDirectoryReplacements } from "./watchDirectoryReplacements.ts";
38import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
39import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
40import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
41import {
42 DEFAULT_KEYBINDINGS,
43 mergeWithDefaultKeybindings,
44 compileResolvedKeybindingRule,
45 compileResolvedKeybindingsConfig,
46 parseKeybindingShortcut,
47 parseKeybindingWhenExpression,
48} from "@t3tools/shared/keybindings";
49
50export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
51 Schema.decodeTo(
52 Schema.toType(ResolvedKeybindingRule),
53 SchemaTransformation.transformEffect({
54 decode: (rule) =>
55 Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(
56 Effect.filterOrFail(
57 Predicate.isNotNull,
58 () =>
59 new SchemaIssue.InvalidValue({
60 message: "Invalid keybinding rule",
61 }),
62 ),
63 Effect.map((resolved) => resolved),
64 ),
65
66 encode: Effect.fn("keybindings.encode")(function* (resolved) {
67 const key = encodeShortcut(resolved.shortcut);
68 if (!key) {
69 return yield* Effect.fail(
70 new SchemaIssue.InvalidValue({
71 message: "Resolved shortcut cannot be encoded to key string",
72 }),
73 );
74 }
75
76 const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
77 return {
78 key,
79 command: resolved.command,
80 when,
81 };
82 }),
83 }),
84 ),
85);
86
87// Settings sends replace/remove targets in its own normalized spelling, which can differ from a
88// hand-edited file ("cmd+k" vs "meta+k", "a&&b" vs "a && b"), so compare parsed forms.
89function keybindingRuleIdentity(rule: KeybindingRule): string {
90 const shortcut = parseKeybindingShortcut(rule.key);
91 const key = (shortcut && encodeShortcut(shortcut)) ?? rule.key;
92 if (rule.when === undefined) return JSON.stringify([rule.command, key, null]);
93 const whenAst = parseKeybindingWhenExpression(rule.when);
94 return JSON.stringify([rule.command, key, whenAst ? encodeWhenAst(whenAst) : rule.when]);
95}
96
97function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {
98 return keybindingRuleIdentity(left) === keybindingRuleIdentity(right);
99}
100
101const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{
102 readonly id: string;
103 readonly alongside: KeybindingRule;
104 readonly rule: KeybindingRule;
105}> = [
106 {
107 id: "composer.sendBackground:mod+enter",
108 alongside: {
109 key: "mod+alt+enter",
110 command: "composer.sendBackground",
111 when: "composerFocus && draftThreadRoute",
112 },
113 rule: {
114 key: "mod+enter",
115 command: "composer.sendBackground",
116 when: "composerFocus && draftThreadRoute",
117 },
118 },
119];
120
121function keybindingShortcutContext(rule: KeybindingRule): string | null {
122 const parsed = parseKeybindingShortcut(rule.key);
123 if (!parsed) return null;
124 const encoded = encodeShortcut(parsed);
125 if (!encoded) return null;
126 return `${encoded}\u0000${rule.when ?? ""}`;
127}
128
129function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean {
130 const leftContext = keybindingShortcutContext(left);
131 const rightContext = keybindingShortcutContext(right);
132 if (!leftContext || !rightContext) return false;
133 return leftContext === rightContext;
134}
135
136function keybindingRuleFromInput(input: ServerRemoveKeybindingInput): KeybindingRule {
137 return input.when === undefined
138 ? { key: input.key, command: input.command }
139 : { key: input.key, command: input.command, when: input.when };
140}
141
142function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
143 if (!input.replace) return null;
144 return input.replace.when === undefined
145 ? { key: input.replace.key, command: input.replace.command }
146 : { key: input.replace.key, command: input.replace.command, when: input.replace.when };
147}
148
149function encodeShortcut(shortcut: KeybindingShortcut): string | null {
150 const modifiers: string[] = [];
151 if (shortcut.modKey) modifiers.push("mod");
152 if (shortcut.metaKey) modifiers.push("meta");
153 if (shortcut.ctrlKey) modifiers.push("ctrl");
154 if (shortcut.altKey) modifiers.push("alt");
155 if (shortcut.shiftKey) modifiers.push("shift");
156 if (!shortcut.key) return null;
157 if (shortcut.key !== "+" && shortcut.key.includes("+")) return null;
158 const key = shortcut.key === " " ? "space" : shortcut.key;
159 return [...modifiers, key].join("+");
160}
161
162function encodeWhenAst(node: KeybindingWhenNode): string {
163 switch (node.type) {
164 case "identifier":
165 return node.name;
166 case "not":
167 return `!(${encodeWhenAst(node.node)})`;
168 case "and":
169 return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;
170 case "or":
171 return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;
172 }
173}
174
175const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
176const RawKeybindingsEntriesPrettyJson = fromJsonStringPretty(Schema.Array(Schema.Unknown));
177const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);
178const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);
179const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);
180const encodeRawKeybindingsEntriesPrettyJson = Schema.encodeEffect(RawKeybindingsEntriesPrettyJson);
181const isSameResolvedKeybindingRule = Schema.toEquivalence(ResolvedKeybindingRule);
182
183export interface KeybindingsConfigState {
184 readonly keybindings: ResolvedKeybindingsConfig;
185 readonly issues: readonly ServerConfigIssue[];
186}
187
188const isSameKeybindingsConfigState = Schema.toEquivalence(
189 Schema.Struct({
190 keybindings: ResolvedKeybindingsConfig,
191 issues: Schema.Array(ServerConfigIssue),
192 }),
193);
194
195export interface KeybindingsChangeEvent {
196 readonly keybindings: ResolvedKeybindingsConfig;
197 readonly issues: readonly ServerConfigIssue[];
198}
199
200function trimIssueMessage(message: string): string {
201 const trimmed = message.trim();
202 return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
203}
204
205function malformedConfigIssue(detail: string): ServerConfigIssue {
206 return {
207 kind: "keybindings.malformed-config",
208 message: trimIssueMessage(detail),
209 };
210}
211
212function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
213 return {
214 kind: "keybindings.invalid-entry",
215 index,
216 message: trimIssueMessage(detail),
217 };
218}
219
220export class Keybindings extends Context.Service<
221 Keybindings,
222 {
223 readonly start: Effect.Effect<void, KeybindingsConfigError>;
224
225 readonly ready: Effect.Effect<void, KeybindingsConfigError>;
226
227 readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
228
229 readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
230
231 readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
232
233 readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
234
235 readonly revalidate: Effect.Effect<void, KeybindingsConfigError>;
236
237 /** Acquire before reading a snapshot to buffer changes until the stream starts. */
238 readonly subscribeChanges: Effect.Effect<
239 Stream.Stream<KeybindingsChangeEvent>,
240 never,
241 Scope.Scope
242 >;
243
244 /**
245 * Writes config atomically and enforces the max rule count by truncating
246 * oldest entries when needed.
247 */
248 readonly upsertKeybindingRule: (
249 input: ServerUpsertKeybindingInput,
250 ) => Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
251
252 readonly removeKeybindingRule: (
253 input: ServerRemoveKeybindingInput,
254 ) => Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
255 }
256>()("t3/keybindings") {}
257
258const make = Effect.gen(function* () {
259 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
260 const fs = yield* FileSystem.FileSystem;
261 const path = yield* Path.Path;
262 const upsertSemaphore = yield* Semaphore.make(1);
263 const resolvedConfigCacheKey = "resolved" as const;
264 const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
265 const lastEmittedStateRef = yield* Ref.make<KeybindingsConfigState | null>(null);
266 const startedRef = yield* Ref.make(false);
267 const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
268 const watcherScope = yield* Scope.make("sequential");
269 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
270 const emitChange = Effect.fn("keybindings.emitChange")(function* (
271 configState: KeybindingsConfigState,
272 ) {
273 yield* Ref.set(lastEmittedStateRef, configState);
274 yield* PubSub.publish(changesPubSub, configState);
275 });
276
277 const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
278 Effect.mapError(
279 (cause) =>
280 new KeybindingsConfigError({
281 configPath: keybindingsConfigPath,
282 detail: "failed to access keybindings config",
283 cause,
284 }),
285 ),
286 );
287
288 const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
289 Effect.mapError(
290 (cause) =>
291 new KeybindingsConfigError({
292 configPath: keybindingsConfigPath,
293 detail: "failed to read keybindings config",
294 cause,
295 }),
296 ),
297 );
298
299 // Entries this build cannot decode, such as a typo or a command from a newer
300 // build, are written back unchanged so editing another shortcut keeps them.
301 const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
302 ReadonlyArray<{ readonly value: unknown; readonly rule: KeybindingRule | null }>,
303 KeybindingsConfigError
304 > {
305 if (!(yield* readConfigExists)) {
306 return [];
307 }
308
309 const rawConfig = yield* readRawConfig.pipe(
310 Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
311 Effect.mapError(
312 (cause) =>
313 new KeybindingsConfigError({
314 configPath: keybindingsConfigPath,
315 detail: "expected JSON array",
316 cause,
317 }),
318 ),
319 );
320
321 return rawConfig.map((entry) => {
322 const decodedRule = decodeKeybindingRuleExit(entry);
323 if (
324 decodedRule._tag === "Success" &&
325 decodeResolvedKeybindingFromConfigExit(decodedRule.value)._tag === "Success"
326 ) {
327 return { value: decodedRule.value, rule: decodedRule.value };
328 }
329 return { value: entry, rule: null };
330 });
331 });
332
333 const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
334 {
335 readonly keybindings: readonly KeybindingRule[];
336 readonly issues: readonly ServerConfigIssue[];
337 },
338 KeybindingsConfigError
339 > {
340 if (!(yield* readConfigExists)) {
341 return { keybindings: [], issues: [] };
342 }
343
344 const rawConfig = yield* readRawConfig;
345 const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
346 if (decodedEntries._tag === "Failure") {
347 const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
348 return {
349 keybindings: [],
350 issues: [malformedConfigIssue(detail)],
351 };
352 }
353
354 const keybindings: KeybindingRule[] = [];
355 const issues: ServerConfigIssue[] = [];
356 for (const [index, entry] of decodedEntries.value.entries()) {
357 const decodedRule = decodeKeybindingRuleExit(entry);
358 if (decodedRule._tag === "Failure") {
359 const detail = Cause.pretty(decodedRule.cause);
360 issues.push(invalidEntryIssue(index, detail));
361 yield* Effect.logWarning("ignoring invalid keybinding entry", {
362 path: keybindingsConfigPath,
363 index,
364 entry,
365 error: detail,
366 });
367 continue;
368 }
369
370 const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
371 if (resolvedRule._tag === "Failure") {
372 const detail = Cause.pretty(resolvedRule.cause);
373 issues.push(invalidEntryIssue(index, detail));
374 yield* Effect.logWarning("ignoring invalid keybinding entry", {
375 path: keybindingsConfigPath,
376 index,
377 entry,
378 error: detail,
379 });
380 continue;
381 }
382 keybindings.push(decodedRule.value);
383 }
384
385 return { keybindings, issues };
386 });
387
388 const appliedMigrationsPath = path.join(
389 path.dirname(keybindingsConfigPath),
390 "keybindings-migrations",
391 );
392 const readAppliedMigrationIds = fs.readFileString(appliedMigrationsPath).pipe(
393 Effect.map((contents) => new Set(contents.split("\n").filter((line) => line.length > 0))),
394 Effect.orElseSucceed(() => new Set<string>()),
395 );
396 const recordAppliedMigrations = (ids: Iterable<string>) =>
397 writeFileStringAtomically({
398 filePath: appliedMigrationsPath,
399 contents: `${[...new Set(ids)].join("\n")}\n`,
400 }).pipe(
401 Effect.provideService(FileSystem.FileSystem, fs),
402 Effect.provideService(Path.Path, path),
403 Effect.mapError(
404 (cause) =>
405 new KeybindingsConfigError({
406 configPath: keybindingsConfigPath,
407 detail: "failed to record keybinding migrations",
408 cause,
409 }),
410 ),
411 );
412
413 const writeConfigAtomically = (entries: ReadonlyArray<unknown>) => {
414 return encodeRawKeybindingsEntriesPrettyJson(entries).pipe(
415 Effect.map((encoded) => `${encoded}\n`),
416 Effect.flatMap((encoded) =>
417 writeFileStringAtomically({
418 filePath: keybindingsConfigPath,
419 contents: encoded,
420 }).pipe(
421 Effect.provideService(FileSystem.FileSystem, fs),
422 Effect.provideService(Path.Path, path),
423 ),
424 ),
425 Effect.mapError(
426 (cause) =>
427 new KeybindingsConfigError({
428 configPath: keybindingsConfigPath,
429 detail: "failed to write keybindings config",
430 cause,
431 }),
432 ),
433 );
434 };
435
436 const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(
437 Effect.map(({ keybindings, issues }) => ({
438 keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
439 issues,
440 })),
441 );
442
443 const resolvedConfigCache = yield* Cache.makeWith<
444 typeof resolvedConfigCacheKey,
445 KeybindingsConfigState,
446 KeybindingsConfigError
447 >(() => loadConfigStateFromDisk, {
448 capacity: 1,
449 timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero),
450 });
451
452 const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
453
454 const reloadConfigState = Effect.gen(function* () {
455 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
456 return yield* loadConfigStateFromCacheOrDisk;
457 });
458
459 const reloadAndEmit = Effect.gen(function* () {
460 const configState = yield* reloadConfigState;
461 yield* emitChange(configState);
462 return configState;
463 });
464
465 const revalidateAndEmit = upsertSemaphore.withPermits(1)(
466 Effect.gen(function* () {
467 const previousState = yield* Ref.get(lastEmittedStateRef);
468 const configState = yield* reloadConfigState;
469 if (!(previousState && isSameKeybindingsConfigState(previousState, configState))) {
470 yield* emitChange(configState);
471 }
472 return configState;
473 }),
474 );
475
476 const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
477 Effect.gen(function* () {
478 const appliedMigrationIds = yield* readAppliedMigrationIds;
479 const pendingLateDefaults = LATE_DEFAULT_KEYBINDINGS.filter(
480 (late) => !appliedMigrationIds.has(late.id),
481 );
482 const configExists = yield* readConfigExists;
483 if (!configExists) {
484 yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
485 if (pendingLateDefaults.length > 0) {
486 yield* recordAppliedMigrations([
487 ...appliedMigrationIds,
488 ...LATE_DEFAULT_KEYBINDINGS.map((late) => late.id),
489 ]);
490 }
491 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
492 return;
493 }
494
495 const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();
496 if (runtimeConfig.issues.length > 0) {
497 yield* Effect.logWarning(
498 "skipping startup keybindings default sync because config has issues",
499 {
500 path: keybindingsConfigPath,
501 issues: runtimeConfig.issues,
502 },
503 );
504 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
505 return;
506 }
507 const customConfig = runtimeConfig.keybindings;
508 const existingCommands = new Set(customConfig.map((entry) => entry.command));
509 const missingDefaults: KeybindingRule[] = [];
510 const shortcutConflictWarnings: Array<{
511 defaultCommand: KeybindingRule["command"];
512 conflictingCommand: KeybindingRule["command"];
513 key: string;
514 when: string | null;
515 }> = [];
516 for (const defaultRule of DEFAULT_KEYBINDINGS) {
517 if (existingCommands.has(defaultRule.command)) {
518 continue;
519 }
520 const conflictingEntry = customConfig.find((entry) =>
521 hasSameShortcutContext(entry, defaultRule),
522 );
523 if (conflictingEntry) {
524 shortcutConflictWarnings.push({
525 defaultCommand: defaultRule.command,
526 conflictingCommand: conflictingEntry.command,
527 key: defaultRule.key,
528 when: defaultRule.when ?? null,
529 });
530 continue;
531 }
532 missingDefaults.push(defaultRule);
533 }
534 for (const { alongside, rule } of pendingLateDefaults) {
535 if (
536 customConfig.some((entry) => isSameKeybindingRule(entry, alongside)) &&
537 !customConfig.some(
538 (entry) =>
539 hasSameShortcutContext(entry, rule) ||
540 isSameKeybindingRule(entry, { ...rule, when: "false" }),
541 )
542 ) {
543 missingDefaults.push(rule);
544 }
545 }
546 for (const conflict of shortcutConflictWarnings) {
547 yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
548 path: keybindingsConfigPath,
549 defaultCommand: conflict.defaultCommand,
550 conflictingCommand: conflict.conflictingCommand,
551 key: conflict.key,
552 when: conflict.when,
553 reason: "shortcut context already used by existing rule",
554 });
555 }
556 if (missingDefaults.length > 0) {
557 const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
558 customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
559 ? Result.succeed(defaultRule.command)
560 : Result.failVoid,
561 );
562 if (matchingDefaults.length > 0) {
563 yield* Effect.logWarning("default keybinding rule already defined in user config", {
564 path: keybindingsConfigPath,
565 commands: matchingDefaults,
566 });
567 }
568 }
569
570 // Put defaults before persisted rules so custom shortcuts win overlapping conditions.
571 const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length);
572 const defaultsToAppend = missingDefaults.slice(0, availableSlots);
573 const skippedDefaults = missingDefaults.slice(availableSlots);
574 if (skippedDefaults.length > 0) {
575 yield* Effect.logWarning("skipping default keybinding backfill at max entries", {
576 path: keybindingsConfigPath,
577 maxEntries: MAX_KEYBINDINGS_COUNT,
578 commands: skippedDefaults.map((rule) => rule.command),
579 });
580 }
581 if (defaultsToAppend.length > 0) {
582 yield* writeConfigAtomically([...defaultsToAppend, ...customConfig]);
583 }
584 const settledLateDefaults = pendingLateDefaults.filter(
585 (late) => !skippedDefaults.includes(late.rule),
586 );
587 if (settledLateDefaults.length > 0) {
588 yield* recordAppliedMigrations([
589 ...appliedMigrationIds,
590 ...settledLateDefaults.map((late) => late.id),
591 ]);
592 }
593 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
594 }),
595 );
596
597 const startWatcher = Effect.gen(function* () {
598 const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
599 const keybindingsConfigFile = path.basename(keybindingsConfigPath);
600 const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
601
602 yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(
603 Effect.mapError(
604 (cause) =>
605 new KeybindingsConfigError({
606 configPath: keybindingsConfigPath,
607 detail: "failed to prepare keybindings config directory",
608 cause,
609 }),
610 ),
611 );
612
613 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
614
615 // `ready` completes once the watch is registered, or once it fails to be.
616 const watchFileChanges = (filePath: string, ready: Deferred.Deferred<void>) => {
617 const directory = path.dirname(filePath);
618 const resolvedFilePath = path.resolve(filePath);
619 const markReady = () => Deferred.doneUnsafe(ready, Exit.void);
620 return fs.watch(directory, { onReady: markReady }).pipe(
621 Stream.filter((event) => path.resolve(directory, event.path) === resolvedFilePath),
622 Stream.as(undefined),
623 Stream.ensuring(Effect.sync(markReady)),
624 );
625 };
626
627 // A symlinked file (dotfiles) changes in its target's directory, which the watch below never sees.
628 // Re-resolve whenever the link itself is replaced so a retargeted link is followed.
629 const resolveLinkTarget = resolveSymlinkTarget(keybindingsConfigPath).pipe(
630 Effect.provideService(FileSystem.FileSystem, fs),
631 Effect.provideService(Path.Path, path),
632 Effect.option,
633 Effect.map(Option.getOrUndefined),
634 );
635 const linkTargetReady = yield* Deferred.make<void>();
636 // `undefined` is an unresolvable chain (a cycle mid-retarget): nothing to watch yet, but keep polling.
637 const watchLinkTarget = (linkTargetPath: string | undefined) => {
638 if (linkTargetPath === undefined || linkTargetPath === keybindingsConfigPathResolved) {
639 return Stream.fromEffect(Deferred.succeed(linkTargetReady, undefined)).pipe(Stream.drain);
640 }
641 return watchDirectoryReplacements(
642 (parentReady) => watchFileChanges(path.dirname(linkTargetPath), parentReady),
643 Stream.unwrap(
644 Effect.gen(function* () {
645 const registered = yield* Deferred.make<void>();
646 return Stream.merge(
647 watchFileChanges(linkTargetPath, registered).pipe(Stream.ignoreCause({ log: true })),
648 // Startup reloads once ready. Later watches trigger their own reload.
649 Stream.fromEffect(
650 Deferred.await(registered).pipe(
651 Effect.andThen(Deferred.succeed(linkTargetReady, undefined)),
652 ),
653 ).pipe(
654 Stream.filter((completedStartup) => !completedStartup),
655 Stream.as(undefined),
656 ),
657 );
658 }),
659 ),
660 );
661 };
662 // A link further along the chain is replaced where no watch here sees it, so poll for it.
663 const linkTargetWatch = Stream.unwrap(
664 Effect.gen(function* () {
665 const linkTargetPath = yield* resolveLinkTarget;
666 const retargeted =
667 linkTargetPath === keybindingsConfigPathResolved
668 ? Stream.never
669 : Stream.tick("1 second").pipe(
670 Stream.mapEffect(() => resolveLinkTarget),
671 Stream.filter((next) => next !== linkTargetPath),
672 Stream.as(true),
673 );
674 return Stream.merge(
675 watchLinkTarget(linkTargetPath).pipe(Stream.as(false)),
676 retargeted,
677 ).pipe(
678 Stream.takeUntil((moved) => moved),
679 Stream.as(undefined),
680 );
681 }),
682 ).pipe(Stream.repeat(Schedule.forever));
683 const linkTargetEvents = watchDirectoryReplacements(
684 (ready) => watchFileChanges(keybindingsConfigPath, ready),
685 linkTargetWatch,
686 );
687
688 // Saves emit multiple events; fs.watch may fire before content is flushed.
689 const keybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
690 Stream.filter((event) => {
691 return (
692 event.path === keybindingsConfigFile ||
693 event.path === keybindingsConfigPath ||
694 path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
695 );
696 }),
697 );
698 const debouncedKeybindingsEvents = Stream.merge(keybindingsEvents, linkTargetEvents).pipe(
699 Stream.debounce(Duration.millis(100)),
700 );
701
702 yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
703 Effect.ignoreCause({ log: true }),
704 Effect.ensuring(Deferred.succeed(linkTargetReady, undefined)),
705 Effect.forkIn(watcherScope),
706 Effect.asVoid,
707 );
708 // Edits made once `start` returns must reach a registered watch.
709 yield* Deferred.await(linkTargetReady);
710 });
711
712 const start = Effect.gen(function* () {
713 const alreadyStarted = yield* Ref.get(startedRef);
714 if (alreadyStarted) {
715 return yield* Deferred.await(startedDeferred);
716 }
717
718 yield* Ref.set(startedRef, true);
719 const startup = Effect.gen(function* () {
720 yield* startWatcher;
721 yield* syncDefaultKeybindingsOnStartup;
722 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
723 const initialState = yield* loadConfigStateFromCacheOrDisk;
724 yield* Ref.set(lastEmittedStateRef, initialState);
725 });
726
727 const startupExit = yield* Effect.exit(startup);
728 if (startupExit._tag === "Failure") {
729 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
730 return yield* Effect.failCause(startupExit.cause);
731 }
732
733 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
734 });
735
736 return {
737 start,
738 ready: Deferred.await(startedDeferred),
739 syncDefaultKeybindingsOnStartup,
740 loadConfigState: loadConfigStateFromCacheOrDisk,
741 getSnapshot: loadConfigStateFromCacheOrDisk,
742 revalidate: revalidateAndEmit,
743 get streamChanges() {
744 return Stream.fromPubSub(changesPubSub);
745 },
746 get subscribeChanges() {
747 return PubSub.subscribe(changesPubSub).pipe(Effect.map(Stream.fromSubscription));
748 },
749 upsertKeybindingRule: (input) =>
750 upsertSemaphore.withPermits(1)(
751 Effect.gen(function* () {
752 const customConfig = yield* loadWritableCustomKeybindingsConfig();
753 const rule = keybindingRuleFromInput(input);
754 const replaceTarget = replaceTargetFromUpsertInput(input);
755 // A saved rule overrides every inherited default for its command.
756 let siblingDefaults: ReadonlyArray<KeybindingRule> = [];
757 if (
758 (!replaceTarget ||
759 (replaceTarget.command === rule.command &&
760 DEFAULT_KEYBINDINGS.some((entry) => isSameKeybindingRule(entry, replaceTarget)))) &&
761 !customConfig.some(({ rule: entry }) => entry?.command === rule.command) &&
762 decodeResolvedKeybindingFromConfigExit(rule)._tag === "Success"
763 ) {
764 const customRules = customConfig.flatMap(({ rule: entry }) => (entry ? [entry] : []));
765 const visibleBindings = mergeWithDefaultKeybindings(
766 compileResolvedKeybindingsConfig(customRules),
767 ).filter((entry) => entry.command === rule.command);
768 siblingDefaults = DEFAULT_KEYBINDINGS.filter((entry) => {
769 if (
770 entry.command !== rule.command ||
771 (replaceTarget && isSameKeybindingRule(entry, replaceTarget)) ||
772 isSameKeybindingRule(entry, rule)
773 ) {
774 return false;
775 }
776 const resolved = compileResolvedKeybindingRule(entry);
777 return (
778 resolved &&
779 visibleBindings.some((binding) => isSameResolvedKeybindingRule(binding, resolved))
780 );
781 });
782 }
783 const retainedConfig = customConfig.filter(({ rule: entry }) => {
784 if (!entry) return true;
785 return (
786 (!replaceTarget || !isSameKeybindingRule(entry, replaceTarget)) &&
787 !isSameKeybindingRule(entry, rule)
788 );
789 });
790 const availableSlots = MAX_KEYBINDINGS_COUNT - 1;
791 if (
792 siblingDefaults.length > 0 &&
793 retainedConfig.length + siblingDefaults.length > availableSlots
794 ) {
795 return yield* new KeybindingsConfigError({
796 configPath: keybindingsConfigPath,
797 detail: "Not enough room to save this shortcut and its inherited shortcuts.",
798 });
799 }
800 const nextConfig = [
801 ...siblingDefaults,
802 ...retainedConfig.slice(-availableSlots).map(({ value }) => value),
803 rule,
804 ];
805 if (retainedConfig.length > availableSlots) {
806 yield* Effect.logWarning("truncating keybindings config to max entries", {
807 path: keybindingsConfigPath,
808 maxEntries: MAX_KEYBINDINGS_COUNT,
809 });
810 }
811 yield* writeConfigAtomically(nextConfig);
812 return yield* reloadAndEmit;
813 }),
814 ),
815 removeKeybindingRule: (input) =>
816 upsertSemaphore.withPermits(1)(
817 Effect.gen(function* () {
818 const customConfig = yield* loadWritableCustomKeybindingsConfig();
819 const target = keybindingRuleFromInput(input);
820 const nextConfig = customConfig.filter(
821 ({ rule }) => !rule || !isSameKeybindingRule(rule, target),
822 );
823 yield* writeConfigAtomically(nextConfig.map(({ value }) => value));
824 return yield* reloadAndEmit;
825 }),
826 ),
827 } satisfies Keybindings["Service"];
828});
829
830export const layer = Layer.effect(Keybindings, make);