Skip to content

Commit fa06a00

Browse files
committed
fix: reconcile preference intent across tabs
1 parent e118e60 commit fa06a00

10 files changed

Lines changed: 299 additions & 72 deletions

‎ui/src/app/server-prefs.test.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1025,6 +1025,89 @@ describe("pushServerUiPrefs", () => {
10251025
await vi.waitFor(() => expect(localStorage.getItem(pendingKey("ws://gw"))).toBeNull());
10261026
});
10271027

1028+
it("does not replay persisted intent that another tab cancelled", async () => {
1029+
const scope = "ws://gw";
1030+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
1031+
const client = createClient(request, scope, false);
1032+
1033+
pushServerUiPrefs(client, { theme: "knot" });
1034+
expect(readPending(scope)).toEqual({ theme: "knot" });
1035+
1036+
localStorage.removeItem(pendingKey(scope));
1037+
(client.state as { connected: boolean }).connected = true;
1038+
flushServerUiPrefs(client);
1039+
await Promise.resolve();
1040+
1041+
expect(request).not.toHaveBeenCalled();
1042+
});
1043+
1044+
it("does not resurrect a sibling key another tab cancelled during a read-only edit", async () => {
1045+
const scope = "ws://gw";
1046+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
1047+
const client = createClient(request, scope, false);
1048+
1049+
pushServerUiPrefs(client, { locale: "de", theme: "knot" });
1050+
localStorage.setItem(pendingKey(scope), JSON.stringify({ theme: "knot" }));
1051+
(client.state as { connected: boolean }).connected = true;
1052+
(client as { canPatch: boolean }).canPatch = false;
1053+
pushServerUiPrefs(client, { themeMode: "dark" });
1054+
1055+
expect(readPending(scope)).toEqual({ theme: "knot" });
1056+
expect(request).not.toHaveBeenCalled();
1057+
1058+
(client as { canPatch: boolean }).canPatch = true;
1059+
flushServerUiPrefs(client);
1060+
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
1061+
expect(request).toHaveBeenCalledWith("config.patch", {
1062+
raw: JSON.stringify({ ui: { prefs: { theme: "knot" } } }),
1063+
note: "control-ui prefs sync",
1064+
});
1065+
});
1066+
1067+
it("dispatches a same-key replacement persisted by another tab", async () => {
1068+
const scope = "ws://gw";
1069+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
1070+
const client = createClient(request, scope, false);
1071+
1072+
pushServerUiPrefs(client, { theme: "knot" });
1073+
localStorage.setItem(pendingKey(scope), JSON.stringify({ theme: "dash" }));
1074+
(client.state as { connected: boolean }).connected = true;
1075+
flushServerUiPrefs(client);
1076+
1077+
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
1078+
expect(request).toHaveBeenCalledWith("config.patch", {
1079+
raw: JSON.stringify({ ui: { prefs: { theme: "dash" } } }),
1080+
note: "control-ui prefs sync",
1081+
});
1082+
});
1083+
1084+
it("retains in-memory pending intent when localStorage is unavailable", async () => {
1085+
const storageError = new Error("storage unavailable");
1086+
vi.stubGlobal("localStorage", {
1087+
getItem: () => {
1088+
throw storageError;
1089+
},
1090+
removeItem: () => {
1091+
throw storageError;
1092+
},
1093+
setItem: () => {
1094+
throw storageError;
1095+
},
1096+
});
1097+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
1098+
const client = createClient(request, "ws://gw", false);
1099+
1100+
pushServerUiPrefs(client, { locale: "de" });
1101+
(client.state as { connected: boolean }).connected = true;
1102+
flushServerUiPrefs(client);
1103+
1104+
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
1105+
expect(request).toHaveBeenCalledWith("config.patch", {
1106+
raw: JSON.stringify({ ui: { prefs: { locale: "de" } } }),
1107+
note: "control-ui prefs sync",
1108+
});
1109+
});
1110+
10281111
it("retains a connected transient failure and retries it on flush", async () => {
10291112
const request = vi
10301113
.fn<(method: string, params?: unknown) => Promise<unknown>>()
@@ -1353,6 +1436,30 @@ describe("pushServerUiPrefs", () => {
13531436
});
13541437
});
13551438

1439+
it("does not migrate cancelled pre-connection intent into an adopted gateway scope", async () => {
1440+
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));
1441+
const writer = createClient(request, "", false);
1442+
(writer.state as { client: GatewayBrowserClient | null }).client = null;
1443+
1444+
pushServerUiPrefs(writer, { theme: "knot" });
1445+
localStorage.removeItem(pendingKey(""));
1446+
1447+
(writer.state as { client: GatewayBrowserClient | null; connected: boolean }).client = {
1448+
request,
1449+
gatewayUrl: "ws://first",
1450+
connected: true,
1451+
} as unknown as GatewayBrowserClient;
1452+
(writer.state as { connected: boolean }).connected = true;
1453+
flushServerUiPrefs(writer);
1454+
pushServerUiPrefs(writer, { themeMode: "dark" });
1455+
1456+
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
1457+
expect(request).toHaveBeenCalledWith("config.patch", {
1458+
raw: JSON.stringify({ ui: { prefs: { themeMode: "dark" } } }),
1459+
note: "control-ui prefs sync",
1460+
});
1461+
});
1462+
13561463
it("recovers persisted pre-connection intent when the first gateway is adopted", async () => {
13571464
localStorage.setItem(pendingKey(""), JSON.stringify({ locale: "de" }));
13581465
const request = vi.fn<(method: string, params?: unknown) => Promise<unknown>>(async () => ({}));

‎ui/src/app/server-prefs.ts‎

Lines changed: 106 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,7 @@ const requestedDeviceLocalPrefResets = new Set<SyncedPrefKey>();
321321
let applyingServerPrefs = false;
322322
let pendingScope = "";
323323
let pendingPrefs: ServerUiPrefs | null = null;
324+
let pendingPersistedKeys = new Set<SyncedPrefKey>();
324325
let pushWriter: ServerUiPrefsWriter | null = null;
325326
let pushScope = "";
326327
let pushAfterCommit: ((commit: ServerUiPrefsCommit) => void) | undefined;
@@ -341,23 +342,39 @@ function clearConflictRedrain(): void {
341342
}
342343
consecutiveConflictRedrains = 0;
343344
}
344-
function readStorage(root: string, scope: string): string | null {
345+
function readStorageState(
346+
root: string,
347+
scope: string,
348+
): { available: boolean; value: string | null } {
345349
try {
346-
return globalThis.localStorage?.getItem(`${root}:${scope}`) ?? null;
350+
const storage = globalThis.localStorage;
351+
if (!storage) {
352+
return { available: false, value: null };
353+
}
354+
return { available: true, value: storage.getItem(`${root}:${scope}`) };
347355
} catch {
348-
return null;
356+
return { available: false, value: null };
349357
}
350358
}
351-
function writeStorage(root: string, scope: string, value: string | null): void {
359+
function readStorage(root: string, scope: string): string | null {
360+
return readStorageState(root, scope).value;
361+
}
362+
function writeStorage(root: string, scope: string, value: string | null): boolean {
352363
try {
364+
const storage = globalThis.localStorage;
365+
if (!storage) {
366+
return false;
367+
}
353368
const key = `${root}:${scope}`;
354369
if (value === null) {
355-
globalThis.localStorage?.removeItem(key);
370+
storage.removeItem(key);
356371
} else {
357-
globalThis.localStorage?.setItem(key, value);
372+
storage.setItem(key, value);
358373
}
374+
return true;
359375
} catch {
360376
// Quota/security failures degrade to in-memory tracking for this session.
377+
return false;
361378
}
362379
}
363380
function parseStoredPrefs(raw: string | null): ServerUiPrefs | null {
@@ -368,6 +385,16 @@ function parseStoredPrefs(raw: string | null): ServerUiPrefs | null {
368385
return null;
369386
}
370387
}
388+
function readStoredPrefs(
389+
root: string,
390+
scope: string,
391+
): { available: boolean; prefs: ServerUiPrefs | null } {
392+
const stored = readStorageState(root, scope);
393+
return {
394+
available: stored.available,
395+
prefs: parseStoredPrefs(stored.value),
396+
};
397+
}
371398
function readRetainedLocalKeys(scope: string): Set<SyncedPrefKey> {
372399
const stored = parseStoredPrefs(readStorage(RETAINED_LOCAL_KEY, scope));
373400
return new Set(
@@ -406,12 +433,26 @@ function adoptPendingScope(scope: string, force = false): void {
406433
return;
407434
}
408435
pendingScope = scope;
409-
pendingPrefs = parseStoredPrefs(readStorage(PENDING_KEY, scope));
436+
const stored = readStoredPrefs(PENDING_KEY, scope);
437+
pendingPrefs = stored.prefs;
438+
pendingPersistedKeys = new Set(
439+
stored.available && stored.prefs ? (Object.keys(stored.prefs) as SyncedPrefKey[]) : [],
440+
);
410441
}
411442
function writePendingStorage(prefs: ServerUiPrefs | null): void {
412-
writeStorage(PENDING_KEY, pendingScope, prefs ? JSON.stringify(prefs) : null);
443+
const persisted = writeStorage(PENDING_KEY, pendingScope, prefs ? JSON.stringify(prefs) : null);
444+
if (persisted) {
445+
pendingPersistedKeys = new Set(
446+
pendingPrefs ? (Object.keys(pendingPrefs) as SyncedPrefKey[]) : [],
447+
);
448+
} else {
449+
pendingPersistedKeys.clear();
450+
}
413451
}
414452
function cancelPendingKeys(scope: string, keys: readonly SyncedPrefKey[]): void {
453+
if (scope === pendingScope) {
454+
reconcilePersistedPendingPrefs();
455+
}
415456
const active = scope === pendingScope ? pendingPrefs : null;
416457
const remaining = {
417458
...parseStoredPrefs(readStorage(PENDING_KEY, scope)),
@@ -423,6 +464,8 @@ function cancelPendingKeys(scope: string, keys: readonly SyncedPrefKey[]): void
423464
const next = Object.keys(remaining).length ? remaining : null;
424465
if (scope === pendingScope) {
425466
pendingPrefs = next;
467+
writePendingStorage(next);
468+
return;
426469
}
427470
writeStorage(PENDING_KEY, scope, next ? JSON.stringify(next) : null);
428471
}
@@ -444,11 +487,46 @@ function settlePendingStorage(ackedBatch: ServerUiPrefs): void {
444487
const merged = { ...stored, ...pendingPrefs };
445488
writePendingStorage(Object.keys(merged).length ? merged : null);
446489
}
490+
// Only persisted keys participate in cross-tab reconciliation. An in-memory-only key means
491+
// localStorage was unavailable, so absence from storage cannot be interpreted as cancellation.
492+
function reconcilePersistedPendingPrefs(): void {
493+
if (!pendingPrefs || pendingPersistedKeys.size === 0) {
494+
return;
495+
}
496+
const stored = readStoredPrefs(PENDING_KEY, pendingScope);
497+
if (!stored.available) {
498+
return;
499+
}
500+
const current = stored.prefs ?? {};
501+
for (const key of [...pendingPersistedKeys]) {
502+
if (!Object.hasOwn(current, key)) {
503+
delete pendingPrefs[key];
504+
pendingPersistedKeys.delete(key);
505+
continue;
506+
}
507+
const storedValue = current[key];
508+
if (!prefValuesEqual(pendingPrefs[key], storedValue)) {
509+
(pendingPrefs as Record<string, unknown>)[key] = storedValue;
510+
}
511+
}
512+
if (!Object.keys(pendingPrefs).length) {
513+
pendingPrefs = null;
514+
}
515+
}
516+
function batchIsCurrent(batch: ServerUiPrefs): boolean {
517+
return Boolean(
518+
pendingPrefs &&
519+
(Object.keys(batch) as SyncedPrefKey[]).every(
520+
(key) => Object.hasOwn(pendingPrefs, key) && prefValuesEqual(pendingPrefs[key], batch[key]),
521+
),
522+
);
523+
}
447524
export function resetServerUiPrefsSync() {
448525
clearConflictRedrain();
449526
applyingServerPrefs = pushDraining = drainRequested = false;
450527
pendingScope = "";
451528
pendingPrefs = pushWriter = null;
529+
pendingPersistedKeys.clear();
452530
pushScope = "";
453531
lastReconciledScope = "";
454532
lastReconciledConfigObject = null;
@@ -562,6 +640,9 @@ function adoptPushWriter(writer: ServerUiPrefsWriter): void {
562640
if (pushWriter === writer && pushScope === scope) {
563641
return;
564642
}
643+
// Reconcile the scope being left before moving pre-connection intent forward.
644+
// Otherwise another tab can cancel storage while this realm later resurrects its stale memory.
645+
reconcilePersistedPendingPrefs();
565646
const unscopedPending =
566647
pendingScope === ""
567648
? {
@@ -591,6 +672,7 @@ function removeBatch(batch: ServerUiPrefs): void {
591672
for (const key of Object.keys(batch) as SyncedPrefKey[]) {
592673
if (prefValuesEqual(pendingPrefs[key], batch[key])) {
593674
delete pendingPrefs[key];
675+
pendingPersistedKeys.delete(key);
594676
}
595677
}
596678
if (!Object.keys(pendingPrefs).length) {
@@ -616,6 +698,10 @@ async function drainPendingPrefs(writer: ServerUiPrefsWriter, epoch: number): Pr
616698
if (pushWriter !== writer || pushEpoch !== epoch) {
617699
return;
618700
}
701+
reconcilePersistedPendingPrefs();
702+
if (!pendingPrefs) {
703+
return;
704+
}
619705
const batch = { ...pendingPrefs };
620706
const afterCommit = pushAfterCommit;
621707
for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -636,7 +722,17 @@ async function drainPendingPrefs(writer: ServerUiPrefsWriter, epoch: number): Pr
636722
}),
637723
{
638724
waitForWritesResumed: true,
639-
canDispatch: () => writer.canPatch !== false,
725+
canDispatch: () => {
726+
if (writer.canPatch === false) {
727+
return false;
728+
}
729+
reconcilePersistedPendingPrefs();
730+
if (batchIsCurrent(batch)) {
731+
return true;
732+
}
733+
drainRequested = Boolean(pendingPrefs);
734+
return false;
735+
},
640736
dispatchError: "Access changed before preferences could sync.",
641737
},
642738
);
@@ -733,6 +829,7 @@ export function pushServerUiPrefs(
733829
hooks.afterCommit?.({ needsRefresh: false, retainedLocal: true });
734830
return;
735831
}
832+
reconcilePersistedPendingPrefs();
736833
pendingPrefs = { ...pendingPrefs, ...prefs };
737834
mergePendingIntoStorage();
738835
startPendingDrain(writer);

‎ui/src/app/settings.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,15 +219,15 @@ export type UiSettings = {
219219

220220
type LastActiveSessionHost = {
221221
settings: UiSettings;
222-
applySettings(next: UiSettings): void;
222+
applySettings(patch: Partial<UiSettings>): void;
223223
};
224224

225225
export function setLastActiveSessionKey(host: LastActiveSessionHost, next: string) {
226226
const trimmed = next.trim();
227227
if (!trimmed || host.settings.lastActiveSessionKey === trimmed) {
228228
return;
229229
}
230-
host.applySettings({ ...host.settings, lastActiveSessionKey: trimmed });
230+
host.applySettings({ lastActiveSessionKey: trimmed });
231231
}
232232

233233
function isViteDevPage(): boolean {

0 commit comments

Comments
 (0)