Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Merge inline rendered views into release/v0.0.297

Rach Pradhan722e28287a9c
diff --cc apps/native/components/site/ChatBubbles.tsx
index 364cb0fe,c90b11f5..4af0323a
--- a/apps/native/components/site/ChatBubbles.tsx
+++ b/apps/native/components/site/ChatBubbles.tsx
@@@ -5,8 -5,8 +5,9 @@@ import Markdown from "@/components/prim
import ThinkingState from "@/components/primitives/ThinkingState";
import ToolChips, { type LiveDiff } from "@/components/primitives/ToolChips";
import TurnActivity from "./TurnActivity";
+import HtmlArtifact from "./HtmlArtifact";
import McpAppResult from "./McpAppResult";
+ import SnapshotView from "./SnapshotView";
import { pinScrollerTail } from "@/lib/follow-scroll";
import { turnBlocks, type AssistantTurn } from "@/lib/acp";
import { createSmoothStream } from "@/lib/smooth-stream";
@@@ -55,8 -55,8 +56,9 @@@ const ToolGroup = memo(function ToolGro
path: tool.path, status: tool.status, startedAt: tool.startedAt, elapsedMs: tool.elapsedMs,
}));
return <><ToolChips rows={rows} diffs={diffs} onOpenPath={onOpenPath} />
+ {tools.filter(tool=>tool.htmlArtifactId).map(tool=><HtmlArtifact key={tool.id} id={tool.htmlArtifactId!} />)}
- {tools.filter(tool=>tool.mcpAppId).map(tool=><McpAppResult key={tool.id} id={tool.mcpAppId!} />)}</>;
+ {tools.filter(tool=>tool.mcpAppId).map(tool=><McpAppResult key={tool.id} id={tool.mcpAppId!} />)}
+ {tools.filter(tool=>tool.viewSnapshotId).map(tool=><SnapshotView key={`view-${tool.id}`} kind="view" id={tool.viewSnapshotId!} />)}</>;
}, (previous, next) => previous.diffs === next.diffs && previous.onOpenPath === next.onOpenPath &&
previous.tools.length === next.tools.length && previous.tools.every((tool, index) => tool === next.tools[index]));
diff --cc apps/native/components/site/SnapshotView.tsx
index 00000000,99fa4164..eced4b82
mode 000000,100644..100644
--- a/apps/native/components/site/SnapshotView.tsx
+++ b/apps/native/components/site/SnapshotView.tsx
@@@ -1,0 -1,41 +1,48 @@@
+ "use client";
+
-import {useState} from "react";
++import {useState, useEffect, useRef} from "react";
+ import {validAppId} from "@/lib/mcp-apps";
+
+ /** One saved HTML snapshot shown inside the transcript. The two kinds differ
+ * only in where the bytes came from and what they may do; neither is ever
+ * injected into the app's own document — each is framed and served by its own
+ * route, whose response policy is the thing that contains it. */
+ const KINDS = {
+ "mcp-app": {
+ label: "Interactive MCP result",
+ title: "Interactive MCP tool result",
+ src: (id: string) => `/api/mcp-apps?id=${id}`,
+ sandbox: "allow-scripts allow-popups allow-popups-to-escape-sandbox",
+ allow: "clipboard-write",
+ },
+ view: {
+ label: "Rendered view",
+ title: "HTML view drawn for this turn",
+ src: (id: string) => `/api/views?id=${id}`,
+ // No popups and no escaping the frame: a view is for looking at.
+ sandbox: "allow-scripts",
+ allow: undefined,
+ },
+ } as const;
+
+ export type SnapshotKind = keyof typeof KINDS;
+
+ export default function SnapshotView({kind, id}: {kind: SnapshotKind; id: string}) {
+ const [visible, setVisible] = useState(true);
++ const host = useRef<HTMLElement>(null);
++ const [nearby, setNearby] = useState(false);
++ useEffect(() => {
++ if (kind !== 'view' || !host.current) return;
++ const observer = new IntersectionObserver(([entry]) => setNearby(entry.isIntersecting), {rootMargin:'80px'});
++ observer.observe(host.current); return () => observer.disconnect();
++ }, [kind]);
+ if (!validAppId(id)) return null;
+ const {label, title, src, sandbox, allow} = KINDS[kind];
- return <section className="my-3 overflow-hidden rounded-lg border border-ink/10" aria-label={label}>
++ return <section ref={host} className="my-3 overflow-hidden rounded-lg border border-ink/10" aria-label={label}>
+ <div className="flex items-center justify-between px-3 py-2 text-xs text-ink-3">
+ <span>{label}</span><button type="button" onClick={()=>setVisible(!visible)} aria-expanded={visible}>{visible ? "Close view" : "Open view"}</button>
+ </div>
- {visible && <iframe title={title} src={src(id)} sandbox={sandbox} allow={allow}
- referrerPolicy="no-referrer" className="block h-[620px] w-full border-0" />}
++ {visible && <div className="h-[620px]">{(kind !== "view" || nearby) && <iframe title={title} src={src(id)} sandbox={sandbox} allow={allow}
++ referrerPolicy="no-referrer" className="block h-[620px] w-full border-0" />}</div>}
+ </section>;
+ }
diff --cc apps/native/e2e/views.pw.ts
index 00000000,b4d76847..350f399f
mode 000000,100644..100644
--- a/apps/native/e2e/views.pw.ts
+++ b/apps/native/e2e/views.pw.ts
@@@ -1,0 -1,69 +1,74 @@@
+ import {test,expect} from "@playwright/test";
+ import {mkdir,writeFile,unlink} from "node:fs/promises";
+ import {randomBytes} from "node:crypto";
+ import {homedir} from "node:os";
+ import path from "node:path";
+
+ const ids:string[]=[];
+ const root=path.join(homedir(),".graff","views");
+ /** What the model would hand `render_html`: one self-contained page that tries
+ * all three things a page is not allowed to do from this fixture — load from
+ * the network, reach the app's DOM, and run its own inline script (which it
+ * IS allowed to do, so the check can tell "contained" from "not rendered"). */
+ const drawn=`<!doctype html><meta charset="utf-8"><style>h1{color:#059669}</style><h1>Revision burn-down</h1>
+ <p id="script"></p><p id="fetch"></p><p id="escape"></p>
+ <script>
+ document.querySelector('#script').textContent='inline script ran';
+ fetch('https://blocked.example/leak').then(r=>{document.querySelector('#fetch').textContent='network reached '+r.status}).catch(()=>{document.querySelector('#fetch').textContent='fetch blocked'});
+ try{top.document.body.innerHTML='escaped';document.querySelector('#escape').textContent='escaped'}catch(e){document.querySelector('#escape').textContent='isolated'}
+ </script>`;
+ async function snapshot(html:string){
+ const id=randomBytes(16).toString('hex');
+ await mkdir(root,{recursive:true});
+ await writeFile(path.join(root,`${id}.html`),html,{mode:0o600});
+ ids.push(id);return id;
+ }
+ test.afterAll(async()=>{await Promise.all(ids.map(id=>unlink(path.join(root,`${id}.html`))));});
+
+ test('a model-drawn page renders inline in a sandbox that cannot reach the app or the network',async({page})=>{
+ let leaks=0;
+ await page.route('https://blocked.example/**',route=>{leaks++;return route.abort();});
+ const id=await snapshot(drawn);
+ await page.goto(`/visual-tests/views?id=${id}`);
+ await expect(page.locator('section[aria-label="Rendered view"]')).toBeVisible();
+ const app=page.frameLocator('iframe');
+ // Rendered, with its own inline script and style — a page, not a screenshot.
+ await expect(app.locator('h1')).toHaveText('Revision burn-down');
+ await expect(app.locator('#script')).toHaveText('inline script ran');
+ // The two things the policy exists for.
+ await expect(app.locator('#fetch')).toHaveText('fetch blocked',{timeout:15000});
+ await expect(app.locator('#escape')).toHaveText('isolated');
+ expect(leaks).toBe(0);
+ await expect(page.locator('h1')).toHaveText('Simulated rendered view');
+ await page.screenshot({path:'/tmp/codegraff-rendered-view.png'});
+ // Closing disposes the frame; reopening restores a live one.
+ await page.getByRole('button',{name:'Close view'}).click();
+ await expect(page.locator('iframe')).toHaveCount(0);
+ await page.getByRole('button',{name:'Open view',exact:true}).click();
+ await expect(app.locator('#script')).toHaveText('inline script ran');
++ // Scrolling a long transcript releases script work, then restores the view.
++ await page.evaluate(() => { document.body.style.paddingBottom = '2200px'; window.scrollTo(0, 2000); });
++ await expect(page.locator('iframe')).toHaveCount(0);
++ await page.evaluate(() => window.scrollTo(0, 0));
++ await expect(app.locator('#script')).toHaveText('inline script ran');
+ });
+
+ test('the view route serves untrusted markup under a containing policy',async({page,request})=>{
+ const id=await snapshot(drawn);
+ const response=await request.get(`/api/views?id=${id}`);
+ expect(response.status()).toBe(200);
+ const headers=response.headers();
+ expect(headers['content-security-policy']).toContain("sandbox allow-scripts");
+ expect(headers['content-security-policy']).toContain("default-src 'none'");
+ expect(headers['content-security-policy']).toContain("connect-src 'none'");
+ expect(headers['content-security-policy']).toContain("frame-ancestors 'self'");
+ expect(headers['x-content-type-options']).toBe('nosniff');
+ // Only opaque ids we wrote, and only from our own origin.
+ expect((await request.get('/api/views?id=../secret')).status()).toBe(400);
+ expect((await request.get(`/api/views?id=${'f'.repeat(32)}`)).status()).toBe(404);
+ expect((await request.get(`/api/views?id=${id}`,{headers:{Origin:'https://evil.example'}})).status()).toBe(403);
+ // A page whose own markup asks for the app's APIs still gets a blank origin.
+ await page.goto(`/visual-tests/views?id=${id}`);
+ await expect(page.frameLocator('iframe').locator('#script')).toHaveText('inline script ran');
+ await expect(page.locator('iframe')).toHaveCount(1);
+ });
diff --cc apps/native/lib/acp.ts
index 2cd92b9d,b37370d7..9a47b750
--- a/apps/native/lib/acp.ts
+++ b/apps/native/lib/acp.ts
@@@ -1,7 -1,6 +1,7 @@@
+import { htmlArtifactId } from "./html-artifacts";
import { boundToolDetail } from "./tool-detail";
import { stripCiteMarkup } from "./cite-markup";
- import { mcpAppId } from "./mcp-apps";
+ import { mcpAppId, viewSnapshotId } from "./mcp-apps";
/** ACP v1 session/update shapes the native harness renders. */
export type AcpContent = { type: "text"; text: string };
@@@ -155,8 -154,7 +155,8 @@@ function upsertTool(turn: AssistantTurn
const idx = turn.tools.findIndex((t) => t.id === id);
const prev = idx >= 0 ? turn.tools[idx] : undefined;
const title = typeof update.title === "string" ? update.title : prev?.chip ?? id;
- const htmlPreview = title === "mcp__codegraff_desktop__create_html" || prev?.htmlArtifactTool;
- const kind = typeof update.kind === "string" ? update.kind : prev ? undefined : "other";
++ const htmlPreview = title === "mcp__codegraff_desktop__create_html" || title === "render_html" || prev?.htmlArtifactTool;
+ const kind = htmlPreview ? "other" : typeof update.kind === "string" ? update.kind : prev ? undefined : "other";
const statusRaw = typeof update.status === "string" ? update.status : prev ? undefined : "pending";
const status: ToolRow["status"] = statusRaw
? statusRaw === "completed"
@@@ -199,8 -197,7 +199,9 @@@
status,
detail: boundToolDetail(detail),
mcpAppId: mcpAppId(contentText) ?? prev?.mcpAppId,
+ htmlArtifactId: htmlArtifactId(contentText) ?? prev?.htmlArtifactId,
+ htmlArtifactTool: !!htmlPreview,
+ viewSnapshotId: viewSnapshotId(contentText) ?? prev?.viewSnapshotId,
path,
startedAt: prev?.startedAt ?? Date.now(),
atChars: prev?.atChars ?? turn.text.length,
diff --cc apps/native/lib/graff-events.ts
index 003f0562,61d938b5..1b2b4014
--- a/apps/native/lib/graff-events.ts
+++ b/apps/native/lib/graff-events.ts
@@@ -1,4 -1,3 +1,5 @@@
++import { viewSnapshotId } from "./mcp-apps";
+import { htmlArtifactId } from "./html-artifacts";
/** Graff `--json` / `graff serve` events that the native harness renders.
* Mirrors `sdk/ts/remote.ts` Event, kept local so the UI does not import
* Node-only SDK code. Unknown types are ignored (forward compatible). */
@@@ -45,8 -44,8 +46,10 @@@ export type ToolIcon = "think" | "write
export type ToolRow = {
mcpAppId?: string;
+ htmlArtifactId?: string;
+ htmlArtifactTool?: boolean;
+ /** A `render_html` page the model drew: rendered inline, like an app result. */
+ viewSnapshotId?: string;
id: string;
name: string;
icon: ToolIcon;
@@@ -212,7 -210,6 +215,7 @@@ function finishTool(turn: AssistantTurn
chip: name,
status: isError ? "error" : "ok",
detail: text ? [{ text: firstLine(text) }] : [],
- htmlArtifactId: htmlArtifactId(text),
++ htmlArtifactId: htmlArtifactId(text), viewSnapshotId: viewSnapshotId(text),
},
],
};
@@@ -222,7 -219,7 +225,7 @@@
? [...prev.detail, { text: firstLine(text), tone: isError ? undefined : undefined }]
: prev.detail;
const tools = turn.tools.slice();
- tools[idx] = { ...prev, status: isError ? "error" : "ok", detail, htmlArtifactId: text ? htmlArtifactId(text) ?? prev.htmlArtifactId : prev.htmlArtifactId };
- tools[idx] = { ...prev, status: isError ? "error" : "ok", detail };
++ tools[idx] = { ...prev, status: isError ? "error" : "ok", detail, htmlArtifactId: text ? htmlArtifactId(text) ?? prev.htmlArtifactId : prev.htmlArtifactId, viewSnapshotId: text ? viewSnapshotId(text) ?? prev.viewSnapshotId : prev.viewSnapshotId };
const diffs = name === "edit_file" || name === "write_file" ? mergeDiff(turn.diffs, prev, text) : turn.diffs;
return { ...turn, tools, diffs };
}
diff --cc apps/native/lib/html-artifacts.test.ts
index d7b7168f,00000000..5ec301da
mode 100644,000000..100644
--- a/apps/native/lib/html-artifacts.test.ts
+++ b/apps/native/lib/html-artifacts.test.ts
@@@ -1,29 -1,0 +1,37 @@@
+import { test, expect } from 'bun:test';
+import { htmlArtifactId } from './html-artifacts';
+import { applyAcpUpdate, emptyTurn } from './acp';
+import { transcriptFromMessages } from './sessions';
+const id='a'.repeat(32), marker=`[HTML preview](graff-html:${id})`;
+test('HTML ids survive live detail bounding and saved transcript projection',()=>{
+ const text=marker+'\n'+'body'.repeat(50000);
+ const turn=applyAcpUpdate(emptyTurn(),{sessionUpdate:'tool_call_update',toolCallId:'t1',title:'mcp__codegraff_desktop__create_html',status:'completed',content:[{type:'content',content:{type:'text',text}}]});
+ expect(turn.tools[0].htmlArtifactId).toBe(id);
+ const saved=transcriptFromMessages([{role:'assistant',tool_calls:[{id:'t1',type:'function',function:{name:'mcp__codegraff_desktop__create_html',arguments:'{}'}}]},{role:'tool',tool_call_id:'t1',content:text}]);
+ const assistant=saved.find(message=>message.role==='assistant');
+ expect(assistant?.role==='assistant' && assistant.turn.tools[0].htmlArtifactId).toBe(id);
+ expect(htmlArtifactId('[HTML preview](https://example.invalid/anything)')).toBeUndefined();
+});
+
+test('ordinary tool-result decoding retains an HTML preview reference', async()=>{
+ const {applyEvent}=await import('./graff-events');
+ const turn=applyEvent(emptyTurn(),{type:'tool_result',name:'mcp__codegraff_desktop__create_html',is_error:false,text:marker});
+ expect(turn.tools[0].htmlArtifactId).toBe(id);
+});
+
+test('HTML preview creation and failure are not workspace file edits',()=>{
+ for (const status of ['completed','failed']) {
+ let turn=applyAcpUpdate(emptyTurn(),{sessionUpdate:'tool_call',toolCallId:'html',title:'mcp__codegraff_desktop__create_html',kind:'edit',status:'pending'});
+ turn=applyAcpUpdate(turn,{sessionUpdate:'tool_call_update',toolCallId:'html',kind:'edit',status,content:[{type:'content',content:{type:'text',text:status==='completed'?marker:'Invalid HTML'}}]});
+ expect(turn.diffs).toHaveLength(0);
+ expect(turn.tools[0].icon).toBe('think');
+ }
+});
++
++ test('render_html survives live and saved projection without inventing a workspace edit', () => {
++ const text=`[Rendered view](/home/test/.graff/views/${id}.html)`;
++ const turn=applyAcpUpdate(emptyTurn(),{sessionUpdate:'tool_call_update',toolCallId:'v1',title:'render_html',kind:'edit',status:'completed',content:[{type:'content',content:{type:'text',text}}]});
++ expect(turn.tools[0].viewSnapshotId).toBe(id); expect(turn.diffs).toEqual([]);
++ const saved=transcriptFromMessages([{role:'assistant',tool_calls:[{id:'v1',type:'function',function:{name:'render_html',arguments:'{}'}}]},{role:'tool',tool_call_id:'v1',content:text}]);
++ expect(saved[0].role==='assistant' && saved[0].turn.tools[0].viewSnapshotId).toBe(id);
++ });
diff --cc apps/native/lib/sessions.ts
index 8de95d8b,85d5c83c..94304d2d
--- a/apps/native/lib/sessions.ts
+++ b/apps/native/lib/sessions.ts
@@@ -1,4 -1,3 +1,5 @@@
++import { viewSnapshotId } from "./mcp-apps";
+import { htmlArtifactId } from "./html-artifacts";
import { withoutGuiSkillContext } from "./gui-skills";
import {
chipFor,
@@@ -305,7 -304,7 +306,7 @@@ export function transcriptFromMessages(
const failed = /^(error|failed|denied)\b/i.test(text);
t.tools = t.tools.map((row, i) =>
i === idx
- ? { ...row, htmlArtifactId: htmlArtifactId(text), status: failed ? "error" : "ok", detail: text ? [...row.detail, { text: firstLine(text) }] : row.detail }
- ? { ...row, status: failed ? "error" : "ok", detail: text ? [...row.detail, { text: firstLine(text) }] : row.detail }
++ ? { ...row, htmlArtifactId: htmlArtifactId(text), viewSnapshotId: viewSnapshotId(text), status: failed ? "error" : "ok", detail: text ? [...row.detail, { text: firstLine(text) }] : row.detail }
: row,
);
}
diff --cc apps/native/package.json
index 7085177d,705b1c8b..eefafc98
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@@ -33,6 -31,7 +33,7 @@@
"test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs",
"benchmark:desktop": "bun scripts/benchmark-desktop.mjs",
"test:mcp-apps": "bun test lib/mcp-apps.test.ts && playwright test -c playwright.mcp.config.ts",
- "test:views": "bun test lib/mcp-apps.test.ts && playwright test -c playwright.views.config.ts",
++ "test:views": "bun test lib/mcp-apps.test.ts && bun scripts/test-views.mjs",
"test:focus": "bun scripts/test-desktop-focus.mjs",
"test:tagged": "GRAFF_VISUAL_SUITE=tagged bun scripts/test-visual.mjs",
"test:browser": "GRAFF_VISUAL_SUITE=browser bun scripts/test-visual.mjs",
diff --cc apps/native/scripts/test-views.mjs
index 00000000,00000000..d9434bb5
new file mode 100644
--- /dev/null
+++ b/apps/native/scripts/test-views.mjs
@@@ -1,0 -1,0 +1,13 @@@
++import { mkdtempSync, rmSync } from 'node:fs';
++import { tmpdir } from 'node:os';
++import path from 'node:path';
++import { runDesktopProcess } from './test-electron.mjs';
++
++const home = mkdtempSync(path.join(tmpdir(), 'graff-view-tests-'));
++try {
++ await runDesktopProcess(process.execPath, ['x', 'playwright', 'test', '-c', 'playwright.views.config.ts'], {
++ ...process.env, HOME: home, USERPROFILE: home,
++ });
++} finally {
++ rmSync(home, { recursive: true, force: true });
++}
diff --cc docs/adr/0107-model-drawn-pages-render-in-an-opaque-frame.md
index 00000000,58668a22..a34bc91e
mode 000000,100644..100644
--- a/docs/adr/0107-model-drawn-pages-render-in-an-opaque-frame.md
+++ b/docs/adr/0107-model-drawn-pages-render-in-an-opaque-frame.md
@@@ -1,0 -1,40 +1,48 @@@
-# 0104. Model-drawn pages are private snapshots in an opaque frame
++# 0107. Model-drawn pages are private snapshots in an opaque frame
+
+ Status: accepted 2026-09-11
+
+ ## Context
+
+ A result the model can only *describe* — a layout, a chart, a before/after — is worse than one it can show. The terminal has no room for it, and the desktop transcript renders text, markdown, images, and MCP app results, nothing else.
+
+ MCP Apps already solved the containment half ([0103](0103-mcp-apps-are-isolated-result-views.md)): a server's declared HTML becomes a private snapshot under `~/.graff/mcp-apps`, model context carries only an opaque link, and the GUI frames it. That path needs a `ui://` resource, an MCP handshake, and a tool that declares a UI — none of which a page the model itself wrote has.
+
+ Two shortcuts were available and both are wrong. Injecting the markup into the app's own document (`dangerouslySetInnerHTML`) hands model-authored script the desktop preload bridge and every local API route. Rendering any `.html` file already in the workspace would run third-party bytes inside the app too, and would put the transcript's trust in whatever happens to be on disk.
+
+ ## Decision
+
+ `render_html` writes the page **verbatim** to one private snapshot — `$HOME/.graff/views/<32-hex>.html`, 0700 directory, 0600 file — and returns a result line carrying only the opaque path. One call, one view. No wrapper document, no host script, no handshake; nothing about the page re-enters model context.
+
+ The desktop's `/api/views` serves that file under a containing policy:
+
+ ```
+ sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline';
+ style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:;
+ font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none';
+ form-action 'none'; base-uri 'none'; frame-ancestors 'self'
+ ```
+
-The CSP `sandbox` directive is the containment — not the iframe attribute — so the document gets an opaque origin: no app DOM, no cookies, no storage, no API reach. That holds even when someone opens the file's own URL directly, which is what makes the snapshot a portable artifact rather than a GUI-only trick. `default-src 'none'` with `connect-src 'none'` keeps it off the network entirely; a page inlines its images as `data:`/`blob:` URIs. Inline script and style stay on, because a self-contained page is exactly what they are for.
++The CSP `sandbox` directive is the containment — not the iframe attribute — so the document gets an opaque origin: no app DOM, no cookies, no storage, no API reach. This also applies to direct visits to the desktop HTTP route. Opening the raw file from disk does not preserve the HTTP sandbox headers. `default-src 'none'` with `connect-src 'none'` keeps it off the network entirely; a page inlines its images as `data:`/`blob:` URIs. Inline script and style stay on, because a self-contained page is exactly what they are for.
+
+ The GUI matches the opaque link (`[Rendered view](…/.graff/views/<32hex>.html)`) the way it matches an app result and renders it in the transcript with close/open chrome, so the model decides when a turn gets a picture instead of a paragraph. A page that needs the network needs a different tool, not a weaker policy.
+
+ ## Consequences
+
+ The model chooses presentation; it cannot choose privilege. Because the snapshot is the model's own bytes, the file stays openable and greppable on disk, and a view is not a screenshot — it keeps its own inline script and style.
+
+ What a page cannot do: fetch, load a CDN script or font or image, open a popup, post a form, or reach outside its frame. Its links navigate only its own frame. Rich remote-hosted content is out of scope by construction, not by a missing flag.
+
+ Views accumulate like MCP app snapshots; deleting `~/.graff/views` reclaims the space, and the transcript's link then 404s into ordinary "no longer available" text.
+
+ `render_html` writes to the host, so `--no-local-tools` strips it exactly as it strips `write_file`. Plan mode still allows it: a diagram is a better plan than a paragraph, and the write lands in the snapshot directory, never the workspace.
+
+ Verification is offline. `zig test src/html_view.zig` covers the snapshot itself (verbatim bytes, opaque id, 0600, size bound, no home, no id collisions). `bun test lib/mcp-apps.test.ts` covers the link matcher and the store's traversal/symlink/size guards. `bun run test:views` covers the containment in real Chrome: inline script runs, the network fetch is refused by CSP, `top.document` is unreachable, the route's policy and its 400/403/404 answers hold.
++
++The desktop retains `create_html` as its explicitly static HTML/CSS tool (ADR
++0106). `render_html` is the engine tool for a self-contained interactive page.
++Their distinct result markers survive live updates and saved transcript replay.
++Neither tool should manufacture a workspace diff. Offscreen interactive views
++release their iframe and restart from the saved snapshot when brought back.
++On Windows the snapshot directory inherits the user's profile ACL; POSIX
++permission calls must not run on that platform.
diff --cc docs/adr/README.md
index eb5efc39,19cea926..48145f51
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@@ -114,9 -114,7 +114,10 @@@ record only when you need the evidence
| [0101](0101-gui-tests-preserve-desktop-focus.md) | GUI tests stay hidden by default; visible opt-in can overlap other apps, and native foreground checks require separate opt-in. |
| [0102](0102-workspace-agents-and-cancel-recovery.md) | Agents uses the workspace area, Tasks visibility is explicit and persisted, and timed-out cancellation retires the worker before session recovery. |
| [0103](0103-mcp-apps-are-isolated-result-views.md) | MCP Apps are private saved result views in isolated GUI/browser sandboxes; app tool calls require a future approval path. |
-| [0104](0104-model-drawn-pages-render-in-an-opaque-frame.md) | A page the model draws (`render_html`) is a private snapshot served under a CSP sandbox; the model picks the presentation, never the privilege. |
+| [0104](0104-live-publication-and-deferred-tool-evidence.md) | Requests merge only ready MCP tasks; publication and completion use fresh head evidence; claim transactions serialize handoffs. |
+| [0105](0105-explicit-legacy-listener-stop.md) | Only an explicit identity-bound stop-suspect action may terminate an unrecorded legacy listener; automatic cleanup stays conservative. |
+| [0106](0106-desktop-html-explanations.md) | Desktop HTML explanations are private saved results in static, opaque sandboxes with bounded source and offscreen teardown. |
++| [0107](0107-model-drawn-pages-render-in-an-opaque-frame.md) | A page the model draws (`render_html`) is a private snapshot served under a CSP sandbox; the model picks the presentation, never the privilege. |
## When to write one
diff --cc docs/rendered-views.md
index 00000000,77274d28..f1d232c0
mode 000000,100644..100644
--- a/docs/rendered-views.md
+++ b/docs/rendered-views.md
@@@ -1,0 -1,76 +1,77 @@@
+ # Rendered views
+
+ The model can draw. When a result is easier to see than to read — a chart, a
+ timeline, a layout mock, a before/after — it calls **`render_html`** with one
+ self-contained page and the desktop app shows that page inline in the
+ transcript, right where the turn happened. Nothing is configured for this and
+ nothing opens automatically: the model chooses to draw, and the turn is still
+ the turn.
+
+ The view keeps its own inline `<style>` and `<script>`, so a page can be
+ animated or interactive. Close view / Open view disposes and restores the
+ frame without touching the conversation.
+
+ ## Where the page lives
+
+ One call writes one private snapshot:
+
+ ```
+ $HOME/.graff/views/<32 hex id>.html 0600 file, 0700 directory
+ ```
+
+ The tool result carries only the opaque path (`[Rendered view](…)`), which is
+ what the desktop matches on to render it. The page appears in model context
+ once — as the argument the model wrote — and never again. Snapshots persist
+ across transcript reloads and are yours to delete: they are ordinary HTML
+ files, so you can also open one in a browser, or `rm ~/.graff/views/*` to
+ reclaim the space. The transcript's link then shows an ordinary "no longer
+ available" frame.
+
+ ## What a page can and cannot do
+
+ The file is served by the desktop's `/api/views` route under a containing
-policy ([ADR 0104](adr/0104-model-drawn-pages-render-in-an-opaque-frame.md)):
++policy ([ADR 0107](adr/0107-model-drawn-pages-render-in-an-opaque-frame.md)):
+
+ - **It can** run its own inline script and style, draw anything CSS can draw,
+ and inline images/fonts/media as `data:` or `blob:` URIs.
+ - **It cannot** reach the network — no `fetch`, no CDN script, no remote image
+ or font, no websocket. `default-src 'none'` and `connect-src 'none'`.
+ - **It cannot** reach the app: the CSP `sandbox` directive gives the document an
+ opaque origin, so there is no app DOM, no `localStorage`, no cookies, and no
+ call into the desktop's own API routes. Links navigate only the frame, and
+ forms and popups are refused.
+
-That holds whether the transcript frames the page or you open the file's URL
-directly, so a snapshot is a portable artifact rather than a GUI-only trick.
++The policy applies to the desktop HTTP route, including a direct visit to that
++route. Opening the raw HTML file from disk does not carry these HTTP headers
++and runs outside the desktop sandbox.
+
+ ## In the REPL
+
+ The tool result names the saved path; open it in your browser from there. There
+ is no `/view` shortcut yet.
+
+ `--no-local-tools` strips `render_html` like any other host-writing tool
+ (`src/no_local_tools.zig`), because the snapshot lands on the machine running
+ graff.
+
+ ## Development and regression checks
+
+ All of these are offline and need no model:
+
+ ```sh
+ zig test src/html_view.zig # the snapshot: verbatim bytes, opaque id, 0600, size bound
+ python3 scripts/test-render-html.py zig-out/bin/graff # the engine: marker, verbatim file, refusal
+ cd apps/native && bun test lib/mcp-apps.test.ts # link matcher + store guards
+ cd apps/native && bun run test:views # containment in real Chrome
+ ```
+
+ The engine fixture (`scripts/test-render-html.py`) drives the real binary with
+ a scripted model: it asserts the saved file is the model's page byte-for-byte,
+ the directory is 0700 and the file 0600, the marker carries the saved path in
+ the exact shape the desktop matches, the page never comes back to the model a
+ second time, and an oversized page is refused without writing anything.
+
-`test:views` starts its own Next dev server, writes a fixture page into
-`~/.graff/views` through the same path the engine uses, and asserts that the
++`test:views` runs headless with an external deadline and a temporary home,
++starts its own Next dev server, writes a fixture page into `~/.graff/views` through the same path the engine uses, and asserts that the
+ inline script runs, the network fetch is refused by CSP, `top.document` is
+ unreachable, and the route answers 200/400/403/404 as documented.
diff --cc evals/harness_behavior.jsonl
index 45cf941e,57b8cfdf..5b4d65c5
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@@ -75,5 -75,4 +75,6 @@@
{"id": "list-dir-near-miss-hint", "why": "ADR 0093: a misspelled list_dir path should name the closest sibling while retaining error status.", "prompt": "what is in the demo-server folder", "workspace_seed": {"demos-servers/README.md": "# runbook\n"}, "script": [{"tool": "codedb", "arguments": {"command": "list_dir demo-server"}}, {"text": "the folder is demos-servers"}], "assert": [{"event": {"type": "tool_result", "name": "codedb", "is_error": true}}, {"request_contains": {"index": 1, "text": "was not found. Closest match: demos-servers/."}}, {"final_text_contains": "demos-servers"}]}
{"id": "subagent-activity-isolated-sink", "why": "Frontendless workers must publish their streamed progress, tool identity and final report to a separate bounded activity feed without emitting child prose as parent text.", "workspace_seed": {"example.txt": "fixture content\n", "check_activity.py": "import json, pathlib\nsnapshots = [json.loads(p.read_text()) for p in pathlib.Path('.graff/live').glob('activity-*/*.json')]\nassert len(snapshots) == 1, len(snapshots)\ns = snapshots[0]\nassert s['agent']['status'] == 'completed', s['agent']\nassert s['response'] == 'Child review complete.', s['response']\nassert any(e['type'] == 'text' and 'Child is inspecting.' in e['text'] for e in s['events']), s['events']\nassert any(e['type'] == 'tool_call' and e['name'] == 'read_file' and e['text'] == 'example.txt' and e['input_key'] == 'path' for e in s['events']), s['events']\nassert any(e['type'] == 'tool_result' and 'fixture content' in e['text'] for e in s['events']), s['events']\nassert not any('Parent has finished.' in e['text'] for e in s['events'])\nprint('child-activity-verified')\n"}, "prompt": "Use one subagent to inspect example.txt, then verify its activity feed with check_activity.py.", "script": [{"tool": "subagent", "arguments": {"description": "Inspect example", "prompt": "Read example.txt and report your findings."}}, {"text": "Child is inspecting.", "tool": "read_file", "arguments": {"path": "example.txt"}}, {"text": "Child review complete."}, {"tool": "bash", "arguments": {"command": "python3 check_activity.py"}}, {"text": "Parent has finished."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "child-activity-verified\n"}}, {"events_at_most": {"match": {"type": "text", "text": "Child is inspecting."}, "count": 0}}, {"final_text_contains": "Parent has finished."}]}
{"id":"opaque-compaction-is-not-success-804","why":"An unsupported local fallback must report that opaque history needs server compaction, not emit successful zero-work compaction or discard the preserved context.","args":["--resume","compact-fixture"],"workspace_seed":{".graff/sessions/compact-fixture.session.json":"{\"provider\":\"lmstudio\",\"model\":\"mock\",\"messages\":[{\"type\":\"compaction\",\"encrypted_content\":\"opaque-fixture-804\"},{\"role\":\"user\",\"content\":\"retained-context-804\"}]}"},"controls_before_prompt":[{"type":"compact"}],"prompt":"Continue using the retained context.","script":[{"text":"Retained context is available."}],"assert":[{"event":{"type":"error","message":"compaction failed: ServerCompactionRequired"}},{"events_at_most":{"match":{"type":"compact","ok":true},"count":0}},{"request_contains":{"index":0,"text":"retained-context-804"}},{"request_contains":{"index":0,"text":"opaque-fixture-804"}},{"final_text_contains":"Retained context is available."}]}
+{"id": "completion-search-citations-clean", "why": "#819: the authoritative completion must remove search citation control spans while preserving human prose; the release regression also covers byte-fragmented line output.", "args": ["--old"], "prompt": "Return the scripted final result.", "script": [{"tool": "attempt_completion", "arguments": {"result": "Read the docsciteturn0search0turn1search2 today."}, "argument_chunk_size": 1}], "assert": [{"final_text_contains": "Read the docs today."}]}
+{"id": "publication-unresolved-command-refused", "why": "#847: a non-literal publication command cannot bypass head/body inspection by chaining checks before creation. No GitHub write or lookup should execute.", "args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Exercise the scripted prepublication refusal.", "script": [{"tool": "bash", "arguments": {"command": "gh pr checks --watch && gh pr create --title fixture --body '## Verification: local passed'"}}, {"text": "The publication was blocked."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "is_error": true}}, {"request_contains": {"text": "separate literal gh pr command"}}, {"final_text_contains": "The publication was blocked."}]}
+ {"id": "render-html-hands-back-an-opaque-view", "why": "The model's own drawing surface must be advertised, dispatch to the snapshot writer, and put only the opaque path into the transcript - a page the model drew must never come back to it as a second copy of the markup.", "args": [], "prompt": "draw the retry flow as a page", "script": [{"tool": "render_html", "arguments": {"html": "<h1 id=\"flow\">Retry flow</h1><p>the second attempt is declined</p>"}}, {"text": "drawn above"}], "assert": [{"request_contains": {"index": 0, "text": "render_html"}}, {"events_at_least": {"match": {"type": "tool_call", "name": "render_html"}, "count": 1}}, {"event": {"type": "tool_result"}}, {"request_contains": {"index": -1, "text": "[Rendered view]"}}, {"request_contains": {"index": -1, "text": "/.graff/views/"}}, {"final_text_contains": "drawn above"}]}
diff --cc src/html_view.zig
index 00000000,b7ce16e4..481458ea
mode 000000,100644..100644
--- a/src/html_view.zig
+++ b/src/html_view.zig
@@@ -1,0 -1,156 +1,158 @@@
+ //! `render_html` — the model draws something for the user, and the desktop
+ //! app renders it inline in the transcript instead of making them imagine it.
+ //!
+ //! The snapshot is the model's page VERBATIM: no wrapper document, no host
+ //! script, no handshake. Isolation is a response header, not a shell — the
+ //! desktop's `/api/views` serves this file with a CSP `sandbox` plus
+ //! `default-src 'none'`, so the page runs in an opaque origin with no network
+ //! and no reach into the app, whether it is framed by the transcript or opened
+ //! straight from disk in a browser.
+ //!
+ //! Same private-snapshot shape as an MCP app result (mcp_apps.zig): a random
+ //! 32-hex id under `$HOME/.graff/views`, 0700 directory, 0600 file, and a
+ //! result line carrying only the path. Nothing about the page enters model
+ //! context a second time.
+
+ const std = @import("std");
+ const Io = std.Io;
+ const Allocator = std.mem.Allocator;
+ const Value = std.json.Value;
+ const tools = @import("tools.zig");
+
+ pub const tool_name = "render_html";
+ pub const tool_desc =
+ "Draw something for the user as a live HTML page and show it in the desktop transcript. Reach for it when a result is easier to SEE than to read — a chart, a diagram, a timeline, a before/after comparison, a small layout mock, or something they can poke at — not for ordinary prose, code, or a file list, which belong in your reply. The page is saved as one private local snapshot and rendered in an isolated frame: no network at all (inline images as data: URIs; no CDNs, no fonts, no fetch), no access to the app or its APIs, no forms, no popups, and links stay inside the frame. Make it self-contained — one document with its own inline <style>/<script> — and keep it under 1 MB. One call makes one view; the user can close it and the saved path stays openable later.";
+ pub const tool_schema =
+ \\{"type": "object", "properties": {"html": {"type": "string", "description": "The complete page: markup plus whatever inline <style>/<script> it needs. It must stand alone — nothing is fetched and nothing outside it is available."}}, "required": ["html"]}
+ ;
+
+ /// Catalog entry for this tool. schema.zig sits on the 600-line ceiling, so
+ /// the spec lives with the module that owns it and is spliced in there as
+ /// `@import("html_view.zig").spec` — the same one-line pattern `skill_docs`
+ /// and `imagegen` use, minus the import.
+ pub const spec: @import("schema.zig").ToolSpec = .{ .name = tool_name, .desc = tool_desc, .schema = tool_schema };
+
+ /// One call, one page. A view is for a pane, not a 40 MB canvas.
+ const max_html = 1024 * 1024;
+ pub const dir_name = ".graff/views";
+
+ /// The home the session resolved: the MCP registry already carries it, the
+ /// fleet pins it before any prompt, and credential_store pins it at startup.
+ /// A tool running on a pool thread has no environment map of its own.
+ fn homeDir(ctx: tools.ToolCtx) []const u8 {
+ if (ctx.registry) |reg| if (reg.home.len > 0) return reg.home;
+ if (@import("fleet.zig").g_home) |h| if (h.len > 0) return h;
+ return @import("credential_store.zig").g_home;
+ }
+
+ /// Why this page cannot be rendered, or null when it can. Separate from exec
+ /// so the wording is testable without a whole ToolCtx.
+ fn refusal(html: []const u8, a: Allocator) !?[]u8 {
+ if (std.mem.trim(u8, html, " \t\r\n").len == 0)
+ return try a.dupe(u8, "render_html needs the page in `html` — an empty string draws nothing.");
+ if (html.len > max_html)
+ return try std.fmt.allocPrint(a, "that page is {d} KB and the limit is {d} KB per view. Inline less (base64 media is what usually blows the budget) or draw it as two views.", .{ html.len / 1024, max_html / 1024 });
+ return null;
+ }
+
+ /// The one line the transcript and the model see. The page itself never
+ /// travels in it — the GUI matches the opaque path.
+ fn marker(a: Allocator, path: []const u8) ![]u8 {
+ return std.fmt.allocPrint(a, "[Rendered view]({s}) — this page is now shown in the desktop transcript; it renders with no network and no access to the app.", .{path});
+ }
+
+ /// Write the page to one private snapshot and return its path (caller-owned).
+ pub fn write(io: Io, a: Allocator, home: []const u8, html: []const u8) ![]const u8 {
+ if (home.len == 0) return error.NoHomeDirectory;
+ var scratch = std.heap.ArenaAllocator.init(a);
+ defer scratch.deinit();
+ const dir = try std.fmt.allocPrint(scratch.allocator(), "{s}/{s}", .{ home, dir_name });
+ try Io.Dir.cwd().createDirPath(io, dir);
- try Io.Dir.cwd().setFilePermissions(io, dir, @enumFromInt(0o700), .{});
++ // Windows inherits the user profile ACL; Zig does not implement POSIX chmod there.
++ if (@import("builtin").os.tag != .windows)
++ try Io.Dir.cwd().setFilePermissions(io, dir, @enumFromInt(0o700), .{});
+ var random: [16]u8 = undefined;
+ io.random(&random);
+ const path = try std.fmt.allocPrint(scratch.allocator(), "{s}/{s}.html", .{ dir, std.fmt.bytesToHex(random, .lower) });
+ try @import("credential_store.zig").replaceFile(io, Io.Dir.cwd(), path, html, @enumFromInt(0o600));
+ return try a.dupe(u8, path);
+ }
+
+ pub fn exec(ctx: tools.ToolCtx, input: Value) !tools.ToolOutput {
+ const html = tools.strField(input, "html") orelse "";
+ if (try refusal(html, ctx.gpa)) |text| return .{ .text = text, .is_error = true };
+ const path = write(ctx.io, ctx.gpa, homeDir(ctx), html) catch |err| return .{
+ .text = try std.fmt.allocPrint(ctx.gpa, "could not save the view: {s}", .{@errorName(err)}),
+ .is_error = true,
+ };
+ return .{ .text = try marker(ctx.gpa, path) };
+ }
+
+ const testing = std.testing;
+
+ fn tmpHome(a: Allocator, tmp: *std.testing.TmpDir) ![]u8 {
+ return std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+ }
+
+ test "render_html writes the page verbatim to one private snapshot" {
+ const a = testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const home = try tmpHome(a, &tmp);
+ defer a.free(home);
+ const html = "<!doctype html><h1>Flow</h1><style>h1{color:#059669}</style>";
+ const path = try write(testing.io, a, home, html);
+ defer a.free(path);
+ // Opaque id, fixed shape — this is what the GUI's link matcher accepts.
+ const suffix = try std.fmt.allocPrint(a, "{s}/{s}", .{ home, dir_name });
+ defer a.free(suffix);
+ try testing.expect(std.mem.startsWith(u8, path, suffix));
+ const id = path[suffix.len + 1 ..];
+ try testing.expectEqual(@as(usize, 32 + 5), id.len);
+ try testing.expect(std.mem.endsWith(u8, id, ".html"));
+ for (id[0..32]) |c| try testing.expect(std.ascii.isHex(c));
+ // The file is the model's bytes, unchanged (no wrapper injected).
+ const saved = try Io.Dir.cwd().readFileAlloc(testing.io, path, a, .limited(4096));
+ defer a.free(saved);
+ try testing.expectEqualStrings(html, saved);
+ if (@import("builtin").os.tag != .windows) {
+ const st = try Io.Dir.cwd().statFile(testing.io, path, .{});
+ try testing.expectEqual(@as(u32, 0o600), st.permissions.toMode() & 0o777);
+ }
+ }
+
+ test "two calls never collide on one id" {
+ const a = testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const home = try tmpHome(a, &tmp);
+ defer a.free(home);
+ const first = try write(testing.io, a, home, "<p>one</p>");
+ defer a.free(first);
+ const second = try write(testing.io, a, home, "<p>two</p>");
+ defer a.free(second);
+ try testing.expect(!std.mem.eql(u8, first, second));
+ }
+
+ test "an empty page, an oversized page and a home-less session are refused" {
+ const a = testing.allocator;
+ const empty = (try refusal(" \n", a)).?;
+ defer a.free(empty);
+ try testing.expect(std.mem.indexOf(u8, empty, "empty string") != null);
+ const big = try a.alloc(u8, max_html + 1);
+ defer a.free(big);
+ @memset(big, 'x');
+ const oversized = (try refusal(big, a)).?;
+ defer a.free(oversized);
+ try testing.expect(std.mem.indexOf(u8, oversized, "limit") != null);
+ try testing.expect((try refusal("<p>fine</p>", a)) == null);
+ try testing.expectError(error.NoHomeDirectory, write(testing.io, a, "", "<p>x</p>"));
+ }
+
+ test "the marker carries the path and never the page" {
+ const a = testing.allocator;
+ const text = try marker(a, "/home/u/.graff/views/0123456789abcdef0123456789abcdef.html");
+ defer a.free(text);
+ try testing.expect(std.mem.indexOf(u8, text, "/.graff/views/0123456789abcdef0123456789abcdef.html") != null);
+ try testing.expect(std.mem.indexOf(u8, text, "<") == null);
+ }