Skip to content

Commit a216eb6

Browse files
yangxianshengobviyus
authored andcommitted
fix(ui): bound stalled widget content loads
1 parent cc39c73 commit a216eb6

3 files changed

Lines changed: 169 additions & 18 deletions

File tree

‎ui/src/lib/board/widget-sandbox-host.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ describe("BoardWidgetSandboxHost", () => {
118118
await vi.waitFor(() => expect(onLoaded).toHaveBeenCalledOnce());
119119
expect(fetchMock).toHaveBeenCalledWith(
120120
"https://gateway.example/__openclaw__/board/weather?bt=ticket",
121-
{ cache: "no-store" },
121+
{ cache: "no-store", signal: expect.any(AbortSignal) },
122122
);
123123
expect(postMessage).toHaveBeenCalledWith(
124124
expect.objectContaining({
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import type { BoardWidget } from "./types.ts";
3+
import { BoardWidgetSandboxHost } from "./widget-sandbox-host.ts";
4+
5+
const SANDBOX_URL = "https://sandbox.example/mcp-app-sandbox";
6+
7+
function widget(viewGeneration = "a".repeat(32)): BoardWidget {
8+
return {
9+
name: "weather",
10+
tabId: "main",
11+
contentKind: "html",
12+
sizeW: 6,
13+
sizeH: 4,
14+
position: 0,
15+
grantState: "granted",
16+
revision: 2,
17+
viewTicket: "ticket",
18+
viewGeneration,
19+
};
20+
}
21+
22+
function createHost() {
23+
const frame = document.createElement("iframe");
24+
document.body.append(frame);
25+
const onLoadFailed = vi.fn();
26+
const onLoaded = vi.fn();
27+
const options = {
28+
frame,
29+
widget: widget(),
30+
sandboxOrigin: "https://sandbox.example",
31+
sandboxUrl: SANDBOX_URL,
32+
sourceOrigin: "https://gateway.example",
33+
resolveFrameUrl: () => "/widget?generation=first",
34+
confirmPrompt: () => true,
35+
onFrameUrl: vi.fn(),
36+
onLoadFailed,
37+
onUnauthorized: vi.fn(),
38+
onReadyTimeout: vi.fn(),
39+
onLoaded,
40+
onError: vi.fn(),
41+
};
42+
const host = new BoardWidgetSandboxHost(options);
43+
host.handleMessage(
44+
new MessageEvent("message", {
45+
source: frame.contentWindow,
46+
origin: "https://sandbox.example",
47+
data: {
48+
method: "ui/notifications/sandbox-proxy-ready",
49+
params: { sandboxUrl: SANDBOX_URL },
50+
},
51+
}),
52+
);
53+
return { host, onLoadFailed, onLoaded, options };
54+
}
55+
56+
afterEach(() => {
57+
vi.useRealTimers();
58+
document.body.replaceChildren();
59+
vi.unstubAllGlobals();
60+
});
61+
62+
describe("BoardWidgetSandboxHost document timeout", () => {
63+
it.each(["headers", "body"] as const)("times out stalled %s delivery", async (phase) => {
64+
vi.useFakeTimers();
65+
vi.stubGlobal(
66+
"fetch",
67+
vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
68+
const signal = init?.signal;
69+
if (phase === "headers") {
70+
return new Promise<Response>((_resolve, reject) => {
71+
signal?.addEventListener("abort", () => reject(new Error("request aborted")));
72+
});
73+
}
74+
return Promise.resolve(
75+
new Response(
76+
new ReadableStream({
77+
start(controller) {
78+
controller.enqueue(new TextEncoder().encode("<!doctype html>"));
79+
signal?.addEventListener("abort", () =>
80+
controller.error(new Error("body aborted")),
81+
);
82+
},
83+
}),
84+
),
85+
);
86+
}),
87+
);
88+
const { host, onLoadFailed, onLoaded } = createHost();
89+
90+
await vi.advanceTimersByTimeAsync(10_000);
91+
92+
expect(onLoadFailed).toHaveBeenCalledWith(widget());
93+
expect(onLoadFailed).toHaveBeenCalledOnce();
94+
expect(onLoaded).not.toHaveBeenCalled();
95+
host.dispose();
96+
});
97+
98+
it("keeps a replacement document after cancelling a stalled load", async () => {
99+
vi.useFakeTimers();
100+
let firstSignal: AbortSignal | undefined;
101+
const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
102+
if (fetchMock.mock.calls.length === 1) {
103+
firstSignal = init?.signal ?? undefined;
104+
return new Promise<Response>((_resolve, reject) => {
105+
firstSignal?.addEventListener("abort", () => reject(new Error("request aborted")));
106+
});
107+
}
108+
return Promise.resolve(new Response("<!doctype html><p>replacement</p>"));
109+
});
110+
vi.stubGlobal("fetch", fetchMock);
111+
const { host, onLoadFailed, onLoaded, options } = createHost();
112+
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
113+
114+
host.update({
115+
...options,
116+
widget: widget("b".repeat(32)),
117+
resolveFrameUrl: () => "/widget?generation=replacement",
118+
});
119+
await vi.waitFor(() => expect(onLoaded).toHaveBeenCalledOnce());
120+
await vi.advanceTimersByTimeAsync(10_000);
121+
122+
expect(firstSignal?.aborted).toBe(true);
123+
expect(fetchMock).toHaveBeenCalledTimes(2);
124+
expect(onLoadFailed).not.toHaveBeenCalled();
125+
expect(onLoaded).toHaveBeenCalledOnce();
126+
host.dispose();
127+
});
128+
});

‎ui/src/lib/board/widget-sandbox-host.ts‎

Lines changed: 40 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
isBoardWidgetBridgeRequest,
88
} from "./widget-bridge.ts";
99

10-
const SANDBOX_READY_TIMEOUT_MS = 10_000;
10+
const WIDGET_LOAD_TIMEOUT_MS = 10_000;
1111

1212
type BoardWidgetSandboxHostOptions = {
1313
frame: HTMLIFrameElement;
@@ -39,8 +39,11 @@ export class BoardWidgetSandboxHost {
3939
private ready = false;
4040
private readyTimer: number | null = null;
4141
private loadedDocumentKey = "";
42-
private loadingDocumentKey = "";
43-
private loadGeneration = 0;
42+
private activeDocumentLoad: {
43+
controller: AbortController;
44+
key: string;
45+
timeout: number;
46+
} | null = null;
4447
private requestGeneration = 0;
4548
private readonly pendingRequests = new Map<string, number>();
4649

@@ -60,8 +63,7 @@ export class BoardWidgetSandboxHost {
6063
this.active = active;
6164
if (!active) {
6265
this.clearReadyTimeout();
63-
this.loadGeneration += 1;
64-
this.loadingDocumentKey = "";
66+
this.cancelDocumentLoad();
6567
this.cancelPendingRequests("Widget inactive");
6668
this.requestGeneration += 1;
6769
return;
@@ -116,11 +118,10 @@ export class BoardWidgetSandboxHost {
116118
}
117119

118120
reset(): void {
119-
this.loadGeneration += 1;
121+
this.cancelDocumentLoad();
120122
this.requestGeneration += 1;
121123
this.pendingRequests.clear();
122124
this.loadedDocumentKey = "";
123-
this.loadingDocumentKey = "";
124125
this.bridgePort?.close();
125126
this.bridgePort = null;
126127
this.adoptedTicket = "";
@@ -292,6 +293,18 @@ export class BoardWidgetSandboxHost {
292293
}
293294
}
294295

296+
private cancelDocumentLoad(): void {
297+
const load = this.activeDocumentLoad;
298+
// Clear ownership before aborting so the rejection is stale and cannot
299+
// spend the retry budget or clear a replacement load.
300+
this.activeDocumentLoad = null;
301+
if (!load) {
302+
return;
303+
}
304+
window.clearTimeout(load.timeout);
305+
load.controller.abort();
306+
}
307+
295308
private scheduleReadyTimeout(): void {
296309
if (!this.active || this.ready || this.readyTimer !== null) {
297310
return;
@@ -304,7 +317,7 @@ export class BoardWidgetSandboxHost {
304317
// Browsers do not expose iframe HTTP failures through `error`. Bound the
305318
// proxy handshake so an unavailable adjacent listener cannot stay blank.
306319
this.retrySandboxFrame();
307-
}, SANDBOX_READY_TIMEOUT_MS);
320+
}, WIDGET_LOAD_TIMEOUT_MS);
308321
}
309322

310323
private retrySandboxFrame(): void {
@@ -379,16 +392,25 @@ export class BoardWidgetSandboxHost {
379392
return;
380393
}
381394
const documentKey = this.documentKey();
382-
if (documentKey === this.loadedDocumentKey || documentKey === this.loadingDocumentKey) {
395+
if (documentKey === this.loadedDocumentKey || documentKey === this.activeDocumentLoad?.key) {
383396
return;
384397
}
385-
this.loadingDocumentKey = documentKey;
398+
this.cancelDocumentLoad();
386399
const sourceHref = sourceUrl.href;
387400
this.options.onFrameUrl(sourceHref);
388-
const generation = ++this.loadGeneration;
401+
const controller = new AbortController();
402+
const load = {
403+
controller,
404+
key: documentKey,
405+
timeout: window.setTimeout(
406+
() => controller.abort(new DOMException("The operation timed out.", "TimeoutError")),
407+
WIDGET_LOAD_TIMEOUT_MS,
408+
),
409+
};
410+
this.activeDocumentLoad = load;
389411
try {
390-
const response = await fetch(sourceHref, { cache: "no-store" });
391-
if (!this.active || generation !== this.loadGeneration || !frame.isConnected) {
412+
const response = await fetch(sourceHref, { cache: "no-store", signal: controller.signal });
413+
if (!this.active || this.activeDocumentLoad !== load || !frame.isConnected) {
392414
return;
393415
}
394416
if (response.status === 401) {
@@ -399,7 +421,7 @@ export class BoardWidgetSandboxHost {
399421
throw new Error(`widget content request failed (${response.status})`);
400422
}
401423
const documentHtml = await response.text();
402-
if (!this.active || generation !== this.loadGeneration || !frame.isConnected) {
424+
if (!this.active || this.activeDocumentLoad !== load || !frame.isConnected) {
403425
return;
404426
}
405427
frame.contentWindow?.postMessage(
@@ -416,12 +438,13 @@ export class BoardWidgetSandboxHost {
416438
// pending. Complete the handshake once these exact bytes become current.
417439
this.postHostInit();
418440
} catch {
419-
if (generation === this.loadGeneration) {
441+
if (this.activeDocumentLoad === load) {
420442
this.options.onLoadFailed(widget);
421443
}
422444
} finally {
423-
if (generation === this.loadGeneration) {
424-
this.loadingDocumentKey = "";
445+
window.clearTimeout(load.timeout);
446+
if (this.activeDocumentLoad === load) {
447+
this.activeDocumentLoad = null;
425448
}
426449
}
427450
}

0 commit comments

Comments
 (0)