Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
perf(chat): preload chart helpers for inline visualizations
zszz36e9fa40dd900
diff --git a/apps/desktop/electron/main/gen-ui-document.ts b/apps/desktop/electron/main/gen-ui-document.tsindex 934084bd7..d2413021f 100644--- a/apps/desktop/electron/main/gen-ui-document.ts+++ b/apps/desktop/electron/main/gen-ui-document.ts@@ -9,7 +9,12 @@ import {isGenUiErrorCode,type GenUiErrorCode,} from "@pi-desktop/shared";-import { GEN_UI_ASSET_ORIGIN, type GenUiKit, rewriteGenUiVendorUrls } from "./gen-ui-kit";+import {+ GEN_UI_ASSET_ORIGIN,+ type GenUiKit,+ rewriteGenUiVendorUrls,+ stripPreloadedGenUiScripts,+} from "./gen-ui-kit";/*** Host shell around a model-written visualization fragment@@ -231,7 +236,7 @@ ${body}export interface GenUiDocumentOptions {/** Kit stylesheet and runtime; see `gen-ui-kit.ts`. */- kit: Pick<GenUiKit, "css" | "runtime" | "vendorUrls">;+ kit: Pick<GenUiKit, "css" | "head" | "runtime" | "vendorUrls">;/** Initial theme variables; filtered with `sanitizeGenUiThemeVars`. */themeVars?: Record<string, string>;}@@ -253,8 +258,8 @@ export function buildGenUiDocument(fragment: string, options: GenUiDocumentOptioconst { kit } = options;return shell(`${kit.css}\n${SHELL_CSS}`,- `${themeStyle(options.themeVars)}<script>${RUNTIME_SCRIPT}</script>`,- `${rewriteGenUiVendorUrls(fragment, kit.vendorUrls)}\n${kit.runtime}`,+ `${themeStyle(options.themeVars)}<script>${RUNTIME_SCRIPT}</script>${kit.head}`,+ `${rewriteGenUiVendorUrls(stripPreloadedGenUiScripts(fragment), kit.vendorUrls)}\n${kit.runtime}`,);}diff --git a/apps/desktop/electron/main/gen-ui-kit.ts b/apps/desktop/electron/main/gen-ui-kit.tsindex 1664a597b..d8ee30844 100644--- a/apps/desktop/electron/main/gen-ui-kit.ts+++ b/apps/desktop/electron/main/gen-ui-kit.ts@@ -31,6 +31,12 @@ export interface GenUiKit {css: string;/** Runtime markup appended after the fragment. */runtime: string;+ /**+ * Markup loaded in `<head>` before the fragment: the bundled D3 and the+ * `viz` chart helpers (`visualize-helpers.js`), so fragment scripts can use+ * both without loading them.+ */+ head: string;/** Pinned CDN URL → `pi-genui://assets/<file>`. */vendorUrls: ReadonlyMap<string, string>;/** Bundled file name → absolute path; the only files `assets` serves. */@@ -98,15 +104,45 @@ export function resolveGenUiKitDir(): string | null {/** Load the kit from `dir`. Throws when a file is missing or malformed. */export async function loadGenUiKit(dir: string): Promise<GenUiKit> {const vendorDir = join(dir, "vendor");- const [css, kitHtml, manifestJson] = await Promise.all([+ const [css, kitHtml, helpers, manifestJson] = await Promise.all([readFile(join(dir, "visualize.css"), "utf8"),readFile(join(dir, "visualize-kit.html"), "utf8"),+ readFile(join(dir, "visualize-helpers.js"), "utf8"),readFile(join(vendorDir, "manifest.json"), "utf8"),]);const vendor = parseGenUiVendorManifest(manifestJson, vendorDir);return {css,+ head: genUiKitHead(helpers, vendor.vendorUrls),runtime: rewriteGenUiVendorUrls(kitHtml.replace(KIT_FRAGMENT_MARKER, ""), vendor.vendorUrls),...vendor,};}++/** Pinned D3 URL the skill used to require in every fragment. */+export const GEN_UI_D3_URL = "https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js";++/**+ * `<head>` markup: the bundled D3, then the chart helpers that build on it.+ * Throws when the manifest does not bundle D3, since the helpers need it.+ * Pure.+ */+export function genUiKitHead(helpers: string, vendorUrls: ReadonlyMap<string, string>): string {+ const d3 = vendorUrls.get(GEN_UI_D3_URL);+ if (!d3) throw new Error("gen-ui kit manifest does not bundle D3");+ if (/<\/script/i.test(helpers)) throw new Error("gen-ui helpers must not contain a closing script tag");+ return `<script src="${d3}"></script><script>${helpers}</script>`;+}++/**+ * Drop `<script src>` tags for D3 from a fragment: the shell already loads+ * it in `<head>`, and a second copy would replace the `d3` global the helpers+ * were built against. Older fragments written under the previous skill still+ * include the tag. Pure.+ */+export function stripPreloadedGenUiScripts(fragment: string): string {+ return fragment.replace(+ /<script\b[^>]*\bsrc\s*=\s*["']https:\/\/cdn\.jsdelivr\.net\/npm\/d3@7\.9\.0\/dist\/d3\.min\.js["'][^>]*>\s*<\/script>/gi,+ "",+ );+}diff --git a/apps/desktop/resources/gen-ui/NOTICE.md b/apps/desktop/resources/gen-ui/NOTICE.mdindex 90fc87afb..d1288afc7 100644--- a/apps/desktop/resources/gen-ui/NOTICE.md+++ b/apps/desktop/resources/gen-ui/NOTICE.md@@ -26,6 +26,9 @@ Changes made for PI-Desktop:tweaks, calendar widget, standalone export, network-loaded map data, and theCDN allowlist were removed, and the text was condensed; the visualizationdirectory, reference line, and sandbox rules describe PI-Desktop.+- The skill's chart guidance was rewritten around PI-Desktop's own `viz`+ helpers (`visualize-helpers.js`, not part of the upstream kit), and+ `visualize.css` gained styles for their axes, legends, and value labels.- Bundled library URLs are served by the `pi-genui:` protocol from `vendor/`instead of being fetched.diff --git a/apps/desktop/resources/gen-ui/visualize-helpers.js b/apps/desktop/resources/gen-ui/visualize-helpers.jsnew file mode 100644index 000000000..1b658c3fe--- /dev/null+++ b/apps/desktop/resources/gen-ui/visualize-helpers.js@@ -0,0 +1,625 @@+/*+ * Chart helpers for model-written visualization fragments (ADR+ * gen-ui-inline-visualization). Loaded in the shell <head> right after the+ * bundled D3, so a fragment script can call `viz.*` and `d3.*` directly.+ *+ * They own the boilerplate every chart would otherwise repeat: sizing the SVG+ * from its container and redrawing on width or theme changes, theme-aware+ * axes with titles, width-aware tick counts, and tick-label overlap pruning.+ * Keeping it here lets the model write only the chart-specific marks.+ */+(() => {+ const root = document.documentElement;+ const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");+ const charts = new Set();+ const DEFAULT_MARGIN = { top: 16, right: 20, bottom: 48, left: 64 };++ const resolveElement = (target) => {+ const element =+ typeof target === "string" ? document.getElementById(target.replace(/^#/, "")) : target;+ if (!(element instanceof Element)) throw new Error(`viz: no element ${String(target)}`);+ return element;+ };++ /** Resolve a theme variable (`"--primary"` or `"primary"`) for canvas or chart APIs. */+ const color = (name) =>+ getComputedStyle(root).getPropertyValue(name.startsWith("--") ? name : `--${name}`).trim();++ /** CSS color for persistent series identity `index` (0-based, wraps after 6). */+ const series = (index) => `var(--viz-series-${(((index % 6) + 6) % 6) + 1})`;++ const defaultHeight = (width) => Math.round(Math.min(420, Math.max(240, width * 0.56)));++ /**+ * Mount a responsive SVG chart in `target` (an element or its id) and call+ * `draw({ svg, width, height, compact, reducedMotion })`. The SVG's viewBox+ * always matches the container's measured width. The first draw runs right+ * after the calling script finishes; `draw` reruns when the width or theme+ * changes, and synchronously whenever the caller invokes `redraw()`.+ * The SVG is emptied before each draw unless `options.keep` is true.+ */+ function chart(target, draw, options = {}) {+ const container = resolveElement(target);+ const svg = d3.select(container).append("svg").attr("role", "img");+ if (options.label) svg.attr("aria-label", options.label);+ let lastWidth = 0;+ let frame = 0;+ const render = () => {+ frame = 0;+ const width = Math.floor(container.clientWidth);+ if (width <= 0) return;+ lastWidth = width;+ const height =+ typeof options.height === "function"+ ? options.height(width)+ : (options.height ?? defaultHeight(width));+ svg.attr("viewBox", `0 0 ${width} ${height}`).attr("width", width).attr("height", height);+ if (!options.keep) svg.selectAll("*").remove();+ draw({ svg, width, height, compact: width < 480, reducedMotion: reducedMotion.matches });+ };+ const schedule = () => {+ if (!frame) frame = requestAnimationFrame(render);+ };+ const observer = new ResizeObserver(() => {+ if (Math.floor(container.clientWidth) !== lastWidth) schedule();+ });+ observer.observe(container);+ const handle = {+ svg,+ redraw: render,+ destroy() {+ observer.disconnect();+ charts.delete(handle);+ },+ };+ charts.add(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(() => {+ if (charts.has(handle) && lastWidth === 0) render();+ });+ return handle;+ }++ /**+ * Translate a plot group inside `svg` by `margin` (merged over the default,+ * which reserves 64px for the y axis) and return the inner plot size.+ */+ function plot(svg, width, height, margin = {}) {+ const m = { ...DEFAULT_MARGIN, ...margin };+ const g = svg.append("g").attr("transform", `translate(${m.left},${m.top})`);+ return {+ g,+ margin: m,+ innerWidth: Math.max(0, width - m.left - m.right),+ innerHeight: Math.max(0, height - m.top - m.bottom),+ };+ }++ /** Domain from all observations with relative `pad` on each side; `zero` keeps 0 in view. */+ function extent(values, accessor = (value) => value, { pad = 0.05, zero = false } = {}) {+ let [min, max] = d3.extent(values, accessor);+ if (min == null || max == null) return [0, 1];+ if (zero) {+ min = Math.min(0, min);+ max = Math.max(0, max);+ }+ if (min === max) return [min - 1, max + 1];+ const span = (max - min) * pad;+ return [zero && min === 0 ? 0 : min - span, zero && max === 0 ? 0 : max + span];+ }++ /** Elements of a D3 selection, an array or NodeList of elements or selections, or one element. */+ const elementsOf = (labels) => {+ if (!labels) return [];+ if (typeof labels.nodes === "function") return labels.nodes();+ if (typeof labels.length === "number") {+ return Array.from(labels, (item) => (item && typeof item.node === "function" ? item.node() : item));+ }+ return [labels];+ };++ /**+ * Hide labels in document order that would sit within `gap` px of the+ * previous visible one. Accepts a D3 selection, an array or NodeList, or a+ * single element.+ */+ function pruneOverlaps(labels, gap = 4, vertical = false) {+ let previous = null;+ for (const label of elementsOf(labels)) {+ if (!label || typeof label.getBoundingClientRect !== "function") continue;+ label.removeAttribute("visibility");+ const box = label.getBoundingClientRect();+ if (box.width === 0 && box.height === 0) continue;+ if (previous) {+ const overlap = vertical+ ? box.bottom + gap > previous.top && box.top - gap < previous.bottom+ : box.left - gap < previous.right && box.right + gap > previous.left;+ if (overlap) {+ label.setAttribute("visibility", "hidden");+ continue;+ }+ }+ previous = box;+ }+ }++ /** Keep the first and last x tick labels inside the plot by anchoring them inward. */+ function anchorEdgeLabels(axisGroup, innerWidth) {+ const ticks = axisGroup.selectAll(".tick text").nodes();+ if (ticks.length === 0) return;+ const frame = axisGroup.node().getBoundingClientRect();+ for (const node of [ticks[0], ticks.at(-1)]) {+ const box = node.getBoundingClientRect();+ if (box.left < frame.left - 1) node.setAttribute("text-anchor", "start");+ else if (box.right > frame.left + innerWidth + 1) node.setAttribute("text-anchor", "end");+ }+ }++ /**+ * Draw bottom and left axes for `x` / `y` scales into the plot group `g`:+ * width-aware tick counts (at most four x ticks below 400px), axis titles,+ * optional horizontal grid lines, inward edge labels, and overlap pruning.+ */+ function axes(g, options) {+ const { x, y, innerWidth, innerHeight, xLabel, yLabel, xFormat, yFormat, grid = false } = options;+ const xTicks = options.xTicks ?? Math.max(2, Math.min(innerWidth < 400 ? 4 : 10, Math.floor(innerWidth / 80)));+ const yTicks = options.yTicks ?? Math.max(2, Math.min(8, Math.floor(innerHeight / 48)));+ const result = {};+ if (x) {+ const axis = d3.axisBottom(x).tickSizeOuter(0);+ if (typeof x.ticks === "function") axis.ticks(xTicks);+ if (xFormat) axis.tickFormat(xFormat);+ const group = g.append("g").attr("class", "viz-axis viz-axis-x").attr("transform", `translate(0,${innerHeight})`).call(axis);+ anchorEdgeLabels(group, innerWidth);+ pruneOverlaps(group.selectAll(".tick text"));+ if (xLabel) {+ g.append("text").attr("class", "viz-axis-title").attr("x", innerWidth / 2).attr("y", innerHeight + 40).attr("text-anchor", "middle").text(xLabel);+ }+ result.x = group;+ }+ if (y) {+ const axis = d3.axisLeft(y).tickSizeOuter(0);+ if (typeof y.ticks === "function") axis.ticks(yTicks);+ if (yFormat) axis.tickFormat(yFormat);+ if (grid) {+ g.append("g").attr("class", "viz-gridlines").call(d3.axisLeft(y).ticks(yTicks).tickSize(-innerWidth).tickFormat(() => "")).call((sel) => sel.select(".domain").remove());+ }+ 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);+ }+ result.y = group;+ }+ return result;+ }++ /** Transition duration that honors `prefers-reduced-motion`. */+ const duration = (ms = 250) => (reducedMotion.matches ? 0 : ms);++ const accessor = (field) => (typeof field === "function" ? field : (d) => d[field]);++ /** Least-squares fit of `y` on `x` (fields or accessors) → `{ slope, intercept, r, n }`, or null. */+ function regression(data, x, y) {+ const getX = accessor(x);+ const getY = accessor(y);+ const points = data+ .map((d) => [Number(getX(d)), Number(getY(d))])+ .filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b));+ if (points.length < 2) return null;+ const meanX = d3.mean(points, (p) => p[0]);+ const meanY = d3.mean(points, (p) => p[1]);+ let sxy = 0;+ let sxx = 0;+ let syy = 0;+ for (const [a, b] of points) {+ sxy += (a - meanX) * (b - meanY);+ sxx += (a - meanX) ** 2;+ syy += (b - meanY) ** 2;+ }+ if (sxx === 0) return null;+ const slope = sxy / sxx;+ return { slope, intercept: meanY - slope * meanX, r: syy === 0 ? 0 : sxy / Math.sqrt(sxx * syy), n: points.length };+ }++ // ---- Declarative charts: `viz.render(target, spec)` ----------------------+ // Common charts are described, not drawn: the spec names the mark and which+ // fields map to x / y / color, and the helpers derive scales, axes, legend,+ // tooltips, and value labels. Custom visuals keep using `viz.chart`.++ const isDateLike = (v) =>+ v instanceof Date || (typeof v === "string" && /^\d{4}-\d{2}-\d{2}/.test(v) && !Number.isNaN(Date.parse(v)));+ 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 });++ function inferType(values) {+ if (values.length > 0 && values.every((v) => typeof v === "number" && Number.isFinite(v))) return "linear";+ if (values.length > 0 && values.every(isDateLike)) return "time";+ return "band";+ }++ function formatter(format, type) {+ if (typeof format === "function") return format;+ if (typeof format === "string") return type === "time" ? d3.timeFormat(format) : d3.format(format);+ if (type === "time") {+ return (v) => d3.timeFormat(v.getHours() || v.getMinutes() ? "%m-%d %H:%M" : "%Y-%m-%d")(v);+ }+ return (v) =>+ typeof v === "number" ? d3.format(Number.isInteger(v) ? "," : ",.2~f")(v) : String(v ?? "");+ }++ /** Resolve one channel (`"field"` or `{ field, title, type, format, domain }`) against the data. */+ function channel(input, data) {+ 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;+ 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 days = lo && hi ? (hi - lo) / 864e5 : 0;+ tick = d3.timeFormat(days > 730 ? "%Y" : days > 60 ? "%Y-%m" : days > 2 ? "%m-%d" : "%H:%M");+ }+ return {+ ...enc,+ type,+ get,+ title: enc.title ?? (typeof enc.field === "string" ? enc.field : ""),+ fmt: formatter(enc.format, type),+ tick,+ };+ }++ /** Rough rendered width of category labels, for the left margin of band y axes. */+ const labelWidth = (values, fmt) =>+ d3.max(values, (v) => [...fmt(v)].reduce((n, ch) => n + (ch.charCodeAt(0) > 0x2e80 ? 12 : 7), 0)) ?? 0;++ function continuous(ch, values, range, zero) {+ if (ch.type === "time") return d3.scaleTime(ch.domain ?? d3.extent(values), range);+ if (ch.type === "band") return d3.scalePoint(ch.domain ?? uniq(values), range).padding(0.5);+ return d3.scaleLinear(ch.domain ?? extent(values, (v) => v, { zero }), range);+ }++ function setLegend(legend, items, ramp) {+ legend.replaceChildren();+ legend.hidden = !items && !ramp;+ for (const item of items ?? []) {+ const entry = document.createElement("span");+ entry.className = "viz-legend-item";+ const swatch = document.createElement("span");+ swatch.className = "viz-legend-swatch";+ swatch.style.background = item.color;+ entry.append(swatch, item.label);+ legend.append(entry);+ }+ if (ramp) {+ const entry = document.createElement("span");+ entry.className = "viz-legend-item";+ const bar = document.createElement("span");+ bar.className = "viz-legend-ramp";+ entry.append(ramp.min, bar, ramp.max);+ legend.append(entry);+ }+ }++ const tip = (s, d, parts) => (s.tooltip ? String(s.tooltip(d)) : parts.filter(Boolean).join(" · "));+ const part = (ch, value) => (ch ? `${ch.title ? `${ch.title}: ` : ""}${ch.fmt(value)}` : "");++ function drawBars(g, s, w, h, compact) {+ const horizontal = s.y.type === "band" && s.x.type !== "band";+ const cat = horizontal ? s.y : s.x;+ const val = horizontal ? s.x : s.y;+ const cats = cat.domain ?? uniq(s.data.map(cat.get));+ const c = d3.scaleBand(cats, horizontal ? [0, h] : [0, w]).padding(0.2);+ const grouped = s.keys.length > 1 && !s.stack;+ const sub = d3.scaleBand(grouped ? s.keys : ["all"], [0, c.bandwidth()]).padding(0.06);+ let layers = null;+ let values = s.data.map(val.get);+ if (s.keys.length > 1 && s.stack) {+ const index = new Map(cats.map((k, i) => [keyOf(k), i]));+ const rows = cats.map((k) => Object.fromEntries([["__cat", k], ...s.keys.map((key) => [key, 0])]));+ for (const d of s.data) {+ 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);+ 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]);+ const [lo, hi] = v.domain();+ const base = v(Math.max(lo, Math.min(0, hi)));+ const place = (rect, pos, thick, a, b) =>+ horizontal+ ? rect.attr("y", pos).attr("height", thick).attr("x", Math.min(a, b)).attr("width", Math.abs(b - a))+ : rect.attr("x", pos).attr("width", thick).attr("y", Math.min(a, b)).attr("height", Math.abs(b - a));+ axes(g, {+ x: horizontal ? v : c,+ y: horizontal ? c : v,+ innerWidth: w,+ innerHeight: h,+ xLabel: horizontal ? val.title : cat.title,+ yLabel: horizontal ? undefined : val.title,+ xFormat: horizontal ? val.tick : cat.tick,+ yFormat: horizontal ? cat.tick : val.tick,+ grid: !horizontal,+ });+ const marks = g.append("g");+ if (layers) {+ layers.forEach((layer, i) => {+ for (const p of layer) {+ place(marks.append("rect"), c(p.data.__cat), c.bandwidth(), v(p[0]), v(p[1]))+ .style("fill", series(i))+ .attr("data-tooltip", tip(s, p.data, [cat.fmt(p.data.__cat), `${layer.key}: ${val.fmt(p[1] - p[0])}`]));+ }+ });+ return;+ }+ const labels = [];+ for (const d of s.data) {+ const key = s.seriesOf ? s.seriesOf(d) : "all";+ const pos = c(cat.get(d));+ if (pos === undefined) continue;+ const at = pos + (grouped ? sub(key) : 0);+ const thick = grouped ? sub.bandwidth() : c.bandwidth();+ const end = v(val.get(d));+ place(marks.append("rect"), at, thick, base, end)+ .style("fill", s.seriesOf ? s.colorOf(key) : series(0))+ .attr("data-tooltip", tip(s, d, [cat.fmt(cat.get(d)), s.seriesOf ? String(key) : "", part(val, val.get(d))]));+ const showLabels = s.labels ?? (!grouped && s.data.length <= (compact ? 8 : 16));+ if (showLabels) {+ const label = marks.append("text").attr("class", "viz-value").text(val.fmt(val.get(d)));+ if (horizontal) label.attr("x", Math.max(end, base) + 4).attr("y", at + thick / 2).attr("dy", "0.35em");+ else label.attr("x", at + thick / 2).attr("y", Math.min(end, base) - 4).attr("text-anchor", "middle");+ labels.push(label.node());+ }+ }+ if (!horizontal) pruneOverlaps(labels);+ }++ function drawXY(g, s, w, h) {+ const area = s.mark === "area";+ const stacked = area && s.keys.length > 1 && s.stack !== false;+ const groups = s.seriesOf ? d3.group(s.data, s.seriesOf) : new Map([["all", s.data]]);+ const x = continuous(s.x, s.data.map(s.x.get), [0, w], false);+ let rows = null;+ let layers = null;+ let yValues = s.data.map(s.y.get);+ if (stacked) {+ const xs = uniq(s.data.map(s.x.get));+ const index = new Map(xs.map((k, i) => [keyOf(k), i]));+ rows = xs.map((k) => Object.fromEntries([["__x", k], ...s.keys.map((key) => [key, 0])]));+ for (const d of s.data) rows[index.get(keyOf(s.x.get(d)))][s.seriesOf(d)] += Number(s.y.get(d)) || 0;+ if (s.x.type !== "band") rows.sort((a, b) => a.__x - b.__x);+ layers = d3.stack().keys(s.keys)(rows);+ yValues = layers.flatMap((layer) => layer.flatMap((p) => [p[0], p[1]]));+ }+ const y = continuous({ ...s.y, type: "linear" }, yValues, [h, 0], area || s.y.zero);+ axes(g, {+ x,+ y,+ innerWidth: w,+ innerHeight: h,+ xLabel: s.x.title,+ yLabel: s.y.title,+ xFormat: s.x.tick,+ yFormat: s.y.tick,+ grid: true,+ });+ const marks = g.append("g");+ if (s.mark === "point") {+ const size = s.size ? channel(s.size, s.data) : null;+ const r = size ? d3.scaleSqrt(d3.extent(s.data, size.get), [3, 14]) : () => 4;+ for (const d of s.data) {+ const key = s.seriesOf ? s.seriesOf(d) : "all";+ marks+ .append("circle")+ .attr("cx", x(s.x.get(d)))+ .attr("cy", y(s.y.get(d)))+ .attr("r", size ? r(size.get(d)) : 4)+ .style("fill", s.seriesOf ? s.colorOf(key) : series(0))+ .style("fill-opacity", 0.75)+ .attr("data-tooltip", tip(s, d, [s.seriesOf ? String(key) : "", part(s.x, s.x.get(d)), part(s.y, s.y.get(d)), size ? part(size, size.get(d)) : ""]));+ }+ const fit = s.trend && s.x.type !== "band" ? regression(s.data, (d) => +s.x.get(d), s.y.get) : null;+ if (fit) {+ const [x0, x1] = x.domain().map(Number);+ marks+ .append("line")+ .attr("class", "viz-trend")+ .attr("x1", x(x0))+ .attr("x2", x(x1))+ .attr("y1", y(fit.intercept + fit.slope * x0))+ .attr("y2", y(fit.intercept + fit.slope * x1));+ }+ return;+ }+ const order = (list) => (s.x.type === "band" ? list : [...list].sort((a, b) => s.x.get(a) - s.x.get(b)));+ if (stacked) {+ layers.forEach((layer, i) => {+ marks+ .append("path")+ .datum(layer)+ .style("fill", series(i))+ .style("fill-opacity", 0.7)+ .attr("d", d3.area((p) => x(p.data.__x), (p) => y(p[0]), (p) => y(p[1])));+ });+ }+ let i = 0;+ for (const [key, list] of groups) {+ const color = s.seriesOf ? s.colorOf(key) : series(i);+ const points = order(list);+ if (area && !stacked) {+ marks+ .append("path")+ .datum(points)+ .style("fill", color)+ .style("fill-opacity", 0.18)+ .attr("d", d3.area((d) => x(s.x.get(d)), y(Math.max(y.domain()[0], 0)), (d) => y(s.y.get(d))));+ }+ if (!stacked) {+ marks+ .append("path")+ .datum(points)+ .style("fill", "none")+ .style("stroke", color)+ .style("stroke-width", 2)+ .attr("d", d3.line((d) => x(s.x.get(d)), (d) => y(s.y.get(d))));+ }+ for (const d of points) {+ const cy = stacked+ ? y(layers[s.keys.indexOf(key)].find((p) => keyOf(p.data.__x) === keyOf(s.x.get(d)))?.[1] ?? 0)+ : y(s.y.get(d));+ if (!stacked && points.length <= 40) {+ marks.append("circle").attr("cx", x(s.x.get(d))).attr("cy", cy).attr("r", 3).style("fill", color);+ }+ marks+ .append("circle")+ .attr("cx", x(s.x.get(d)))+ .attr("cy", cy)+ .attr("r", 10)+ .style("fill", "transparent")+ .attr("data-tooltip", tip(s, d, [s.seriesOf ? String(key) : "", part(s.x, s.x.get(d)), part(s.y, s.y.get(d))]));+ }+ i += 1;+ }+ }++ function drawHeatmap(g, s, w, h, legend) {+ const xs = s.x.domain ?? uniq(s.data.map(s.x.get));+ const ys = s.y.domain ?? uniq(s.data.map(s.y.get));+ const x = d3.scaleBand(xs, [0, w]).padding(0.04);+ const y = d3.scaleBand(ys, [0, h]).padding(0.04);+ 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 });+ const marks = g.append("g");+ for (const d of s.data) {+ marks+ .append("rect")+ .attr("x", x(s.x.get(d)))+ .attr("y", y(s.y.get(d)))+ .attr("width", x.bandwidth())+ .attr("height", y.bandwidth())+ .attr("rx", 2)+ .style("fill", series(0))+ .style("fill-opacity", opacity(value.get(d)))+ .attr("data-tooltip", tip(s, d, [s.x.fmt(s.x.get(d)), s.y.fmt(s.y.get(d)), part(value, value.get(d))]));+ }+ setLegend(legend, null, { min: value.fmt(min ?? 0), max: value.fmt(max ?? 0) });+ }++ function drawArc(svg, s, width, height, legend) {+ const total = d3.sum(s.data, s.theta.get);+ const radius = Math.max(0, Math.min(width, height) / 2 - 8);+ const g = svg.append("g").attr("transform", `translate(${width / 2},${height / 2})`);+ const arcs = d3.pie().sort(null).value(s.theta.get)(s.data);+ const shape = d3.arc().innerRadius(radius * 0.6).outerRadius(radius).padAngle(0.01);+ const pct = (v) => (total ? d3.format(".1%")(v / total) : "");+ arcs.forEach((a, i) => {+ const key = s.seriesOf ? s.seriesOf(a.data) : String(i);+ g.append("path")+ .attr("d", shape(a))+ .style("fill", s.seriesOf ? s.colorOf(key) : series(i))+ .attr("data-tooltip", tip(s, a.data, [String(key), `${s.theta.fmt(s.theta.get(a.data))} (${pct(s.theta.get(a.data))})`]));+ });+ if (s.center !== false) {+ g.append("text").attr("class", "viz-value").attr("text-anchor", "middle").attr("dy", "0.35em").text(s.center ?? s.theta.fmt(total));+ }+ setLegend(+ legend,+ arcs.map((a, i) => {+ const key = s.seriesOf ? s.seriesOf(a.data) : String(i);+ return { label: `${key} ${pct(s.theta.get(a.data))}`, color: s.seriesOf ? s.colorOf(key) : series(i) };+ }),+ );+ }++ const MARKS = new Set(["bar", "line", "area", "point", "heatmap", "arc"]);++ function drawSpec({ svg, width, height, compact }, spec, legend) {+ if (!MARKS.has(spec.mark)) throw new Error(`viz.render: unknown mark ${JSON.stringify(spec.mark)}`);+ const data = Array.isArray(spec.data) ? spec.data : [];+ const s = { ...spec, data };+ const color = spec.mark === "heatmap" ? null : channel(spec.color, data);+ s.seriesOf = color ? (d) => String(color.get(d)) : null;+ s.keys = color ? uniq(data.map(s.seriesOf)) : [];+ s.colorOf = (key) => series(Math.max(0, s.keys.indexOf(key)));+ 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);+ drawArc(svg, s, width, height, legend);+ return;+ }+ s.x = channel(spec.x, data);+ s.y = channel(spec.y, data);+ if (!s.x || !s.y) throw new Error(`viz.render: mark ${spec.mark} needs x and y`);+ if (spec.mark === "heatmap") {+ s.x = { ...s.x, type: "band" };+ s.y = { ...s.y, type: "band" };+ s.value = channel(spec.value ?? spec.color, data);+ }+ 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;+ 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);+ else drawXY(g, s, innerWidth, innerHeight);+ }++ /**+ * Draw a standard chart from a declarative spec and return+ * `{ update(patch), redraw, destroy, svg }`. `update` merges `patch` (or the+ * result of `patch(spec)`) into the spec and redraws, for controls.+ */+ function render(target, initial) {+ const container = resolveElement(target);+ let spec = { ...initial };+ const legend = document.createElement("div");+ legend.className = "viz-legend";+ legend.hidden = true;+ container.append(legend);+ const height = (width) =>+ 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 });+ return {+ svg: handle.svg,+ redraw: handle.redraw,+ destroy: handle.destroy,+ update(patch) {+ spec = { ...spec, ...(typeof patch === "function" ? patch(spec) : patch) };+ handle.redraw();+ },+ };+ }++ // Theme updates rewrite the root's inline style; redraw charts once per frame+ // so canvas colors and anything resolved through `viz.color` stay current.+ let themeFrame = 0;+ new MutationObserver(() => {+ if (themeFrame) return;+ themeFrame = requestAnimationFrame(() => {+ themeFrame = 0;+ for (const handle of charts) handle.redraw();+ });+ }).observe(root, { attributes: true, attributeFilter: ["style"] });++ window.viz = Object.freeze({+ render,+ chart,+ plot,+ axes,+ extent,+ regression,+ pruneOverlaps,+ color,+ series,+ duration,+ });+})();diff --git a/apps/desktop/resources/gen-ui/visualize.css b/apps/desktop/resources/gen-ui/visualize.cssindex b21a2968d..eea78ec52 100644--- a/apps/desktop/resources/gen-ui/visualize.css+++ b/apps/desktop/resources/gen-ui/visualize.css@@ -1011,6 +1011,80 @@ svg {width: 100%;}+/* Axes drawn by `viz.axes` (visualize-helpers.js). */+.viz-axis {+ color: var(--muted-foreground);+ font-size: var(--font-size-small);+}++.viz-axis .domain,+.viz-axis .tick line {+ stroke: var(--border);+}++.viz-axis .tick text {+ fill: var(--muted-foreground);+}++.viz-axis-title {+ fill: var(--foreground);+ font-size: var(--font-size-small);+}++.viz-gridlines .tick line {+ stroke: var(--border);+ stroke-opacity: 0.6;+}++/* Value labels, trend lines, and legends drawn by `viz.render`. */+.viz-value {+ fill: var(--foreground);+ font-size: var(--font-size-small);+ font-variant-numeric: tabular-nums;+}++.viz-trend {+ stroke: var(--foreground);+ stroke-width: 1.5;+ stroke-dasharray: 5 4;+}++.viz-legend {+ display: flex;+ flex-wrap: wrap;+ gap: 4px 14px;+ margin-bottom: 6px;+ color: var(--muted-foreground);+ font-size: var(--font-size-small);+}++.viz-legend[hidden] {+ display: none;+}++.viz-legend-item {+ display: inline-flex;+ align-items: center;+ gap: 6px;+}++.viz-legend-swatch {+ width: 10px;+ height: 10px;+ border-radius: 2px;+}++.viz-legend-ramp {+ width: 72px;+ height: 8px;+ border-radius: var(--radius-full);+ background: linear-gradient(+ to right,+ color-mix(in srgb, var(--viz-series-1) 8%, transparent),+ var(--viz-series-1)+ );+}+/* Model-authored chart rules can otherwise stretch icons after these styles load. */diff --git a/apps/desktop/resources/skills/visualize.md b/apps/desktop/resources/skills/visualize.mdindex c7d61dcb3..4003c8f28 100644--- a/apps/desktop/resources/skills/visualize.md+++ b/apps/desktop/resources/skills/visualize.md@@ -7,31 +7,38 @@ description: "Create interactive visualizations directly in the conversation. Us# Visualize-- A request for a new standalone file, website, app page, component, or other- project change is not an in-conversation visualization, even when it- contains charts or interactive content. Build that in the project instead.+- A request for a new standalone file, website, app page, component, or+ project change is not an in-conversation visualization, even with charts.+ Build it in the project.- Create a visual only when the user needs to see or explore it in theconversation and it materially improves the explanation.-- Use a normal Markdown table when the user asks for a table. Use a fenced- Mermaid block when labeled nodes and edges fully explain a static structure.- Use a visualization for dynamics, motion, adjustable inputs, spatial layout,- and data worth hovering or filtering.-- Work silently: no progress commentary while reading this skill or writing- the file. In the reply, describe only what the visual helps the user see or- decide. Never announce this skill, HTML, SVG, scripts, or local files.+- Use a Markdown table when asked for a table; a fenced Mermaid block when+ labeled nodes and edges explain a static structure. Visualize dynamics,+ motion, adjustable inputs, spatial layout, and data worth hovering or+ filtering.+- Work silently: no progress commentary. In the reply, describe only what the+ visual helps the user see or decide. Never announce this skill, HTML, SVG,+ scripts, or local files.Read this file in full before authoring. Copy into every compaction summary:`Reload the full visualize skill before creating or updating a visualization.`+## 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.+- 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.+## Output contract### File-- Write `<title>.html` with a concise lowercase-hyphenated ASCII title into- the **visualization directory named in the system prompt**, using its- absolute path. Files must sit directly in that directory. If no- visualization directory is listed, or you cannot write files there,- inline visualizations are unavailable: answer without one.+- Write `<title>.html` (concise lowercase-hyphenated ASCII) with its+ absolute path into the **visualization directory named in the system+ prompt**, directly in that directory. No directory listed, or not+ writable: answer without a visual.- Never write inline fragments into the project or a temp directory.### Fragment@@ -40,14 +47,14 @@ Read this file in full before authoring. Copy into every compaction summary:`<body>`. The host supplies the document, the stylesheet below, and theruntime.- Write literal markup with real newlines, never an escaped string- (`<div class=\"card\">`, `\n`). Read the file back if unsure.+ (`<div class=\"card\">`, `\n`).- Give the fragment root a unique ID and select it with`document.getElementById(...)`; never derive it from `document.currentScript`.-- Keep it under 1 MB: aggregate, bin, downsample, or drop unused fields from- large inline datasets.-- Check that the script has no undefined identifiers, every queried element- exists, and the primary interaction updates the visual. Review with the- Read tool; do not run shell commands to check the file.+- Keep it under 1 MB: aggregate, bin, or downsample large datasets.+- Write the file once, complete. Before writing, check that the script has+ no undefined identifiers, every queried element exists, and the primary+ interaction updates the visual. Do not read it back (see Hard rules); reply+ right after the write succeeds.### Reference in the reply@@ -61,21 +68,16 @@ the reply, as plain text. The line looks like this (with real values):forward slashes (`C:/Users/...` on Windows).- Whenever you create or update a visualization, reference it again in thatturn's final reply, even when editing an existing file.-- Do not repeat the visual's data as a table; add at most one short- conclusion.+- Do not repeat the data as a table; add at most one short conclusion.### Sandbox- There is no network: `fetch`, XHR, WebSocket, remote scripts, fonts, images,and map data are all blocked and fail silently. Draw with inline SVG or`<canvas>`; embed small assets as `data:` URIs.-- Bundled libraries are available offline through these exact URLs. Keep them- unchanged; any other URL or version is blocked:- - D3 7.9.0: `<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js"></script>`.- D3 is not preloaded: a fragment that calls `d3` must include this tag- before its own script.- - Floating UI is already loaded by the runtime for tooltips; do not load it- again.+- D3 7.9.0 (`d3`) and the `viz` helpers below are preloaded; use them+ directly and never add a `<script src>`. Floating UI is loaded by the+ runtime for tooltips. Any other library is unavailable.- No popups, alerts, navigation, external links, form submission, cookies,or `localStorage`. Keep state in script variables; it resets when the cardreloads.@@ -101,14 +103,13 @@ the reply, as plain text. The line looks like this (with real values):values and labels in `--foreground` / `--muted-foreground`.- Keep grids and inactive structure thin (1–2px) and neutral. Never outlinebars, progress tracks, or stacked segments.-- For canvas or chart APIs that cannot read CSS variables, resolve them with- `getComputedStyle(document.documentElement).getPropertyValue(...)` and redraw- when the root's `style` attribute changes (`MutationObserver`).+- Where CSS variables cannot be read (canvas), use `viz.color("--primary")`+ inside a `viz.chart` draw function, which reruns on theme changes.- Type scales from `--font-size-base` (14px); `.text-small` is 12px. Never gobelow 11px, never set custom font sizes or line heights, and use only`var(--font-weight-normal)` and `var(--font-weight-medium)`. Use `.tabular-nums` on changing numbers.-- Use at most one concise visible heading (`h1`–`h3`) for a self-contained- chart; do not restate the prompt.+- Use at most one concise heading (`h1`–`h3`) per chart; do not restate the+ prompt.## Composition@@ -121,8 +122,8 @@ Choose the smallest composition that fits.- **Explainer or simulation:** compact controls, one dominant visual, at mostone single-line selected-state detail. For step-throughs, add only stepcontrols and update one current visual.-- **Graphs and plots:** use D3 for data-rich Cartesian or statistical plots- and handwritten SVG for simple, directly labeled values.+- **Graphs and plots:** D3 with `viz` for data-rich plots; handwritten SVG+ for a few directly labeled values.- **Dense categorical grid:** one compact selected-item summary, a grid withone readable identifier per cell, one small legend.- **Part-to-whole over time:** one stacked chart of category allocation per@@ -146,15 +147,13 @@ Choose the smallest composition that fits.widths, horizontal overflow, internal scrolling, `position: fixed`, orviewport-height layouts. Use `.table-responsive` only when table columnscannot fit.-- Size every SVG from its actual container: set its `viewBox` from the- container's measured width and redraw with `ResizeObserver`. Never scale- down a fixed-width `viewBox`; at narrow widths reduce ticks and annotations- instead.+- Draw chart SVGs with `viz.chart` (below); never a fixed-width `viewBox`.+ When `compact`, drop annotations.## Utility classes-Let the utilities own geometry, appearance, and interaction. Never restyle-them: no custom sizes, spacing, borders, radii, shadows, or colors.+Let the utilities own geometry, appearance, and interaction; never restyle+them.- **Surfaces:** `.card` is the only card-like surface — use it for a necessarynumeric summary, a selected-item summary, or a bounded interactive field.@@ -189,25 +188,42 @@ them: no custom sizes, spacing, borders, radii, shadows, or colors.## Charts-- Give every axis a title with quantity and units, reserve at least 64px for- the y axis, and label important values directly. Add a legend only when- series cannot be labeled directly.-- Derive padded domains from all observations (`d3.extent`); never hard-code- them. Keep marks inside the plot frame.-- After drawing, keep tick, axis, and value labels from overlapping: leave- about 4px between labels, anchor edge labels inward, and drop optional- annotations first. At 360px show at most four x ticks.-- Use one tooltip per chart, attached to real marks with `data-tooltip`- (label, value, units). Give isolated marks hit targets at least 32px across.-- Animate transitions between chart states, not the initial appearance; never- loop motion, and honor `prefers-reduced-motion`.-- Scope SVG styles to the chart's class.+Preloaded `viz` helpers own sizing, redraw, axes, ticks, legends, tooltips,+and label overlap; never write that code yourself. For a standard chart,+describe it with `viz.render` instead of drawing it:++```js+const c = viz.render("sales", { mark: "line", data, label: "Sales by month",+ x: { field: "month", title: "Month" }, y: { field: "sales", title: "Sales (k)" },+ color: "region" });+slider.oninput = () => c.update({ data: filter(slider.value) });+```++- `mark`: `bar` (horizontal when `y` is categorical; `stack: true`),+ `line`, `area` (stacks with `color`), `point` (`size`, `trend: true`+ regression line), `heatmap` (`x`, `y`, `value`), `arc` (donut: `theta`,+ `color`). Channels: a field name or `{ field, title, format, domain }`;+ types are inferred (numbers, ISO dates, categories). Optional `tooltip: (d) => text`, `height`.+- `viz.regression(data, x, y)` → `{ slope, intercept, r }`.++For custom visuals use `viz.chart(el, ({ svg, width, height, compact }) => {...}, { label })`,+which redraws an emptied, container-sized SVG on width or theme change+(and on `redraw()`); inside it `viz.plot(svg, width, height)` →+`{ g, innerWidth, innerHeight }`, `viz.axes(g, { x, y, innerWidth, innerHeight, xLabel, yLabel })`,+`viz.extent(data, accessor, { zero })`, `viz.series(i)`, `viz.duration(ms)`,+`viz.pruneOverlaps(labels)`.++- Title axes with quantity and units.+- Custom marks get tooltips via `data-tooltip`; isolated marks need 32px+ hit targets.+- Animate only state transitions, with `viz.duration`; never loop motion.+- Scope custom SVG styles to the chart's class.## Accessibility- Use semantic HTML, keyboard-accessible controls, and concise labels.-- Give every chart, SVG, and canvas a screen-reader summary (`<title>` /- `<desc>`, `aria-label`, or an `.sr-only` description).+- Give every chart (`viz.chart` `label`), SVG, and canvas a screen-reader+ summary (`aria-label` or an `.sr-only` description).- Use `aria-live="polite"` for dynamic results and `role="alert"` forvalidation errors; do not announce every hover or frame.- Keep essential content and actions available without hover, and keepdiff --git a/apps/desktop/test/gen-ui-file-safety.test.mjs b/apps/desktop/test/gen-ui-file-safety.test.mjsindex 6eb368c15..719ff5ea3 100644--- a/apps/desktop/test/gen-ui-file-safety.test.mjs+++ b/apps/desktop/test/gen-ui-file-safety.test.mjs@@ -29,7 +29,7 @@ test("the protocol asks the native Host for identity only and enforces response}));const result = await resolveGenUiRequest({method: "GET", url: "pi-genui://session/session/chart.html", readFragment,- loadKit: async () => ({ css: "", runtime: "", vendorUrls: new Map(), vendorFiles: new Map() }),+ loadKit: async () => ({ css: "", head: "", runtime: "", vendorUrls: new Map(), vendorFiles: new Map() }),});assert.equal(result.ok, true);assert.match(result.document, /<p>chart<\/p>/);diff --git a/apps/desktop/test/gen-ui-protocol.test.mjs b/apps/desktop/test/gen-ui-protocol.test.mjsindex fc0ade160..ed2a84b27 100644--- a/apps/desktop/test/gen-ui-protocol.test.mjs+++ b/apps/desktop/test/gen-ui-protocol.test.mjs@@ -91,14 +91,22 @@ test("shell wraps the fragment between the kit stylesheet/host runtime and the k// No remote script URL survives; bundled libraries load from pi-genui://assets.assert.doesNotMatch(html, /src="https:/);assert.match(html, /src="pi-genui:\/\/assets\/floating-ui-dom-1\.7\.4\.min\.js"/);+ // D3 and the `viz` helpers are preloaded in <head>, D3 first, before the fragment.+ const d3 = html.indexOf('<script src="pi-genui://assets/d3-7.9.0.min.js"></script>');+ const helpers = html.indexOf("window.viz = Object.freeze(");+ assert.ok(d3 > 0 && d3 < helpers && helpers < html.indexOf("</head>"));+ assert.ok(helpers < fragment);});-test("pinned library URLs in the fragment are rewritten to bundled copies; others are left to the CSP", () => {+test("a fragment's pinned D3 tag is dropped (preloaded); other pinned URLs are rewritten; others are left to the CSP", () => {const html = buildGenUiDocument(`<script src="${D3_CDN}"></script><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js"></script>`,{ kit },);- assert.match(html, /<script src="pi-genui:\/\/assets\/d3-7\.9\.0\.min\.js"><\/script>/);+ // Only the <head> preload remains, so the helpers' `d3` global is not replaced.+ assert.equal(html.split("pi-genui://assets/d3-7.9.0.min.js").length - 1, 1);+ assert.ok(html.indexOf("pi-genui://assets/d3-7.9.0.min.js") < html.indexOf("</head>"));+ assert.doesNotMatch(html, /d3@7\.9\.0/);// An unpinned version stays remote and is blocked by script-src.assert.match(html, /d3@7\.8\.0/);});diff --git a/apps/desktop/test/gen-ui-runtime.test.mjs b/apps/desktop/test/gen-ui-runtime.test.mjsindex 0e9927452..3223acdcb 100644--- a/apps/desktop/test/gen-ui-runtime.test.mjs+++ b/apps/desktop/test/gen-ui-runtime.test.mjs@@ -61,7 +61,7 @@ test("the error shell reports a code and never echoes caller text", async () =>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: "", runtime: "", vendorUrls: new Map() } });+ 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 READY = "pi-genui:ready"/);assert.match(head, /parent\.postMessage\(\{ type: READY \}, "\*"\)/);diff --git a/apps/desktop/test/visualize-skill.test.mjs b/apps/desktop/test/visualize-skill.test.mjsindex 25d04bb36..966ded267 100644--- a/apps/desktop/test/visualize-skill.test.mjs+++ b/apps/desktop/test/visualize-skill.test.mjs@@ -33,6 +33,10 @@ test("the skill only names tokens, classes, and libraries the bundled kit providconst css = readFileSync(join(desktopRoot, "resources/gen-ui/visualize.css"), "utf8");const kit = readFileSync(join(desktopRoot, "resources/gen-ui/visualize-kit.html"), "utf8");const manifest = JSON.parse(readFileSync(join(desktopRoot, "resources/gen-ui/vendor/manifest.json"), "utf8"));+ const helpers = readFileSync(join(desktopRoot, "resources/gen-ui/visualize-helpers.js"), "utf8");+ const exported = new Set(+ helpers.match(/window\.viz = Object\.freeze\(\{([^}]*)\}\)/)?.[1].split(",").map((name) => name.trim()),+ );// Theme tokens the skill tells the model to use are defined by the stylesheet.const tokens = new Set(body.match(/`--[a-z0-9-]+`/g)?.map((token) => token.slice(1, -1)));assert.ok(tokens.size > 20);@@ -47,11 +51,16 @@ test("the skill only names tokens, classes, and libraries the bundled kit provid// Tabs and tooltips are wired by the kit runtime.assert.match(kit, /pi-desktop-visualization-tabs/);assert.match(kit, /closest\("\[data-tooltip\]"\)/);- // Every library URL in the skill is a bundled, pinned one.+ // Every library URL the skill still names is a bundled, pinned one; D3 is+ // preloaded by the kit, so the skill must not ask for a script tag.const bundled = new Set(manifest.resources.map((resource) => resource.url));const urls = body.match(/https:\/\/[^\s"'`<>]+/g) ?? [];- assert.ok(urls.length > 0);for (const url of urls) assert.ok(bundled.has(url), url);+ assert.doesNotMatch(body, /<script src=/);+ // Every `viz.*` helper the skill names exists in the preloaded helpers.+ const helperNames = new Set(body.match(/viz\.[a-zA-Z]+/g)?.map((name) => name.slice(4)));+ assert.ok(helperNames.size >= 6);+ for (const name of helperNames) assert.ok(exported.has(name), `viz.${name}`);// Host APIs from the upstream kit that PI-Desktop does not provide.assert.doesNotMatch(body, /window\.zcode|widgetState|sendFollowUpMessage|openExternal|Tweak|lucide|viz-carousel|render\.py/);});diff --git a/docs/adr/gen-ui-inline-visualization.md b/docs/adr/gen-ui-inline-visualization.mdindex 4138ad452..1ad2cee6d 100644--- a/docs/adr/gen-ui-inline-visualization.md+++ b/docs/adr/gen-ui-inline-visualization.md@@ -125,8 +125,14 @@ state is only a fallback for older messages.(`resources/gen-ui/visualize.css`, which defines the agent-facing tokenssuch as `--foreground` and `--viz-series-1` from MCP Apps-style`--color-*` host variables), a small host runtime that reports content- height and applies theme updates, the fragment, and then the kit runtime- (tooltips and tabs). Bundled libraries (D3 7.9.0, Floating UI 1.7.x) are+ height and applies theme updates, the preloaded chart layer (bundled D3+ 7.9.0 and the `viz` helpers in `resources/gen-ui/visualize-helpers.js`,+ which own container sizing, resize and theme redraw, axes, and label+ overlap), the fragment, and then the kit runtime (tooltips and tabs).+ Preloading keeps that boilerplate out of every model-written fragment, so+ fragments are shorter and faster to generate; a fragment's own pinned D3+ tag (written under the earlier skill) is dropped so it cannot replace the+ `d3` global. Bundled libraries (D3 7.9.0, Floating UI 1.7.x) arereferenced by their pinned CDN URLs; the shell rewrites exactly those URLsto `pi-genui://assets/<file>`, which serves only files listed in`resources/gen-ui/vendor/manifest.json`. The response carries the CSP and a deny-alldiff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 4809010b8..e6f62998f 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,3 +1,9 @@# Unreleased changes-No unreleased changes. See the in-app changelog for version 0.21.0.+- Generate inline visualizations faster. The visualization shell now preloads+ the bundled D3 and a `viz` chart helper layer (container sizing, resize and+ theme redraw, axes, tick overlap, legends, and a declarative `viz.render`+ 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.diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 133457018..4e1a31564 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -327,7 +327,9 @@ visualization lives as long as its session:suffix and never sends the absolute path to Main. Host Core reads only regularnon-symlink fragments up to 2 MB using pinned native directory capabilities.Main validates the private byte response, rejects full documents, and wraps- the fragment in a host shell with a strict CSP.+ 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.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 relativediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 37b6f89c4..21db690c8 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -18714,7 +18714,8 @@ host-created files. The full app's file-preview viewer is covered separately.card's original inline control state remains unchanged.- 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, focus/guest Escape,+ including real protocol responses, bundled assets, the preloaded `viz`+ helpers (`viz.chart` sizing and a `viz.render` chart), 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.mdindex 762724b4b..87d12018e 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@@ -248,7 +248,8 @@ Electron 主要低于 `<data_dir>/scratch/<sessionId>/pasted/` 之前的回合完成后渲染为内联卡片。渲染层由路径后缀推导出`pi-genui://session/<sessionId>/<file>`,从不把绝对路径发给 Main。Main 只提供当前数据目录下不超过 2 MB 的普通非符号链接片段,拒绝完整文档,并把片段包进带严格 CSP- (无网络、子框架、表单)的宿主外壳;框架为 `sandbox="allow-scripts"`。+ (无网络、子框架、表单)的宿主外壳;框架为 `sandbox="allow-scripts"`。外壳在片段+ 之前预加载内置 D3 和 `viz` 图表辅助函数,并移除片段自带的固定版本 D3 标签。## 4c。消息拥有的审核快照和回滚diff --git a/scripts/e2e/gen-ui-main.mjs b/scripts/e2e/gen-ui-main.mjsindex 8735d7f04..82df3b839 100644--- a/scripts/e2e/gen-ui-main.mjs+++ b/scripts/e2e/gen-ui-main.mjs@@ -85,6 +85,20 @@ async function run() {await host(`window.genUiProbe.mount(${JSON.stringify(message(0))});window.genUiProbe.waitLoaded(1)`);const inline = guests()[0];assert.equal(await inline.executeJavaScript("d3.version"), "7.9.0");+ // The `viz` helpers are preloaded and draw a container-sized chart.+ assert.equal(+ await inline.executeJavaScript(+ '(async()=>{const el=document.createElement("div");el.style.width="300px";document.body.append(el);viz.chart(el,({svg,width})=>svg.append("rect").attr("width",width),{label:"probe"});await Promise.resolve();return el.querySelector("svg").getAttribute("viewBox")})()',+ ),+ "0 0 300 240",+ );+ // A declarative `viz.render` spec draws marks, axes, and a legend.+ assert.equal(+ await inline.executeJavaScript(+ '(async()=>{const el=document.createElement("div");el.style.width="400px";document.body.append(el);viz.render(el,{mark:"bar",data:[{k:"a",v:1,s:"x"},{k:"b",v:2,s:"y"}],x:"k",y:"v",color:"s",label:"probe"});await Promise.resolve();return [el.querySelectorAll("rect").length,el.querySelectorAll(".viz-axis").length>0,el.querySelectorAll(".viz-legend-item").length].join()})()',+ ),+ "2,true,2",+ );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");