Repository navigation
fix(ui): playing chat widgets reload when the run finishes or the gateway reconnects - #168181
Conversation
Run completion moves a live show_widget document from its tool-result preview into the final assistant reply, then reorders the run frame. Preserve its connected element through a bounded parking handoff and atomic keyed body-part moves without changing transcript projection. Disable prompts and runtime-error wakes while parked. Retain rendered content by document, session, and principal facts rather than Gateway client identity. Retire request and prompt bindings when the client changes, revalidate through the new client, and keep the iframe when document bytes and sandbox configuration are unchanged. Credential revision changes still clear the view, and wakes use the validated client. State-preserving DOM moves require native moveBefore (Chrome/Edge 133+ and Firefox 144+). Safari retains the original Lit and remount behavior. Unclaimed parked elements are disposed after one second; a second parked copy with the same key replaces the older copy as requested. Regressions failed before the fixes and pass afterward: replacement-client retention and prompt revalidation, live tool-result to final-reply handoff, parked authority, and non-atomic prepend behavior. The real transcript E2E retains the original iframe, inner counter, and one view read, and verifies scroll forwarding after completion. Validation: 32 view tests, 2 mount tests, 3 keyed-range tests, 15 existing widget-card tests, and the focused Chromium transcript E2E pass. The full changed-file gate passed on a verified remote Crabbox SSH checkout, with candidate hashes checked before and after. Oxfmt and isolated review pass.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesPreserve inline chat widgets across run completion and same-account Gateway client replacement. Example: The cv_retained_counter widget reaches count 1 before its agent run finishes.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR fixes a current widget-state bug; the new browser trace resolves the earlier authorization-proof concern, and no actionable introduced defect was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe Control UI renders authenticated Canvas documents inside sandboxed chat iframes; transcript updates move their presentation, while Gateway state governs document reads and prompt or wake authority. flowchart TD
A[Gateway transcript events] --> B[Chat run frame]
B --> C[Widget mount and handoff]
C --> D[Canvas widget view]
E[Current Gateway authority] --> D
D --> F[Sandbox iframe]
F --> G[Guarded prompts and wakes]
G --> E
Technical reviewBest possible solution: Land the focused lifecycle repair with current-client authorization intact and the documented Safari fallback. Do we have a high-confidence way to reproduce the issue? Current-main source exposes both destructive iframe movement and replacement-client invalidation; supplied Chromium evidence exercises the repaired paths, but this read-only review ran no code. Is this the best way to solve the issue? The change repairs widget presentation lifetime at its existing owners while preserving authoritative revalidation and avoiding transcript-projection changes. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d5172e6d2202. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +238, Tests +503, Docs +5. Total +746 across 11 files. Added test files: 3. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 10, 2026, 12:48 AM ET / 04:48 UTC (Revision 2). |
|
@clawsweeper re-review The requested retained-port authorization proof is now complete on unchanged head A disposable Chromium E2E probe used the built Control UI, real Canvas sandbox server/wrapper, real private MessagePorts, trusted pointer clicks, and the existing mock WebSocket Gateway. It observed final outbound The probe induces event-sequence gaps, verifies the actual Gateway client object changes, waits for document revalidation, and confirms the original iframe survives. Positive controls then send two prompts through the normal chat path and one deliberate runtime-error wake. The wake assertion matches both the exact document ID and For the negative controls, it moves that original iframe to a connected test-only holder before revocation, keeping the actual old sandbox and private port alive even when the application clears its view. It then changes the next real handshake to a different account/recovery scope, a different recovery scope alone, or pairing-only scopes (no read/write/admin access), and induces a fresh client replacement. Pointer clicks in the original sandbox try both a prompt and a runtime error. A top-level observer confirms the original sandbox's runtime-error message arrives. No This is browser + mock-Gateway boundary evidence, not a live external Gateway claim. No production or committed test source changed. The probe uses Disposable probe sourceimport { expect, it } from "vitest";
import { buildWidgetDocument } from "../../../src/canvas/wrap.js";
import { clickBoardWidgetControl } from "../test-helpers/control-ui-e2e-widget.ts";
import { useCanvasSandboxFixture } from "./canvas-sandbox.test-support.ts";
import { controlUiSessionUrl, createChatFlowE2eSuite, installMockGateway } from "./chat-flow.test-support.ts";
import { createControlUiE2eContextOptions } from "./control-ui-e2e-suite.test-support.ts";
// Disposable boundary proof for PR #168181; no production hooks or synthetic ports.
const suite = createChatFlowE2eSuite();
suite.define(() => {
const canvasView = useCanvasSandboxFixture();
for (const change of ["account", "recovery-scope", "read-access"] as const) {
it(`retained widget authority: ${change}`, async () => {
await suite.withPage({ ...createControlUiE2eContextOptions(), serviceWorkers: "allow" }, async ({ page }) => {
const sessionKey = `agent:main:dashboard:authority-${change}`;
const ids = [`cv_positive_${change}`, `cv_negative_${change}`];
const html = buildWidgetDocument("Authority proof", `<main style="height:180px"><button onclick="sendPrompt('authority probe')">Prompt</button><button onclick="throw new Error('authority crash probe')">Crash</button></main>`);
const messages = [{ role: "assistant", timestamp: Date.now(), content: ids.flatMap(id => [
{ type: "text", text: `[embed](/__openclaw__/canvas/documents/${id}/index.html)` },
{ type: "canvas", preview: { kind: "canvas", surface: "assistant_message", render: "url", viewId: id, url: `/__openclaw__/canvas/documents/${id}/index.html`, title: id, preferredHeight: 180, sandbox: "scripts" } },
]) }];
const gateway = await installMockGateway(page, {
sessionKey, historyMessages: messages,
presenceUsers: [{ self: true, id: "proof-account-a", name: "Synthetic A" }],
methodResponses: { "canvas.document.view": canvasView(html) },
});
await page.goto(controlUiSessionUrl(suite.server.baseUrl, sessionKey));
const widgets = page.locator(".chat-thread openclaw-canvas-widget-view");
await expect.poll(() => widgets.count()).toBe(2);
const positive = widgets.nth(0).locator("iframe");
const negative = widgets.nth(1).locator("iframe");
const positiveInner = positive.contentFrame().frameLocator("iframe");
const negativeInner = negative.contentFrame().frameLocator("iframe");
await positiveInner.getByRole("button", { name: "Prompt", exact: true }).waitFor();
await negativeInner.getByRole("button", { name: "Prompt", exact: true }).waitFor();
const original = await positive.elementHandle();
await page.evaluate(() => { const app = document.querySelector("openclaw-app") as any; (window as any).proofOldClient = app.runtime.context.gateway.snapshot.client; });
await gateway.deliverLatest({ type: "event", event: "proof-gap", payload: {}, seq: 1000000 });
await gateway.deliverLatest({ type: "event", event: "proof-gap", payload: {}, seq: 1000002 });
await page.waitForFunction(() => (document.querySelector("openclaw-app") as any).runtime.context.gateway.snapshot.phase === "connected");
await page.waitForFunction(() => { const app = document.querySelector("openclaw-app") as any; return app.runtime.context.gateway.snapshot.client !== (window as any).proofOldClient; });
await expect.poll(async () => (await gateway.getRequests("canvas.document.view")).length).toBe(4);
expect(await positive.evaluate((frame, old) => frame === old, original)).toBe(true);
await page.waitForFunction(() => [...document.querySelectorAll("openclaw-canvas-widget-view")].every((view: any) => !view.pending));
const send = async (inner: typeof positiveInner) => {
const count = (await gateway.getRequests("chat.send")).length;
await clickBoardWidgetControl(page, inner.getByRole("button", { name: "Prompt", exact: true }));
const request = await gateway.waitForRequest("chat.send", { after: count });
expect(request.params).toMatchObject({ sessionKey, message: "authority probe" });
await gateway.emitChatFinal({ runId: String((request.params as any).idempotencyKey), sessionKey, text: "Acknowledged." });
};
await send(positiveInner);
await clickBoardWidgetControl(page, positiveInner.getByRole("button", { name: "Crash", exact: true }));
await expect.poll(async () => (await gateway.getRequests("wake")).filter(request => JSON.stringify(request.params).includes(ids[0]!) && JSON.stringify(request.params).includes("authority crash probe")).length).toBe(1);
// Negative control uses a distinct document: no error-dedup/rate limiter was spent.
await send(negativeInner);
expect((await gateway.getRequests("wake")).filter(request => JSON.stringify(request.params).includes(ids[1]!))).toHaveLength(0);
const counts = { chat: (await gateway.getRequests("chat.send")).length, wake: (await gateway.getRequests("wake")).length };
const oldNegative = await negative.elementHandle();
await negative.evaluate(frame => {
const holder = document.createElement("div");
holder.style.cssText = "position:fixed;bottom:0;left:0;z-index:99999;height:180px;width:600px;background:white";
document.body.append(holder);
holder.moveBefore(frame, null);
(window as any).proofRawErrors = 0;
(window as any).proofPromptEvents = 0;
document.addEventListener("openclaw-widget-prompt", () => (window as any).proofPromptEvents++, true);
window.addEventListener("message", event => {
if (event.source === frame.contentWindow && event.data?.type === "openclaw:widget-runtime-error") (window as any).proofRawErrors++;
});
});
const hello = await page.evaluate(() => JSON.parse(JSON.stringify((document.querySelector("openclaw-app") as any).runtime.context.gateway.snapshot.hello)));
if (change === "read-access") hello.auth.scopes = ["operator.pairing"];
else hello.auth.recoveryScope = `proof-new-${change}`;
if (change === "account") {
await gateway.setMethodResponse("users.self", { profile: { id: "proof-account-b", displayName: "Synthetic B", emails: [], avatarMime: null, hasAvatar: false, githubIdentity: null, mergedInto: null, createdAt: 1, updatedAt: 1 } });
}
await gateway.setMethodResponse("connect", hello);
await gateway.deliverLatest({ type: "event", event: "proof-gap", payload: {}, seq: 1000000 });
await gateway.deliverLatest({ type: "event", event: "proof-gap", payload: {}, seq: 1000002 });
await page.waitForFunction(() => (document.querySelector("openclaw-app") as any).runtime.context.gateway.snapshot.phase === "connected");
await page.waitForFunction(({ change }) => {
const snapshot = (document.querySelector("openclaw-app") as any).runtime.context.gateway.snapshot;
return change === "read-access" ? snapshot.hello.auth.scopes.includes("operator.pairing") && !snapshot.hello.auth.scopes.includes("operator.read") : snapshot.hello.auth.recoveryScope === `proof-new-${change}`;
}, { change });
// Keep the revoked original sandbox running to exercise real stale messages,
// rather than accepting browser destruction as the reason they cannot send.
const oldOuter = await oldNegative!.contentFrame();
const oldInner = oldOuter!.frameLocator("iframe");
await clickBoardWidgetControl(page, oldInner.getByRole("button", { name: "Prompt", exact: true }));
await clickBoardWidgetControl(page, oldInner.getByRole("button", { name: "Crash", exact: true }));
await page.waitForFunction(() => (window as any).proofRawErrors === 1);
await page.evaluate(() => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
expect(await page.evaluate(() => (window as any).proofPromptEvents)).toBe(0);
expect(await gateway.getRequests("chat.send")).toHaveLength(counts.chat);
expect(await gateway.getRequests("wake")).toHaveLength(counts.wake);
console.log(JSON.stringify({ proof: change, clientReplaced: true, originalIframeRetained: true, postRevalidationChatSends: counts.chat, postRevalidationWakes: counts.wake, revokedOriginalSandboxStillRunning: true, revokedRawErrorArrived: true, revokedPromptEventDelta: 0, revokedChatSendDelta: 0, revokedWakeDelta: 0 }));
});
});
}
}); |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…enclaw#168181) Run completion moves a live show_widget document from its tool-result preview into the final assistant reply, then reorders the run frame. Preserve its connected element through a bounded parking handoff and atomic keyed body-part moves without changing transcript projection. Disable prompts and runtime-error wakes while parked. Retain rendered content by document, session, and principal facts rather than Gateway client identity. Retire request and prompt bindings when the client changes, revalidate through the new client, and keep the iframe when document bytes and sandbox configuration are unchanged. Credential revision changes still clear the view, and wakes use the validated client. State-preserving DOM moves require native moveBefore (Chrome/Edge 133+ and Firefox 144+). Safari retains the original Lit and remount behavior. Unclaimed parked elements are disposed after one second; a second parked copy with the same key replaces the older copy as requested. Regressions failed before the fixes and pass afterward: replacement-client retention and prompt revalidation, live tool-result to final-reply handoff, parked authority, and non-atomic prepend behavior. The real transcript E2E retains the original iframe, inner counter, and one view read, and verifies scroll forwarding after completion. Validation: 32 view tests, 2 mount tests, 3 keyed-range tests, 15 existing widget-card tests, and the focused Chromium transcript E2E pass. The full changed-file gate passed on a verified remote Crabbox SSH checkout, with candidate hashes checked before and after. Oxfmt and isolated review pass.
What Problem This Solves
Fixes: a playing inline chat widget (for example a
show_widgetvideo) reloads and loses its state when the agent's run finishes or the Control UI's gateway client reconnects.User Impact
User impact: in Chrome/Edge 133+ and Firefox 144+, a widget keeps playing and keeps its local interaction state when its run completes and the widget moves into the final reply. Every browser keeps rendered widgets across event-gap recovery, wake reconnects,
onlinerecovery, and Retry now. Safari still reloads the widget when it moves into the final reply, because it lacks atomic DOM moves; it gets the reconnect fix.Why This Change Was Made
show_widgetresult renders as its own transcript row. When the final assistant reply embeds that same document, the reply row takes over the widget, and the run frame reorders its body parts. Both steps removed or reinserted the iframe, and removing an iframe discards its document. Production evidence: the gateway log shows a secondcanvas.document.viewread 1.5 s after the final reply, on the same open WebSocket. This change keeps the transcript projection as-is and hands the live element across instead:AsyncDirectiveparks the widget element in an inert offscreen container. Lit's clear path notifies the directive before it removes DOM, so the element is still connected when it parks.moveBefore.connectedMoveCallbackkeeps the view's sandbox lifecycle intact during atomic moves.moveBefore, rendering is exactly what Lit did before.Evidence
ui/src/e2e/chat-widget-retention.e2e.test.ts(real chat transcript, mock gateway, Chromium, ~25 s forpnpm test <file> --maxWorkers=1):show_widgetresult, and a click sets in-widget state.canvas.document.viewread. Wheel scroll still forwards to the transcript.ui/src/components/canvas-widget-view.test.ts, 32 tests:check:changedpassed on Testbox (146 s). oxfmt and Codex autoreview are clean.Related: #168143 (widget fullscreen, content-fit sizing, and clipped captions; same user report).
Retained-widget authorization proof
Additional Chromium browser proof and its disposable source pass on head
77310579857f722c70b206392486c4694ab5cf17: same-account client replacement retains the original iframe and permits prompts/wakes after revalidation; account replacement, recovery-scope replacement, and loss of read access block the original sandbox before prompt dispatch or outboundchat.send/wake. The stale sandbox is deliberately kept alive, and its real runtime-error message is observed, so iframe destruction and error deduplication cannot explain the negative result. Three cases pass in 24.71 s wall time. This uses the real UI/sandbox with a mock Gateway, not a live external Gateway.Exact-head CI run 38023254215 passed.