Skip to content

Commit 5b67b61

Browse files
feat(dashboard): let widgets run granted actions and open links (#127315)
1 parent 47d21dc commit 5b67b61

14 files changed

Lines changed: 102 additions & 23 deletions

‎docs/tools/show-widget.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,13 +133,17 @@ Accepted prompts appear in the transcript as regular user messages and start a n
133133

134134
## Dashboard capabilities
135135

136-
Pinned widgets can use one ticket-bound host API after the operator reviews the declaration shown on the pending card:
136+
Pinned widgets expose one ticket-bound host API. Calls that require declared capabilities work only after the operator reviews the declaration shown on the pending card:
137137

138+
- `openclaw.host.controlUiBaseUrl` exposes the Control UI origin plus its configured base path after the dashboard host initializes. It is `null` before initialization and outside the dashboard, so read it in the link's click handler rather than when the widget script first runs.
138139
- `openclaw.prompt.send(text)` requires transient user activation and posts a visible composer message. Declaring and receiving the `prompt` tool grant skips the extra per-click confirmation; validation, focus checks, and rate limits still apply.
139140
- `openclaw.state.emit(payload)` adds a session notice. Payloads are capped at 8 KiB, and identical client emissions within five seconds are coalesced.
140141
- `openclaw.data.read(bindingId, params?)` resolves only at the Gateway. Grantable bindings are `sessions.list`, `usage.status`, `usage.cost`, `cron.list`, `cron.status`, `agents.list`, and `health`.
142+
- `openclaw.action.run(actionId, params?)` invokes an operator-granted plugin dashboard action verb through its write-scoped Gateway method.
141143
- `openclaw.cron.trigger(jobId)` runs an existing job now only when the exact `cron.trigger:<jobId>` capability was granted.
142144

145+
Links are ordinary user navigation, not a granted host capability. Rendered widgets can open user-clicked links in a new tab; use `target="_blank"` with `rel="noopener noreferrer"` so the dashboard stays open and the destination cannot retain an opener reference.
146+
143147
Network access is separate from host tools. Put exact HTTPS origins in `capabilities.netOrigins`; after approval, only those origins enter the widget's `connect-src`. Wildcards, credentials, paths, query strings, and undeclared origins remain blocked. A literal port is allowed only when it is part of the declared origin.
144148

145149
## Security and storage

‎docs/web/dashboard-architecture.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ Shared infrastructure underneath (this is where the simplification lands):
165165
- `openclaw.state.emit` — tier 1 session notices (coalesced, size-capped)
166166
- `openclaw.data.read` — parameterized read-only bindings (existing
167167
allowlisted read RPC set), resolved gateway-side
168+
- `openclaw.action.run` — tier 3 plugin-owned automation
168169
- `openclaw.cron.trigger` — tier 3 automation
169170
- **`net` = CSP.** Network reach uses the already-shipped per-widget CSP
170171
declaration (`connect-src` origins) — the self-updating weather widget
@@ -175,12 +176,14 @@ Shared infrastructure underneath (this is where the simplification lands):
175176
`pending` on the board: a placeholder card lists them human-readably with
176177
one-tap **Allow**/**Reject**. Grants are per widget name; for `html` widgets
177178
they are byte-frozen (sha256), and changed bytes keep the grant only if the
178-
declaration shrank.
179+
declaration shrank. User-clicked links are ordinary navigation rather than a
180+
grant capability and open in a new tab for every rendered widget.
179181
- **Authoring shim.** The document wrapper injects `window.openclaw.prompt`,
180-
`window.openclaw.state`, `window.openclaw.data`, and `window.openclaw.cron`
181-
as the stable author API. Dashboard calls share one view-ticket-bound
182-
request channel; size reporting and theme tokens remain separate host
183-
notifications.
182+
`window.openclaw.state`, `window.openclaw.data`, `window.openclaw.action`,
183+
`window.openclaw.cron`, and the host-provided
184+
`window.openclaw.host.controlUiBaseUrl` as the stable author API. Dashboard
185+
calls share one view-ticket-bound request channel; size reporting and theme
186+
tokens remain separate host notifications.
184187

185188
### Plugin capability declarations
186189

‎src/agents/sandbox-host.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,14 @@ export function buildSandboxHostProxyHtml(csp?: SandboxHostCsp): string {
230230
}
231231
const createInner = () => {
232232
const frame = document.createElement("iframe");
233-
frame.setAttribute("sandbox", "allow-scripts allow-forms");
233+
// Nested sandbox restrictions compose with the host iframe. The inner
234+
// document must declare popup support so a granted outer widget can open
235+
// user-clicked links, while ungranted widgets remain blocked by the outer
236+
// frame's stricter sandbox.
237+
frame.setAttribute(
238+
"sandbox",
239+
"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",
240+
);
234241
return frame;
235242
};
236243
let inner = createInner();

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,9 @@ describe("show_widget", () => {
248248
it("keeps widget documents from duplicating host-owned metadata and controls", () => {
249249
const description = createShowWidgetTool().description;
250250

251+
expect(description).toContain("openclaw.host.controlUiBaseUrl");
252+
expect(description).toContain("read it at click time");
253+
expect(description).toContain('target="_blank" and rel="noopener noreferrer"');
251254
expect(description).toContain("`title` is host metadata");
252255
expect(description).toContain("Start directly with content");
253256
expect(description).toContain("do not repeat the title");
@@ -541,11 +544,13 @@ describe("show_widget", () => {
541544
'<SvG viewBox="0 0 10 10"><circle r="4" /></SvG>',
542545
);
543546

544-
expect(Buffer.byteLength(html)).toBe(13493);
547+
expect(Buffer.byteLength(html)).toBe(13859);
545548
expect(createHash("sha256").update(html).digest("hex")).toBe(
546-
"e50212b277bc75dc07a1c6c46cc313ff8f5cbfe261211b12d1714ad9d6b8c912",
549+
"a3d6c52c6b19498b1041a3e2c0feac20b234f6497cf3d41c8783feba3ae47dcf",
547550
);
548551
expect(html).toContain("openclaw:widget-host-init-ack");
552+
expect(html).toContain("controlUiBaseUrl");
553+
expect(html).toContain('define(host,"controlUiBaseUrl"');
549554
expect(html).toContain("else push.call(waiting,{send,reject})");
550555
expect(html).toContain("else push.call(promptWaiting,{send,inline,reject})");
551556
expect(html).toContain("openclaw:widget-prompt-host-ready");
@@ -1019,6 +1024,7 @@ describe("show_widget", () => {
10191024
expect(html).toContain("prompt:freeze({send:sendPrompt})");
10201025
expect(html).toContain('state:freeze({emit:payload=>request("state.emit"');
10211026
expect(html).toContain('data:freeze({read:(bindingId,params)=>request("data.read"');
1027+
expect(html).toContain('action:freeze({run:(action,params)=>request("action.run"');
10221028
expect(html).toContain('cron:freeze({trigger:jobId=>request("cron.trigger"');
10231029
expect(html).toContain("navigator.userActivation");
10241030
expect(html).toContain("c.port1.postMessage.bind(c.port1)");

‎src/canvas/widget-tool.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ export function createShowWidgetTool(options: ShowWidgetToolOptions = {}): AnyAg
273273
return {
274274
label: "Show Widget",
275275
name: "show_widget",
276-
description: `Visual helps? Make widget. Do not wait for ask. Keep one ad hoc non-code visualization inline. Pin only for an explicit dashboard request or multiple non-code visualizations. Use for comparisons, trends, timelines, flows, hierarchies, dashboards, status, progress, layouts, and choices. Text clearer? Skip. Show a widget on the user's current surface; kind defaults to html${advertisedRegisteredKinds.length ? ` and registered kinds are ${advertisedRegisteredKinds.join(", ")}` : ""}. ${inlineHostEnabled ? "Set pin=true to also place it on this session's dashboard" : "Inline hosting is disabled; set pin=true to place it on this session's dashboard"}; use name for a stable widget id, tab for a tab slug, size sm|md|lg|xl|full, presentation.frame card|full-bleed|frameless, and after for a sibling widget anchor. Pinned widgets may declare capabilities.netOrigins and capabilities.tools for operator approval. HTML widgets are self-contained HTML or SVG. Dashboard host APIs: openclaw.prompt.send(text), openclaw.state.emit(payload), openclaw.data.read(bindingId, params?), and openclaw.cron.trigger(jobId). \`title\` is host metadata. Start directly with content; do not repeat the title or recreate dashboard chrome. HTML is pre-themed with --surface --card --elevated --text --text-strong --muted --border --border-strong --accent --accent-fill --accent-fg --ok --warn --danger --info --radius --font-body --font-mono.${presenterPrompt}`,
276+
description: `Visual helps? Make widget. Do not wait for ask. Keep one ad hoc non-code visualization inline. Pin only for an explicit dashboard request or multiple non-code visualizations. Use for comparisons, trends, timelines, flows, hierarchies, dashboards, status, progress, layouts, and choices. Text clearer? Skip. Show a widget on the user's current surface; kind defaults to html${advertisedRegisteredKinds.length ? ` and registered kinds are ${advertisedRegisteredKinds.join(", ")}` : ""}. ${inlineHostEnabled ? "Set pin=true to also place it on this session's dashboard" : "Inline hosting is disabled; set pin=true to place it on this session's dashboard"}; use name for a stable widget id, tab for a tab slug, size sm|md|lg|xl|full, presentation.frame card|full-bleed|frameless, and after for a sibling widget anchor. Pinned widgets may declare capabilities.netOrigins and capabilities.tools for operator approval. HTML widgets are self-contained HTML or SVG. Dashboard host APIs: openclaw.prompt.send(text), openclaw.state.emit(payload), openclaw.data.read(bindingId, params?), openclaw.action.run(actionId, params?), and openclaw.cron.trigger(jobId). openclaw.host.controlUiBaseUrl is the Control UI origin plus base path after dashboard host initialization, otherwise null; read it at click time. Open links in a new tab with target="_blank" and rel="noopener noreferrer". \`title\` is host metadata. Start directly with content; do not repeat the title or recreate dashboard chrome. HTML is pre-themed with --surface --card --elevated --text --text-strong --muted --border --border-strong --accent --accent-fill --accent-fg --ok --warn --danger --info --radius --font-body --font-mono.${presenterPrompt}`,
277277
parameters: createShowWidgetToolSchema(kinds, explicitPresenters),
278278
...(currentChannelPresenter ? {} : { requiredClientCaps: SHOW_WIDGET_REQUIRED_CLIENT_CAPS }),
279279
execute: async (_toolCallId, args) => {

‎src/canvas/wrap.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,12 @@ export function buildWidgetDocument(
127127
"if(d&&d.get)act=d.get.bind(ua);}catch{}" +
128128
'post({type:"openclaw:widget-prompt-offer"},"*",[c.port2]);' +
129129
'post({type:"openclaw:widget-bridge-port-offer"},"*",[b.port2]);' +
130-
"let ticket=null;let sequence=0;let hostInitExpired=false;const pending=new Map();const waiting=[];" +
130+
"let ticket=null;let controlUiBaseUrl=null;let sequence=0;let hostInitExpired=false;const pending=new Map();const waiting=[];" +
131131
'const initTimer=later(()=>{hostInitExpired=true;while(waiting.length){const entry=shift.call(waiting);if(entry)entry.reject(new ErrorCtor("widget host capabilities unavailable"));}' +
132132
'while(promptWaiting.length){const entry=shift.call(promptWaiting);if(entry)entry.reject(new ErrorCtor("widget prompt host unavailable"));}},5000);' +
133133
'b.port1.addEventListener("message",event=>{const data=event.data;' +
134134
'if(data?.type==="openclaw:widget-host-init"&&typeof data.ticket==="string"){ticket=data.ticket;' +
135+
'const base=data.controlUiBaseUrl;controlUiBaseUrl=typeof base==="string"&&/^https?:\\/\\//.test(base)?base:null;' +
135136
'bridgePost({type:"openclaw:widget-host-init-ack",ticket});cancel(initTimer);' +
136137
"while(waiting.length){const entry=shift.call(waiting);if(entry)entry.send();}" +
137138
"while(promptWaiting.length){const entry=shift.call(promptWaiting);if(entry)entry.send();}return;}" +
@@ -150,9 +151,11 @@ export function buildWidgetDocument(
150151
'const inline=()=>{promptPost({type:"openclaw:widget-prompt",prompt:value});resolve(true);};' +
151152
'if(inlinePromptReady)inline();else if(hostInitExpired)reject(new ErrorCtor("widget prompt host unavailable"));' +
152153
"else push.call(promptWaiting,{send,inline,reject});});};" +
153-
"const api=freeze({" +
154+
'const host={};define(host,"controlUiBaseUrl",{enumerable:true,get:()=>controlUiBaseUrl});freeze(host);' +
155+
"const api=freeze({host," +
154156
'prompt:freeze({send:sendPrompt}),state:freeze({emit:payload=>request("state.emit",{payload})}),' +
155157
'data:freeze({read:(bindingId,params)=>request("data.read",{bindingId:stringify(bindingId),params})}),' +
158+
'action:freeze({run:(action,params)=>request("action.run",{action:stringify(action),params:params===undefined?{}:params})}),' +
156159
'cron:freeze({trigger:jobId=>request("cron.trigger",{jobId:stringify(jobId)})})});' +
157160
'define(window,"openclaw",{value:api,writable:false,configurable:false});' +
158161
"window.sendPrompt=text=>{void sendPrompt(text);};" +

‎src/gateway/mcp-app-sandbox-http.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,11 @@ describe("MCP App sandbox HTTP origin", () => {
5959
);
6060
expect(result.end).toHaveBeenCalledWith(expect.stringContaining("document.referrer"));
6161
expect(result.end).toHaveBeenCalledWith(expect.stringContaining("sandbox-proxy-ready"));
62-
expect(result.end).toHaveBeenCalledWith(expect.stringContaining("allow-scripts allow-forms"));
62+
expect(result.end).toHaveBeenCalledWith(
63+
expect.stringContaining(
64+
"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",
65+
),
66+
);
6367
expect(result.end).toHaveBeenCalledWith(
6468
expect.stringContaining("openclaw:widget-bridge-port-offer"),
6569
);

‎ui/src/components/board/board-view.test-support.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,12 @@ export function callbacks(overrides: Partial<BoardViewCallbacks> = {}): BoardVie
6161
};
6262
}
6363

64-
export function gatewayContext(client: { request: ReturnType<typeof vi.fn> } | null) {
64+
export function gatewayContext(
65+
client: { request: ReturnType<typeof vi.fn> } | null,
66+
basePath = "",
67+
) {
6568
return {
69+
basePath,
6670
gateway: {
6771
connection: { gatewayUrl: "" },
6872
snapshot: { client },

‎ui/src/components/board/board-view.test.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ describe("openclaw-board-view", () => {
5858

5959
const frame = view.querySelector("iframe");
6060
expect(frame?.getAttribute("src")).toContain(":18790/mcp-app-sandbox");
61+
expect(frame?.getAttribute("sandbox")).toBe(
62+
"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
63+
);
6164
expect(frame?.getAttribute("loading")).toBe("eager");
6265
expect(view.querySelector('[data-test-id="board-widget-error"]')).toBeNull();
6366
});
@@ -94,7 +97,7 @@ describe("openclaw-board-view", () => {
9497
const fetchMock = vi.fn(async () => new Response("<!doctype html><p>weather</p>"));
9598
vi.stubGlobal("fetch", fetchMock);
9699
const view = await mount({
97-
context: gatewayContext({ request: firstRequest }),
100+
context: gatewayContext({ request: firstRequest }, "/control"),
98101
snapshot: snapshot({
99102
widgets: [
100103
boardWidget({
@@ -125,7 +128,7 @@ describe("openclaw-board-view", () => {
125128
});
126129
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
127130
const bridgeChannel = new MessageChannel();
128-
const initialized = new Promise<void>((resolve) => {
131+
const initialized = new Promise<{ controlUiBaseUrl?: string }>((resolve) => {
129132
bridgeChannel.port2.addEventListener("message", (event) => {
130133
if (event.data?.type !== "openclaw:widget-host-init") {
131134
return;
@@ -137,12 +140,13 @@ describe("openclaw-board-view", () => {
137140
},
138141
[],
139142
);
140-
resolve();
143+
resolve(event.data as { controlUiBaseUrl?: string });
141144
});
142145
});
143146
bridgeChannel.port2.start();
144147
send({ type: "openclaw:widget-bridge-port-offer" }, [bridgeChannel.port1]);
145-
await initialized;
148+
const hostInit = await initialized;
149+
expect(hostInit.controlUiBaseUrl).toBe(`${window.location.origin}/control`);
146150
bridgeChannel.port2.postMessage(
147151
{
148152
type: "openclaw:widget-bridge-request",
@@ -161,7 +165,7 @@ describe("openclaw-board-view", () => {
161165
);
162166

163167
const provider = view.parentElement as ReturnType<typeof createApplicationContextProvider>;
164-
provider.setContext(gatewayContext({ request: secondRequest }));
168+
provider.setContext(gatewayContext({ request: secondRequest }, "/control"));
165169
await cell.updateComplete;
166170
bridgeChannel.port2.postMessage(
167171
{

‎ui/src/components/board/board-widget-frame.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ const TICKET_REFRESH_LEAD_MS = 15_000;
1717
const TICKET_REFRESH_MIN_DELAY_MS = 1_000;
1818
const TICKET_REFRESH_RETRY_MS = 1_000;
1919
const TICKET_REFRESH_MAX_RETRY_MS = 30_000;
20+
const WIDGET_SANDBOX =
21+
"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox";
2022

2123
function documentHidden(): boolean {
2224
return typeof document !== "undefined" && document.visibilityState === "hidden";
@@ -240,7 +242,7 @@ export class BoardWidgetFrameLifecycle {
240242
return html`
241243
<iframe
242244
class="board-widget__frame"
243-
sandbox="allow-scripts allow-same-origin allow-forms"
245+
sandbox=${WIDGET_SANDBOX}
244246
referrerpolicy="origin"
245247
loading="eager"
246248
title=${widget.title || widget.name}
@@ -402,6 +404,7 @@ export class BoardWidgetFrameLifecycle {
402404
this.host.context()?.gateway.connection.gatewayUrl ?? "",
403405
window.location.origin,
404406
),
407+
controlUiBaseUrl: `${window.location.origin}${this.host.context()?.basePath ?? ""}`,
405408
client: this.host.context()?.gateway.snapshot.client ?? undefined,
406409
resolveFrameUrl,
407410
confirmPrompt: (prompt) => window.confirm(`${t("common.confirm")}:\n\n${prompt}`),

0 commit comments

Comments
 (0)