import { KeybindingRule, KeybindingsConfigError, KeybindingShortcut, KeybindingWhenNode, MAX_KEYBINDINGS_COUNT, ResolvedKeybindingRule, ResolvedKeybindingsConfig, type ServerRemoveKeybindingInput, type ServerUpsertKeybindingInput, ServerConfigIssue, } from "@t3tools/contracts"; import * as Array from "effect/Array"; import * as Cache from "effect/Cache"; import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Predicate from "effect/Predicate"; import * as PubSub from "effect/PubSub"; import * as Result from "effect/Result"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as SchemaIssue from "effect/SchemaIssue"; import * as SchemaTransformation from "effect/SchemaTransformation"; import * as Ref from "effect/Ref"; import * as Context from "effect/Context"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "./config.ts"; import { watchDirectoryReplacements } from "./watchDirectoryReplacements.ts"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import { resolveSymlinkTarget } from "@t3tools/shared/symlink"; import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson"; import { DEFAULT_KEYBINDINGS, mergeWithDefaultKeybindings, compileResolvedKeybindingRule, compileResolvedKeybindingsConfig, parseKeybindingShortcut, parseKeybindingWhenExpression, } from "@t3tools/shared/keybindings"; export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( Schema.decodeTo( Schema.toType(ResolvedKeybindingRule), SchemaTransformation.transformEffect({ decode: (rule) => Effect.succeed(compileResolvedKeybindingRule(rule)).pipe( Effect.filterOrFail( Predicate.isNotNull, () => new SchemaIssue.InvalidValue({ message: "Invalid keybinding rule", }), ), Effect.map((resolved) => resolved), ), encode: Effect.fn("keybindings.encode")(function* (resolved) { const key = encodeShortcut(resolved.shortcut); if (!key) { return yield* Effect.fail( new SchemaIssue.InvalidValue({ message: "Resolved shortcut cannot be encoded to key string", }), ); } const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined; return { key, command: resolved.command, when, }; }), }), ), ); // Settings sends replace/remove targets in its own normalized spelling, which can differ from a // hand-edited file ("cmd+k" vs "meta+k", "a&&b" vs "a && b"), so compare parsed forms. function keybindingRuleIdentity(rule: KeybindingRule): string { const shortcut = parseKeybindingShortcut(rule.key); const key = (shortcut && encodeShortcut(shortcut)) ?? rule.key; if (rule.when === undefined) return JSON.stringify([rule.command, key, null]); const whenAst = parseKeybindingWhenExpression(rule.when); return JSON.stringify([rule.command, key, whenAst ? encodeWhenAst(whenAst) : rule.when]); } function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean { return keybindingRuleIdentity(left) === keybindingRuleIdentity(right); } const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{ readonly id: string; readonly alongside: KeybindingRule; readonly rule: KeybindingRule; }> = [ { id: "composer.sendBackground:mod+enter", alongside: { key: "mod+alt+enter", command: "composer.sendBackground", when: "composerFocus && draftThreadRoute", }, rule: { key: "mod+enter", command: "composer.sendBackground", when: "composerFocus && draftThreadRoute", }, }, ]; function keybindingShortcutContext(rule: KeybindingRule): string | null { const parsed = parseKeybindingShortcut(rule.key); if (!parsed) return null; const encoded = encodeShortcut(parsed); if (!encoded) return null; return `${encoded}\u0000${rule.when ?? ""}`; } function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean { const leftContext = keybindingShortcutContext(left); const rightContext = keybindingShortcutContext(right); if (!leftContext || !rightContext) return false; return leftContext === rightContext; } function keybindingRuleFromInput(input: ServerRemoveKeybindingInput): KeybindingRule { return input.when === undefined ? { key: input.key, command: input.command } : { key: input.key, command: input.command, when: input.when }; } function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null { if (!input.replace) return null; return input.replace.when === undefined ? { key: input.replace.key, command: input.replace.command } : { key: input.replace.key, command: input.replace.command, when: input.replace.when }; } function encodeShortcut(shortcut: KeybindingShortcut): string | null { const modifiers: string[] = []; if (shortcut.modKey) modifiers.push("mod"); if (shortcut.metaKey) modifiers.push("meta"); if (shortcut.ctrlKey) modifiers.push("ctrl"); if (shortcut.altKey) modifiers.push("alt"); if (shortcut.shiftKey) modifiers.push("shift"); if (!shortcut.key) return null; if (shortcut.key !== "+" && shortcut.key.includes("+")) return null; const key = shortcut.key === " " ? "space" : shortcut.key; return [...modifiers, key].join("+"); } function encodeWhenAst(node: KeybindingWhenNode): string { switch (node.type) { case "identifier": return node.name; case "not": return `!(${encodeWhenAst(node.node)})`; case "and": return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`; case "or": return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`; } } const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown)); const RawKeybindingsEntriesPrettyJson = fromJsonStringPretty(Schema.Array(Schema.Unknown)); const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule); const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig); const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries); const encodeRawKeybindingsEntriesPrettyJson = Schema.encodeEffect(RawKeybindingsEntriesPrettyJson); const isSameResolvedKeybindingRule = Schema.toEquivalence(ResolvedKeybindingRule); export interface KeybindingsConfigState { readonly keybindings: ResolvedKeybindingsConfig; readonly issues: readonly ServerConfigIssue[]; } const isSameKeybindingsConfigState = Schema.toEquivalence( Schema.Struct({ keybindings: ResolvedKeybindingsConfig, issues: Schema.Array(ServerConfigIssue), }), ); export interface KeybindingsChangeEvent { readonly keybindings: ResolvedKeybindingsConfig; readonly issues: readonly ServerConfigIssue[]; } function trimIssueMessage(message: string): string { const trimmed = message.trim(); return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration."; } function malformedConfigIssue(detail: string): ServerConfigIssue { return { kind: "keybindings.malformed-config", message: trimIssueMessage(detail), }; } function invalidEntryIssue(index: number, detail: string): ServerConfigIssue { return { kind: "keybindings.invalid-entry", index, message: trimIssueMessage(detail), }; } export class Keybindings extends Context.Service< Keybindings, { readonly start: Effect.Effect; readonly ready: Effect.Effect; readonly syncDefaultKeybindingsOnStartup: Effect.Effect; readonly loadConfigState: Effect.Effect; readonly getSnapshot: Effect.Effect; readonly streamChanges: Stream.Stream; readonly revalidate: Effect.Effect; /** Acquire before reading a snapshot to buffer changes until the stream starts. */ readonly subscribeChanges: Effect.Effect< Stream.Stream, never, Scope.Scope >; /** * Writes config atomically and enforces the max rule count by truncating * oldest entries when needed. */ readonly upsertKeybindingRule: ( input: ServerUpsertKeybindingInput, ) => Effect.Effect; readonly removeKeybindingRule: ( input: ServerRemoveKeybindingInput, ) => Effect.Effect; } >()("t3/keybindings") {} const make = Effect.gen(function* () { const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const upsertSemaphore = yield* Semaphore.make(1); const resolvedConfigCacheKey = "resolved" as const; const changesPubSub = yield* PubSub.unbounded(); const lastEmittedStateRef = yield* Ref.make(null); const startedRef = yield* Ref.make(false); const startedDeferred = yield* Deferred.make(); const watcherScope = yield* Scope.make("sequential"); yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void)); const emitChange = Effect.fn("keybindings.emitChange")(function* ( configState: KeybindingsConfigState, ) { yield* Ref.set(lastEmittedStateRef, configState); yield* PubSub.publish(changesPubSub, configState); }); const readConfigExists = fs.exists(keybindingsConfigPath).pipe( Effect.mapError( (cause) => new KeybindingsConfigError({ configPath: keybindingsConfigPath, detail: "failed to access keybindings config", cause, }), ), ); const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe( Effect.mapError( (cause) => new KeybindingsConfigError({ configPath: keybindingsConfigPath, detail: "failed to read keybindings config", cause, }), ), ); // Entries this build cannot decode, such as a typo or a command from a newer // build, are written back unchanged so editing another shortcut keeps them. const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return< ReadonlyArray<{ readonly value: unknown; readonly rule: KeybindingRule | null }>, KeybindingsConfigError > { if (!(yield* readConfigExists)) { return []; } const rawConfig = yield* readRawConfig.pipe( Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)), Effect.mapError( (cause) => new KeybindingsConfigError({ configPath: keybindingsConfigPath, detail: "expected JSON array", cause, }), ), ); return rawConfig.map((entry) => { const decodedRule = decodeKeybindingRuleExit(entry); if ( decodedRule._tag === "Success" && decodeResolvedKeybindingFromConfigExit(decodedRule.value)._tag === "Success" ) { return { value: decodedRule.value, rule: decodedRule.value }; } return { value: entry, rule: null }; }); }); const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return< { readonly keybindings: readonly KeybindingRule[]; readonly issues: readonly ServerConfigIssue[]; }, KeybindingsConfigError > { if (!(yield* readConfigExists)) { return { keybindings: [], issues: [] }; } const rawConfig = yield* readRawConfig; const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig); if (decodedEntries._tag === "Failure") { const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`; return { keybindings: [], issues: [malformedConfigIssue(detail)], }; } const keybindings: KeybindingRule[] = []; const issues: ServerConfigIssue[] = []; for (const [index, entry] of decodedEntries.value.entries()) { const decodedRule = decodeKeybindingRuleExit(entry); if (decodedRule._tag === "Failure") { const detail = Cause.pretty(decodedRule.cause); issues.push(invalidEntryIssue(index, detail)); yield* Effect.logWarning("ignoring invalid keybinding entry", { path: keybindingsConfigPath, index, entry, error: detail, }); continue; } const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value); if (resolvedRule._tag === "Failure") { const detail = Cause.pretty(resolvedRule.cause); issues.push(invalidEntryIssue(index, detail)); yield* Effect.logWarning("ignoring invalid keybinding entry", { path: keybindingsConfigPath, index, entry, error: detail, }); continue; } keybindings.push(decodedRule.value); } return { keybindings, issues }; }); const appliedMigrationsPath = path.join( path.dirname(keybindingsConfigPath), "keybindings-migrations", ); const readAppliedMigrationIds = fs.readFileString(appliedMigrationsPath).pipe( Effect.map((contents) => new Set(contents.split("\n").filter((line) => line.length > 0))), Effect.orElseSucceed(() => new Set()), ); const recordAppliedMigrations = (ids: Iterable) => writeFileStringAtomically({ filePath: appliedMigrationsPath, contents: `${[...new Set(ids)].join("\n")}\n`, }).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), Effect.mapError( (cause) => new KeybindingsConfigError({ configPath: keybindingsConfigPath, detail: "failed to record keybinding migrations", cause, }), ), ); const writeConfigAtomically = (entries: ReadonlyArray) => { return encodeRawKeybindingsEntriesPrettyJson(entries).pipe( Effect.map((encoded) => `${encoded}\n`), Effect.flatMap((encoded) => writeFileStringAtomically({ filePath: keybindingsConfigPath, contents: encoded, }).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), ), ), Effect.mapError( (cause) => new KeybindingsConfigError({ configPath: keybindingsConfigPath, detail: "failed to write keybindings config", cause, }), ), ); }; const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe( Effect.map(({ keybindings, issues }) => ({ keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)), issues, })), ); const resolvedConfigCache = yield* Cache.makeWith< typeof resolvedConfigCacheKey, KeybindingsConfigState, KeybindingsConfigError >(() => loadConfigStateFromDisk, { capacity: 1, timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero), }); const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey); const reloadConfigState = Effect.gen(function* () { yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); return yield* loadConfigStateFromCacheOrDisk; }); const reloadAndEmit = Effect.gen(function* () { const configState = yield* reloadConfigState; yield* emitChange(configState); return configState; }); const revalidateAndEmit = upsertSemaphore.withPermits(1)( Effect.gen(function* () { const previousState = yield* Ref.get(lastEmittedStateRef); const configState = yield* reloadConfigState; if (!(previousState && isSameKeybindingsConfigState(previousState, configState))) { yield* emitChange(configState); } return configState; }), ); const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)( Effect.gen(function* () { const appliedMigrationIds = yield* readAppliedMigrationIds; const pendingLateDefaults = LATE_DEFAULT_KEYBINDINGS.filter( (late) => !appliedMigrationIds.has(late.id), ); const configExists = yield* readConfigExists; if (!configExists) { yield* writeConfigAtomically(DEFAULT_KEYBINDINGS); if (pendingLateDefaults.length > 0) { yield* recordAppliedMigrations([ ...appliedMigrationIds, ...LATE_DEFAULT_KEYBINDINGS.map((late) => late.id), ]); } yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); return; } const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig(); if (runtimeConfig.issues.length > 0) { yield* Effect.logWarning( "skipping startup keybindings default sync because config has issues", { path: keybindingsConfigPath, issues: runtimeConfig.issues, }, ); yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); return; } const customConfig = runtimeConfig.keybindings; const existingCommands = new Set(customConfig.map((entry) => entry.command)); const missingDefaults: KeybindingRule[] = []; const shortcutConflictWarnings: Array<{ defaultCommand: KeybindingRule["command"]; conflictingCommand: KeybindingRule["command"]; key: string; when: string | null; }> = []; for (const defaultRule of DEFAULT_KEYBINDINGS) { if (existingCommands.has(defaultRule.command)) { continue; } const conflictingEntry = customConfig.find((entry) => hasSameShortcutContext(entry, defaultRule), ); if (conflictingEntry) { shortcutConflictWarnings.push({ defaultCommand: defaultRule.command, conflictingCommand: conflictingEntry.command, key: defaultRule.key, when: defaultRule.when ?? null, }); continue; } missingDefaults.push(defaultRule); } for (const { alongside, rule } of pendingLateDefaults) { if ( customConfig.some((entry) => isSameKeybindingRule(entry, alongside)) && !customConfig.some( (entry) => hasSameShortcutContext(entry, rule) || isSameKeybindingRule(entry, { ...rule, when: "false" }), ) ) { missingDefaults.push(rule); } } for (const conflict of shortcutConflictWarnings) { yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", { path: keybindingsConfigPath, defaultCommand: conflict.defaultCommand, conflictingCommand: conflict.conflictingCommand, key: conflict.key, when: conflict.when, reason: "shortcut context already used by existing rule", }); } if (missingDefaults.length > 0) { const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) => customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)) ? Result.succeed(defaultRule.command) : Result.failVoid, ); if (matchingDefaults.length > 0) { yield* Effect.logWarning("default keybinding rule already defined in user config", { path: keybindingsConfigPath, commands: matchingDefaults, }); } } // Put defaults before persisted rules so custom shortcuts win overlapping conditions. const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length); const defaultsToAppend = missingDefaults.slice(0, availableSlots); const skippedDefaults = missingDefaults.slice(availableSlots); if (skippedDefaults.length > 0) { yield* Effect.logWarning("skipping default keybinding backfill at max entries", { path: keybindingsConfigPath, maxEntries: MAX_KEYBINDINGS_COUNT, commands: skippedDefaults.map((rule) => rule.command), }); } if (defaultsToAppend.length > 0) { yield* writeConfigAtomically([...defaultsToAppend, ...customConfig]); } const settledLateDefaults = pendingLateDefaults.filter( (late) => !skippedDefaults.includes(late.rule), ); if (settledLateDefaults.length > 0) { yield* recordAppliedMigrations([ ...appliedMigrationIds, ...settledLateDefaults.map((late) => late.id), ]); } yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); }), ); const startWatcher = Effect.gen(function* () { const keybindingsConfigDir = path.dirname(keybindingsConfigPath); const keybindingsConfigFile = path.basename(keybindingsConfigPath); const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath); yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe( Effect.mapError( (cause) => new KeybindingsConfigError({ configPath: keybindingsConfigPath, detail: "failed to prepare keybindings config directory", cause, }), ), ); const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true })); // `ready` completes once the watch is registered, or once it fails to be. const watchFileChanges = (filePath: string, ready: Deferred.Deferred) => { const directory = path.dirname(filePath); const resolvedFilePath = path.resolve(filePath); const markReady = () => Deferred.doneUnsafe(ready, Exit.void); return fs.watch(directory, { onReady: markReady }).pipe( Stream.filter((event) => path.resolve(directory, event.path) === resolvedFilePath), Stream.as(undefined), Stream.ensuring(Effect.sync(markReady)), ); }; // A symlinked file (dotfiles) changes in its target's directory, which the watch below never sees. // Re-resolve whenever the link itself is replaced so a retargeted link is followed. const resolveLinkTarget = resolveSymlinkTarget(keybindingsConfigPath).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), Effect.orElseSucceed(() => keybindingsConfigPathResolved), ); const linkTargetReady = yield* Deferred.make(); const watchLinkTargetOnce = Stream.unwrap( Effect.gen(function* () { const linkTargetPath = yield* resolveLinkTarget; if (linkTargetPath === keybindingsConfigPathResolved) { return Stream.fromEffect(Deferred.succeed(linkTargetReady, undefined)).pipe(Stream.drain); } return watchDirectoryReplacements( (parentReady) => watchFileChanges(path.dirname(linkTargetPath), parentReady), Stream.unwrap( Effect.gen(function* () { const registered = yield* Deferred.make(); return Stream.merge( watchFileChanges(linkTargetPath, registered).pipe( Stream.ignoreCause({ log: true }), ), // Startup reloads once ready. Later watches trigger their own reload. Stream.fromEffect( Deferred.await(registered).pipe( Effect.andThen(Deferred.succeed(linkTargetReady, undefined)), ), ).pipe( Stream.filter((completedStartup) => !completedStartup), Stream.as(undefined), ), ); }), ), ); }), ); // A link further along the chain is replaced where no watch here sees it, so poll for it. const linkTargetWatch = Stream.unwrap( Effect.gen(function* () { const linkTargetPath = yield* resolveLinkTarget; const retargeted = linkTargetPath === keybindingsConfigPathResolved ? Stream.never : Stream.tick("1 second").pipe( Stream.mapEffect(() => resolveLinkTarget), Stream.filter((next) => next !== linkTargetPath), Stream.as(true), ); return Stream.merge(watchLinkTargetOnce.pipe(Stream.as(false)), retargeted).pipe( Stream.takeUntil((moved) => moved), Stream.as(undefined), ); }), ).pipe(Stream.repeat(Schedule.forever)); const linkTargetEvents = watchDirectoryReplacements( (ready) => watchFileChanges(keybindingsConfigPath, ready), linkTargetWatch, ); // Saves emit multiple events; fs.watch may fire before content is flushed. const keybindingsEvents = fs.watch(keybindingsConfigDir).pipe( Stream.filter((event) => { return ( event.path === keybindingsConfigFile || event.path === keybindingsConfigPath || path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved ); }), ); const debouncedKeybindingsEvents = Stream.merge(keybindingsEvents, linkTargetEvents).pipe( Stream.debounce(Duration.millis(100)), ); yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe( Effect.ignoreCause({ log: true }), Effect.ensuring(Deferred.succeed(linkTargetReady, undefined)), Effect.forkIn(watcherScope), Effect.asVoid, ); // Edits made once `start` returns must reach a registered watch. yield* Deferred.await(linkTargetReady); }); const start = Effect.gen(function* () { const alreadyStarted = yield* Ref.get(startedRef); if (alreadyStarted) { return yield* Deferred.await(startedDeferred); } yield* Ref.set(startedRef, true); const startup = Effect.gen(function* () { yield* startWatcher; yield* syncDefaultKeybindingsOnStartup; yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey); const initialState = yield* loadConfigStateFromCacheOrDisk; yield* Ref.set(lastEmittedStateRef, initialState); }); const startupExit = yield* Effect.exit(startup); if (startupExit._tag === "Failure") { yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie); return yield* Effect.failCause(startupExit.cause); } yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie); }); return { start, ready: Deferred.await(startedDeferred), syncDefaultKeybindingsOnStartup, loadConfigState: loadConfigStateFromCacheOrDisk, getSnapshot: loadConfigStateFromCacheOrDisk, revalidate: revalidateAndEmit, get streamChanges() { return Stream.fromPubSub(changesPubSub); }, get subscribeChanges() { return PubSub.subscribe(changesPubSub).pipe(Effect.map(Stream.fromSubscription)); }, upsertKeybindingRule: (input) => upsertSemaphore.withPermits(1)( Effect.gen(function* () { const customConfig = yield* loadWritableCustomKeybindingsConfig(); const rule = keybindingRuleFromInput(input); const replaceTarget = replaceTargetFromUpsertInput(input); // A saved rule overrides every inherited default for its command. let siblingDefaults: ReadonlyArray = []; if ( (!replaceTarget || (replaceTarget.command === rule.command && DEFAULT_KEYBINDINGS.some((entry) => isSameKeybindingRule(entry, replaceTarget)))) && !customConfig.some(({ rule: entry }) => entry?.command === rule.command) && decodeResolvedKeybindingFromConfigExit(rule)._tag === "Success" ) { const customRules = customConfig.flatMap(({ rule: entry }) => (entry ? [entry] : [])); const visibleBindings = mergeWithDefaultKeybindings( compileResolvedKeybindingsConfig(customRules), ).filter((entry) => entry.command === rule.command); siblingDefaults = DEFAULT_KEYBINDINGS.filter((entry) => { if ( entry.command !== rule.command || (replaceTarget && isSameKeybindingRule(entry, replaceTarget)) || isSameKeybindingRule(entry, rule) ) { return false; } const resolved = compileResolvedKeybindingRule(entry); return ( resolved && visibleBindings.some((binding) => isSameResolvedKeybindingRule(binding, resolved)) ); }); } const retainedConfig = customConfig.filter(({ rule: entry }) => { if (!entry) return true; return ( (!replaceTarget || !isSameKeybindingRule(entry, replaceTarget)) && !isSameKeybindingRule(entry, rule) ); }); const availableSlots = MAX_KEYBINDINGS_COUNT - 1; if ( siblingDefaults.length > 0 && retainedConfig.length + siblingDefaults.length > availableSlots ) { return yield* new KeybindingsConfigError({ configPath: keybindingsConfigPath, detail: "Not enough room to save this shortcut and its inherited shortcuts.", }); } const nextConfig = [ ...siblingDefaults, ...retainedConfig.slice(-availableSlots).map(({ value }) => value), rule, ]; if (retainedConfig.length > availableSlots) { yield* Effect.logWarning("truncating keybindings config to max entries", { path: keybindingsConfigPath, maxEntries: MAX_KEYBINDINGS_COUNT, }); } yield* writeConfigAtomically(nextConfig); return yield* reloadAndEmit; }), ), removeKeybindingRule: (input) => upsertSemaphore.withPermits(1)( Effect.gen(function* () { const customConfig = yield* loadWritableCustomKeybindingsConfig(); const target = keybindingRuleFromInput(input); const nextConfig = customConfig.filter( ({ rule }) => !rule || !isSameKeybindingRule(rule, target), ); yield* writeConfigAtomically(nextConfig.map(({ value }) => value)); return yield* reloadAndEmit; }), ), } satisfies Keybindings["Service"]; }); export const layer = Layer.effect(Keybindings, make);