Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.ts

748 lines26.8 KB

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