Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): restore the kit's #widget layout for inline visualizations
zszz3b33c05eea47e
diff --git a/apps/desktop/electron/main/gen-ui-document.ts b/apps/desktop/electron/main/gen-ui-document.tsindex cd5ca19a2..3e4ae8186 100644--- a/apps/desktop/electron/main/gen-ui-document.ts+++ b/apps/desktop/electron/main/gen-ui-document.ts@@ -270,7 +270,8 @@ function themeStyle(themeVars: Record<string, string> | undefined): string {/*** Wrap a validated fragment in the host shell: kit stylesheet and host runtime- * in `<head>`, then the fragment, then the kit runtime so its tooltip and tab+ * in `<head>`, then the fragment inside the kit's `#widget` container (which+ * spaces its top-level blocks), then the kit runtime so its tooltip and tab* scripts see the fragment's markup. Pinned library URLs in the fragment* are rewritten to bundled copies.*/@@ -279,7 +280,7 @@ export function buildGenUiDocument(fragment: string, options: GenUiDocumentOptioreturn shell(`${kit.css}\n${SHELL_CSS}`,`${themeStyle(options.themeVars)}<script>${RUNTIME_SCRIPT}</script>${kit.head}`,- `${rewriteGenUiVendorUrls(stripPreloadedGenUiScripts(fragment), kit.vendorUrls)}\n${kit.runtime}`,+ `<div id="widget">\n${rewriteGenUiVendorUrls(stripPreloadedGenUiScripts(fragment), kit.vendorUrls)}\n</div>\n${kit.runtime}`,);}diff --git a/apps/desktop/resources/gen-ui/NOTICE.md b/apps/desktop/resources/gen-ui/NOTICE.mdindex d1288afc7..abf261325 100644--- a/apps/desktop/resources/gen-ui/NOTICE.md+++ b/apps/desktop/resources/gen-ui/NOTICE.md@@ -29,6 +29,11 @@ Changes made for 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.+- The shell writes the fragment into the kit's `#widget` container, as the+ upstream host does. `#widget` stacks top-level blocks with a 12px top+ margin instead of a flex column, and the upstream reset of its direct+ children (`margin`, `padding`, `border`, `!important`) was dropped so+ fragment styling is kept.- 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.css b/apps/desktop/resources/gen-ui/visualize.cssindex 408fc589e..bd33f20e0 100644--- a/apps/desktop/resources/gen-ui/visualize.css+++ b/apps/desktop/resources/gen-ui/visualize.css@@ -301,37 +301,26 @@ code:not(pre code) {white-space: nowrap;}+/*+ * The shell writes the fragment into #widget. Its top-level blocks are+ * stacked 12px apart with a top margin rather than the upstream kit's flex+ * column, so a top-level inline control or image keeps flowing as it did+ * and is not stretched. Element-level specificity, placed after the heading+ * and paragraph margin reset so it beats that, while any margin the fragment+ * sets still wins. A block whose own layout is flex or grid is unaffected.+ */#widget {- display: flex;- flex-direction: column;- gap: 12px;+ display: flow-root;width: 100%;padding: 0;background: transparent !important;}-/*- * Vertical rhythm. PI-Desktop writes the fragment straight into the body (there- * is no #widget wrapper), and the skill asks for one root element with a unique- * id, so neither level spaced its blocks: headings, controls, charts, legends,- * and captions touched. Stack the blocks of the body and of a sole root container- * with the #widget gap. Zero specificity, so a fragment that lays out its own- * root (any display or gap) keeps it. Only a container with a block child is- * stacked, so a root of inline controls keeps flowing inline. Scripts, styles,- * and out-of-flow nodes such as the tooltip are not flex items and take no gap.- */-:where(- :is(- body,- body:not(:has(> :not(script, style, template, .tooltip) ~ :not(script, style, template, .tooltip)))- > :is(div, section, article, main, form)- ):has(- > :is(div, p, section, article, header, footer, nav, figure, form, fieldset, details, table, ul, ol, dl, pre, blockquote, hr, h1, h2, h3, h4, h5, h6, svg, canvas)- )+:where(#widget)+ > :is(div, p, section, article, header, footer, nav, figure, form, fieldset, details, table, ul, ol, dl, pre, blockquote, hr, h1, h2, h3, h4, h5, h6, svg, canvas):where(+ :not(script, style, template) ~ *) {- display: flex;- flex-direction: column;- gap: 12px;+ margin-block-start: 12px;}.card {@@ -356,17 +345,6 @@ code:not(pre code) {background: var(--background);}-#widget > :not(.card, .widget, .progress) {- width: 100% !important;- max-width: none !important;- margin: 0 !important;- padding: 0 !important;- border: 0 !important;- border-radius: 0 !important;- background: transparent !important;- box-shadow: none !important;-}-.tooltip {position: fixed;z-index: 50;@@ -1031,9 +1009,6 @@ svg {height: auto;}-#widget > svg {- width: 100%;-}/* Axes drawn by `viz.axes` (visualize-helpers.js). */.viz-axis {diff --git a/apps/desktop/resources/skills/visualize.md b/apps/desktop/resources/skills/visualize.mdindex 45f44f1b3..11cfdd1a7 100644--- a/apps/desktop/resources/skills/visualize.md+++ b/apps/desktop/resources/skills/visualize.md@@ -49,8 +49,10 @@ Read this file in full before authoring. Copy into every compaction summary:runtime.- Write literal markup with real newlines, never an escaped string(`<div class=\"card\">`, `\n`).-- Give the fragment root a unique ID and select it with- `document.getElementById(...)`; never derive it from `document.currentScript`.+- Write the blocks (heading, controls, visual, legend, notes) as top-level+ elements; the host stacks them 12px apart. Do not wrap the whole fragment in+ one container. Give scripted elements unique IDs and select them with+ `document.getElementById(...)`; never use `document.currentScript`.- Keep it under 1 MB: aggregate, bin, or downsample large datasets.- Write the file once, complete. Before writing, check that the script hasno undefined identifiers, every queried element exists, and the primary@@ -134,7 +136,7 @@ Choose the smallest composition that fits.form.- **UI mockups:** match the product's own chrome, colors, and type. Do not usethe visualization utility classes or variables inside the mocked product;- define root-scoped product styles with `light-dark(<light>, <dark>)`. Give+ scope product styles to the mockup with `light-dark(<light>, <dark>)`. Giveproduct surfaces opaque backgrounds and keep the surrounding areatransparent. Show realistic states, not filler dashboards.diff --git a/apps/desktop/test/gen-ui-protocol.test.mjs b/apps/desktop/test/gen-ui-protocol.test.mjsindex 6304f6135..b0c4f1406 100644--- a/apps/desktop/test/gen-ui-protocol.test.mjs+++ b/apps/desktop/test/gen-ui-protocol.test.mjs@@ -87,6 +87,11 @@ test("shell wraps the fragment between the kit stylesheet/host runtime and the kassert.ok(fragment > html.indexOf("<body>"));assert.ok(html.indexOf("<body>") > html.indexOf("pi-genui:size"));assert.ok(html.indexOf('id="pi-desktop-visualization-tabs"') > fragment);+ // The fragment sits inside the kit's #widget container, which spaces its+ // top-level blocks; the kit runtime stays outside it.+ const widget = html.indexOf('<div id="widget">');+ assert.ok(widget > html.indexOf("<body>") && widget < fragment);+ assert.ok(html.indexOf("</div>", fragment + '<div id="viz">hello</div>'.length) < html.indexOf('id="pi-desktop-visualization-tabs"'));assert.doesNotMatch(html, /__INLINE_VISUALIZATION_FRAGMENT__/);assert.doesNotMatch(html, /zcode-visualization|window\.zcode/);// No remote script URL survives; bundled libraries load from pi-genui://assets.diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 8343605cf..fafb0d4da 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -27,9 +27,9 @@card now says so and shows the error instead of staying blank, and themodel's write result flags syntax errors and missing chart containers so itcan fix them with one edit.-- Fixed cramped inline visualizations. A visualization's title, controls,- chart, legend, and captions no longer touch: top-level blocks, and the- blocks inside a single wrapping root element (the shape most visualizations- use), are now spaced 12px apart. Visualizations that lay out their own root- keep their layout, and existing cards pick up the spacing when they next- load.+- Fixed cramped inline visualizations. The visualization shell now places a+ fragment in the kit's `#widget` container, which spaces its top-level blocks+ 12px apart, and the `visualize` skill asks for the title, controls, chart,+ legend, and captions as top-level blocks instead of one wrapping element.+ Inline controls, block styling, and roots that lay themselves out keep their+ geometry; cards written earlier inside one wrapping element render as before.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 94a2840e8..4bbce09a4 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -19304,7 +19304,9 @@ their separate platform acceptance.including real protocol responses, bundled assets, the preloaded `viz`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, block spacing inside a single wrapping root, focus/guest Escape,+ card, the fragment inside the kit's `#widget` container with its top-level+ blocks spaced while inline controls, block styling, wrapped roots, and flex,+ grid, and column roots keep their geometry, 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/scripts/e2e/gen-ui-main.mjs b/scripts/e2e/gen-ui-main.mjsindex 22181278a..65dcc73f4 100644--- a/scripts/e2e/gen-ui-main.mjs+++ b/scripts/e2e/gen-ui-main.mjs@@ -48,10 +48,24 @@ async function run() {"<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>`);- // The usual model shape: one id'd root wrapping title, controls, stage, and- // caption, with the script beside it.- await writeFile(join(sessionDir, "stack.html"),- `<div id="stack-root"><h3>Title</h3><div class="viz-controls"><button class="btn" type="button">Next</button></div><div style="height:40px"></div><p>Caption</p></div><script>parent.postMessage({type:'fixture:loaded'},'*')</script>`);+ // Layout shapes model fragments use; only plain block flow gets spaced.+ const loaded = "<script>parent.postMessage({type:'fixture:loaded'},'*')</script>";+ const layouts = {+ // The shape the skill asks for: top-level blocks, no wrapper.+ flat: `<h3 id="a">Title</h3><div id="b" class="viz-controls"><button class="btn" type="button" id="b1">One</button><button class="btn" type="button" id="b2">Two</button></div><div id="c" style="height:40px"></div><p id="d">Caption</p>`,+ // Top-level inline controls keep flowing on their line, unstretched.+ inline: `<button class="btn" type="button" id="b1">One</button><button class="btn" type="button" id="b2">Two</button><div id="c" style="height:40px"></div><p id="d">Caption</p>`,+ // A top-level block keeps its own padding and background.+ styled: `<div id="a" style="padding:10px;background:rgb(1, 2, 3)">Stage</div>`,+ // Fragments written before: one wrapping root keeps its exact geometry.+ wrapped: `<div id="r"><h3 id="a">Title</h3><div id="b" style="height:40px"></div><p id="c">Caption</p></div>`,+ // Roots that lay themselves out keep their geometry.+ flexRow: `<div id="r" style="display:flex;gap:8px"><div id="a" style="width:100px;height:40px">A</div><div id="b" style="width:100px;height:40px">B</div></div>`,+ flexColumn: `<div id="r" style="display:flex;flex-direction:column;gap:5px"><div id="a" style="height:40px">A</div><div id="b" style="height:40px">B</div></div>`,+ grid: `<div id="r" style="display:grid;grid-template-columns:100px 100px;gap:4px"><div id="a" style="height:40px">A</div><div id="b" style="height:40px">B</div></div>`,+ };++ for (const [name, markup] of Object.entries(layouts)) await writeFile(join(sessionDir, `layout-${name}.html`), markup + loaded);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" });@@ -180,19 +194,39 @@ async function run() {assert.equal(await host('document.querySelectorAll(".gen-ui-card iframe").length'), 1);checks.push("fragment script errors show in the card");- // Blocks inside a single wrapping root used to touch (no gap at either- // level); the kit now stacks them, and a root that sets its own layout- // keeps it.- const stack = message(0).replace("chart0.html", "stack.html");- await host(`window.genUiProbe.mount(${JSON.stringify(stack)});window.genUiProbe.waitLoaded(1)`);- const stackGuest = guests()[0];- const gaps = 'new Promise((resolve)=>requestAnimationFrame(()=>{const boxes=Array.from(document.getElementById("stack-root").children,(el)=>el.getBoundingClientRect());resolve(boxes.slice(1).map((box,index)=>Math.round(box.top-boxes[index].bottom)))}))';- const stacked = await stackGuest.executeJavaScript(gaps);- assert.equal(stacked.length, 3);- for (const gap of stacked) assert.ok(gap >= 8, `blocks in a wrapping root are spaced: ${stacked}`);- const own = await stackGuest.executeJavaScript(`document.getElementById("stack-root").style.display="block";${gaps}`);- assert.deepEqual(own, [0, 0, 0]);- checks.push("blocks in a wrapping root are spaced; fragment layout wins");+ // The shell had no #widget container, so the kit's block spacing never+ // applied and blocks touched. Top-level blocks are now spaced; inline+ // controls, block styling, and every root that lays itself out keep their+ // geometry.+ const layoutBoxes = async (name, ids) => {+ const at = message(0).replace("chart0.html", `layout-${name}.html`);+ await host(`window.genUiProbe.mount(${JSON.stringify(at)});window.genUiProbe.waitLoaded(1)`);+ return guests()[0].executeJavaScript(`new Promise((resolve) => requestAnimationFrame(() => resolve(${JSON.stringify(ids)}.map((id) => {+ const el = document.getElementById(id);+ const box = el.getBoundingClientRect();+ return { top: Math.round(box.top), bottom: Math.round(box.bottom), left: Math.round(box.left), width: Math.round(box.width), padding: getComputedStyle(el).paddingTop, inWidget: document.getElementById("widget").contains(el) };+ }))))`);+ };+ const spaced = (boxes) => boxes.slice(1).map((box, index) => box.top - boxes[index].bottom);+ const flat = await layoutBoxes("flat", ["a", "b", "c", "d", "b1", "b2"]);+ assert.ok(flat.every((box) => box.inWidget), "the fragment renders inside #widget");+ for (const gap of spaced(flat.slice(0, 4))) assert.ok(gap >= 8, `top-level blocks are spaced: ${spaced(flat.slice(0, 4))}`);+ assert.equal(flat[4].top, flat[5].top, "controls in a row stay on one line");+ const inlineRow = await layoutBoxes("inline", ["b1", "b2", "c", "d"]);+ assert.equal(inlineRow[0].top, inlineRow[1].top, "top-level inline controls stay on one line");+ assert.ok(inlineRow[0].width < 300, `top-level inline controls are not stretched: ${inlineRow[0].width}`);+ assert.ok(inlineRow[3].top - inlineRow[2].bottom >= 8, `blocks after inline controls are spaced: ${JSON.stringify(inlineRow)}`);+ const styled = await layoutBoxes("styled", ["a"]);+ assert.equal(styled[0].padding, "10px", "a top-level block keeps its own padding");+ const wrapped = await layoutBoxes("wrapped", ["a", "b", "c"]);+ assert.deepEqual(spaced(wrapped), [0, 0], "a wrapped root from an earlier fragment keeps its geometry");+ const flexRow = await layoutBoxes("flexRow", ["a", "b"]);+ assert.deepEqual([flexRow[1].left - flexRow[0].left, flexRow[1].top - flexRow[0].top], [108, 0], "default-row flex root keeps its row");+ const flexColumn = await layoutBoxes("flexColumn", ["a", "b"]);+ assert.equal(flexColumn[1].top - flexColumn[0].bottom, 5, "flex column root keeps its own gap");+ const grid = await layoutBoxes("grid", ["a", "b"]);+ assert.deepEqual([grid[1].left - grid[0].left, grid[1].top - grid[0].top], [104, 0], "grid root keeps its columns");+ checks.push("top-level blocks are spaced in #widget; inline, styled, wrapped, flex, and grid layouts keep their geometry");window.setContentSize(900, 2600);const all = Array.from({ length: 8 }, (_, index) => message(index)).join("\n");