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