Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(chat): surface visualization failures without slowing generation

zszz3084818cb7389
diff --git a/apps/desktop/electron/main/gen-ui-document.ts b/apps/desktop/electron/main/gen-ui-document.ts
index d2413021f..cd5ca19a2 100644
--- a/apps/desktop/electron/main/gen-ui-document.ts
+++ b/apps/desktop/electron/main/gen-ui-document.ts
@@ -1,6 +1,8 @@
import {
GEN_UI_ERROR_MESSAGE,
GEN_UI_KEY_MESSAGE,
+ GEN_UI_MAX_SCRIPT_ERROR_LENGTH,
+ GEN_UI_SCRIPT_ERROR_MESSAGE,
GEN_UI_READY_MESSAGE,
GEN_UI_SIZE_MESSAGE,
GEN_UI_THEME_MESSAGE,
@@ -124,6 +126,8 @@ const RUNTIME_SCRIPT = `(() => {
const VIEW = ${JSON.stringify(GEN_UI_VIEW_MESSAGE)};
const READY = ${JSON.stringify(GEN_UI_READY_MESSAGE)};
const KEY = ${JSON.stringify(GEN_UI_KEY_MESSAGE)};
+ const SCRIPT_ERROR = ${JSON.stringify(GEN_UI_SCRIPT_ERROR_MESSAGE)};
+ const MAX_ERROR = ${GEN_UI_MAX_SCRIPT_ERROR_LENGTH};
const NAME = ${THEME_VAR_NAME.toString()};
const MAX_VARS = ${MAX_THEME_VARS};
const MAX_VALUE = ${MAX_THEME_VALUE_LENGTH};
@@ -152,6 +156,22 @@ const RUNTIME_SCRIPT = `(() => {
if (event.key !== "Escape") return;
parent.postMessage({ type: KEY, key: "Escape" }, "*");
});
+ // A fragment script that throws usually leaves the chart blank, and the
+ // console is out of the user's reach. Report the first failure so the card
+ // can say why; later errors are typically consequences of the first.
+ let reportedError = false;
+ const reportError = (reason) => {
+ if (reportedError) return;
+ reportedError = true;
+ let message = "";
+ try {
+ message = String(reason && typeof reason === "object" && "message" in reason ? reason.message : reason);
+ } catch {}
+ message = message.replace(/\\s+/g, " ").trim().slice(0, MAX_ERROR);
+ parent.postMessage({ type: SCRIPT_ERROR, message }, "*");
+ };
+ addEventListener("error", (event) => reportError(event.error ?? event.message));
+ addEventListener("unhandledrejection", (event) => reportError(event.reason));
addEventListener("message", (event) => {
if (event.source !== parent) return;
const data = event.data;
diff --git a/apps/desktop/resources/gen-ui/visualize-helpers.js b/apps/desktop/resources/gen-ui/visualize-helpers.js
index 1b658c3fe..4543154bd 100644
--- a/apps/desktop/resources/gen-ui/visualize-helpers.js
+++ b/apps/desktop/resources/gen-ui/visualize-helpers.js
@@ -12,6 +12,7 @@
const root = document.documentElement;
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
const charts = new Set();
+ const mounts = new WeakMap();
const DEFAULT_MARGIN = { top: 16, right: 20, bottom: 48, left: 64 };
const resolveElement = (target) => {
@@ -40,7 +41,17 @@
*/
function chart(target, draw, options = {}) {
const container = resolveElement(target);
- const svg = d3.select(container).append("svg").attr("role", "img");
+ // Drawing again into the same container (e.g. on a button click) replaces
+ // the previous chart instead of stacking a second SVG and observer.
+ mounts.get(container)?.destroy();
+ const svg = d3
+ .select(container)
+ .append("svg")
+ .attr("role", "img")
+ // Sized by the viewBox alone so a flex or grid container can still shrink.
+ .style("display", "block")
+ .style("width", "100%")
+ .style("height", "auto");
if (options.label) svg.attr("aria-label", options.label);
let lastWidth = 0;
let frame = 0;
@@ -53,7 +64,7 @@
typeof options.height === "function"
? options.height(width)
: (options.height ?? defaultHeight(width));
- svg.attr("viewBox", `0 0 ${width} ${height}`).attr("width", width).attr("height", height);
+ svg.attr("viewBox", `0 0 ${width} ${height}`);
if (!options.keep) svg.selectAll("*").remove();
draw({ svg, width, height, compact: width < 480, reducedMotion: reducedMotion.matches });
};
@@ -68,11 +79,18 @@
svg,
redraw: render,
destroy() {
+ if (!charts.has(handle)) return;
observer.disconnect();
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
charts.delete(handle);
+ if (mounts.get(container) === handle) mounts.delete(container);
+ svg.remove();
+ options.onDestroy?.();
},
};
charts.add(handle);
+ mounts.set(container, handle);
// First draw runs once the fragment script finishes, so state declared or
// computed after the `viz.chart` call is ready; `redraw()` stays synchronous.
queueMicrotask(() => {
@@ -188,7 +206,10 @@
const group = g.append("g").attr("class", "viz-axis viz-axis-y").call(axis);
pruneOverlaps(group.selectAll(".tick text"), 2, true);
if (yLabel) {
- g.append("text").attr("class", "viz-axis-title").attr("transform", "rotate(-90)").attr("x", -innerHeight / 2).attr("y", -48).attr("text-anchor", "middle").text(yLabel);
+ // Sit just outside the widest tick label so long numbers don't run into it.
+ const widest = d3.max(group.selectAll(".tick text").nodes(), (node) => node.getBBox?.().width ?? 0) ?? 0;
+ const offset = Math.max(36, Math.ceil(widest) + 16);
+ g.append("text").attr("class", "viz-axis-title").attr("transform", "rotate(-90)").attr("x", -innerHeight / 2).attr("y", -offset).attr("text-anchor", "middle").text(yLabel);
}
result.y = group;
}
@@ -228,8 +249,23 @@
// fields map to x / y / color, and the helpers derive scales, axes, legend,
// tooltips, and value labels. Custom visuals keep using `viz.chart`.
+ // Date-only strings ("2025-03-14", "2025-03") are calendar dates in local
+ // time; `new Date("2025-03-14")` would read them as UTC midnight and shift
+ // every point (and its label) by the zone offset.
+ const DATE_ONLY = /^\d{4}-\d{2}(?:-\d{2})?$/;
+ const parseDay = d3.timeParse("%Y-%m-%d");
+ const parseMonth = d3.timeParse("%Y-%m");
+ const toDate = (v) => {
+ if (v instanceof Date) return v;
+ if (typeof v === "string" && DATE_ONLY.test(v)) return (v.length === 7 ? parseMonth(v) : parseDay(v)) ?? new Date(Number.NaN);
+ return new Date(v);
+ };
const isDateLike = (v) =>
- v instanceof Date || (typeof v === "string" && /^\d{4}-\d{2}-\d{2}/.test(v) && !Number.isNaN(Date.parse(v)));
+ v instanceof Date || (typeof v === "string" && /^\d{4}-\d{2}/.test(v) && !Number.isNaN(+toDate(v)));
+ const isMidnight = (d) => !(d.getHours() || d.getMinutes() || d.getSeconds());
+ // Whole numbers that read as years render without a thousands separator.
+ const isYearLike = (values) =>
+ values.length > 0 && values.every((v) => Number.isInteger(v) && v >= 1000 && v <= 2999);
const keyOf = (v) => (v instanceof Date ? +v : v);
const uniq = (values) => [...new Map(values.map((v) => [keyOf(v), v])).values()];
const normalize = (enc) => (enc == null ? null : typeof enc === "object" ? enc : { field: enc });
@@ -255,21 +291,26 @@
const enc = normalize(input);
if (!enc) return null;
const read = accessor(enc.field);
- const type = enc.type ?? inferType(data.map(read));
- const get = type === "time" ? (d) => new Date(read(d)) : read;
- let tick = enc.format ? formatter(enc.format, type) : undefined;
+ const values = data.map(read);
+ const type = enc.type ?? inferType(values);
+ const get = type === "time" ? (d) => toDate(read(d)) : read;
+ const year = type === "linear" && !enc.format && isYearLike(values);
+ const format = enc.format ?? (year ? "d" : undefined);
+ let tick = format ? formatter(format, type) : undefined;
if (!tick && type === "time") {
// D3's default multi-scale time ticks mix "November" with "2026"; use one numeric format instead.
- const [lo, hi] = d3.extent(data, get);
+ const dates = data.map(get).filter((d) => !Number.isNaN(+d));
+ const [lo, hi] = d3.extent(dates);
const days = lo && hi ? (hi - lo) / 864e5 : 0;
- tick = d3.timeFormat(days > 730 ? "%Y" : days > 60 ? "%Y-%m" : days > 2 ? "%m-%d" : "%H:%M");
+ const dateOnly = dates.length > 0 && dates.every(isMidnight);
+ tick = d3.timeFormat(days > 730 ? "%Y" : days > 60 ? "%Y-%m" : days > 2 || dateOnly ? "%m-%d" : "%H:%M");
}
return {
...enc,
type,
get,
title: enc.title ?? (typeof enc.field === "string" ? enc.field : ""),
- fmt: formatter(enc.format, type),
+ fmt: formatter(format, type),
tick,
};
}
@@ -326,7 +367,7 @@
const row = rows[index.get(keyOf(cat.get(d)))];
if (row) row[s.seriesOf(d)] += Number(val.get(d)) || 0;
}
- layers = d3.stack().keys(s.keys)(rows);
+ layers = d3.stack().keys(s.keys).offset(d3.stackOffsetDiverging)(rows);
values = layers.flatMap((layer) => layer.flatMap((p) => [p[0], p[1]]));
}
const v = d3.scaleLinear(val.domain ?? extent(values, (x) => x, { zero: true }), horizontal ? [0, w] : [h, 0]);
@@ -496,7 +537,7 @@
const value = s.value;
const [min, max] = value.domain ?? d3.extent(s.data, value.get);
const opacity = d3.scaleLinear([min ?? 0, max ?? 1], [0.08, 1]).clamp(true);
- axes(g, { x, y, innerWidth: w, innerHeight: h, xLabel: s.x.title, xFormat: s.x.tick, yFormat: s.y.tick });
+ axes(g, { x, y, innerWidth: w, innerHeight: h, xLabel: s.x.title, yLabel: s.y.title, xFormat: s.x.tick, yFormat: s.y.tick });
const marks = g.append("g");
for (const d of s.data) {
marks
@@ -552,6 +593,14 @@
setLegend(legend, s.keys.length > 1 && spec.mark !== "arc" ? s.keys.map((key) => ({ label: key, color: s.colorOf(key) })) : null);
if (spec.mark === "arc") {
s.theta = channel(spec.theta ?? spec.y ?? spec.value, data);
+ if (!s.theta) throw new Error("viz.render: mark arc needs theta (or y)");
+ // Models often name the category as `x`; without any category the
+ // slices would be labelled by index.
+ if (!color && spec.x != null) {
+ const category = channel(spec.x, data);
+ s.seriesOf = (d) => String(category.get(d));
+ s.keys = uniq(data.map(s.seriesOf));
+ }
drawArc(svg, s, width, height, legend);
return;
}
@@ -562,9 +611,12 @@
s.x = { ...s.x, type: "band" };
s.y = { ...s.y, type: "band" };
s.value = channel(spec.value ?? spec.color, data);
+ if (!s.value) throw new Error("viz.render: mark heatmap needs value");
}
const bandY = s.y.type === "band";
- const left = bandY ? Math.min(Math.round(width * 0.35), Math.max(40, 16 + labelWidth(uniq(data.map(s.y.get)), s.y.fmt))) : undefined;
+ // Band y labels set the left margin; a heatmap also keeps room for its y title.
+ const titleRoom = spec.mark === "heatmap" && s.y.title ? 20 : 0;
+ const left = bandY ? Math.min(Math.round(width * 0.35), Math.max(40, 16 + labelWidth(uniq(data.map(s.y.get)), s.y.fmt)) + titleRoom) : undefined;
const { g, innerWidth, innerHeight } = plot(svg, width, height, left === undefined ? {} : { left });
if (spec.mark === "bar") drawBars(g, s, innerWidth, innerHeight, compact);
else if (spec.mark === "heatmap") drawHeatmap(g, s, innerWidth, innerHeight, legend);
@@ -578,6 +630,8 @@
*/
function render(target, initial) {
const container = resolveElement(target);
+ // Tear down an earlier chart here first, so its legend goes with it.
+ mounts.get(container)?.destroy();
let spec = { ...initial };
const legend = document.createElement("div");
legend.className = "viz-legend";
@@ -587,7 +641,11 @@
typeof spec.height === "function"
? spec.height(width)
: (spec.height ?? (spec.mark === "arc" ? Math.min(320, Math.max(220, width * 0.5)) : defaultHeight(width)));
- const handle = chart(container, (ctx) => drawSpec(ctx, spec, legend), { label: spec.label ?? spec.title, height });
+ const handle = chart(container, (ctx) => drawSpec(ctx, spec, legend), {
+ label: spec.label ?? spec.title,
+ height,
+ onDestroy: () => legend.remove(),
+ });
return {
svg: handle.svg,
redraw: handle.redraw,
diff --git a/apps/desktop/resources/skills/visualize.md b/apps/desktop/resources/skills/visualize.md
index 4003c8f28..45f44f1b3 100644
--- a/apps/desktop/resources/skills/visualize.md
+++ b/apps/desktop/resources/skills/visualize.md
@@ -26,7 +26,8 @@ Read this file in full before authoring. Copy into every compaction summary:
## Hard rules
- One `Write`, then the reply. Do not verify the fragment: no Bash or shell
- command, no browser, no screenshot, no reading it back.
+ command, no browser, no screenshot, no reading it back. The Write result
+ checks it; if that lists problems, fix them with one `Edit`, then reply.
- Do not open the kit, stylesheet, or helper source to look things up; the
classes and `viz` API you need are in this skill. Anything missing goes in
the reply, not in another tool call.
diff --git a/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx b/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx
index d33bd71aa..78d3093d7 100644
--- a/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx
+++ b/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx
@@ -43,6 +43,20 @@ export function GenUiCard({ reference, ...owner }: { reference: GenUiReference }
return <LiveGenUiCard key={source.url} url={source.url} title={title} />;
}
+/** Shown above a live frame whose fragment script threw. */
+export function GenUiScriptErrorNotice({ message }: { message: string }) {
+ const { t } = useTranslation();
+ return (
+ <div className="gen-ui-script-error" role="alert">
+ <IconCircleAlert size={14} className="gen-ui-unavailable-icon" />
+ <div className="gen-ui-unavailable-text">
+ <span>{t("chat.genUi.scriptError")}</span>
+ {message ? <code className="gen-ui-script-error-message">{message}</code> : null}
+ </div>
+ </div>
+ );
+}
+
function LiveGenUiCard({ url, title }: { url: string; title: string }) {
const [error, setError] = useState<GenUiErrorCode | null>(null);
if (error) return <UnavailableCard title={title} reason={error} />;
@@ -62,6 +76,9 @@ function PooledGenUiCard({
const rootRef = useRef<HTMLDivElement | null>(null);
const [viewport, dispatch] = useGenUiViewport(rootRef);
const [expanded, setExpanded] = useState(false);
+ // A fragment script failure. The frame stays mounted (it may still show
+ // part of the content); the notice says why the rest is missing.
+ const [scriptError, setScriptError] = useState<string | null>(null);
// The last reported height keeps a released or reloading card from jumping.
const [height, setHeight] = useState(GEN_UI_INITIAL_HEIGHT);
const live = isGenUiViewportLive(viewport);
@@ -100,9 +117,17 @@ function PooledGenUiCard({
<IconPanelMaximize size={14} />
</TooltipButton>
</header>
+ {scriptError !== null ? <GenUiScriptErrorNotice message={scriptError} /> : null}
<div className="gen-ui-body">
{live ? (
- <GenUiFrame url={url} title={frameTitle} initialHeight={height} onHeight={setHeight} onError={onError} />
+ <GenUiFrame
+ url={url}
+ title={frameTitle}
+ initialHeight={height}
+ onHeight={setHeight}
+ onError={onError}
+ onScriptError={setScriptError}
+ />
) : (
<div className="gen-ui-placeholder" style={{ height }}>
{viewport.evicted ? (
diff --git a/apps/desktop/src/features/chat/gen-ui/GenUiFrame.tsx b/apps/desktop/src/features/chat/gen-ui/GenUiFrame.tsx
index 2bb061676..2512db747 100644
--- a/apps/desktop/src/features/chat/gen-ui/GenUiFrame.tsx
+++ b/apps/desktop/src/features/chat/gen-ui/GenUiFrame.tsx
@@ -9,6 +9,7 @@ import {
genUiErrorFromMessage,
genUiHeightFromMessage,
genUiKeyFromMessage,
+ genUiScriptErrorFromMessage,
genUiWheelFromMessage,
isGenUiReadyMessage,
} from "./gen-ui-frames";
@@ -27,6 +28,7 @@ export function GenUiFrame({
initialHeight = GEN_UI_INITIAL_HEIGHT,
onHeight,
onError,
+ onScriptError,
onEscape,
}: {
url: string;
@@ -38,14 +40,16 @@ export function GenUiFrame({
onHeight?: (height: number) => void;
/** Main served an error shell for this URL. */
onError?: (code: GenUiErrorCode) => void;
+ /** A fragment script threw; the bounded, plain-text message. */
+ onScriptError?: (message: string) => void;
/** Escape was pressed inside the guest. */
onEscape?: () => void;
}) {
const frameRef = useRef<HTMLIFrameElement | null>(null);
const [height, setHeight] = useState(initialHeight);
- const callbacks = useRef({ onHeight, onError, onEscape });
+ const callbacks = useRef({ onHeight, onError, onScriptError, onEscape });
useEffect(() => {
- callbacks.current = { onHeight, onError, onEscape };
+ callbacks.current = { onHeight, onError, onScriptError, onEscape };
});
useEffect(() => {
@@ -88,6 +92,11 @@ export function GenUiFrame({
callbacks.current.onError?.(error);
return;
}
+ const scriptError = genUiScriptErrorFromMessage(event, frameWindow);
+ if (scriptError !== null) {
+ callbacks.current.onScriptError?.(scriptError);
+ return;
+ }
if (genUiKeyFromMessage(event, frameWindow) === "Escape") callbacks.current.onEscape?.();
};
window.addEventListener("message", onMessage);
diff --git a/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts b/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts
index f9e9393a9..4daa57e07 100644
--- a/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts
+++ b/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts
@@ -7,8 +7,10 @@ import {
GEN_UI_ERROR_MESSAGE,
GEN_UI_KEY_MESSAGE,
GEN_UI_MAX_HEIGHT,
+ GEN_UI_MAX_SCRIPT_ERROR_LENGTH,
GEN_UI_MIN_HEIGHT,
GEN_UI_READY_MESSAGE,
+ GEN_UI_SCRIPT_ERROR_MESSAGE,
GEN_UI_SIZE_MESSAGE,
GEN_UI_WHEEL_MESSAGE,
isGenUiErrorCode,
@@ -84,6 +86,18 @@ export function genUiErrorFromMessage(event: FrameMessageEvent, frameWindow: unk
return record && isGenUiErrorCode(record.code) ? record.code : null;
}
+/**
+ * A fragment script failure from this card's own frame, or null. The text is
+ * guest-controlled: it is whitespace-collapsed and bounded here and must only
+ * ever be rendered as plain text. An empty message is still a failure.
+ */
+export function genUiScriptErrorFromMessage(event: FrameMessageEvent, frameWindow: unknown): string | null {
+ const record = ownFrameMessage(event, frameWindow, GEN_UI_SCRIPT_ERROR_MESSAGE);
+ if (!record) return null;
+ const message = typeof record.message === "string" ? record.message : "";
+ return message.replace(/\s+/g, " ").trim().slice(0, GEN_UI_MAX_SCRIPT_ERROR_LENGTH);
+}
+
/** A forwarded key from this card's own frame; only `Escape` is accepted. */
export function genUiKeyFromMessage(event: FrameMessageEvent, frameWindow: unknown): "Escape" | null {
const record = ownFrameMessage(event, frameWindow, GEN_UI_KEY_MESSAGE);
diff --git a/apps/desktop/src/styles/gen-ui.css b/apps/desktop/src/styles/gen-ui.css
index 098ca9a9f..c0df00599 100644
--- a/apps/desktop/src/styles/gen-ui.css
+++ b/apps/desktop/src/styles/gen-ui.css
@@ -89,6 +89,22 @@
font-size: var(--text-xs);
}
+.gen-ui-script-error {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 6px 12px;
+ color: var(--ds-error);
+ font-size: var(--text-sm-plus);
+}
+
+.gen-ui-script-error-message {
+ overflow-wrap: anywhere;
+ color: var(--ds-text-muted);
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: var(--text-xs);
+}
+
.gen-ui-dialog {
display: flex;
width: min(100%, 1100px);
diff --git a/apps/desktop/test/gen-ui-runtime.test.mjs b/apps/desktop/test/gen-ui-runtime.test.mjs
index 3223acdcb..23636f15b 100644
--- a/apps/desktop/test/gen-ui-runtime.test.mjs
+++ b/apps/desktop/test/gen-ui-runtime.test.mjs
@@ -59,6 +59,48 @@ test("the error shell reports a code and never echoes caller text", async () =>
assert.match(unknown, /"code":"not-found"/);
});
+test("script errors are honored only from the card's own frame and stay bounded plain text", async (t) => {
+ const ssr = await slotSsr(t);
+ const { genUiScriptErrorFromMessage } = await ssr.load("/src/features/chat/gen-ui/gen-ui-frames.ts");
+ const own = {};
+ const event = (data, source = own) => ({ source, data });
+ const type = "pi-genui:script-error";
+
+ assert.equal(
+ genUiScriptErrorFromMessage(event({ type, message: "Error: viz: no element sb-bar" }), own),
+ "Error: viz: no element sb-bar",
+ );
+ assert.equal(genUiScriptErrorFromMessage(event({ type, message: "x" }, {}), own), null);
+ assert.equal(genUiScriptErrorFromMessage(event({ type, message: "x" }), null), null);
+ assert.equal(genUiScriptErrorFromMessage(event({ type: "pi-genui:error", message: "x" }), own), null);
+ // A failure without a usable message is still a failure.
+ assert.equal(genUiScriptErrorFromMessage(event({ type, message: 42 }), own), "");
+ assert.equal(genUiScriptErrorFromMessage(event({ type, message: "a\n\n b" }), own), "a b");
+ assert.equal(genUiScriptErrorFromMessage(event({ type, message: "y".repeat(1000) }), own).length, 300);
+});
+
+test("the guest runtime reports the first script error to its parent", async () => {
+ const { buildGenUiDocument } = await import("../electron/main/gen-ui-document.ts");
+ const html = buildGenUiDocument("<p>hi</p>", { kit: { css: "", head: "", runtime: "", vendorUrls: new Map() } });
+ const head = html.slice(0, html.indexOf("</head>"));
+ assert.match(head, /const SCRIPT_ERROR = "pi-genui:script-error"/);
+ assert.match(head, /addEventListener\("error", /);
+ assert.match(head, /addEventListener\("unhandledrejection", /);
+ assert.match(head, /parent\.postMessage\(\{ type: SCRIPT_ERROR, message \}, "\*"\)/);
+ // The runtime script, including its error listener, runs before the fragment.
+ assert.ok(html.indexOf("SCRIPT_ERROR") < html.indexOf("<p>hi</p>"));
+});
+
+test("a script error notice renders the guest message as text, not markup", async (t) => {
+ const ssr = await slotSsr(t);
+ const { GenUiScriptErrorNotice } = await ssr.load("/src/features/chat/gen-ui/GenUiCard.tsx");
+ const html = ssr.render(createElement(GenUiScriptErrorNotice, { message: "<img src=x onerror=alert(1)>" }));
+ assert.match(html, /role="alert"/);
+ assert.match(html, new RegExp(catalogs.en.chat.genUi.scriptError.replace("'", "&#x27;")));
+ assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/);
+ assert.doesNotMatch(html, /<img/);
+});
+
test("the guest runtime announces readiness and forwards only Escape", async () => {
const { buildGenUiDocument } = await import("../electron/main/gen-ui-document.ts");
const html = buildGenUiDocument("<p>hi</p>", { kit: { css: "", head: "", runtime: "", vendorUrls: new Map() } });
@@ -239,6 +281,7 @@ test("every locale has a reason for each unavailable state", () => {
"unavailableTooLarge",
"unavailableNotFragment",
"unavailableRuntime",
+ "scriptError",
];
for (const [locale, catalog] of Object.entries(catalogs)) {
for (const key of keys) {
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
index e6f62998f..0ca7ae879 100644
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@ -6,4 +6,7 @@
for bar, line, area, point, heatmap, and donut charts), so model-written
fragments are shorter. The `visualize` skill asks for a single write
followed by the reply instead of reading the file back. Fragments written
- under the earlier skill keep rendering.
+ under the earlier skill keep rendering. When a fragment's script fails, the
+ card now says so and shows the error instead of staying blank, and the
+ model's write result flags syntax errors and missing chart containers so it
+ can fix them with one edit.
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 4e1a31564..9f27c59aa 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -329,7 +329,14 @@ visualization lives as long as its session:
Main validates the private byte response, rejects full documents, and wraps
the fragment in a host shell with a strict CSP. The shell preloads the
bundled D3 and the `viz` chart helpers before the fragment and drops a
- fragment's own pinned D3 tag.
+ fragment's own pinned D3 tag. The guest runtime reports the first uncaught
+ fragment script error to the card, which keeps the frame and shows a notice
+ with the bounded message as plain text. A successful `Write` of an `.html`
+ file directly in the session's visualization directory also gets a static
+ check in its result: inline scripts are compiled without running, and
+ literal element ids passed to `viz.render`, `viz.chart`, `getElementById`,
+ or `querySelector("#…")` must exist; problems are listed so the model can fix
+ them with one `Edit`.
Both the iframe and the response CSP header enforce `sandbox allow-scripts`,
so omitting the caller's sandbox cannot enable cross-session DOM reads.
Unix uses relative `openat` and a nonblocking leaf; Windows uses relative
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 21db690c8..d4a18b00a 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -18715,7 +18715,9 @@ host-created files. The full app's file-preview viewer is covered separately.
- The remote session gets no visualization directory or skill.
- **Coverage**: `pnpm test:e2e:gen-ui` runs the offline Electron card journey,
including real protocol responses, bundled assets, the preloaded `viz`
- helpers (`viz.chart` sizing and a `viz.render` chart), focus/guest Escape,
+ helpers (`viz.chart` sizing, `viz.render` charts and their date, year,
+ re-render, and donut edge cases), a fragment script error shown in the
+ card, focus/guest Escape,
viewport release, and unsandboxed callers through a real isolated Host.
Native directory, FIFO, and ABA regressions run in `visualizations/files`;
`gen-ui-file-safety.test.mjs` validates the private Host-to-Main boundary.
diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
index 87d12018e..89c3e192e 100644
--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
@@ -249,7 +249,7 @@ Electron 主要低于 `<data_dir>/scratch/<sessionId>/pasted/` 之前的
`pi-genui://session/<sessionId>/<file>`,从不把绝对路径发给 Main。Main 只提供当前
数据目录下不超过 2 MB 的普通非符号链接片段,拒绝完整文档,并把片段包进带严格 CSP
(无网络、子框架、表单)的宿主外壳;框架为 `sandbox="allow-scripts"`。外壳在片段
- 之前预加载内置 D3 和 `viz` 图表辅助函数,并移除片段自带的固定版本 D3 标签。
+ 之前预加载内置 D3 和 `viz` 图表辅助函数,并移除片段自带的固定版本 D3 标签。客户端运行时会把片段脚本的第一个未捕获错误报告给卡片;卡片保留框架,并以纯文本显示截断后的错误提示。对会话可视化目录下 `.html` 文件的成功 `Write`,结果里还会附带一次静态检查:内联脚本只编译不执行,传给 `viz.render`、`viz.chart`、`getElementById` 或 `querySelector("#…")` 的字面量元素 id 必须存在;发现问题会列出来,让模型用一次 `Edit` 修好。
## 4c。消息拥有的审核快照和回滚
diff --git a/packages/agent-runtime/src/gen-ui-fragment-check-runtime.test.ts b/packages/agent-runtime/src/gen-ui-fragment-check-runtime.test.ts
new file mode 100644
index 000000000..2cfe343c3
--- /dev/null
+++ b/packages/agent-runtime/src/gen-ui-fragment-check-runtime.test.ts
@@ -0,0 +1,101 @@
+import { randomUUID } from "node:crypto";
+import { createServer } from "node:http";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { DEEPSEEK_MODELS } from "@earendil-works/pi-ai/providers/deepseek.models";
+import type { UiMessage } from "@pi-desktop/shared";
+import { modelConfigFromPi } from "./model-capabilities.js";
+import { DesktopAgentRuntime, type RuntimeProviderConfig } from "./runtime.js";
+
+// User path: the model writes a visualization fragment through the real Write
+// tool wiring, and the next model request carries the check result.
+
+const DIR = "/data/visualizations/sess_check";
+
+function provider(): RuntimeProviderConfig {
+ const model = Object.values(DEEPSEEK_MODELS).find((m) => m.id === "deepseek-flash")!;
+ return { id: "flash-fixture", name: "Flash", modelId: model.id, baseUrl: model.baseUrl,
+ apiKey: "fixture", authKind: "api_key", supportsReasoning: false, supportedThinkingLevels: ["off"],
+ modelConfig: modelConfigFromPi(model) };
+}
+
+type Payload = { messages: { role: string; content?: unknown }[] };
+
+async function wire(args: Record<string, unknown>) {
+ const requests: Payload[] = [];
+ const realFetch = globalThis.fetch;
+ let first = true;
+ const server = createServer(async (req, res) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
+ requests.push(JSON.parse(Buffer.concat(chunks).toString()));
+ const delta = first
+ ? { role: "assistant", tool_calls: [{ index: 0, id: randomUUID(), type: "function",
+ function: { name: "Write", arguments: JSON.stringify(args) } }] }
+ : { role: "assistant", content: "Done." };
+ const finish = first ? "tool_calls" : "stop";
+ first = false;
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ res.end(`data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason: finish }] })}\n\ndata: [DONE]\n\n`);
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Missing HTTP address");
+ vi.stubGlobal("fetch", ((_url, init) => realFetch(`http://127.0.0.1:${address.port}`, init)) satisfies typeof fetch);
+ return { requests, close: () => new Promise<void>((resolve, reject) => server.close((e) => (e ? reject(e) : resolve()))) };
+}
+
+async function writeThrough(args: Record<string, unknown>, hostOk = true) {
+ const w = await wire(args);
+ const rows: UiMessage[] = [];
+ const runtime = new DesktopAgentRuntime({
+ sessionId: "sess_check", mode: "agent", provider: provider(), thinkingLevel: "off", history: rows,
+ visualizationsDir: DIR,
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ host: { call: async <T>(method: string, params?: unknown): Promise<T> => {
+ if (method === "session.appendMessage") rows.push((params as { message: UiMessage }).message);
+ else if (method === "tools.execute") {
+ return (hostOk ? { ok: true, content: "Wrote file" } : { ok: false, content: "EACCES" }) as T;
+ } else if (method !== "instructions.forPath") throw new Error(`Unexpected host method: ${method}`);
+ return undefined as T;
+ } },
+ onEvent: () => undefined,
+ });
+ try {
+ rows.push({ id: "u1", role: "user", content: "Chart it", createdAt: new Date().toISOString() });
+ await runtime.prompt("Chart it", "u1", "turn-u1");
+ const tool = w.requests[1]?.messages.find((m) => m.role === "tool");
+ return typeof tool?.content === "string" ? tool.content : JSON.stringify(tool?.content);
+ } finally {
+ await runtime.dispose();
+ vi.unstubAllGlobals();
+ await w.close();
+ }
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("visualization fragment check in the Write result", () => {
+ it("tells the model about a wrong container id", async () => {
+ const result = await writeThrough({
+ path: `${DIR}/sorts.html`,
+ content: `<div id="sb-chart"></div><script>viz.render("sb-bar", { mark: "bar" });</script>`,
+ });
+ expect(result).toContain("Wrote file");
+ expect(result).toContain("Fix them with one Edit, then reply:");
+ expect(result).toContain('element id "sb-bar"');
+ });
+
+ it("leaves a clean fragment's result unchanged", async () => {
+ const result = await writeThrough({
+ path: `${DIR}/ok.html`,
+ content: `<div id="c"></div><script>viz.render("c", { mark: "bar" });</script>`,
+ });
+ expect(result).toBe("Wrote file");
+ });
+
+ it("does not check files outside the visualization directory or failed writes", async () => {
+ const broken = `<script>viz.render("nope", {});</script>`;
+ expect(await writeThrough({ path: "/project/page.html", content: broken })).toBe("Wrote file");
+ expect(await writeThrough({ path: `${DIR}/x.html`, content: broken }, false)).not.toContain("Visualization check");
+ });
+});
diff --git a/packages/agent-runtime/src/gen-ui-fragment-check.test.ts b/packages/agent-runtime/src/gen-ui-fragment-check.test.ts
new file mode 100644
index 000000000..c31f7b5bd
--- /dev/null
+++ b/packages/agent-runtime/src/gen-ui-fragment-check.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from "vitest";
+import { checkGenUiFragment, genUiFragmentCheckNote, isGenUiFragmentPath } from "./gen-ui-fragment-check.js";
+
+describe("isGenUiFragmentPath", () => {
+ const dir = "/data/visualizations/sess_1";
+
+ it("accepts an absolute .html file directly in the session directory", () => {
+ expect(isGenUiFragmentPath(`${dir}/sales.html`, dir)).toBe(true);
+ expect(isGenUiFragmentPath(`${dir}/Sales.HTML`, dir)).toBe(true);
+ });
+
+ it("rejects other files, other directories, and relative paths", () => {
+ expect(isGenUiFragmentPath(`${dir}/notes.md`, dir)).toBe(false);
+ expect(isGenUiFragmentPath(`${dir}/nested/a.html`, dir)).toBe(false);
+ expect(isGenUiFragmentPath(`${dir}/../sess_2/a.html`, dir)).toBe(false);
+ expect(isGenUiFragmentPath("/project/index.html", dir)).toBe(false);
+ expect(isGenUiFragmentPath("sales.html", dir)).toBe(false);
+ expect(isGenUiFragmentPath(`${dir}/a.html`, undefined)).toBe(false);
+ expect(isGenUiFragmentPath(42, dir)).toBe(false);
+ });
+});
+
+describe("checkGenUiFragment", () => {
+ it("passes a well-formed fragment", () => {
+ const fragment = `<div id="sales"></div><button id="more">More</button>
+<script>
+const c = viz.render("sales", { mark: "line", data: [], x: "m", y: "v" });
+document.getElementById("more").onclick = () => c.update({ data: [] });
+document.querySelector("#sales");
+</script>`;
+ expect(checkGenUiFragment(fragment)).toEqual([]);
+ });
+
+ it("reports a container id the fragment never defines, listing the ids it has", () => {
+ // The blank card seen in a live model run: the chart targeted "sb-bar".
+ const issues = checkGenUiFragment(`<div id="sb-chart"></div><script>viz.render("sb-bar", { mark: "bar" });</script>`);
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toContain('element id "sb-bar"');
+ expect(issues[0]).toContain('"sb-chart"');
+ });
+
+ it("checks viz.chart, getElementById, and #id querySelector targets", () => {
+ const issues = checkGenUiFragment(
+ `<script>viz.chart("#a", () => {}); document.getElementById('b'); document.querySelector("#c");</script>`,
+ );
+ expect(issues.map((issue) => issue.match(/element id "(\w+)"/)?.[1])).toEqual(["a", "b", "c"]);
+ });
+
+ it("counts ids a script creates itself and ignores dynamic ids", () => {
+ const fragment = `<script>
+const el = document.createElement("div"); el.id = "made"; document.body.append(el);
+d3.select("body").append("div").attr("id", "d3made");
+viz.render("made", {}); viz.render("d3made", {});
+viz.render(\`chart-\${n}\`, {}); document.getElementById(name);
+</script>`;
+ expect(checkGenUiFragment(fragment)).toEqual([]);
+ });
+
+ it("reports a script that does not parse without running it", () => {
+ const issues = checkGenUiFragment(`<div id="x"></div><script>globalThis.ran = true; const a = ;</script>`);
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatch(/^Script 1 does not parse: /);
+ expect((globalThis as { ran?: boolean }).ran).toBeUndefined();
+ });
+
+ it("skips external, JSON, and module scripts for syntax checks", () => {
+ const fragment = `<div id="x"></div>
+<script src="pi-genui://assets/x.js"></script>
+<script type="application/json">{ not js </script>
+<script type="module">import x from "y"; viz.render("x", {});</script>`;
+ expect(checkGenUiFragment(fragment)).toEqual([]);
+ });
+
+ it("ignores ids that only appear inside script text when collecting markup ids", () => {
+ const issues = checkGenUiFragment(`<script>const html = '<div id="fake"></div>'; viz.render("fake", {});</script>`);
+ expect(issues).toHaveLength(1);
+ });
+
+ it("bounds the number of reported issues", () => {
+ const calls = Array.from({ length: 9 }, (_, i) => `viz.render("m${i}", {});`).join("");
+ expect(checkGenUiFragment(`<script>${calls}</script>`)).toHaveLength(5);
+ });
+});
+
+describe("genUiFragmentCheckNote", () => {
+ it("asks for one Edit and lists each issue", () => {
+ const note = genUiFragmentCheckNote(["first", "second"]);
+ expect(note).toContain("Fix them with one Edit, then reply:");
+ expect(note).toContain("- first\n- second");
+ });
+});
diff --git a/packages/agent-runtime/src/gen-ui-fragment-check.ts b/packages/agent-runtime/src/gen-ui-fragment-check.ts
new file mode 100644
index 000000000..ffbeb52a4
--- /dev/null
+++ b/packages/agent-runtime/src/gen-ui-fragment-check.ts
@@ -0,0 +1,110 @@
+import { Script } from "node:vm";
+import { isAbsolute, relative, resolve } from "node:path";
+
+/**
+ * Cheap result check for a visualization fragment the model just wrote
+ * (ADR gen-ui-inline-visualization). The `visualize` skill forbids reading
+ * the fragment back or opening a browser, so the Write result is the one
+ * place to tell the model about mistakes it can fix with a single Edit.
+ *
+ * Only static checks run here: every inline classic script is compiled (never
+ * executed) to catch syntax errors, and string-literal element ids passed to
+ * the `viz` helpers or DOM lookups must exist in the fragment. Dynamic ids are
+ * not reported, so a passing check never claims more than it verified.
+ */
+
+const MAX_ISSUES = 5;
+const MAX_LISTED_IDS = 12;
+
+const SCRIPT_RE = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
+const SRC_ATTR_RE = /\bsrc\s*=/i;
+const TYPE_ATTR_RE = /\btype\s*=\s*["']?([^"'\s>]+)/i;
+const CLASSIC_TYPES = new Set(["", "text/javascript", "application/javascript", "module"]);
+const HTML_ID_RE = /\sid\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>=`]+))/gi;
+// Ids a script assigns itself: `el.id = "x"`, `setAttribute("id", "x")`, `.attr("id", "x")`.
+const SCRIPT_ID_RES = [
+ /\.id\s*=\s*(["'`])([^"'`$]+)\1/g,
+ /\.(?:setAttribute|attr)\(\s*["']id["']\s*,\s*(["'`])([^"'`$]+)\1/g,
+];
+const REFERENCE_RES = [
+ /\bviz\.(?:render|chart)\(\s*(["'`])#?([^"'`$]+)\1/g,
+ /\bgetElementById\(\s*(["'`])([^"'`$]+)\1/g,
+ /\bquerySelector\(\s*(["'`])#([A-Za-z_][\w-]*)\1/g,
+];
+
+/** Whether `path` is an absolute `.html` path directly under `visualizationsDir`. */
+export function isGenUiFragmentPath(path: unknown, visualizationsDir: string | undefined): path is string {
+ // Relative Write paths resolve against the workspace, never this directory.
+ if (typeof path !== "string" || !isAbsolute(path)) return false;
+ if (!visualizationsDir || !isAbsolute(visualizationsDir)) return false;
+ if (!path.toLowerCase().endsWith(".html")) return false;
+ const rel = relative(resolve(visualizationsDir), resolve(path));
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) && !/[\\/]/.test(rel);
+}
+
+/** Problems a model can fix in one Edit; empty when nothing was found. */
+export function checkGenUiFragment(content: string): string[] {
+ const issues: string[] = [];
+ const scripts: string[] = [];
+ let markup = "";
+ let last = 0;
+ for (const match of content.matchAll(SCRIPT_RE)) {
+ markup += content.slice(last, match.index);
+ last = match.index + match[0].length;
+ const attrs = match[1] ?? "";
+ const body = match[2] ?? "";
+ if (SRC_ATTR_RE.test(attrs)) continue;
+ const type = (TYPE_ATTR_RE.exec(attrs)?.[1] ?? "").toLowerCase();
+ if (!CLASSIC_TYPES.has(type)) continue;
+ scripts.push(body);
+ // Module syntax is not valid in a classic script; only classic scripts are compiled.
+ if (type === "module") continue;
+ const error = syntaxError(body);
+ if (error) issues.push(`Script ${scripts.length} does not parse: ${error}`);
+ }
+ markup += content.slice(last);
+
+ const ids = new Set<string>();
+ for (const match of markup.matchAll(HTML_ID_RE)) {
+ const id = match[1] ?? match[2] ?? match[3];
+ if (id) ids.add(id);
+ }
+ const code = scripts.join("\n");
+ for (const re of SCRIPT_ID_RES) {
+ for (const match of code.matchAll(re)) ids.add(match[2]);
+ }
+ const missing = new Map<string, string>();
+ for (const re of REFERENCE_RES) {
+ for (const match of code.matchAll(re)) {
+ const id = match[2];
+ if (!ids.has(id) && !missing.has(id)) missing.set(id, match[0]);
+ }
+ }
+ if (missing.size > 0) {
+ const known = [...ids].slice(0, MAX_LISTED_IDS);
+ const list = known.length > 0 ? known.map((id) => `"${id}"`).join(", ") : "none";
+ for (const [id, call] of missing) {
+ issues.push(`\`${call.trim()}…\` refers to element id "${id}", which the fragment never defines (ids present: ${list}).`);
+ }
+ }
+ return issues.slice(0, MAX_ISSUES);
+}
+
+/** Text appended to a successful Write result when the check found problems. */
+export function genUiFragmentCheckNote(issues: readonly string[]): string {
+ return [
+ "",
+ "Visualization check found problems that will break the card. Fix them with one Edit, then reply:",
+ ...issues.map((issue) => `- ${issue}`),
+ ].join("\n");
+}
+
+function syntaxError(source: string): string | undefined {
+ try {
+ // Compiling a Script parses it without running any of its code.
+ new Script(source);
+ return undefined;
+ } catch (error) {
+ return error instanceof SyntaxError ? error.message : undefined;
+ }
+}
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 683007315..7d8ce8169 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -126,6 +126,7 @@ import {
GEN_UI_SKILL_ID,
} from "@pi-desktop/shared";
import { createStreamCoalescer, type StreamCoalescer } from "./stream-coalescer.js";
+import { checkGenUiFragment, genUiFragmentCheckNote, isGenUiFragmentPath } from "./gen-ui-fragment-check.js";
import type { RuntimeHost } from "./host-client.js";
import { classifyAgentError } from "./agent-errors.js";
import {
@@ -3855,6 +3856,17 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
text = JSON.stringify(rawContent, null, 2);
}
if (!result.ok) this.failedHostToolCalls.add(toolCallId);
+ // A visualization fragment gets one cheap static check in its Write
+ // result, so a broken card is fixed in one Edit instead of left blank.
+ if (
+ toolName === "Write" &&
+ result.ok &&
+ typeof recordParams?.content === "string" &&
+ isGenUiFragmentPath(recordParams.path, this.visualizationsDir)
+ ) {
+ const issues = checkGenUiFragment(recordParams.content);
+ if (issues.length > 0) text += `\n${genUiFragmentCheckNote(issues)}`;
+ }
return {
content: [{ type: "text", text }, ...imageBlocks],
details,
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 63e702617..09502bb10 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -659,6 +659,7 @@ export const de = {
"unavailableNotFragment": "Die Datei ist ein vollständiges HTML-Dokument, kein Fragment.",
"unavailableRuntime": "Die Visualisierungslaufzeit ist nicht verfügbar.",
"loadPrompt": "Visualisierung laden",
+ "scriptError": "Das Skript dieser Visualisierung ist fehlgeschlagen; Teile können fehlen.",
"frameTitle": "Visualisierung: {{title}}",
},
"model": "Modell",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 8b93bb542..954b01a8a 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -671,6 +671,7 @@ export const en = {
unavailableNotFragment: "The file is a full HTML document, not a fragment.",
unavailableRuntime: "The visualization runtime is unavailable.",
loadPrompt: "Load visualization",
+ scriptError: "This visualization's script failed, so part of it may be missing.",
frameTitle: "Visualization: {{title}}",
},
model: "Model",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index eca25feba..efe068465 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -659,6 +659,7 @@ export const es = {
"unavailableNotFragment": "El archivo es un documento HTML completo, no un fragmento.",
"unavailableRuntime": "El entorno de ejecución de visualizaciones no está disponible.",
"loadPrompt": "Cargar visualización",
+ "scriptError": "El script de esta visualización falló; puede faltar parte del contenido.",
"frameTitle": "Visualización: {{title}}",
},
"model": "Modelo",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index a40b57527..7cc4977af 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -659,6 +659,7 @@ export const fr = {
"unavailableNotFragment": "Le fichier est un document HTML complet, pas un fragment.",
"unavailableRuntime": "L'environnement d'exécution des visualisations est indisponible.",
"loadPrompt": "Charger la visualisation",
+ "scriptError": "Le script de cette visualisation a échoué ; une partie peut manquer.",
"frameTitle": "Visualisation : {{title}}",
},
"model": "Modèle",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index eedbbf607..f5d453607 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -668,6 +668,7 @@ export const ko = {
unavailableNotFragment: "파일이 조각이 아닌 완전한 HTML 문서입니다.",
unavailableRuntime: "시각화 런타임을 사용할 수 없습니다.",
loadPrompt: "시각화 불러오기",
+ scriptError: "이 시각화의 스크립트가 실패하여 일부 내용이 표시되지 않을 수 있습니다.",
frameTitle: "시각화: {{title}}",
},
model: "모델",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index a83bd2b0d..3d5c00735 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -658,6 +658,7 @@ export const ptBR = {
unavailableNotFragment: "O arquivo é um documento HTML completo, não um fragmento.",
unavailableRuntime: "O runtime de visualizações não está disponível.",
loadPrompt: "Carregar visualização",
+ scriptError: "O script desta visualização falhou; parte do conteúdo pode estar faltando.",
frameTitle: "Visualização: {{title}}",
},
model: "Modelo",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 3e84b7327..9880d2059 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -668,6 +668,7 @@ export const tr = {
unavailableNotFragment: "Dosya bir parça değil, tam bir HTML belgesi.",
unavailableRuntime: "Görselleştirme çalışma zamanı kullanılamıyor.",
loadPrompt: "Görselleştirmeyi yükle",
+ scriptError: "Bu görselleştirmenin betiği başarısız oldu; bir kısmı eksik olabilir.",
frameTitle: "Görselleştirme: {{title}}",
},
model: "Model",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index a403f3a85..4e1b9c39d 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -664,6 +664,7 @@ export const zhCN = {
unavailableNotFragment: "该文件是完整的 HTML 文档,而非片段。",
unavailableRuntime: "可视化运行时不可用。",
loadPrompt: "加载可视化",
+ scriptError: "可视化脚本运行出错,部分内容可能无法显示。",
frameTitle: "可视化:{{title}}",
},
model: "模型",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 94e14a621..f127768e7 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -664,6 +664,7 @@ export const zhTW = {
unavailableNotFragment: "此檔案是完整的 HTML 文件,而非片段。",
unavailableRuntime: "視覺化執行環境無法使用。",
loadPrompt: "載入視覺化",
+ scriptError: "視覺化腳本執行出錯,部分內容可能無法顯示。",
frameTitle: "視覺化:{{title}}",
},
model: "模型",
diff --git a/packages/shared/src/gen-ui.ts b/packages/shared/src/gen-ui.ts
index f35b92cec..5f50eacac 100644
--- a/packages/shared/src/gen-ui.ts
+++ b/packages/shared/src/gen-ui.ts
@@ -64,6 +64,15 @@ export const GEN_UI_READY_MESSAGE = "pi-genui:ready";
export const GEN_UI_KEY_MESSAGE = "pi-genui:key";
/** Guest → host: Main served an error shell instead of the fragment. */
export const GEN_UI_ERROR_MESSAGE = "pi-genui:error";
+/**
+ * Guest → host: a fragment script threw (an uncaught error or an unhandled
+ * rejection). The card stays mounted and shows the message, so a chart that
+ * failed to draw is not just a blank frame. Sent with `{ message }`, where
+ * the message is guest text: the host bounds it and renders it as plain text.
+ */
+export const GEN_UI_SCRIPT_ERROR_MESSAGE = "pi-genui:script-error";
+/** Longest script-error message the host shows; longer text is truncated. */
+export const GEN_UI_MAX_SCRIPT_ERROR_LENGTH = 300;
/** Why Main could not serve a visualization; carried by `GEN_UI_ERROR_MESSAGE`. */
export const GEN_UI_ERROR_CODES = ["not-found", "too-large", "not-fragment", "runtime-unavailable"] as const;
diff --git a/scripts/e2e/gen-ui-main.mjs b/scripts/e2e/gen-ui-main.mjs
index 82df3b839..b0743a612 100644
--- a/scripts/e2e/gen-ui-main.mjs
+++ b/scripts/e2e/gen-ui-main.mjs
@@ -46,6 +46,8 @@ async function run() {
await mkdir(join(dataDir, "visualizations", "victim"), { recursive: true });
await writeFile(join(dataDir, "visualizations", "victim", "secret.html"),
"<p>CROSS_SESSION_PRIVATE_MARKER</p><script>parent.postMessage({type:'fixture:loaded'},'*')</script>");
+ await writeFile(join(sessionDir, "broken.html"),
+ `<div id="chart"></div><script>viz.render("missing-chart", { mark: "bar", data: [{ k: "a", v: 1 }], x: "k", y: "v" });</script>`);
await writeFile(join(sessionDir, "attacker.html"), `<p>attacker</p><script>addEventListener('message',event=>{if(event.data!=='attack')return;try{parent.postMessage({type:'cross-read',stolen:parent.frames[1].document.querySelector('p').textContent},'*')}catch(error){parent.postMessage({type:'cross-read',error:error.name},'*')}});parent.postMessage({type:'fixture:loaded'},'*')</script>`);
await writeFile(join(sessionDir, "limit.html"), Buffer.alloc(GEN_UI_MAX_FRAGMENT_BYTES, 0x20));
const limit = await readFragment({ sessionId: "probe_session", fileName: "limit.html" });
@@ -99,6 +101,44 @@ async function run() {
),
"2,true,2",
);
+ // Spec edge cases that a model-written fragment hits in practice.
+ const vizCases = await inline.executeJavaScript(`(async () => {
+ const box = (w = 400) => { const el = document.createElement("div"); el.style.width = w + "px"; document.body.append(el); return el; };
+ const out = {};
+ const days = box();
+ viz.render(days, { mark: "line", data: [{ d: "2025-01-15", v: 1 }, { d: "2025-01-16", v: 2 }], x: "d", y: "v" });
+ const years = box();
+ viz.render(years, { mark: "line", data: [{ y: 2019, v: 1 }, { y: 2026, v: 3 }], x: "y", y: "v" });
+ const again = box();
+ viz.render(again, { mark: "bar", data: [{ k: "a", v: 1, s: "x" }, { k: "b", v: 2, s: "y" }], x: "k", y: "v", color: "s" });
+ const second = viz.render(again, { mark: "bar", data: [{ k: "a", v: 3, s: "x" }, { k: "b", v: 1, s: "y" }], x: "k", y: "v", color: "s" });
+ second.update({ data: [{ k: "c", v: 5, s: "x" }, { k: "d", v: 2, s: "y" }] });
+ const donut = box();
+ viz.render(donut, { mark: "arc", data: [{ k: "rent", v: 3 }, { k: "food", v: 1 }], x: "k", y: "v" });
+ await Promise.resolve();
+ out.dateTip = days.querySelector("[data-tooltip]").getAttribute("data-tooltip");
+ out.dateTicks = [...days.querySelectorAll(".viz-axis-x .tick text")].map((t) => t.textContent).join("|");
+ out.yearTicks = [...years.querySelectorAll(".viz-axis-x .tick text")].map((t) => t.textContent).join("|");
+ out.again = [again.querySelectorAll("svg").length, again.querySelectorAll(".viz-legend").length, [...again.querySelectorAll(".viz-axis-x .tick text")].map((t) => t.textContent).join("")].join();
+ out.fixedWidth = days.querySelector("svg").hasAttribute("width");
+ out.donutLegend = donut.querySelector(".viz-legend-item").textContent;
+ // redraw() draws synchronously, so the spec error is caught here instead
+ // of escaping as an uncaught guest error.
+ try { viz.render(box(), { mark: "heatmap", data: [{ a: 1, b: 2 }], x: "a", y: "b" }).redraw(); out.heatmap = "no error"; }
+ catch (error) { out.heatmap = error.message; }
+ second.destroy();
+ out.destroyed = [again.querySelectorAll("svg").length, again.querySelectorAll(".viz-legend").length].join();
+ return out;
+ })()`);
+ assert.match(vizCases.dateTip, /2025-01-15/);
+ assert.doesNotMatch(vizCases.dateTip, /08:00|00:00/);
+ assert.doesNotMatch(vizCases.dateTicks, /:/);
+ assert.doesNotMatch(vizCases.yearTicks, /,/);
+ assert.equal(vizCases.again, "1,1,cd");
+ assert.equal(vizCases.fixedWidth, false);
+ assert.match(vizCases.donutLegend, /^rent /);
+ assert.equal(vizCases.heatmap, "viz.render: mark heatmap needs value");
+ assert.equal(vizCases.destroyed, "0,0");
assert.equal(await host('document.querySelector("iframe").getAttribute("sandbox")'), "allow-scripts");
await inline.executeJavaScript('document.getElementById("slider").value="17";document.getElementById("slider").dispatchEvent(new Event("input",{bubbles:true}));');
assert.equal(await inline.executeJavaScript("window.fixtureValue()"), "17");
@@ -127,6 +167,15 @@ async function run() {
await host(`window.genUiProbe.mount(${JSON.stringify(missing)});window.genUiProbe.wait(()=>!!document.querySelector(".is-unavailable"),"missing error shell")`);
checks.push("remote and missing files show unavailable cards");
+ // A fragment that passes a wrong container id to `viz.render` (seen in a
+ // real model run) used to leave a blank card with the error only in the
+ // guest console; the card now says why.
+ const broken = message(0).replace("chart0.html", "broken.html");
+ await host(`window.genUiProbe.mount(${JSON.stringify(broken)});window.genUiProbe.wait(()=>!!document.querySelector(".gen-ui-script-error"),"script error notice")`);
+ assert.match(await host('document.querySelector(".gen-ui-script-error").textContent'), /viz: no element missing-chart/);
+ assert.equal(await host('document.querySelectorAll(".gen-ui-card iframe").length'), 1);
+ checks.push("fragment script errors show in the card");
+
window.setContentSize(900, 2600);
const all = Array.from({ length: 8 }, (_, index) => message(index)).join("\n");
await host(`window.genUiProbe.mount(${JSON.stringify(all)});window.genUiProbe.waitLoaded(8)`);