Skip to content

Commit ec998a0

Browse files
authored
feat(canvas): export widgets as PNG — copy or download from the card menu (#110992)
* feat(canvas): export widgets as PNG — copy to clipboard or download from the card menu * fix(ui): widget-export lint, knip, and lines-budget cleanup
1 parent 941ed4f commit ec998a0

9 files changed

Lines changed: 503 additions & 8 deletions

File tree

‎docs/tools/show-widget.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,12 @@ read_when:
1515

1616
When the agent calls `show_widget`, OpenClaw core wraps `widget_code` in a minimal HTML document, stores it as a Canvas document, and returns a preview handle. The Control UI renders that handle as a sandboxed iframe directly under the tool call, while native apps use an isolated web view. Both restore the widget after history reload.
1717

18-
For browser embedding, the wrapper document injects three small host bridges around the widget code:
18+
For browser embedding, the wrapper document injects four small host bridges around the widget code:
1919

2020
- A size reporter posts the rendered content height to the embedding chat, which clamps it and fits the iframe (160 to 1200 pixels).
2121
- A prompt bridge defines a global `sendPrompt(text)` function that widget scripts can call to submit a follow-up message into the chat. The bridge creates a private message channel and offers one endpoint to the chat before any widget code runs; the chat adopts only that first offer. See [Interactive widgets](#interactive-widgets).
2222
- A theme bridge listens for the Control UI's current design tokens and applies them as CSS variables, on load and again on every theme change.
23+
- A snapshot bridge renders the current widget document as a PNG when the embedding chat requests an export.
2324

2425
Everything else stays inside the frame: the document runs in an opaque origin with a strict Content Security Policy, so widget scripts cannot reach the Control UI, the Gateway, or the network.
2526

@@ -70,6 +71,8 @@ Author widgets with three rules:
7071
2. Keep the page background transparent so the widget belongs to its host surface.
7172
3. Reserve `--accent-fill` for at most one primary action.
7273

74+
**Export:** In web chat, open the widget card menu to copy the rendered widget to the clipboard or download it as a PNG. Older widget documents without the snapshot bridge fall back to an HTML file download.
75+
7376
## Use the tool
7477

7578
Both implementations use the same required fields:

‎src/canvas/widget-tool.test.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,9 @@ describe("show_widget", () => {
6666
'<SvG viewBox="0 0 10 10"><circle r="4" /></SvG>',
6767
);
6868

69-
expect(Buffer.byteLength(html)).toBe(5221);
69+
expect(Buffer.byteLength(html)).toBe(9649);
7070
expect(createHash("sha256").update(html).digest("hex")).toBe(
71-
"8a6c07f9004e816fcadd8fab009f9c78ef831a8027991d61dbeeb4b254721acc",
71+
"3326950b5fde8ef742df1f288102f6cb3cc330548b4b4c157424a54d1e164b3a",
7272
);
7373
});
7474

@@ -125,7 +125,7 @@ describe("show_widget", () => {
125125
expect(manifest.cspSandbox).toBe("scripts");
126126
});
127127

128-
it("keeps the prompt bridge ahead of HTML widget code", async () => {
128+
it("keeps the host bridges ordered around HTML widget code", async () => {
129129
const stateDir = await createStateDir();
130130
const { viewId } = await executeWidget({
131131
stateDir,
@@ -140,6 +140,13 @@ describe("show_widget", () => {
140140
expect(html.indexOf("window.sendPrompt")).toBeLessThan(html.indexOf("<section>"));
141141
expect(html).toContain("openclaw:widget-theme");
142142
expect(html.indexOf("openclaw:widget-theme")).toBeLessThan(html.indexOf("<section>"));
143+
expect(html).toContain("openclaw:widget-snapshot-request");
144+
expect(html.indexOf("openclaw:widget-theme")).toBeLessThan(
145+
html.indexOf("openclaw:widget-snapshot-request"),
146+
);
147+
expect(html.indexOf("openclaw:widget-snapshot-request")).toBeLessThan(
148+
html.indexOf("<section>"),
149+
);
143150
const bridgeKeys = JSON.parse(html.match(/const keys=(\[[^\]]+\])/)?.[1] ?? "[]") as string[];
144151
expect(bridgeKeys).toEqual([
145152
"surface",
@@ -166,6 +173,11 @@ describe("show_widget", () => {
166173
expect(html).toContain("c.port1.postMessage.bind(c.port1)");
167174
expect(html).toContain('post({type:"openclaw:widget-prompt"');
168175
expect(html).not.toContain('window.parent.postMessage({type:"openclaw:widget-prompt",');
176+
expect(html).toContain("const post=(message,origin)=>parent.postMessage(message,origin)");
177+
expect(html).toContain('query.call(root,"script")');
178+
expect(html).toContain('queryDocument("canvas")');
179+
expect(html).toContain("canvasWidth*canvasHeight>16777216");
180+
expect(html).toContain('toDataURL.call(canvas,"image/png")');
169181
});
170182

171183
it("uses opaque ids and evicts the oldest widget within a session scope", async () => {

‎src/canvas/wrap.ts‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,64 @@ export function buildWidgetDocument(title: string, widgetCode: string): string {
139139
'const value=typeof raw==="string"?raw.trim():"";' +
140140
'if(value&&value.length<=256)set("--"+key,value);else rm("--"+key);}' +
141141
'if(data.mode==="light"||data.mode==="dark")set("color-scheme",data.mode);});})();</script>';
142+
/*
143+
* Snapshot requests come from the embedding parent and replies return only
144+
* there. Capture the response channel and rendering primitives before widget
145+
* code can patch them; the widget still owns the document being rendered.
146+
*/
147+
const snapshotBridge =
148+
"<script>(()=>{if(!window.parent||window.parent===window)return;" +
149+
"const parent=window.parent;const post=(message,origin)=>parent.postMessage(message,origin);" +
150+
"const listen=window.addEventListener.bind(window);" +
151+
"const clone=Node.prototype.cloneNode;const query=Element.prototype.querySelectorAll;" +
152+
"const queryDocument=document.querySelectorAll.bind(document);" +
153+
"const item=NodeList.prototype.item;const remove=Node.prototype.removeChild;" +
154+
"const replace=Node.prototype.replaceChild;" +
155+
'const getParent=Object.getOwnPropertyDescriptor(Node.prototype,"parentNode")?.get;' +
156+
"const names=Element.prototype.getAttributeNames;const getAttr=Element.prototype.getAttribute;" +
157+
"const setAttr=Element.prototype.setAttribute;" +
158+
"const serializer=new XMLSerializer();const serialize=serializer.serializeToString.bind(serializer);" +
159+
"const create=document.createElement.bind(document);const styles=getComputedStyle.bind(window);" +
160+
"const getProperty=CSSStyleDeclaration.prototype.getPropertyValue;" +
161+
"const getContext=HTMLCanvasElement.prototype.getContext;" +
162+
"const toDataURL=HTMLCanvasElement.prototype.toDataURL;" +
163+
'const setWidth=Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,"width")?.set;' +
164+
'const setHeight=Object.getOwnPropertyDescriptor(HTMLCanvasElement.prototype,"height")?.set;' +
165+
'const setFill=Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype,"fillStyle")?.set;' +
166+
"const fill=CanvasRenderingContext2D.prototype.fillRect;" +
167+
"const draw=CanvasRenderingContext2D.prototype.drawImage;" +
168+
"const add=EventTarget.prototype.addEventListener;const ImageCtor=Image;" +
169+
'const setSrc=Object.getOwnPropertyDescriptor(HTMLImageElement.prototype,"src")?.set;' +
170+
"const encode=encodeURIComponent;const P=Promise;const ErrorCtor=Error;const stringify=String;" +
171+
"const max=Math.max.bind(Math);const min=Math.min.bind(Math);const ceil=Math.ceil.bind(Math);" +
172+
'listen("message",event=>{if(event.source!==parent)return;' +
173+
'const data=event.data;if(!data||data.type!=="openclaw:widget-snapshot-request"||typeof data.id!=="string")return;' +
174+
"void (async()=>{try{const body=document.body;" +
175+
"const width=max(1,body.scrollWidth);const height=max(1,body.scrollHeight);" +
176+
'const root=clone.call(document.documentElement,true);const scripts=query.call(root,"script");' +
177+
"for(let index=scripts.length-1;index>=0;index--){const script=item.call(scripts,index);" +
178+
"if(script&&getParent){const owner=getParent.call(script);if(owner)remove.call(owner,script);}}" +
179+
'const liveCanvases=queryDocument("canvas");const clonedCanvases=query.call(root,"canvas");' +
180+
"for(let index=0;index<liveCanvases.length;index++){const live=item.call(liveCanvases,index);" +
181+
"const cloned=item.call(clonedCanvases,index);if(!live||!cloned||!getParent||!setSrc)continue;" +
182+
'const image=create("img");for(const name of names.call(cloned)){const value=getAttr.call(cloned,name);' +
183+
'if(value!==null)setAttr.call(image,name,value);}setSrc.call(image,toDataURL.call(live,"image/png"));' +
184+
"const owner=getParent.call(cloned);if(owner)replace.call(owner,image,cloned);}" +
185+
'const svg=\'<svg xmlns="http://www.w3.org/2000/svg" width="\'+width+\'" height="\'+height+\'"><foreignObject width="100%" height="100%">\'+serialize(root)+"</foreignObject></svg>";' +
186+
'const url="data:image/svg+xml;charset=utf-8,"+encode(svg);' +
187+
"const image=new ImageCtor();await new P((resolve,reject)=>{" +
188+
'add.call(image,"load",resolve,{once:true});add.call(image,"error",()=>reject(new ErrorCtor("widget snapshot image failed to load")),{once:true});' +
189+
'if(!setSrc)throw new ErrorCtor("widget snapshot image source unavailable");setSrc.call(image,url);});' +
190+
'const canvas=create("canvas");const scale=min(window.devicePixelRatio||1,2);' +
191+
'if(!setWidth||!setHeight)throw new ErrorCtor("widget snapshot canvas dimensions unavailable");' +
192+
"const canvasWidth=ceil(width*scale);const canvasHeight=ceil(height*scale);" +
193+
'if(canvasWidth>16384||canvasHeight>16384||canvasWidth*canvasHeight>16777216)throw new ErrorCtor("widget snapshot dimensions exceed limit");' +
194+
"setWidth.call(canvas,canvasWidth);setHeight.call(canvas,canvasHeight);" +
195+
'const context=getContext.call(canvas,"2d");if(!context||!setFill)throw new ErrorCtor("widget snapshot canvas unavailable");' +
196+
'setFill.call(context,getProperty.call(styles(document.documentElement),"--surface"));' +
197+
"fill.call(context,0,0,canvasWidth,canvasHeight);draw.call(context,image,0,0,canvasWidth,canvasHeight);" +
198+
'post({type:"openclaw:widget-snapshot",id:data.id,dataUrl:toDataURL.call(canvas,"image/png"),width,height},"*");' +
199+
'}catch(error){post({type:"openclaw:widget-snapshot",id:data.id,error:stringify(error)},"*");}})();});})();</script>';
142200
return `<!doctype html>
143-
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:;"><title>${escapeHtml(title)}</title><style>${WIDGET_BASE_STYLES}</style></head><body${bodyClass}>${promptBridge}${themeBridge}${widgetCode}${sizeReporter}</body></html>`;
201+
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:;"><title>${escapeHtml(title)}</title><style>${WIDGET_BASE_STYLES}</style></head><body${bodyClass}>${promptBridge}${themeBridge}${snapshotBridge}${widgetCode}${sizeReporter}</body></html>`;
144202
}

‎ui/src/i18n/locales/en.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3926,6 +3926,11 @@ export const en: TranslationMap = {
39263926
rawDetails: "Raw details",
39273927
openFile: "Open file",
39283928
openDetails: "Open tool details in side panel",
3929+
widgetActions: "Widget actions",
3930+
copyToClipboard: "Copy to clipboard",
3931+
downloadFile: "Download file",
3932+
widgetExportRerender: "This widget needs to be re-rendered to export as an image.",
3933+
widgetExportFailed: "Widget export failed. Try again.",
39293934
fileChanges: "File changes",
39303935
attemptedChanges: "Attempted changes",
39313936
failed: "failed",

‎ui/src/pages/chat/components/widget-card.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ describe("widget-card", () => {
2222
);
2323
expect(canvas.querySelector("iframe.chat-tool-card__preview-frame")).not.toBeNull();
2424
expect(canvas.querySelector("mcp-app-view")).toBeNull();
25+
expect(canvas.querySelector('button[aria-label="Widget actions"]')).not.toBeNull();
26+
expect(
27+
Array.from(canvas.querySelectorAll("wa-dropdown-item"), (item) => item.textContent?.trim()),
28+
).toEqual(["Copy to clipboard", "Download file"]);
2529

2630
const app = document.createElement("div");
2731
render(
@@ -41,6 +45,7 @@ describe("widget-card", () => {
4145
);
4246
expect(app.querySelector("mcp-app-view")).not.toBeNull();
4347
expect(app.querySelector("iframe")).toBeNull();
48+
expect(app.querySelector('button[aria-label="Widget actions"]')).toBeNull();
4449

4550
const unknown = document.createElement("div");
4651
render(renderToolPreview({ kind: "unknown" } as never, "chat_message"), unknown);

‎ui/src/pages/chat/components/widget-card.ts‎

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import { html, nothing } from "lit";
22
import { keyed } from "lit/directives/keyed.js";
33
import { ensureCustomElementDefined } from "../../../app/lazy-custom-element.ts";
4+
import { icons } from "../../../components/icons.ts";
45
import {
56
dispatchWidgetPrompt,
67
WIDGET_PROMPT_EVENT,
78
type WidgetPromptEventDetail,
89
} from "../../../components/mcp-app-security.ts";
10+
import "../../../components/web-awesome.ts";
911
import { t } from "../../../i18n/index.ts";
1012
import type { ToolPreview } from "../../../lib/chat/tool-cards.ts";
1113
import {
@@ -14,7 +16,9 @@ import {
1416
resolveEmbedSandbox,
1517
type EmbedSandboxMode,
1618
} from "../../../lib/chat/tool-display.ts";
19+
import { showToast } from "../../../lib/toast.ts";
1720
import type { SidebarContent } from "./chat-sidebar.ts";
21+
import { exportWidget } from "./widget-export.ts";
1822
import { installWidgetThemeObserver, postWidgetTheme } from "./widget-theme.ts";
1923

2024
export { WIDGET_PROMPT_EVENT };
@@ -284,6 +288,63 @@ function renderWidgetContent(
284288
return nothing;
285289
}
286290

291+
function handleWidgetExportAction(
292+
event: CustomEvent<{ item: { value?: string } }>,
293+
title: string | undefined,
294+
) {
295+
const value = event.detail.item.value;
296+
if (value !== "copy" && value !== "download") {
297+
return;
298+
}
299+
const dropdown = event.currentTarget;
300+
const frame =
301+
dropdown instanceof HTMLElement
302+
? dropdown
303+
.closest(".chat-tool-card__preview")
304+
?.querySelector<HTMLIFrameElement>(".chat-tool-card__preview-frame")
305+
: null;
306+
if (!frame) {
307+
showToast({ message: t("chat.toolCards.widgetExportFailed") });
308+
return;
309+
}
310+
void exportWidget(value, frame, title)
311+
.then((result) => {
312+
if (result === "rerender-required") {
313+
showToast({ message: t("chat.toolCards.widgetExportRerender") });
314+
}
315+
})
316+
.catch(() => {
317+
showToast({ message: t("chat.toolCards.widgetExportFailed") });
318+
});
319+
}
320+
321+
function renderWidgetActions(preview: ToolPreview) {
322+
if (preview.mcpApp || !isInternalCanvasEntryUrl(preview.url)) {
323+
return nothing;
324+
}
325+
return html`
326+
<wa-dropdown
327+
class="chat-tool-card__widget-actions"
328+
placement="bottom-end"
329+
aria-label=${t("chat.toolCards.widgetActions")}
330+
@wa-select=${(event: CustomEvent<{ item: { value?: string } }>) =>
331+
handleWidgetExportAction(event, preview.title)}
332+
>
333+
<button
334+
slot="trigger"
335+
type="button"
336+
class="btn btn--ghost btn--icon chat-tool-card__widget-actions-trigger"
337+
aria-label=${t("chat.toolCards.widgetActions")}
338+
title=${t("chat.toolCards.widgetActions")}
339+
>
340+
${icons.moreHorizontal}
341+
</button>
342+
<wa-dropdown-item value="copy">${t("chat.toolCards.copyToClipboard")}</wa-dropdown-item>
343+
<wa-dropdown-item value="download">${t("chat.toolCards.downloadFile")}</wa-dropdown-item>
344+
</wa-dropdown>
345+
`;
346+
}
347+
287348
function renderWidgetCard(
288349
preview: ToolPreview | undefined,
289350
surface: "chat_tool" | "chat_message" | "sidebar",
@@ -304,13 +365,11 @@ function renderWidgetCard(
304365
}
305366
const label = preview.title?.trim() || t("chat.toolCards.canvas");
306367
const contentKind = preview.mcpApp ? "mcp-app" : "canvas-html";
307-
// Keep the reserved action hook hidden until populated so it adds no layout
308-
// or accessibility chrome to today's widget card.
309368
return html`
310369
<div class="chat-tool-card__preview" data-kind="canvas" data-surface=${surface}>
311370
<div class="chat-tool-card__preview-header">
312371
<span class="chat-tool-card__preview-label">${label}</span>
313-
<div data-widget-actions hidden></div>
372+
${renderWidgetActions(preview)}
314373
</div>
315374
<div class="chat-tool-card__preview-panel" data-side="canvas">
316375
${renderWidgetContent(contentKind, preview, options)}

0 commit comments

Comments
 (0)