Skip to content

Commit a0d08d7

Browse files
only21milclaudemaria-rcks
authored
fix(server): saving a shortcut no longer deletes rules it can't read (pingdotgg#24494)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 80a5ffa commit a0d08d7

6 files changed

Lines changed: 147 additions & 84 deletions

File tree

‎apps/server/src/keybindings.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,53 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
444444
}).pipe(Effect.provide(layerKeybindings())),
445445
);
446446

447+
it.effect("keeps entries it cannot decode when editing other keybindings", () =>
448+
Effect.gen(function* () {
449+
const fs = yield* FileSystem.FileSystem;
450+
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
451+
const futureCommand = { key: "mod+shift+k", command: "command.from-a-newer-build" };
452+
const badShortcut = { key: "mod+shift+d+o", command: "terminal.new" };
453+
yield* fs.writeFileString(
454+
keybindingsConfigPath,
455+
JSON.stringify([
456+
{ key: "mod+r", command: "script.run-tests.run" },
457+
futureCommand,
458+
badShortcut,
459+
]),
460+
);
461+
const keybindings = yield* Keybindings.Keybindings;
462+
const persisted = Effect.map(fs.readFileString(keybindingsConfigPath), JSON.parse);
463+
464+
const saved = yield* keybindings.upsertKeybindingRule({
465+
key: "mod+shift+r",
466+
command: "script.run-tests.run",
467+
});
468+
assert.equal(saved.issues.length, 2);
469+
assert.deepEqual(yield* persisted, [
470+
{ key: "mod+r", command: "script.run-tests.run" },
471+
futureCommand,
472+
badShortcut,
473+
{ key: "mod+shift+r", command: "script.run-tests.run" },
474+
]);
475+
476+
const removed = yield* keybindings.removeKeybindingRule({
477+
key: "mod+r",
478+
command: "script.run-tests.run",
479+
});
480+
assert.deepEqual(yield* persisted, [
481+
futureCommand,
482+
badShortcut,
483+
{ key: "mod+shift+r", command: "script.run-tests.run" },
484+
]);
485+
const { issues } = yield* keybindings.loadConfigState;
486+
assert.deepEqual(removed.issues, issues);
487+
assert.deepEqual(
488+
issues.map((issue) => issue.kind === "keybindings.invalid-entry" && issue.index),
489+
[0, 1],
490+
);
491+
}).pipe(Effect.provide(layerKeybindings())),
492+
);
493+
447494
it.effect("removes a hand-written keybinding targeted by its settings spelling", () =>
448495
Effect.gen(function* () {
449496
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;

‎apps/server/src/keybindings.ts‎

Lines changed: 36 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import {
22
KeybindingRule,
3-
KeybindingsConfig,
43
KeybindingsConfigError,
54
KeybindingShortcut,
65
KeybindingWhenNode,
@@ -170,11 +169,11 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
170169
}
171170

172171
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
173-
const KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);
172+
const RawKeybindingsEntriesPrettyJson = fromJsonStringPretty(Schema.Array(Schema.Unknown));
174173
const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);
175174
const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);
176175
const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);
177-
const encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);
176+
const encodeRawKeybindingsEntriesPrettyJson = Schema.encodeEffect(RawKeybindingsEntriesPrettyJson);
178177

179178
export interface KeybindingsConfigState {
180179
readonly keybindings: ResolvedKeybindingsConfig;
@@ -234,11 +233,11 @@ export class Keybindings extends Context.Service<
234233
*/
235234
readonly upsertKeybindingRule: (
236235
input: ServerUpsertKeybindingInput,
237-
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
236+
) => Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
238237

239238
readonly removeKeybindingRule: (
240239
input: ServerRemoveKeybindingInput,
241-
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
240+
) => Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
242241
}
243242
>()("t3/keybindings") {}
244243

@@ -278,8 +277,10 @@ const make = Effect.gen(function* () {
278277
),
279278
);
280279

280+
// Entries this build cannot decode, such as a typo or a command from a newer
281+
// build, are written back unchanged so editing another shortcut keeps them.
281282
const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
282-
readonly KeybindingRule[],
283+
ReadonlyArray<{ readonly value: unknown; readonly rule: KeybindingRule | null }>,
283284
KeybindingsConfigError
284285
> {
285286
if (!(yield* readConfigExists)) {
@@ -298,29 +299,16 @@ const make = Effect.gen(function* () {
298299
),
299300
);
300301

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)));
302+
return rawConfig.map((entry) => {
303+
const decodedRule = decodeKeybindingRuleExit(entry);
304+
if (
305+
decodedRule._tag === "Success" &&
306+
decodeResolvedKeybindingFromConfigExit(decodedRule.value)._tag === "Success"
307+
) {
308+
return { value: decodedRule.value, rule: decodedRule.value };
309+
}
310+
return { value: entry, rule: null };
311+
});
324312
});
325313

326314
const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
@@ -403,8 +391,8 @@ const make = Effect.gen(function* () {
403391
),
404392
);
405393

406-
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
407-
return encodeKeybindingsConfigPrettyJson(rules).pipe(
394+
const writeConfigAtomically = (entries: ReadonlyArray<unknown>) => {
395+
return encodeRawKeybindingsEntriesPrettyJson(entries).pipe(
408396
Effect.map((encoded) => `${encoded}\n`),
409397
Effect.flatMap((encoded) =>
410398
writeFileStringAtomically({
@@ -444,13 +432,14 @@ const make = Effect.gen(function* () {
444432

445433
const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
446434

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-
);
435+
const reloadAndEmit = Effect.gen(function* () {
436+
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
437+
const configState = yield* loadConfigStateFromCacheOrDisk;
438+
yield* emitChange(configState);
439+
return configState;
440+
});
441+
442+
const revalidateAndEmit = upsertSemaphore.withPermits(1)(reloadAndEmit);
454443

455444
const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
456445
Effect.gen(function* () {
@@ -648,15 +637,16 @@ const make = Effect.gen(function* () {
648637
const rule = keybindingRuleFromInput(input);
649638
const replaceTarget = replaceTargetFromUpsertInput(input);
650639
const nextConfig = [
651-
...customConfig.filter((entry) => {
640+
...customConfig.filter(({ rule: entry }) => {
641+
if (!entry) return true;
652642
if (replaceTarget) {
653643
return (
654644
!isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
655645
);
656646
}
657647
return !isSameKeybindingRule(entry, rule);
658648
}),
659-
rule,
649+
{ value: rule, rule },
660650
];
661651
const cappedConfig =
662652
nextConfig.length > MAX_KEYBINDINGS_COUNT
@@ -668,40 +658,20 @@ const make = Effect.gen(function* () {
668658
maxEntries: MAX_KEYBINDINGS_COUNT,
669659
});
670660
}
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;
661+
yield* writeConfigAtomically(cappedConfig.map(({ value }) => value));
662+
return yield* reloadAndEmit;
684663
}),
685664
),
686665
removeKeybindingRule: (input) =>
687666
upsertSemaphore.withPermits(1)(
688667
Effect.gen(function* () {
689668
const customConfig = yield* loadWritableCustomKeybindingsConfig();
690669
const target = keybindingRuleFromInput(input);
691-
const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
692-
yield* writeConfigAtomically(nextConfig);
693-
const nextResolved = mergeWithDefaultKeybindings(
694-
compileResolvedKeybindingsConfig(nextConfig),
670+
const nextConfig = customConfig.filter(
671+
({ rule }) => !rule || !isSameKeybindingRule(rule, target),
695672
);
696-
yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
697-
keybindings: nextResolved,
698-
issues: [],
699-
});
700-
yield* emitChange({
701-
keybindings: nextResolved,
702-
issues: [],
703-
});
704-
return nextResolved;
673+
yield* writeConfigAtomically(nextConfig.map(({ value }) => value));
674+
return yield* reloadAndEmit;
705675
}),
706676
),
707677
} satisfies Keybindings["Service"];

‎apps/server/src/ws.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,7 @@ it.effect.each(["pending", "cached"] as const)(
762762
const expectedSettings = [duringDiscovery, latestSettings].map(
763763
ServerSettings.redactServerSettingsForClient,
764764
);
765-
const expectedKeybindings = [duringAck, latestKeybindings];
765+
const expectedKeybindings = [duringAck.keybindings, latestKeybindings.keybindings];
766766
// The two sources can interleave, but each must retain its own publication order.
767767
for (let i = 0; i < 4; i++) {
768768
const event = yield* Queue.take(responses);
@@ -790,7 +790,7 @@ it.effect.each(["pending", "cached"] as const)(
790790
resolved.config.settings,
791791
ServerSettings.redactServerSettingsForClient(latestSettings),
792792
);
793-
assert.deepEqual(resolved.config.keybindings, latestKeybindings);
793+
assert.deepEqual(resolved.config.keybindings, latestKeybindings.keybindings);
794794
yield* acknowledge;
795795
}
796796
yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] });

‎apps/server/src/ws.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2538,14 +2538,12 @@ export const layerWsRpc = (
25382538
[WS_METHODS.serverUpsertKeybinding]:
25392539
/* Request instrumentation already owns the span; keep this helper in that context. */
25402540
Effect.fnUntraced(function* (rule) {
2541-
const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);
2542-
return { keybindings: keybindingsConfig, issues: [] };
2541+
return yield* keybindings.upsertKeybindingRule(rule);
25432542
}),
25442543
[WS_METHODS.serverRemoveKeybinding]:
25452544
/* Request instrumentation already owns the span; keep this helper in that context. */
25462545
Effect.fnUntraced(function* (rule) {
2547-
const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);
2548-
return { keybindings: keybindingsConfig, issues: [] };
2546+
return yield* keybindings.removeKeybindingRule(rule);
25492547
}),
25502548
[WS_METHODS.serverRunStorageCleanup]: () => storageCleanup.runNow,
25512549
[WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports,
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
import type { ServerConfigStreamEvent } from "@t3tools/contracts";
3+
4+
import { createKeybindingsUpdateToastController } from "./KeybindingsUpdateToast.logic";
5+
6+
function keybindingsUpdated(issueMessages: ReadonlyArray<string>): ServerConfigStreamEvent {
7+
return {
8+
version: 1,
9+
type: "keybindingsUpdated",
10+
payload: {
11+
keybindings: [],
12+
issues: issueMessages.map((message, index) => ({
13+
kind: "keybindings.invalid-entry" as const,
14+
message,
15+
index,
16+
})),
17+
},
18+
};
19+
}
20+
21+
describe("keybindings update toast", () => {
22+
it("shows one warning when a save and the file watcher report the same issue", () => {
23+
let currentTime = 0;
24+
const controller = createKeybindingsUpdateToastController({ now: () => currentTime });
25+
const invalid = { _tag: "InvalidConfiguration", message: "unknown command" };
26+
27+
expect(controller.handle(keybindingsUpdated(["unknown command"]))).toEqual(invalid);
28+
currentTime = 100;
29+
expect(controller.handle(keybindingsUpdated(["unknown command"]))).toBeNull();
30+
31+
currentTime = 200;
32+
expect(controller.handle(keybindingsUpdated(["bad shortcut"]))).toEqual({
33+
_tag: "InvalidConfiguration",
34+
message: "bad shortcut",
35+
});
36+
37+
currentTime = 5_000;
38+
expect(controller.handle(keybindingsUpdated(["bad shortcut"]))).toEqual({
39+
_tag: "InvalidConfiguration",
40+
message: "bad shortcut",
41+
});
42+
currentTime = 5_100;
43+
expect(controller.handle(keybindingsUpdated([]))).toEqual({ _tag: "Success" });
44+
currentTime = 5_200;
45+
expect(controller.handle(keybindingsUpdated([]))).toBeNull();
46+
});
47+
});
Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { ServerConfigStreamEvent } from "@t3tools/contracts";
22

3-
const KEYBINDINGS_SUCCESS_TOAST_COOLDOWN_MS = 2_000;
3+
const KEYBINDINGS_TOAST_COOLDOWN_MS = 2_000;
44

55
export type KeybindingsUpdateToastDecision =
66
| { readonly _tag: "Success" }
@@ -14,7 +14,7 @@ export function createKeybindingsUpdateToastController(input: {
1414
readonly now?: () => number;
1515
}): KeybindingsUpdateToastController {
1616
const now = input.now ?? Date.now;
17-
let lastSuccessToastAt: number | null = null;
17+
let lastToast: { readonly key: string; readonly at: number } | null = null;
1818

1919
return {
2020
handle: (event) => {
@@ -23,23 +23,24 @@ export function createKeybindingsUpdateToastController(input: {
2323
}
2424

2525
const issue = event.payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
26-
if (issue) {
27-
return {
28-
_tag: "InvalidConfiguration",
29-
message: issue.message,
30-
};
31-
}
26+
const decision: KeybindingsUpdateToastDecision = issue
27+
? { _tag: "InvalidConfiguration", message: issue.message }
28+
: { _tag: "Success" };
3229

30+
// A save and the server's file watcher each publish the same snapshot,
31+
// so an identical toast inside the cooldown is the same change twice.
32+
const key = issue ? `invalid:${issue.message}` : "success";
3333
const currentTime = now();
3434
if (
35-
lastSuccessToastAt !== null &&
36-
currentTime - lastSuccessToastAt < KEYBINDINGS_SUCCESS_TOAST_COOLDOWN_MS
35+
lastToast !== null &&
36+
lastToast.key === key &&
37+
currentTime - lastToast.at < KEYBINDINGS_TOAST_COOLDOWN_MS
3738
) {
3839
return null;
3940
}
4041

41-
lastSuccessToastAt = currentTime;
42-
return { _tag: "Success" };
42+
lastToast = { key, at: currentTime };
43+
return decision;
4344
},
4445
};
4546
}

0 commit comments

Comments
 (0)