Skip to content

Commit 233f1f0

Browse files
authored
fix(ui): stop dismissed lazy retries from reloading the page (#130988)
* fix(ui): retain lazy recovery ownership through reload * refactor(ui): simplify pending action dispatch
1 parent db08f93 commit 233f1f0

9 files changed

Lines changed: 330 additions & 60 deletions

‎ui/src/app/app-host.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ import {
7070
type OptionalCustomElement,
7171
TERMINAL_PANEL_ELEMENT,
7272
} from "./lazy-custom-element.ts";
73-
import { hasStoredLazyShellAction } from "./lazy-shell-action.ts";
7473
import { postNativeNavState, type NativeNavState } from "./native-nav-state.ts";
7574
import { readNativeHistoryState, type NativeHistoryState } from "./native-web-chrome.ts";
7675
import { resolveOnboardingMode } from "./onboarding-mode.ts";
@@ -81,11 +80,7 @@ import {
8180
pushServerUiPrefs,
8281
} from "./server-prefs.ts";
8382
import { setSettingsChangeListener } from "./settings.ts";
84-
import {
85-
isStaleChunkImportError,
86-
retryStaleChunkReloadWhenReachable,
87-
scheduleStaleChunkReload,
88-
} from "./stale-chunk-reload.ts";
83+
import { isStaleChunkImportError, scheduleStaleChunkReload } from "./stale-chunk-reload.ts";
8984

9085
type AppSidebarElement = HTMLElement & {
9186
dismissTransientMenus: () => boolean;
@@ -157,8 +152,7 @@ class OpenClawShell
157152
readonly lazyCustomElements = new LazyCustomElementRequestController(
158153
this,
159154
() => this.shellChrome.cancelPendingLazyAction(),
160-
() =>
161-
hasStoredLazyShellAction() ? retryStaleChunkReloadWhenReachable() : Promise.resolve(false),
155+
(canReload) => this.shellChrome.retryPendingLazyAction(canReload),
162156
);
163157
// Gates lazy-action replay on the element being rendered; while the shell is
164158
// still splash-gated, replaying would loop through the open handlers forever.

‎ui/src/app/app-shell-chrome.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import {
6161
} from "./navigation-surface.ts";
6262
import { isBrowserPanelAvailable, isDesktopPanelAvailable } from "./panel-availability.ts";
6363
import { NAV_WIDTH_MAX, NAV_WIDTH_MIN } from "./settings.ts";
64+
import { retryStaleChunkReloadWhenReachable } from "./stale-chunk-reload.ts";
6465

6566
type DebugOverlayElement = HTMLElement & {
6667
toggle: () => void;
@@ -692,10 +693,18 @@ export class ShellChromeOwner {
692693
});
693694
}
694695

695-
private dispatchLazyShellEvent(event: LazyShellEvent): boolean {
696-
return window.dispatchEvent(
697-
new CustomEvent(event.eventType, { cancelable: true, detail: event.detail }),
698-
);
696+
retryPendingLazyAction(canReload: () => boolean): Promise<boolean> {
697+
const event = this.pendingLazyAction;
698+
return event
699+
? retryStaleChunkReloadWhenReachable({
700+
canReload: () =>
701+
canReload() && this.pendingLazyAction === event && persistLazyShellAction(event),
702+
})
703+
: Promise.resolve(false);
704+
}
705+
706+
private dispatchLazyShellEvent({ eventType, detail }: LazyShellEvent): boolean {
707+
return window.dispatchEvent(new CustomEvent(eventType, { cancelable: true, detail }));
699708
}
700709

701710
private clearPendingLazyAction(event: LazyShellEvent): void {

‎ui/src/app/lazy-custom-element.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,9 @@ describe("optional custom element requests", () => {
5959
function createRequestHarness() {
6060
const requestUpdate = vi.fn();
6161
const host = { requestUpdate, updateComplete: Promise.resolve(true) };
62-
const retryStale = vi.fn(async () => false);
62+
const retryStale = vi
63+
.fn<(canReload: () => boolean) => Promise<boolean>>()
64+
.mockResolvedValue(false);
6365
const requests = new LazyCustomElementRequestController(host, undefined, retryStale);
6466
return { requests, retryStale };
6567
}
@@ -228,9 +230,11 @@ describe("optional custom element requests", () => {
228230
expect(requests.visibleState).toMatchObject({ stale: true });
229231

230232
requests.retry();
233+
expect(retryStale.mock.calls[0]?.[0]?.()).toBe(true);
231234

232235
await waitForFast(() => expect(continuation).toHaveBeenCalledOnce());
233236
expect(retryStale).toHaveBeenCalledOnce();
237+
expect(retryStale.mock.calls[0]?.[0]?.()).toBe(false);
234238
expect(element.loadModule).toHaveBeenCalledTimes(2);
235239
});
236240

‎ui/src/app/lazy-custom-element.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ export class LazyCustomElementRequestController {
7272
constructor(
7373
private readonly host: UpdatingHost,
7474
private readonly onClose?: () => void,
75-
private readonly retryStale = retryStaleChunkReloadWhenReachable,
75+
private readonly retryStale = (canReload: () => boolean) =>
76+
retryStaleChunkReloadWhenReachable({ canReload }),
7677
) {}
7778

7879
get visibleState(): LazyCustomElementRequestState | undefined {
@@ -142,7 +143,8 @@ export class LazyCustomElementRequestController {
142143
} satisfies LazyCustomElementRequest;
143144
this.current = retryRequest;
144145
this.host.requestUpdate();
145-
void (request.stale ? this.retryStale() : Promise.resolve(false)).then((reloading) => {
146+
const canReload = () => this.current === retryRequest;
147+
void (request.stale ? this.retryStale(canReload) : Promise.resolve(false)).then((reloading) => {
146148
if (!reloading && this.current === retryRequest) {
147149
this.load(retryRequest);
148150
}

‎ui/src/app/lazy-shell-action.test.ts‎

Lines changed: 169 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,30 @@ import {
1515
stubRenderedWhenDefined,
1616
} from "./app-host.test-support.ts";
1717
import "./app-host.ts";
18-
import { DEBUG_OVERLAY_ELEMENT, KEYBOARD_SHORTCUTS_ELEMENT } from "./lazy-custom-element.ts";
19-
import { readLazyShellAction } from "./lazy-shell-action.ts";
18+
import {
19+
DEBUG_OVERLAY_ELEMENT,
20+
KEYBOARD_SHORTCUTS_ELEMENT,
21+
type LazyCustomElementRequestController,
22+
} from "./lazy-custom-element.ts";
23+
import { readLazyShellAction, SHELL_APPROVALS_OPEN_EVENT } from "./lazy-shell-action.ts";
24+
25+
const recovery = vi.hoisted(() => ({ reload: vi.fn(), pending: new Array<Promise<boolean>>() }));
26+
vi.mock("./stale-chunk-reload.ts", async (importOriginal) => {
27+
const actual = await importOriginal<typeof import("./stale-chunk-reload.ts")>();
28+
return {
29+
...actual,
30+
retryStaleChunkReloadWhenReachable: (
31+
deps: Parameters<typeof actual.retryStaleChunkReloadWhenReachable>[0],
32+
) => {
33+
const pending = actual.retryStaleChunkReloadWhenReachable({
34+
...deps,
35+
reload: recovery.reload,
36+
});
37+
recovery.pending.push(pending);
38+
return pending;
39+
},
40+
};
41+
});
2042

2143
const storageKey = "openclaw:lazy-event";
2244

@@ -34,7 +56,41 @@ async function withConnectedShell(shell: ShellLifecycle, run: () => void | Promi
3456
}
3557
}
3658

37-
afterEach(resetAppHostTestGlobals);
59+
afterEach(() => {
60+
resetAppHostTestGlobals();
61+
vi.restoreAllMocks();
62+
recovery.reload.mockClear();
63+
recovery.pending.length = 0;
64+
});
65+
66+
type PaletteShell = HTMLElement &
67+
ShellLifecycle & {
68+
commandPaletteElement: TestOptionalCustomElement;
69+
lazyCustomElements: LazyCustomElementRequestController;
70+
openPalette(): void;
71+
restorePendingLazyAction(): void;
72+
resetForContextEpoch(): void;
73+
};
74+
75+
function paletteShell(element: TestOptionalCustomElement, open: () => void): PaletteShell {
76+
const shell = document.createElement("openclaw-app-shell") as PaletteShell;
77+
shell.commandPaletteElement = element;
78+
Object.defineProperty(shell, "updateComplete", { get: () => Promise.resolve(true) });
79+
Object.defineProperty(shell, "commandPalette", {
80+
get: () =>
81+
customElements.get(element.tagName)
82+
? { isOpen: false, openPalette: open, togglePalette: open }
83+
: undefined,
84+
});
85+
stubRenderedWhenDefined(shell);
86+
return shell;
87+
}
88+
89+
function stalePalette() {
90+
return createLazyElementSpec("command palette", {
91+
firstError: new Error("Failed to fetch dynamically imported module: palette-old.js"),
92+
});
93+
}
3894

3995
describe("lazy shell action storage", () => {
4096
it.each([
@@ -53,6 +109,116 @@ describe("lazy shell action storage", () => {
53109
});
54110

55111
describe("shell lazy events", () => {
112+
it.each(["unavailable", "denied", "replacement-write-failed"] as const)(
113+
"retries in place without replaying an older action when storage is %s",
114+
async (mode) => {
115+
const storage = createStorageMock();
116+
if (mode === "replacement-write-failed") {
117+
storage.setItem(storageKey, JSON.stringify({ eventType: SHELL_APPROVALS_OPEN_EVENT }));
118+
}
119+
vi.stubGlobal("sessionStorage", mode === "unavailable" ? null : storage);
120+
if (mode === "denied") {
121+
Object.defineProperty(globalThis, "sessionStorage", {
122+
configurable: true,
123+
get() {
124+
throw new DOMException("Storage blocked", "SecurityError");
125+
},
126+
});
127+
}
128+
const head = vi.fn(async () => new Response(null, { status: 200 }));
129+
vi.stubGlobal("fetch", head);
130+
const open = vi.fn();
131+
const shell = paletteShell(stalePalette(), open);
132+
if (mode === "replacement-write-failed") {
133+
vi.spyOn(storage, "setItem").mockImplementation(() => {
134+
throw new DOMException("Storage full", "QuotaExceededError");
135+
});
136+
}
137+
138+
await withConnectedShell(shell, async () => {
139+
shell.openPalette();
140+
await vi.waitFor(() => expect(shell.lazyCustomElements.visibleState?.status).toBe("error"));
141+
shell.lazyCustomElements.retry();
142+
await Promise.all(recovery.pending);
143+
144+
await vi.waitFor(() => expect(open).toHaveBeenCalledOnce());
145+
expect(recovery.reload).not.toHaveBeenCalled();
146+
expect(head).not.toHaveBeenCalled();
147+
expect(readLazyShellAction()).toBeNull();
148+
});
149+
},
150+
);
151+
152+
it.each(["close", "context-replaced", "disconnected", "new-request"] as const)(
153+
"does not reload a retired retry after %s while the document probe is pending",
154+
async (retirement) => {
155+
vi.stubGlobal("sessionStorage", createStorageMock());
156+
let resolveHead = (_response: Response): void => {
157+
throw new Error("Document probe not started");
158+
};
159+
const head = vi.fn(
160+
() =>
161+
new Promise<Response>((resolve) => {
162+
resolveHead = resolve;
163+
}),
164+
);
165+
vi.stubGlobal("fetch", head);
166+
const open = vi.fn();
167+
const shell = paletteShell(stalePalette(), open);
168+
169+
await withConnectedShell(shell, async () => {
170+
shell.openPalette();
171+
await vi.waitFor(() => expect(shell.lazyCustomElements.visibleState?.status).toBe("error"));
172+
shell.lazyCustomElements.retry();
173+
await vi.waitFor(() => expect(head).toHaveBeenCalledOnce());
174+
175+
if (retirement === "close") {
176+
shell.lazyCustomElements.close();
177+
} else if (retirement === "context-replaced") {
178+
shell.resetForContextEpoch();
179+
} else if (retirement === "disconnected") {
180+
shell.disconnectedCallback();
181+
} else {
182+
shell.lazyCustomElements.request(createLazyElementSpec("new request"));
183+
}
184+
resolveHead(new Response(null, { status: 200 }));
185+
await expect(Promise.all(recovery.pending)).resolves.toEqual([false]);
186+
187+
expect(recovery.reload).not.toHaveBeenCalled();
188+
expect(open).not.toHaveBeenCalled();
189+
});
190+
},
191+
);
192+
193+
it("repairs stale stored intent before reloading and replays the current action once", async () => {
194+
const storage = createStorageMock();
195+
vi.stubGlobal("sessionStorage", storage);
196+
vi.stubGlobal(
197+
"fetch",
198+
vi.fn(async () => new Response(null, { status: 200 })),
199+
);
200+
const element = stalePalette();
201+
const open = vi.fn();
202+
const shell = paletteShell(element, open);
203+
204+
shell.openPalette();
205+
await vi.waitFor(() => expect(shell.lazyCustomElements.visibleState?.status).toBe("error"));
206+
storage.setItem(storageKey, "{}");
207+
shell.lazyCustomElements.retry();
208+
await expect(Promise.all(recovery.pending)).resolves.toEqual([true]);
209+
expect(recovery.reload).toHaveBeenCalledOnce();
210+
expect(readLazyShellAction()).toEqual({ eventType: COMMAND_PALETTE_OPEN_EVENT });
211+
212+
const replacement = paletteShell(element, open);
213+
await withConnectedShell(replacement, async () => {
214+
replacement.restorePendingLazyAction();
215+
await vi.waitFor(() => expect(open).toHaveBeenCalledOnce());
216+
replacement.restorePendingLazyAction();
217+
expect(open).toHaveBeenCalledOnce();
218+
expect(readLazyShellAction()).toBeNull();
219+
});
220+
});
221+
56222
it("requests the keyboard shortcuts dialog even from a focused text input", async () => {
57223
const requested = vi.fn();
58224
const toggled = vi.fn();

‎ui/src/app/lazy-shell-action.ts‎

Lines changed: 12 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,7 @@ const eventTypes = [
2323
] as const;
2424

2525
export type LazyShellEvent = {
26-
eventType:
27-
| typeof COMMAND_PALETTE_OPEN_EVENT
28-
| typeof DEBUG_OVERLAY_REQUEST_EVENT
29-
| typeof KEYBOARD_SHORTCUTS_REQUEST_EVENT
30-
| typeof TERMINAL_PANEL_TOGGLE_EVENT
31-
| typeof BROWSER_PANEL_TOGGLE_EVENT
32-
| typeof DESKTOP_PANEL_TOGGLE_EVENT
33-
| typeof CUSTODIAN_PANEL_TOGGLE_EVENT
34-
| typeof SHELL_APPROVALS_OPEN_EVENT;
26+
eventType: (typeof eventTypes)[number];
3527
detail?: object;
3628
};
3729

@@ -45,14 +37,6 @@ export function lazyShellEvent(
4537
: { eventType };
4638
}
4739

48-
export function hasStoredLazyShellAction(): boolean {
49-
try {
50-
return getSafeSessionStorage()?.getItem(STORAGE_KEY) !== null;
51-
} catch {
52-
return false;
53-
}
54-
}
55-
5640
export function readLazyShellAction(): LazyShellEvent | null {
5741
try {
5842
const stored = getSafeSessionStorage()?.getItem(STORAGE_KEY);
@@ -82,21 +66,22 @@ export function readLazyShellAction(): LazyShellEvent | null {
8266
return null;
8367
}
8468

85-
function writeStoredAction(value?: string): void {
69+
export function persistLazyShellAction(event: LazyShellEvent): boolean {
8670
try {
8771
const storage = getSafeSessionStorage();
88-
if (value === undefined) {
89-
storage?.removeItem(STORAGE_KEY);
90-
} else {
91-
storage?.setItem(STORAGE_KEY, value);
72+
if (!storage) {
73+
return false;
9274
}
75+
storage.setItem(STORAGE_KEY, JSON.stringify(event));
76+
return true;
9377
} catch {}
94-
}
95-
96-
export function persistLazyShellAction(event: LazyShellEvent): void {
97-
writeStoredAction(JSON.stringify(event));
78+
// A failed replacement must not leave a superseded action to replay on reload.
79+
clearLazyShellAction();
80+
return false;
9881
}
9982

10083
export function clearLazyShellAction(): void {
101-
writeStoredAction();
84+
try {
85+
getSafeSessionStorage()?.removeItem(STORAGE_KEY);
86+
} catch {}
10287
}

‎ui/src/app/stale-chunk-reload.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,28 @@ describe("retryStaleChunkReloadWhenReachable single-shot", () => {
331331
});
332332

333333
describe("retryStaleChunkReloadWhenReachable", () => {
334+
it.each(["before", "during"] as const)(
335+
"does not reload when recovery is retired %s the document probe",
336+
async (retirement) => {
337+
const response = deferred<boolean>();
338+
const probe = vi.fn(() => response.promise);
339+
const reload = vi.fn();
340+
let current = retirement === "during";
341+
const pending = retryStaleChunkReloadWhenReachable({
342+
canReload: () => current,
343+
probe,
344+
reload,
345+
});
346+
347+
current = false;
348+
response.resolve(true);
349+
350+
await expect(pending).resolves.toBe(false);
351+
expect(reload).not.toHaveBeenCalled();
352+
expect(probe).toHaveBeenCalledTimes(retirement === "during" ? 1 : 0);
353+
},
354+
);
355+
334356
it("reloads immediately when the gateway already answers", async () => {
335357
const reload = vi.fn();
336358
const probe = vi.fn().mockResolvedValue(true);

0 commit comments

Comments
 (0)