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