Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(dashboard): draw widget cards with their own sandboxed HTML (#22123)

Arvin Xu8d0e8d613782
diff --git a/apps/cli/src/commands/widget.test.ts b/apps/cli/src/commands/widget.test.ts
index c2a0491a3fa..1ef615da69a 100644
--- a/apps/cli/src/commands/widget.test.ts
+++ b/apps/cli/src/commands/widget.test.ts
@@ -1,3 +1,7 @@
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -124,6 +128,22 @@ describe('widget command', () => {
});
});
+ it('reads view.html from --html-file and keeps the other view fields', async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), 'lh-widget-html-'));
+ const file = path.join(dir, 'card.html');
+ await writeFile(file, '<svg></svg>');
+ mockClient.widget.detail.query.mockResolvedValue({
+ data: { draftVersion: { ...draftVersion, view: { size: 'lg' } }, publishedVersion: null },
+ });
+ mockClient.widget.saveDraft.mutate.mockResolvedValue({ data: { id: 'ver-2', version: 2 } });
+
+ await run('widget', 'draft', 'w-1', '--html-file', file);
+
+ expect(mockClient.widget.saveDraft.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ view: { html: '<svg></svg>', size: 'lg' } }),
+ );
+ });
+
it('refuses a first draft without a script, runtime and output type', async () => {
mockClient.widget.detail.query.mockResolvedValue({
data: { draftVersion: null, publishedVersion: null },
diff --git a/apps/cli/src/commands/widget.ts b/apps/cli/src/commands/widget.ts
index 7c378d5eb5d..e07fee0007a 100644
--- a/apps/cli/src/commands/widget.ts
+++ b/apps/cli/src/commands/widget.ts
@@ -181,13 +181,15 @@ export function registerWidgetCommand(program: Command) {
.option('--runtime <runtime>', `Runtime (${WIDGET_RUNTIMES.join(', ')})`)
.option('--output-type <type>', `Printed JSON shape (${WIDGET_OUTPUT_TYPES.join(', ')})`)
.option('--manifest <json>', 'Manifest JSON: env, network, schedule, metric, timeoutMs')
- .option('--view <json>', 'View hints JSON: chart, columns, limit')
+ .option('--view <json>', 'View JSON: chart, columns, limit, layout, surface, html')
+ .option('--html-file <path>', "Read view.html (the card's own sandboxed HTML) from a file")
.option('--note <text>', 'One line on what changed')
.option('--json [fields]', 'Output JSON')
.action(
async (
widgetId: string,
options: {
+ htmlFile?: string;
json?: boolean | string;
manifest?: string;
note?: string;
@@ -217,13 +219,16 @@ export function registerWidgetCommand(program: Command) {
return fail(`--output-type must be one of: ${WIDGET_OUTPUT_TYPES.join(', ')}`);
}
+ const view = parseJsonOption(options.view, '--view') ?? base?.view;
+ const html = options.htmlFile ? await readFile(options.htmlFile, 'utf8') : undefined;
+
const { data } = await client.widget.saveDraft.mutate({
changeNote: options.note,
manifest: (parseJsonOption(options.manifest, '--manifest') ?? base?.manifest) as any,
outputType: outputType as WidgetOutputType,
runtime: runtime as WidgetRuntime,
script,
- view: (parseJsonOption(options.view, '--view') ?? base?.view) as any,
+ view: (html === undefined ? view : { ...view, html }) as any,
widgetId,
});
if (options.json !== undefined) return outputJson(data, options.json);
diff --git a/apps/server/src/services/widget/__tests__/versionSchema.test.ts b/apps/server/src/services/widget/__tests__/versionSchema.test.ts
index 24684b43363..7a6d54d7941 100644
--- a/apps/server/src/services/widget/__tests__/versionSchema.test.ts
+++ b/apps/server/src/services/widget/__tests__/versionSchema.test.ts
@@ -1,6 +1,7 @@
+import { WIDGET_HTML_MAX_LENGTH } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { widgetManifestSchema } from '../versionSchema';
+import { widgetManifestSchema, widgetViewSchema } from '../versionSchema';
const withInject = (inject: unknown) =>
widgetManifestSchema.safeParse({ env: [{ connector: 'github', inject, name: 'GITHUB_TOKEN' }] });
@@ -24,3 +25,16 @@ describe('widgetManifestSchema env[].inject', () => {
expect(withInject(inject).success).toBe(false);
});
});
+
+describe('widgetViewSchema html', () => {
+ it('accepts a document up to the size limit', () => {
+ expect(widgetViewSchema.safeParse({ html: '<svg></svg>' }).success).toBe(true);
+ expect(widgetViewSchema.safeParse({ html: 'x'.repeat(WIDGET_HTML_MAX_LENGTH) }).success).toBe(
+ true,
+ );
+ });
+
+ it.each([[''], ['x'.repeat(WIDGET_HTML_MAX_LENGTH + 1)], [42]])('rejects %#', (html) => {
+ expect(widgetViewSchema.safeParse({ html }).success).toBe(false);
+ });
+});
diff --git a/locales/en-US/dashboard.json b/locales/en-US/dashboard.json
index 8a6273ef94e..4d3aba68a03 100644
--- a/locales/en-US/dashboard.json
+++ b/locales/en-US/dashboard.json
@@ -171,6 +171,9 @@
"version.status.archived": "Archived",
"version.status.draft": "Draft",
"version.status.published": "Live",
+ "widget.fullscreen.enter": "Full screen",
+ "widget.fullscreen.exit": "Exit full screen",
+ "widget.html.blocked": "This card tried to leave its sandbox, so it was stopped.",
"widget.lastAttemptAt": "Last attempt {{time}}",
"widget.refresh.action": "Refresh now",
"widget.refresh.failed": "Refresh failed: {{message}}. The last successful result is still shown.",
diff --git a/locales/zh-CN/dashboard.json b/locales/zh-CN/dashboard.json
index 3a8eece5cf6..dd53992e2ad 100644
--- a/locales/zh-CN/dashboard.json
+++ b/locales/zh-CN/dashboard.json
@@ -171,6 +171,9 @@
"version.status.archived": "已归档",
"version.status.draft": "草稿",
"version.status.published": "生效中",
+ "widget.fullscreen.enter": "全屏",
+ "widget.fullscreen.exit": "退出全屏",
+ "widget.html.blocked": "这张卡片试图离开沙箱,已停止显示。",
"widget.lastAttemptAt": "最近尝试于 {{time}}",
"widget.refresh.action": "立即刷新",
"widget.refresh.failed": "刷新失败:{{message}}。仍显示上次成功的结果。",
diff --git a/packages/builtin-tool-dashboard/src/manifest.ts b/packages/builtin-tool-dashboard/src/manifest.ts
index 5f138046fbf..5a25e611c05 100644
--- a/packages/builtin-tool-dashboard/src/manifest.ts
+++ b/packages/builtin-tool-dashboard/src/manifest.ts
@@ -164,6 +164,11 @@ const viewSchema = {
items: { type: 'string' },
type: 'array',
},
+ html: {
+ description:
+ 'A self-contained HTML document (inline CSS / JS / SVG / canvas) that draws the whole card in a sandboxed frame — for visuals the layout nodes cannot express, such as an illustrated scene or an animation. It reads the output from window.widgetData and cannot load anything from the network. Takes precedence over layout. See <card_html>.',
+ type: 'string',
+ },
layout: {
description:
'Declarative card template (a tree of stack / grid / text / icon / image / progress / ring / dots / sparkline / badge / divider / spacer / repeat nodes) whose values bind to the output by path. Required for outputType data; replaces the default rendering for the other types. See <card_layout>.',
diff --git a/packages/builtin-tool-dashboard/src/systemRole.ts b/packages/builtin-tool-dashboard/src/systemRole.ts
index 03b368b5314..1aa5d03f4bb 100644
--- a/packages/builtin-tool-dashboard/src/systemRole.ts
+++ b/packages/builtin-tool-dashboard/src/systemRole.ts
@@ -70,6 +70,15 @@ Example — weather (outputType "data", network.allow ["api.open-meteo.com"], ma
{"surface":{"bind":"data.cond","map":{"clear":"sky","partly":"sky","night":"night","cloudy":"cloudy","fog":"cloudy","rain":"rain","snow":"snow","storm":"storm"}},"layout":{"type":"stack","gap":4,"children":[{"type":"stack","direction":"row","justify":"between","align":"start","children":[{"type":"stack","gap":2,"children":[{"type":"text","value":{"bind":"data.city"},"weight":"semibold"},{"type":"text","value":{"template":"{data.temp|number:0}°"},"size":"display","weight":"regular"}]},{"type":"icon","name":{"bind":"data.cond","map":{"clear":"sun","partly":"cloud-sun","night":"moon","cloudy":"cloud","fog":"cloud-fog","rain":"cloud-rain","snow":"cloud-snow","storm":"cloud-lightning","*":"cloud"}},"size":40}]},{"type":"text","value":{"template":"{data.condText} H {data.hi}° L {data.lo}°"},"size":"sm","tone":"secondary"},{"type":"stack","direction":"row","gap":14,"hideWhen":"narrow","children":[{"type":"stack","direction":"row","gap":4,"align":"center","children":[{"type":"icon","name":"droplets","size":14},{"type":"text","value":{"template":"{data.humidity}%"},"size":"sm"}]},{"type":"stack","direction":"row","gap":4,"align":"center","children":[{"type":"icon","name":"wind","size":14},{"type":"text","value":{"template":"{data.wind|number:0} km/h"},"size":"sm"}]},{"type":"stack","direction":"row","gap":4,"align":"center","children":[{"type":"icon","name":"umbrella","size":14},{"type":"text","value":{"template":"{data.rainChance}%"},"size":"sm"}]}]},{"type":"spacer"},{"type":"repeat","items":"data.hourly","limit":6,"direction":"row","justify":"between","hideWhen":"short","template":{"type":"stack","gap":6,"align":"center","children":[{"type":"text","value":"Now","size":"xs","tone":"secondary","visible":{"bind":"index","eq":0}},{"type":"text","value":{"bind":"item.t","format":"time"},"size":"xs","tone":"secondary","visible":{"bind":"index","ne":0}},{"type":"icon","name":{"bind":"item.cond","map":{"clear":"sun","partly":"cloud-sun","night":"moon","cloudy":"cloud","fog":"cloud-fog","rain":"cloud-rain","snow":"cloud-snow","storm":"cloud-lightning","*":"cloud"}},"size":18},{"type":"text","value":{"template":"{item.temp}°"},"size":"sm","weight":"medium"}]}}]}}
</card_layout>
+<card_html>
+Prefer view.layout. When the user asks for a visual it cannot draw — an illustrated scene (a farm whose crops are the items, a city skyline, a garden), custom charts, animation — set view.html instead: one self-contained HTML document that draws the card. It replaces layout and surface.
+- It runs in a sandboxed frame with no network: no external scripts, styles, fonts or images. Inline everything (CSS, JS, SVG, canvas); images only as data: URLs. It cannot read cookies or call any API.
+- The script still collects the data; the HTML only draws it. Read it from window.widgetData: .data (output.data for outputType data, else the whole output), .output, .theme.appearance ("light" | "dark"). Register window.widgetData.onUpdate((state) => draw(state.data)) — it fires once the output arrives and again on every refresh; the document is not reloaded between runs.
+- window.widgetData.open(url) opens an http(s) link in a new tab, e.g. when a part of the scene is clicked. Plain <a> navigation does not work.
+- The frame fills the card body (default card ≈ 300×220 px, larger on the drill-down, the whole screen when the user expands it) and resizes with it — the same document, so keep state across resizes and use the extra room for detail: size from the viewport (100vw / 100vh, a resize listener or a scaled SVG viewBox), never a fixed pixel canvas. Leave the top-right 40×40 px corner free of text and controls: the full-screen button sits there. The page background is transparent; paint your own. Follow theme.appearance for text and background contrast. Keep it under 200 KB; draw from the data, do not hard-code values.
+Skeleton: <style>…</style><svg id="scene" viewBox="0 0 320 200" width="100%" height="100%"></svg><script>window.widgetData.onUpdate(({ data, theme }) => { /* draw data into #scene */ });</script>
+</card_html>
+
<metric_definition>
The description (口径) is shown on the card and must let the user trust the number: the data source, filters, time window, and unit — e.g. "Open issues labelled bug in lobehub/lobehub, excluding pull requests; counted at run time." Update it whenever the script's logic changes.
</metric_definition>
diff --git a/packages/locales/src/default/dashboard.ts b/packages/locales/src/default/dashboard.ts
index 591df342633..30316cb7755 100644
--- a/packages/locales/src/default/dashboard.ts
+++ b/packages/locales/src/default/dashboard.ts
@@ -139,6 +139,9 @@ export default {
'version.status.archived': 'Archived',
'version.status.draft': 'Draft',
'version.status.published': 'Live',
+ 'widget.fullscreen.enter': 'Full screen',
+ 'widget.fullscreen.exit': 'Exit full screen',
+ 'widget.html.blocked': 'This card tried to leave its sandbox, so it was stopped.',
'widget.lastAttemptAt': 'Last attempt {{time}}',
'widget.refresh.action': 'Refresh now',
'widget.refresh.failed':
diff --git a/packages/types/src/widget/index.ts b/packages/types/src/widget/index.ts
index 255fe5dc368..e8e8a1fd82d 100644
--- a/packages/types/src/widget/index.ts
+++ b/packages/types/src/widget/index.ts
@@ -246,11 +246,20 @@ export interface WidgetParam {
value?: WidgetParamValue;
}
+/** Largest `view.html` document, in characters. */
+export const WIDGET_HTML_MAX_LENGTH = 200 * 1024;
+
/** Rendering hints for the widget card, independent of the data. */
export interface WidgetView {
chart?: 'line' | 'bar' | 'area';
/** Column keys to show, in order, for table output. */
columns?: string[];
+ /**
+ * A self-contained HTML document that draws the card in a sandboxed frame:
+ * no network, no access to the app. It receives the output and theme by
+ * `postMessage` as `window.widgetData`. Takes precedence over `layout`.
+ */
+ html?: string;
/**
* Declarative card template. When set it replaces the built-in rendering of
* the output type; required to show a `data` output.
diff --git a/packages/widget-spec/src/manifest.ts b/packages/widget-spec/src/manifest.ts
index 5e49990391d..52c3ea63f97 100644
--- a/packages/widget-spec/src/manifest.ts
+++ b/packages/widget-spec/src/manifest.ts
@@ -1,4 +1,4 @@
-import { WIDGET_OUTPUT_TYPES, WIDGET_RUNTIMES } from '@lobechat/types';
+import { WIDGET_HTML_MAX_LENGTH, WIDGET_OUTPUT_TYPES, WIDGET_RUNTIMES } from '@lobechat/types';
import { z } from 'zod';
import { widgetLayoutSchema, widgetSurfaceSchema } from './layout';
@@ -95,6 +95,7 @@ export const widgetManifestSchema = z
export const widgetViewSchema = z.object({
chart: z.enum(['line', 'bar', 'area']).optional(),
columns: z.array(z.string()).optional(),
+ html: z.string().min(1).max(WIDGET_HTML_MAX_LENGTH).optional(),
layout: widgetLayoutSchema.optional(),
limit: z.number().int().positive().max(500).optional(),
size: z.enum(['sm', 'md', 'lg']).optional(),
diff --git a/src/features/Dashboard/WidgetCard/index.tsx b/src/features/Dashboard/WidgetCard/index.tsx
index ce6ebfb627b..f63213fb3ec 100644
--- a/src/features/Dashboard/WidgetCard/index.tsx
+++ b/src/features/Dashboard/WidgetCard/index.tsx
@@ -138,11 +138,12 @@ const WidgetCard = memo<WidgetCardProps>(
// Lists and tables are the only outputs taller than their card; the rest size to it.
const scrollable =
bodyState === 'output' &&
+ !view?.html &&
!view?.layout &&
(output?.type === 'list' || output?.type === 'table');
// A layout may paint the whole card; header and footer then follow its text color.
const surface =
- view?.layout && output
+ !view?.html && view?.layout && output
? WIDGET_SURFACE_STYLES[resolveSurface(view.surface, createLayoutScope(output))]
: undefined;
diff --git a/src/features/Dashboard/WidgetCard/views/HtmlView/document.test.ts b/src/features/Dashboard/WidgetCard/views/HtmlView/document.test.ts
new file mode 100644
index 00000000000..e447125fe09
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/HtmlView/document.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createWidgetHtmlDocument,
+ isOpenableWidgetUrl,
+ isWidgetHtmlFrameMessage,
+ WIDGET_HTML_CSP,
+ WIDGET_HTML_WRAPPER_CSP,
+ WIDGET_HTML_WRAPPER_DOCUMENT,
+} from './document';
+
+describe('createWidgetHtmlDocument', () => {
+ it('puts the CSP before the author markup', () => {
+ const doc = createWidgetHtmlDocument(
+ '<!doctype html><html><head></head><body>hi</body></html>',
+ );
+ const csp = doc.indexOf(`content="${WIDGET_HTML_CSP}"`);
+ expect(csp).toBeGreaterThanOrEqual(0);
+ expect(csp).toBeLessThan(doc.indexOf('<!doctype html>'));
+ expect(doc.indexOf('window.widgetData')).toBeLessThan(doc.indexOf('<!doctype html>'));
+ });
+
+ it('blocks network access', () => {
+ expect(WIDGET_HTML_CSP).toContain("default-src 'none'");
+ expect(WIDGET_HTML_CSP).not.toMatch(/connect-src|https?:/);
+ });
+});
+
+describe('WIDGET_HTML_WRAPPER_DOCUMENT', () => {
+ it('forbids its content frame from navigating anywhere', () => {
+ expect(WIDGET_HTML_WRAPPER_CSP).toContain("frame-src 'none'");
+ expect(WIDGET_HTML_WRAPPER_CSP).toContain("default-src 'none'");
+ // The content frame inherits this policy, so it must not take away what the content may load.
+ expect(WIDGET_HTML_WRAPPER_CSP.startsWith(WIDGET_HTML_CSP)).toBe(true);
+ expect(WIDGET_HTML_WRAPPER_DOCUMENT.indexOf(`content="${WIDGET_HTML_WRAPPER_CSP}"`)).toBe(
+ WIDGET_HTML_WRAPPER_DOCUMENT.indexOf('content="'),
+ );
+ });
+
+ it('runs the content in a script-only sandbox and drops it on a second load', () => {
+ expect(WIDGET_HTML_WRAPPER_DOCUMENT).toContain("setAttribute('sandbox', 'allow-scripts')");
+ expect(WIDGET_HTML_WRAPPER_DOCUMENT).toContain("type: 'navigated'");
+ });
+});
+
+describe('isOpenableWidgetUrl', () => {
+ it.each([
+ ['https://github.com/lobehub/lobehub/pull/1', true],
+ ['http://example.com', true],
+ ['javascript:alert(1)', false],
+ ['data:text/html,hi', false],
+ ['/relative', false],
+ [42, false],
+ ])('%s → %s', (url, expected) => {
+ expect(isOpenableWidgetUrl(url)).toBe(expected);
+ });
+});
+
+describe('isWidgetHtmlFrameMessage', () => {
+ it('only accepts messages from the widget frame', () => {
+ expect(isWidgetHtmlFrameMessage({ source: 'lobe-widget-frame', type: 'ready' })).toBe(true);
+ expect(isWidgetHtmlFrameMessage({ source: 'other', type: 'ready' })).toBe(false);
+ expect(isWidgetHtmlFrameMessage(null)).toBe(false);
+ });
+});
diff --git a/src/features/Dashboard/WidgetCard/views/HtmlView/document.ts b/src/features/Dashboard/WidgetCard/views/HtmlView/document.ts
new file mode 100644
index 00000000000..0a79e7c234a
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/HtmlView/document.ts
@@ -0,0 +1,171 @@
+/**
+ * The sandboxed documents a `view.html` card runs in, and the messages they
+ * exchange with the host.
+ *
+ * Two nested frames, both `sandbox="allow-scripts"` (opaque origin: no
+ * cookies, storage or app API):
+ *
+ * - the **wrapper** (`WIDGET_HTML_WRAPPER_DOCUMENT`) is ours and fixed. Its
+ * CSP `frame-src 'none'` makes the browser refuse every navigation of its
+ * child frame, whoever starts it — `default-src` alone does not cover
+ * navigation, so a frame could otherwise leave with the data in its URL.
+ * It relays messages both ways, and if the child ever loads a second
+ * document it removes it and stops relaying.
+ * - the **content** frame runs the author's HTML (`createWidgetHtmlDocument`),
+ * whose CSP blocks every fetch, so a card can only draw what it is handed.
+ */
+
+export const WIDGET_HTML_HOST_SOURCE = 'lobe-widget-host';
+export const WIDGET_HTML_FRAME_SOURCE = 'lobe-widget-frame';
+
+export const WIDGET_HTML_CSP = [
+ "default-src 'none'",
+ "script-src 'unsafe-inline'",
+ "style-src 'unsafe-inline'",
+ 'img-src data: blob:',
+ 'font-src data:',
+ 'media-src data: blob:',
+ "base-uri 'none'",
+ "form-action 'none'",
+].join('; ');
+
+/**
+ * A srcdoc frame inherits its parent's CSP on top of its own, so the wrapper
+ * allows what the content needs (data: images and fonts) and adds only the
+ * navigation rule.
+ */
+export const WIDGET_HTML_WRAPPER_CSP = `${WIDGET_HTML_CSP}; frame-src 'none'`;
+
+export type WidgetHtmlFrameMessage =
+ /** The wrapper is listening; send it the content document. */
+ | { source: typeof WIDGET_HTML_FRAME_SOURCE; type: 'wrapper-ready' }
+ /** The content document's bridge is listening; send it the output. */
+ | { source: typeof WIDGET_HTML_FRAME_SOURCE; type: 'ready' }
+ | { source: typeof WIDGET_HTML_FRAME_SOURCE; type: 'open'; url: string }
+ /** The content frame tried to leave its document; the wrapper dropped it. */
+ | { source: typeof WIDGET_HTML_FRAME_SOURCE; type: 'navigated' };
+
+/**
+ * Runs before the author's markup. `window.widgetData` exposes the latest
+ * output (`data` is `output.data` for a data output, else the whole output,
+ * matching layout bindings) and calls `onUpdate` listeners on every refresh.
+ */
+const BRIDGE = `(() => {
+ const HOST = '${WIDGET_HTML_HOST_SOURCE}';
+ const FRAME = '${WIDGET_HTML_FRAME_SOURCE}';
+ const state = { data: null, output: null, theme: { appearance: 'light' } };
+ const listeners = new Set();
+ const notify = (listener) => {
+ try { listener(state); } catch (error) { console.error(error); }
+ };
+ window.widgetData = {
+ get data() { return state.data; },
+ get output() { return state.output; },
+ get theme() { return state.theme; },
+ onUpdate(listener) {
+ listeners.add(listener);
+ if (state.output) notify(listener);
+ return () => listeners.delete(listener);
+ },
+ open(url) { parent.postMessage({ source: FRAME, type: 'open', url: String(url) }, '*'); },
+ };
+ addEventListener('message', (event) => {
+ const message = event.data;
+ if (event.source !== parent || !message || message.source !== HOST || message.type !== 'update') return;
+ state.output = message.output;
+ state.data = message.output && message.output.type === 'data' ? message.output.data : message.output;
+ state.theme = message.theme;
+ document.documentElement.dataset.theme = message.theme.appearance;
+ listeners.forEach(notify);
+ });
+ parent.postMessage({ source: FRAME, type: 'ready' }, '*');
+})();`;
+
+const BASE_STYLE =
+ 'html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent}';
+
+/**
+ * Wrap an author's document. The CSP meta comes first so it applies before
+ * any author markup is parsed; a later CSP in the author's markup can only
+ * tighten it. A full document (`<!doctype html><html>…`) and a bare fragment
+ * both work: the parser folds the author's `<html>` / `<head>` into this one.
+ */
+export const createWidgetHtmlDocument = (html: string) =>
+ [
+ `<meta http-equiv="Content-Security-Policy" content="${WIDGET_HTML_CSP}">`,
+ '<meta charset="utf-8">',
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
+ `<style>${BASE_STYLE}</style>`,
+ `<script>${BRIDGE}</script>`,
+ html,
+ ].join('\n');
+
+const WRAPPER = `(() => {
+ const HOST = '${WIDGET_HTML_HOST_SOURCE}';
+ const FRAME = '${WIDGET_HTML_FRAME_SOURCE}';
+ let content = null;
+ let escaped = false;
+ const drop = () => {
+ escaped = true;
+ content?.remove();
+ content = null;
+ parent.postMessage({ source: FRAME, type: 'navigated' }, '*');
+ };
+ addEventListener('message', (event) => {
+ const message = event.data;
+ if (escaped || !message) return;
+ if (event.source === parent && message.source === HOST) {
+ if (message.type === 'document') {
+ content?.remove();
+ const frame = document.createElement('iframe');
+ frame.setAttribute('sandbox', 'allow-scripts');
+ frame.setAttribute('title', 'widget');
+ let loads = 0;
+ // Only the srcdoc ever loads; a second load means the frame left it.
+ frame.addEventListener('load', () => {
+ loads += 1;
+ if (loads > 1 && frame === content) drop();
+ });
+ frame.srcdoc = message.html;
+ content = frame;
+ document.body.append(frame);
+ return;
+ }
+ content?.contentWindow?.postMessage(message, '*');
+ return;
+ }
+ if (content && event.source === content.contentWindow && message.source === FRAME) {
+ parent.postMessage(message, '*');
+ }
+ });
+ parent.postMessage({ source: FRAME, type: 'wrapper-ready' }, '*');
+})();`;
+
+const WRAPPER_STYLE =
+ 'html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent}' +
+ 'iframe{display:block;width:100%;height:100%;border:0;background:transparent;color-scheme:normal}';
+
+/** The fixed outer document every widget HTML frame loads first. */
+export const WIDGET_HTML_WRAPPER_DOCUMENT = [
+ `<meta http-equiv="Content-Security-Policy" content="${WIDGET_HTML_WRAPPER_CSP}">`,
+ '<meta charset="utf-8">',
+ `<style>${WRAPPER_STYLE}</style>`,
+ '<body>',
+ `<script>${WRAPPER}</script>`,
+].join('\n');
+
+/** Only web links leave the card, in a new tab. */
+export const isOpenableWidgetUrl = (url: unknown): url is string => {
+ if (typeof url !== 'string') return false;
+ try {
+ const { protocol } = new URL(url);
+ return protocol === 'https:' || protocol === 'http:';
+ } catch {
+ return false;
+ }
+};
+
+export const isWidgetHtmlFrameMessage = (data: unknown): data is WidgetHtmlFrameMessage =>
+ !!data &&
+ typeof data === 'object' &&
+ (data as { source?: unknown }).source === WIDGET_HTML_FRAME_SOURCE;
diff --git a/src/features/Dashboard/WidgetCard/views/HtmlView/index.tsx b/src/features/Dashboard/WidgetCard/views/HtmlView/index.tsx
new file mode 100644
index 00000000000..06b817c9f1f
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/HtmlView/index.tsx
@@ -0,0 +1,149 @@
+'use client';
+
+import type { WidgetOutput } from '@lobechat/types';
+import { ActionIcon, Center, Text, useThemeMode } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Maximize2Icon, Minimize2Icon } from 'lucide-react';
+import { memo, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { createWidgetHtmlDocument, WIDGET_HTML_WRAPPER_DOCUMENT } from './document';
+import { useElementFullscreen } from './useElementFullscreen';
+import { useWidgetHtmlBridge } from './useWidgetHtmlBridge';
+
+const styles = stylex.create({
+ frame: {
+ backgroundColor: 'transparent',
+ borderWidth: 0,
+ display: 'block',
+ height: '100%',
+ width: '100%',
+ },
+ framed: {
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ height: 360,
+ overflow: 'hidden',
+ },
+ // The browser paints a full-screen element's backdrop black; keep the app's page color.
+ fullscreen: {
+ backgroundColor: cssVar.colorBgLayout,
+ borderRadius: 0,
+ borderWidth: 0,
+ height: '100%',
+ },
+ hidden: {
+ display: 'none',
+ },
+ root: {
+ height: '100%',
+ position: 'relative',
+ width: '100%',
+ },
+ // Always visible: the pointer is usually over the frame, and a parent's :hover
+ // does not reliably match while it is inside a sandboxed iframe.
+ toggle: {
+ backgroundColor: cssVar.colorBgElevated,
+ boxShadow: cssVar.boxShadowTertiary,
+ insetBlockStart: 8,
+ insetInlineEnd: 8,
+ opacity: {
+ ':focus-visible': 1,
+ ':hover': 1,
+ 'default': 0.72,
+ },
+ position: 'absolute',
+ zIndex: 1,
+ },
+ toggleShown: {
+ opacity: 1,
+ },
+});
+
+// An iframe whose color scheme differs from its embedder's is painted opaque;
+// the document inside keeps the default `normal`.
+const FRAME_STYLE = { colorScheme: 'normal' } as const;
+
+interface HtmlViewProps {
+ /** Draw in its own bordered frame, for hosts without a widget card around it. */
+ framed?: boolean;
+ html: string;
+ output: WidgetOutput;
+}
+
+/**
+ * A widget output drawn by its version's own HTML, in a sandboxed frame. The
+ * view can go full screen in place: the same frame grows, so it keeps its
+ * state and live updates, and Esc brings it back.
+ */
+const HtmlView = memo<HtmlViewProps>(({ html, output, framed }) => {
+ const { t } = useTranslation('dashboard');
+ const containerRef = useRef<HTMLDivElement>(null);
+ const frameRef = useRef<HTMLIFrameElement>(null);
+ const { isDarkMode } = useThemeMode();
+ const contentDocument = useMemo(() => createWidgetHtmlDocument(html), [html]);
+ const { blocked } = useWidgetHtmlBridge(
+ frameRef,
+ contentDocument,
+ output,
+ isDarkMode ? 'dark' : 'light',
+ );
+ const fullscreen = useElementFullscreen(containerRef);
+ const toggleLabel = t(
+ fullscreen.isFullscreen ? 'widget.fullscreen.exit' : 'widget.fullscreen.enter',
+ );
+
+ return (
+ <div
+ data-widget-html-root
+ data-widget-html-fullscreen={fullscreen.isFullscreen || undefined}
+ ref={containerRef}
+ {...stylex.props(
+ styles.root,
+ framed && styles.framed,
+ fullscreen.isFullscreen && styles.fullscreen,
+ )}
+ >
+ <iframe
+ data-widget-html
+ className={stylex.props(styles.frame, blocked && styles.hidden).className}
+ ref={frameRef}
+ sandbox={'allow-scripts'}
+ srcDoc={WIDGET_HTML_WRAPPER_DOCUMENT}
+ style={FRAME_STYLE}
+ title={'widget'}
+ />
+ {blocked && (
+ <Center data-widget-html-blocked height={'100%'} padding={12}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('widget.html.blocked')}
+ </Text>
+ </Center>
+ )}
+ {fullscreen.supported && !blocked && (
+ <ActionIcon
+ data-widget-html-fullscreen-toggle
+ aria-label={toggleLabel}
+ icon={fullscreen.isFullscreen ? Minimize2Icon : Maximize2Icon}
+ size={'small'}
+ className={
+ stylex.props(styles.toggle, fullscreen.isFullscreen && styles.toggleShown).className
+ }
+ title={toggleLabel}
+ // The card around the view opens the drill-down on click.
+ onClick={(event) => {
+ event.stopPropagation();
+ void fullscreen.toggle();
+ }}
+ />
+ )}
+ </div>
+ );
+});
+
+HtmlView.displayName = 'DashboardWidgetHtmlView';
+
+export default HtmlView;
diff --git a/src/features/Dashboard/WidgetCard/views/HtmlView/useElementFullscreen.test.ts b/src/features/Dashboard/WidgetCard/views/HtmlView/useElementFullscreen.test.ts
new file mode 100644
index 00000000000..fd8c5b50c6f
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/HtmlView/useElementFullscreen.test.ts
@@ -0,0 +1,60 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useElementFullscreen } from './useElementFullscreen';
+
+describe('useElementFullscreen', () => {
+ let current: Element | null;
+ let element: HTMLDivElement;
+
+ beforeEach(() => {
+ current = null;
+ element = document.createElement('div');
+ Object.defineProperty(document, 'fullscreenElement', {
+ configurable: true,
+ get: () => current,
+ });
+ Object.defineProperty(document, 'fullscreenEnabled', { configurable: true, value: true });
+ document.exitFullscreen = vi.fn(async () => {
+ current = null;
+ document.dispatchEvent(new Event('fullscreenchange'));
+ });
+ element.requestFullscreen = vi.fn(async () => {
+ current = element;
+ document.dispatchEvent(new Event('fullscreenchange'));
+ });
+ });
+
+ afterEach(() => vi.restoreAllMocks());
+
+ it('enters full screen on its element and reports it', async () => {
+ const { result } = renderHook(() => useElementFullscreen({ current: element }));
+ expect(result.current.isFullscreen).toBe(false);
+
+ await act(() => result.current.toggle());
+
+ expect(element.requestFullscreen).toHaveBeenCalled();
+ expect(result.current.isFullscreen).toBe(true);
+ });
+
+ it('exits when toggled again, and follows an exit made elsewhere (Esc)', async () => {
+ const { result } = renderHook(() => useElementFullscreen({ current: element }));
+ await act(() => result.current.toggle());
+ await act(() => result.current.toggle());
+ expect(document.exitFullscreen).toHaveBeenCalled();
+ expect(result.current.isFullscreen).toBe(false);
+
+ await act(() => result.current.toggle());
+ act(() => {
+ current = null;
+ document.dispatchEvent(new Event('fullscreenchange'));
+ });
+ expect(result.current.isFullscreen).toBe(false);
+ });
+
+ it('is not active when another element is full screen', () => {
+ current = document.createElement('section');
+ const { result } = renderHook(() => useElementFullscreen({ current: element }));
+ expect(result.current.isFullscreen).toBe(false);
+ });
+});
diff --git a/src/features/Dashboard/WidgetCard/views/HtmlView/useElementFullscreen.ts b/src/features/Dashboard/WidgetCard/views/HtmlView/useElementFullscreen.ts
new file mode 100644
index 00000000000..b072ba8d645
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/HtmlView/useElementFullscreen.ts
@@ -0,0 +1,29 @@
+import { type RefObject, useSyncExternalStore } from 'react';
+
+const subscribe = (onChange: () => void) => {
+ document.addEventListener('fullscreenchange', onChange);
+ return () => document.removeEventListener('fullscreenchange', onChange);
+};
+
+/**
+ * Native full screen for one element: whether it is the full-screen element
+ * now, and a toggle. `supported` is false where the page may not go full
+ * screen (an embedding frame without `allowfullscreen`, some mobile browsers).
+ */
+export const useElementFullscreen = (ref: RefObject<HTMLElement | null>) => {
+ const isFullscreen = useSyncExternalStore(
+ subscribe,
+ () => !!ref.current && document.fullscreenElement === ref.current,
+ () => false,
+ );
+
+ const toggle = async () => {
+ if (isFullscreen) {
+ await document.exitFullscreen();
+ return;
+ }
+ await ref.current?.requestFullscreen();
+ };
+
+ return { isFullscreen, supported: !!document.fullscreenEnabled, toggle };
+};
diff --git a/src/features/Dashboard/WidgetCard/views/HtmlView/useWidgetHtmlBridge.test.ts b/src/features/Dashboard/WidgetCard/views/HtmlView/useWidgetHtmlBridge.test.ts
new file mode 100644
index 00000000000..3a7a612297c
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/HtmlView/useWidgetHtmlBridge.test.ts
@@ -0,0 +1,86 @@
+import type { WidgetOutput } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useWidgetHtmlBridge } from './useWidgetHtmlBridge';
+
+const output: WidgetOutput = { data: { ready: 3 }, type: 'data' };
+
+const setup = () => {
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
+ const hook = renderHook(
+ ({ appearance, doc }: { appearance: 'dark' | 'light'; doc: string }) =>
+ useWidgetHtmlBridge({ current: frame }, doc, output, appearance),
+ { initialProps: { appearance: 'dark', doc: '<p>v1</p>' } },
+ );
+ const fromFrame = (data: unknown, source: MessageEventSource | null = frame.contentWindow) =>
+ act(() => {
+ window.dispatchEvent(new MessageEvent('message', { data, source }));
+ });
+ return { fromFrame, hook, post };
+};
+
+const update = (appearance: 'dark' | 'light') => [
+ { output, source: 'lobe-widget-host', theme: { appearance }, type: 'update' },
+ '*',
+];
+const document_ = (html: string) => [{ html, source: 'lobe-widget-host', type: 'document' }, '*'];
+
+describe('useWidgetHtmlBridge', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+ });
+
+ it('sends the content document when the wrapper is ready, and again when it changes', () => {
+ const { fromFrame, hook, post } = setup();
+ expect(post).not.toHaveBeenCalledWith(...document_('<p>v1</p>'));
+
+ fromFrame({ source: 'lobe-widget-frame', type: 'wrapper-ready' });
+ expect(post).toHaveBeenCalledWith(...document_('<p>v1</p>'));
+
+ hook.rerender({ appearance: 'dark', doc: '<p>v2</p>' });
+ expect(post).toHaveBeenLastCalledWith(...document_('<p>v2</p>'));
+ });
+
+ it('sends the output and theme when the content reports ready', () => {
+ const { fromFrame, post } = setup();
+ post.mockClear();
+ fromFrame({ source: 'lobe-widget-frame', type: 'ready' });
+ expect(post).toHaveBeenCalledWith(...update('dark'));
+ });
+
+ it('sends the new theme when it changes', () => {
+ const { hook, post } = setup();
+ hook.rerender({ appearance: 'light', doc: '<p>v1</p>' });
+ expect(post).toHaveBeenLastCalledWith(...update('light'));
+ });
+
+ it('stops posting for good once the content tried to navigate away', () => {
+ const { fromFrame, hook, post } = setup();
+ expect(hook.result.current.blocked).toBe(false);
+
+ fromFrame({ source: 'lobe-widget-frame', type: 'navigated' });
+ expect(hook.result.current.blocked).toBe(true);
+
+ post.mockClear();
+ fromFrame({ source: 'lobe-widget-frame', type: 'ready' });
+ fromFrame({ source: 'lobe-widget-frame', type: 'wrapper-ready' });
+ hook.rerender({ appearance: 'light', doc: '<p>v2</p>' });
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('opens only web links, and only from its own frame', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ const { fromFrame } = setup();
+
+ fromFrame({ source: 'lobe-widget-frame', type: 'open', url: 'javascript:alert(1)' });
+ fromFrame({ source: 'lobe-widget-frame', type: 'open', url: 'https://a.com' }, window);
+ expect(open).not.toHaveBeenCalled();
+
+ fromFrame({ source: 'lobe-widget-frame', type: 'open', url: 'https://github.com' });
+ expect(open).toHaveBeenCalledWith('https://github.com', '_blank', 'noopener,noreferrer');
+ });
+});
diff --git a/src/features/Dashboard/WidgetCard/views/HtmlView/useWidgetHtmlBridge.ts b/src/features/Dashboard/WidgetCard/views/HtmlView/useWidgetHtmlBridge.ts
new file mode 100644
index 00000000000..c0b490a1fbf
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/HtmlView/useWidgetHtmlBridge.ts
@@ -0,0 +1,87 @@
+import type { WidgetOutput } from '@lobechat/types';
+import { type RefObject, useEffect, useRef, useState } from 'react';
+
+import { isOpenableWidgetUrl, isWidgetHtmlFrameMessage, WIDGET_HTML_HOST_SOURCE } from './document';
+
+/**
+ * Keep a widget HTML frame fed. The frame loads the fixed wrapper; once it
+ * reports `wrapper-ready` it gets the content document (`contentDocument`,
+ * again whenever that changes), and once the content reports `ready` it gets
+ * the output and theme, again whenever either changes. Opens the web links
+ * the content asks for.
+ *
+ * If the content frame tries to leave its document, the wrapper drops it and
+ * the frame is `blocked`: nothing is posted to it any more.
+ */
+export const useWidgetHtmlBridge = (
+ frameRef: RefObject<HTMLIFrameElement | null>,
+ contentDocument: string,
+ output: WidgetOutput,
+ appearance: 'dark' | 'light',
+) => {
+ const [blocked, setBlocked] = useState(false);
+ // Read by the message listener, which outlives renders.
+ const latest = useRef({ contentDocument, output, theme: { appearance } });
+ const isBlocked = useRef(false);
+
+ const send = (message: Record<string, unknown>) => {
+ if (isBlocked.current) return;
+ frameRef.current?.contentWindow?.postMessage(
+ { source: WIDGET_HTML_HOST_SOURCE, ...message },
+ '*',
+ );
+ };
+ const postDocument = () => send({ html: latest.current.contentDocument, type: 'document' });
+ const postUpdate = () =>
+ send({ output: latest.current.output, theme: latest.current.theme, type: 'update' });
+
+ useEffect(() => {
+ latest.current = { ...latest.current, output, theme: { appearance } };
+ postUpdate();
+ }, [output, appearance]);
+
+ // Skip the first run: the wrapper asks for the document when it is ready.
+ const mounted = useRef(false);
+ useEffect(() => {
+ latest.current = { ...latest.current, contentDocument };
+ if (mounted.current) postDocument();
+ mounted.current = true;
+ }, [contentDocument]);
+
+ useEffect(() => {
+ const onMessage = (event: MessageEvent) => {
+ if (
+ event.source !== frameRef.current?.contentWindow ||
+ !isWidgetHtmlFrameMessage(event.data)
+ ) {
+ return;
+ }
+ const message = event.data;
+ switch (message.type) {
+ case 'wrapper-ready': {
+ postDocument();
+ break;
+ }
+ case 'ready': {
+ postUpdate();
+ break;
+ }
+ case 'open': {
+ if (isOpenableWidgetUrl(message.url)) {
+ window.open(message.url, '_blank', 'noopener,noreferrer');
+ }
+ break;
+ }
+ case 'navigated': {
+ isBlocked.current = true;
+ setBlocked(true);
+ break;
+ }
+ }
+ };
+ window.addEventListener('message', onMessage);
+ return () => window.removeEventListener('message', onMessage);
+ }, []);
+
+ return { blocked };
+};
diff --git a/src/features/Dashboard/WidgetCard/views/index.tsx b/src/features/Dashboard/WidgetCard/views/index.tsx
index 5321b622fff..4b13f9794f1 100644
--- a/src/features/Dashboard/WidgetCard/views/index.tsx
+++ b/src/features/Dashboard/WidgetCard/views/index.tsx
@@ -6,6 +6,7 @@ import { memo } from 'react';
import type { DashboardTrendSeries } from '@/services/dashboard';
import DataView from './DataView';
+import HtmlView from './HtmlView';
import LayoutView from './LayoutView';
import ListView from './ListView';
import SeriesView from './SeriesView';
@@ -20,13 +21,17 @@ export interface WidgetOutputViewProps {
view?: WidgetViewHints | null;
}
-/** Render one widget output by its version's layout, else by its contract type. */
+/** Render one widget output by its version's HTML or layout, else by its contract type. */
const WidgetOutputView = memo<WidgetOutputViewProps>(
({ output, trend, view, density = 'compact' }) => {
// Cards scroll and load rows as needed; only an explicit `view.limit` caps them.
const compact = density === 'compact';
const limit = compact ? view?.limit : undefined;
+ if (view?.html) {
+ return <HtmlView framed={!compact} html={view.html} output={output} />;
+ }
+
if (view?.layout) {
return (
<LayoutView framed={!compact} layout={view.layout} output={output} surface={view.surface} />