Skip to content
TypeScript

fix(server): saving a shortcut no longer deletes rules it can't read (#24494)

Victor Vogela0d08d7550d5
diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts
index 8b513c4ca30..cb92c24242d 100644
--- a/apps/server/src/keybindings.test.ts
+++ b/apps/server/src/keybindings.test.ts
@@ -444,6 +444,53 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}).pipe(Effect.provide(layerKeybindings())),
);
+ it.effect("keeps entries it cannot decode when editing other keybindings", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
+ const futureCommand = { key: "mod+shift+k", command: "command.from-a-newer-build" };
+ const badShortcut = { key: "mod+shift+d+o", command: "terminal.new" };
+ yield* fs.writeFileString(
+ keybindingsConfigPath,
+ JSON.stringify([
+ { key: "mod+r", command: "script.run-tests.run" },
+ futureCommand,
+ badShortcut,
+ ]),
+ );
+ const keybindings = yield* Keybindings.Keybindings;
+ const persisted = Effect.map(fs.readFileString(keybindingsConfigPath), JSON.parse);
+
+ const saved = yield* keybindings.upsertKeybindingRule({
+ key: "mod+shift+r",
+ command: "script.run-tests.run",
+ });
+ assert.equal(saved.issues.length, 2);
+ assert.deepEqual(yield* persisted, [
+ { key: "mod+r", command: "script.run-tests.run" },
+ futureCommand,
+ badShortcut,
+ { key: "mod+shift+r", command: "script.run-tests.run" },
+ ]);
+
+ const removed = yield* keybindings.removeKeybindingRule({
+ key: "mod+r",
+ command: "script.run-tests.run",
+ });
+ assert.deepEqual(yield* persisted, [
+ futureCommand,
+ badShortcut,
+ { key: "mod+shift+r", command: "script.run-tests.run" },
+ ]);
+ const { issues } = yield* keybindings.loadConfigState;
+ assert.deepEqual(removed.issues, issues);
+ assert.deepEqual(
+ issues.map((issue) => issue.kind === "keybindings.invalid-entry" && issue.index),
+ [0, 1],
+ );
+ }).pipe(Effect.provide(layerKeybindings())),
+ );
+
it.effect("removes a hand-written keybinding targeted by its settings spelling", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts
index 1247428a56d..0a5bfdd4246 100644
--- a/apps/server/src/keybindings.ts
+++ b/apps/server/src/keybindings.ts
@@ -1,6 +1,5 @@
import {
KeybindingRule,
- KeybindingsConfig,
KeybindingsConfigError,
KeybindingShortcut,
KeybindingWhenNode,
@@ -170,11 +169,11 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
}
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
-const KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);
+const RawKeybindingsEntriesPrettyJson = fromJsonStringPretty(Schema.Array(Schema.Unknown));
const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);
const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);
const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);
-const encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);
+const encodeRawKeybindingsEntriesPrettyJson = Schema.encodeEffect(RawKeybindingsEntriesPrettyJson);
export interface KeybindingsConfigState {
readonly keybindings: ResolvedKeybindingsConfig;
@@ -234,11 +233,11 @@ export class Keybindings extends Context.Service<
*/
readonly upsertKeybindingRule: (
input: ServerUpsertKeybindingInput,
- ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
+ ) => Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
readonly removeKeybindingRule: (
input: ServerRemoveKeybindingInput,
- ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
+ ) => Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
}
>()("t3/keybindings") {}
@@ -278,8 +277,10 @@ const make = Effect.gen(function* () {
),
);
+ // 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<
- readonly KeybindingRule[],
+ ReadonlyArray<{ readonly value: unknown; readonly rule: KeybindingRule | null }>,
KeybindingsConfigError
> {
if (!(yield* readConfigExists)) {
@@ -298,29 +299,16 @@ const make = Effect.gen(function* () {
),
);
- return yield* Effect.forEach(rawConfig, (entry) =>
- Effect.gen(function* () {
- const decodedRule = decodeKeybindingRuleExit(entry);
- if (decodedRule._tag === "Failure") {
- yield* Effect.logWarning("ignoring invalid keybinding entry", {
- path: keybindingsConfigPath,
- entry,
- error: Cause.pretty(decodedRule.cause),
- });
- return null;
- }
- const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
- if (resolved._tag === "Failure") {
- yield* Effect.logWarning("ignoring invalid keybinding entry", {
- path: keybindingsConfigPath,
- entry,
- error: Cause.pretty(resolved.cause),
- });
- return null;
- }
- return decodedRule.value;
- }),
- ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
+ 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<
@@ -403,8 +391,8 @@ const make = Effect.gen(function* () {
),
);
- const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
- return encodeKeybindingsConfigPrettyJson(rules).pipe(
+ const writeConfigAtomically = (entries: ReadonlyArray<unknown>) => {
+ return encodeRawKeybindingsEntriesPrettyJson(entries).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.flatMap((encoded) =>
writeFileStringAtomically({
@@ -444,13 +432,14 @@ const make = Effect.gen(function* () {
const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
- const revalidateAndEmit = upsertSemaphore.withPermits(1)(
- Effect.gen(function* () {
- yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
- const configState = yield* loadConfigStateFromCacheOrDisk;
- yield* emitChange(configState);
- }),
- );
+ const reloadAndEmit = Effect.gen(function* () {
+ yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
+ const configState = yield* loadConfigStateFromCacheOrDisk;
+ yield* emitChange(configState);
+ return configState;
+ });
+
+ const revalidateAndEmit = upsertSemaphore.withPermits(1)(reloadAndEmit);
const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
@@ -648,7 +637,8 @@ const make = Effect.gen(function* () {
const rule = keybindingRuleFromInput(input);
const replaceTarget = replaceTargetFromUpsertInput(input);
const nextConfig = [
- ...customConfig.filter((entry) => {
+ ...customConfig.filter(({ rule: entry }) => {
+ if (!entry) return true;
if (replaceTarget) {
return (
!isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
@@ -656,7 +646,7 @@ const make = Effect.gen(function* () {
}
return !isSameKeybindingRule(entry, rule);
}),
- rule,
+ { value: rule, rule },
];
const cappedConfig =
nextConfig.length > MAX_KEYBINDINGS_COUNT
@@ -668,19 +658,8 @@ const make = Effect.gen(function* () {
maxEntries: MAX_KEYBINDINGS_COUNT,
});
}
- yield* writeConfigAtomically(cappedConfig);
- const nextResolved = mergeWithDefaultKeybindings(
- compileResolvedKeybindingsConfig(cappedConfig),
- );
- yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
- keybindings: nextResolved,
- issues: [],
- });
- yield* emitChange({
- keybindings: nextResolved,
- issues: [],
- });
- return nextResolved;
+ yield* writeConfigAtomically(cappedConfig.map(({ value }) => value));
+ return yield* reloadAndEmit;
}),
),
removeKeybindingRule: (input) =>
@@ -688,20 +667,11 @@ const make = Effect.gen(function* () {
Effect.gen(function* () {
const customConfig = yield* loadWritableCustomKeybindingsConfig();
const target = keybindingRuleFromInput(input);
- const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
- yield* writeConfigAtomically(nextConfig);
- const nextResolved = mergeWithDefaultKeybindings(
- compileResolvedKeybindingsConfig(nextConfig),
+ const nextConfig = customConfig.filter(
+ ({ rule }) => !rule || !isSameKeybindingRule(rule, target),
);
- yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
- keybindings: nextResolved,
- issues: [],
- });
- yield* emitChange({
- keybindings: nextResolved,
- issues: [],
- });
- return nextResolved;
+ yield* writeConfigAtomically(nextConfig.map(({ value }) => value));
+ return yield* reloadAndEmit;
}),
),
} satisfies Keybindings["Service"];
diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts
index 09db12ea35b..97ed92fe21b 100644
--- a/apps/server/src/ws.test.ts
+++ b/apps/server/src/ws.test.ts
@@ -762,7 +762,7 @@ it.effect.each(["pending", "cached"] as const)(
const expectedSettings = [duringDiscovery, latestSettings].map(
ServerSettings.redactServerSettingsForClient,
);
- const expectedKeybindings = [duringAck, latestKeybindings];
+ const expectedKeybindings = [duringAck.keybindings, latestKeybindings.keybindings];
// The two sources can interleave, but each must retain its own publication order.
for (let i = 0; i < 4; i++) {
const event = yield* Queue.take(responses);
@@ -790,7 +790,7 @@ it.effect.each(["pending", "cached"] as const)(
resolved.config.settings,
ServerSettings.redactServerSettingsForClient(latestSettings),
);
- assert.deepEqual(resolved.config.keybindings, latestKeybindings);
+ assert.deepEqual(resolved.config.keybindings, latestKeybindings.keybindings);
yield* acknowledge;
}
yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] });
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 12436650b07..b4fe2e7ebd7 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -2538,14 +2538,12 @@ export const layerWsRpc = (
[WS_METHODS.serverUpsertKeybinding]:
/* Request instrumentation already owns the span; keep this helper in that context. */
Effect.fnUntraced(function* (rule) {
- const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
- return { keybindings: keybindingsConfig, issues: [] };
+ return yield* keybindings.upsertKeybindingRule(rule);
}),
[WS_METHODS.serverRemoveKeybinding]:
/* Request instrumentation already owns the span; keep this helper in that context. */
Effect.fnUntraced(function* (rule) {
- const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);
- return { keybindings: keybindingsConfig, issues: [] };
+ return yield* keybindings.removeKeybindingRule(rule);
}),
[WS_METHODS.serverRunStorageCleanup]: () => storageCleanup.runNow,
[WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports,
diff --git a/apps/web/src/components/KeybindingsUpdateToast.logic.test.ts b/apps/web/src/components/KeybindingsUpdateToast.logic.test.ts
new file mode 100644
index 00000000000..05602fda4c4
--- /dev/null
+++ b/apps/web/src/components/KeybindingsUpdateToast.logic.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vite-plus/test";
+import type { ServerConfigStreamEvent } from "@t3tools/contracts";
+
+import { createKeybindingsUpdateToastController } from "./KeybindingsUpdateToast.logic";
+
+function keybindingsUpdated(issueMessages: ReadonlyArray<string>): ServerConfigStreamEvent {
+ return {
+ version: 1,
+ type: "keybindingsUpdated",
+ payload: {
+ keybindings: [],
+ issues: issueMessages.map((message, index) => ({
+ kind: "keybindings.invalid-entry" as const,
+ message,
+ index,
+ })),
+ },
+ };
+}
+
+describe("keybindings update toast", () => {
+ it("shows one warning when a save and the file watcher report the same issue", () => {
+ let currentTime = 0;
+ const controller = createKeybindingsUpdateToastController({ now: () => currentTime });
+ const invalid = { _tag: "InvalidConfiguration", message: "unknown command" };
+
+ expect(controller.handle(keybindingsUpdated(["unknown command"]))).toEqual(invalid);
+ currentTime = 100;
+ expect(controller.handle(keybindingsUpdated(["unknown command"]))).toBeNull();
+
+ currentTime = 200;
+ expect(controller.handle(keybindingsUpdated(["bad shortcut"]))).toEqual({
+ _tag: "InvalidConfiguration",
+ message: "bad shortcut",
+ });
+
+ currentTime = 5_000;
+ expect(controller.handle(keybindingsUpdated(["bad shortcut"]))).toEqual({
+ _tag: "InvalidConfiguration",
+ message: "bad shortcut",
+ });
+ currentTime = 5_100;
+ expect(controller.handle(keybindingsUpdated([]))).toEqual({ _tag: "Success" });
+ currentTime = 5_200;
+ expect(controller.handle(keybindingsUpdated([]))).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/KeybindingsUpdateToast.logic.ts b/apps/web/src/components/KeybindingsUpdateToast.logic.ts
index ed13e6a1c80..f7724f38d13 100644
--- a/apps/web/src/components/KeybindingsUpdateToast.logic.ts
+++ b/apps/web/src/components/KeybindingsUpdateToast.logic.ts
@@ -1,6 +1,6 @@
import type { ServerConfigStreamEvent } from "@t3tools/contracts";
-const KEYBINDINGS_SUCCESS_TOAST_COOLDOWN_MS = 2_000;
+const KEYBINDINGS_TOAST_COOLDOWN_MS = 2_000;
export type KeybindingsUpdateToastDecision =
| { readonly _tag: "Success" }
@@ -14,7 +14,7 @@ export function createKeybindingsUpdateToastController(input: {
readonly now?: () => number;
}): KeybindingsUpdateToastController {
const now = input.now ?? Date.now;
- let lastSuccessToastAt: number | null = null;
+ let lastToast: { readonly key: string; readonly at: number } | null = null;
return {
handle: (event) => {
@@ -23,23 +23,24 @@ export function createKeybindingsUpdateToastController(input: {
}
const issue = event.payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
- if (issue) {
- return {
- _tag: "InvalidConfiguration",
- message: issue.message,
- };
- }
+ const decision: KeybindingsUpdateToastDecision = issue
+ ? { _tag: "InvalidConfiguration", message: issue.message }
+ : { _tag: "Success" };
+ // A save and the server's file watcher each publish the same snapshot,
+ // so an identical toast inside the cooldown is the same change twice.
+ const key = issue ? `invalid:${issue.message}` : "success";
const currentTime = now();
if (
- lastSuccessToastAt !== null &&
- currentTime - lastSuccessToastAt < KEYBINDINGS_SUCCESS_TOAST_COOLDOWN_MS
+ lastToast !== null &&
+ lastToast.key === key &&
+ currentTime - lastToast.at < KEYBINDINGS_TOAST_COOLDOWN_MS
) {
return null;
}
- lastSuccessToastAt = currentTime;
- return { _tag: "Success" };
+ lastToast = { key, at: currentTime };
+ return decision;
},
};
}