Skip to content

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

Python

feat: render_html draws a private snapshot in an opaque frame

Rach Pradhan438ba8879ee6
diff --git a/apps/native/app/api/mcp-apps/route.ts b/apps/native/app/api/mcp-apps/route.ts
index 950785f2..3a03b663 100644
--- a/apps/native/app/api/mcp-apps/route.ts
+++ b/apps/native/app/api/mcp-apps/route.ts
@@ -1,4 +1,4 @@
-import {readMcpApp} from "@/lib/mcp-app-store";
+import {readMcpApp} from "@/lib/snapshot-store";
import {validAppId} from "@/lib/mcp-apps";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
diff --git a/apps/native/app/api/views/route.ts b/apps/native/app/api/views/route.ts
new file mode 100644
index 00000000..3c6bc24f
--- /dev/null
+++ b/apps/native/app/api/views/route.ts
@@ -0,0 +1,27 @@
+import {readView} from "@/lib/snapshot-store";
+import {validAppId} from "@/lib/mcp-apps";
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+/** A model-authored page is contained by policy, not by a wrapper document:
+ * the CSP `sandbox` directive gives the response an opaque origin (no app
+ * DOM, no cookies, no storage, no API reach) and `default-src 'none'` keeps
+ * it off the network, whether the transcript frames it or someone opens the
+ * file's own URL. Inline script and style stay on — that is what makes a
+ * self-contained page work — and images must be `data:`/`blob:`. */
+const 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'";
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const origin = request.headers.get("origin");
+ if (request.headers.get("sec-fetch-site") === "cross-site" || (origin && origin !== url.origin))
+ return new Response("Forbidden", {status:403});
+ const id = url.searchParams.get("id");
+ if (!validAppId(id)) return new Response("Invalid view id", {status:400});
+ try {
+ return new Response(await readView(id), {headers:{
+ "Content-Type":"text/html; charset=utf-8", "Cache-Control":"no-store",
+ "X-Content-Type-Options":"nosniff", "Referrer-Policy":"no-referrer", "Content-Security-Policy":POLICY,
+ }});
+ } catch { return new Response("This view is no longer available.", {status:404}); }
+}
diff --git a/apps/native/app/visual-tests/views/page.tsx b/apps/native/app/visual-tests/views/page.tsx
new file mode 100644
index 00000000..30bc6a5f
--- /dev/null
+++ b/apps/native/app/visual-tests/views/page.tsx
@@ -0,0 +1,8 @@
+import {notFound} from "next/navigation";
+import SnapshotView from "@/components/site/SnapshotView";
+export const dynamic = "force-dynamic";
+export default async function Page({searchParams}: {searchParams:Promise<{id?:string}>}) {
+ if (process.env.GRAFF_VISUAL_TESTS !== "1") notFound();
+ const {id} = await searchParams;
+ return <main style={{maxWidth:900,margin:"30px auto"}}><h1>Simulated rendered view</h1><SnapshotView kind="view" id={id ?? ""} /></main>;
+}
diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsx
index aa3f57ee..c90b11f5 100644
--- a/apps/native/components/site/ChatBubbles.tsx
+++ b/apps/native/components/site/ChatBubbles.tsx
@@ -6,6 +6,7 @@ import ThinkingState from "@/components/primitives/ThinkingState";
import ToolChips, { type LiveDiff } from "@/components/primitives/ToolChips";
import TurnActivity from "./TurnActivity";
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";
@@ -54,7 +55,8 @@ const ToolGroup = memo(function ToolGroup({ tools, diffs, onOpenPath }: {
path: tool.path, status: tool.status, startedAt: tool.startedAt, elapsedMs: tool.elapsedMs,
}));
return <><ToolChips rows={rows} diffs={diffs} onOpenPath={onOpenPath} />
- {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 --git a/apps/native/components/site/McpAppResult.tsx b/apps/native/components/site/McpAppResult.tsx
index 3f135799..47d3ee3d 100644
--- a/apps/native/components/site/McpAppResult.tsx
+++ b/apps/native/components/site/McpAppResult.tsx
@@ -1,16 +1,6 @@
"use client";
-import {useState} from "react";
-import {validAppId} from "@/lib/mcp-apps";
+import SnapshotView from "./SnapshotView";
export default function McpAppResult({id}: {id: string}) {
- const [visible, setVisible] = useState(true);
- if (!validAppId(id)) return null;
- return <section className="my-3 overflow-hidden rounded-lg border border-ink/10" aria-label="MCP app result">
- <div className="flex items-center justify-between px-3 py-2 text-xs text-ink-3">
- <span>Interactive MCP result</span><button type="button" onClick={()=>setVisible(!visible)} aria-expanded={visible}>{visible ? "Close view" : "Open view"}</button>
- </div>
- {visible && <iframe title="Interactive MCP tool result" src={`/api/mcp-apps?id=${id}`}
- sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" allow="clipboard-write"
- referrerPolicy="no-referrer" className="block h-[620px] w-full border-0" />}
- </section>;
+ return <SnapshotView kind="mcp-app" id={id} />;
}
diff --git a/apps/native/components/site/SnapshotView.tsx b/apps/native/components/site/SnapshotView.tsx
new file mode 100644
index 00000000..99fa4164
--- /dev/null
+++ b/apps/native/components/site/SnapshotView.tsx
@@ -0,0 +1,41 @@
+"use client";
+
+import {useState} 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);
+ 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}>
+ <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" />}
+ </section>;
+}
diff --git a/apps/native/e2e/views.pw.ts b/apps/native/e2e/views.pw.ts
new file mode 100644
index 00000000..b4d76847
--- /dev/null
+++ b/apps/native/e2e/views.pw.ts
@@ -0,0 +1,69 @@
+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');
+});
+
+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 --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.ts
index 64c90010..b37370d7 100644
--- a/apps/native/lib/acp.ts
+++ b/apps/native/lib/acp.ts
@@ -1,6 +1,6 @@
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 };
@@ -197,6 +197,7 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId
status,
detail: boundToolDetail(detail),
mcpAppId: mcpAppId(contentText) ?? prev?.mcpAppId,
+ viewSnapshotId: viewSnapshotId(contentText) ?? prev?.viewSnapshotId,
path,
startedAt: prev?.startedAt ?? Date.now(),
atChars: prev?.atChars ?? turn.text.length,
diff --git a/apps/native/lib/graff-events.ts b/apps/native/lib/graff-events.ts
index d7d2767f..61d938b5 100644
--- a/apps/native/lib/graff-events.ts
+++ b/apps/native/lib/graff-events.ts
@@ -44,6 +44,8 @@ export type ToolIcon = "think" | "write" | "run" | "read";
export type ToolRow = {
mcpAppId?: string;
+ /** A `render_html` page the model drew: rendered inline, like an app result. */
+ viewSnapshotId?: string;
id: string;
name: string;
icon: ToolIcon;
diff --git a/apps/native/lib/mcp-app-store.ts b/apps/native/lib/mcp-app-store.ts
deleted file mode 100644
index 3b288f05..00000000
--- a/apps/native/lib/mcp-app-store.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import {open, lstat} from "node:fs/promises";
-import {constants} from "node:fs";
-import {homedir} from "node:os";
-import path from "node:path";
-import {validAppId} from "./mcp-apps";
-
-export async function readMcpApp(id: string, root = path.join(homedir(), ".graff", "mcp-apps")): Promise<string> {
- if (!validAppId(id)) throw Error("Invalid app id");
- if ((await lstat(root)).isSymbolicLink()) throw Error("Invalid app directory");
- const file = await open(path.join(root, `${id}.html`), constants.O_RDONLY | constants.O_NOFOLLOW);
- try {
- const stat = await file.stat();
- if (!stat.isFile() || stat.size > 18 * 1024 * 1024) throw Error("Invalid app snapshot");
- return await file.readFile("utf8");
- } finally { await file.close(); }
-}
diff --git a/apps/native/lib/mcp-apps.test.ts b/apps/native/lib/mcp-apps.test.ts
index ac4b70db..1a1e1b7e 100644
--- a/apps/native/lib/mcp-apps.test.ts
+++ b/apps/native/lib/mcp-apps.test.ts
@@ -2,8 +2,8 @@ import {test,expect} from "bun:test";
import {mkdtemp,writeFile,symlink,rm} from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import {mcpAppId,validAppId} from "./mcp-apps";
-import {readMcpApp} from "./mcp-app-store";
+import {mcpAppId,viewSnapshotId,validAppId} from "./mcp-apps";
+import {readMcpApp,readView} from "./snapshot-store";
import {applyAcpUpdate,emptyTurn} from "./acp";
const id="a".repeat(32);
test("only opaque local app ids are recognized",()=>{
@@ -11,6 +11,12 @@ test("only opaque local app ids are recognized",()=>{
expect(mcpAppId(`[MCP app](https://evil/${id}.html)`)).toBeUndefined();
for(const bad of ['../secret','a'.repeat(31),'A'.repeat(32),'a'.repeat(33)])expect(validAppId(bad)).toBe(false);
});
+test("a rendered view is matched by its own marker and directory only",()=>{
+ expect(viewSnapshotId(`[Rendered view](/home/test/.graff/views/${id}.html)`)).toBe(id);
+ expect(viewSnapshotId(`[Rendered view](/home/test/.graff/mcp-apps/${id}.html)`)).toBeUndefined();
+ expect(viewSnapshotId(`[Rendered view](https://evil/${id}.html)`)).toBeUndefined();
+ expect(mcpAppId(`[Rendered view](/home/test/.graff/views/${id}.html)`)).toBeUndefined();
+});
test("ACP retains app id before details are truncated",()=>{
const turn=applyAcpUpdate(emptyTurn(),{sessionUpdate:'tool_call_update',toolCallId:'t1',title:'mcp__test__search',status:'completed',content:[{type:'content',content:{type:'text',text:`[MCP app](/home/test/.graff/mcp-apps/${id}.html)\n`+'data'.repeat(50000)}}]});
expect(turn.tools[0].mcpAppId).toBe(id);
@@ -22,5 +28,14 @@ test("app store rejects traversal, oversized files and symlinks",async()=>{
await expect(readMcpApp('../secret',root)).rejects.toThrow();
const other='b'.repeat(32);await symlink(path.join(root,`${id}.html`),path.join(root,`${other}.html`));await expect(readMcpApp(other,root)).rejects.toThrow();
await writeFile(path.join(root,`${id}.html`),Buffer.alloc(19*1024*1024));await expect(readMcpApp(id,root)).rejects.toThrow();
+ // A rendered view goes through the same reader, so it inherits the same guards.
+ const views=await mkdtemp(path.join(os.tmpdir(),'graff-view-test-'));
+ try{
+ await writeFile(path.join(views,`${id}.html`),'<h1>drawn</h1>');
+ expect(await readView(id,views)).toBe('<h1>drawn</h1>');
+ await expect(readView('../secret',views)).rejects.toThrow();
+ await symlink(path.join(views,`${id}.html`),path.join(views,`${other}.html`));
+ await expect(readView(other,views)).rejects.toThrow();
+ }finally{await rm(views,{recursive:true,force:true});}
}finally{await rm(root,{recursive:true,force:true});}
});
diff --git a/apps/native/lib/mcp-apps.ts b/apps/native/lib/mcp-apps.ts
index 1a7c6a6d..a265a486 100644
--- a/apps/native/lib/mcp-apps.ts
+++ b/apps/native/lib/mcp-apps.ts
@@ -3,6 +3,12 @@ export function mcpAppId(text: string): string | undefined {
return /\[MCP app\]\([^\r\n]*\/\.graff\/mcp-apps\/([a-f0-9]{32})\.html\)/.exec(text)?.[1];
}
+/** The model's own page (`render_html`), saved and matched the same opaque
+ * way: an id, never a path a tool result could talk us into fetching. */
+export function viewSnapshotId(text: string): string | undefined {
+ return /\[Rendered view\]\([^\r\n]*\/\.graff\/views\/([a-f0-9]{32})\.html\)/.exec(text)?.[1];
+}
+
export function validAppId(value: unknown): value is string {
return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
}
diff --git a/apps/native/lib/snapshot-store.ts b/apps/native/lib/snapshot-store.ts
new file mode 100644
index 00000000..4ca2ee73
--- /dev/null
+++ b/apps/native/lib/snapshot-store.ts
@@ -0,0 +1,30 @@
+import {open, lstat} from "node:fs/promises";
+import {constants} from "node:fs";
+import {homedir} from "node:os";
+import path from "node:path";
+import {validAppId} from "./mcp-apps";
+
+/** Read one bounded HTML snapshot. The id is an opaque 32-hex name we wrote
+ * ourselves — never a caller-supplied path — and the open refuses to follow
+ * a symlink out of the snapshot directory. */
+async function readSnapshot(id: string, root: string): Promise<string> {
+ if (!validAppId(id)) throw Error("Invalid snapshot id");
+ if ((await lstat(root)).isSymbolicLink()) throw Error("Invalid snapshot directory");
+ const file = await open(path.join(root, `${id}.html`), constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const stat = await file.stat();
+ if (!stat.isFile() || stat.size > 18 * 1024 * 1024) throw Error("Invalid snapshot");
+ return await file.readFile("utf8");
+ } finally { await file.close(); }
+}
+
+/** An MCP server's declared app view (ADR 0091), saved by the engine. */
+export function readMcpApp(id: string, root = path.join(homedir(), ".graff", "mcp-apps")): Promise<string> {
+ return readSnapshot(id, root);
+}
+
+/** A page the model drew for the user (`render_html`). Its own directory so
+ * the two kinds stay tellable apart on disk, the same guards either way. */
+export function readView(id: string, root = path.join(homedir(), ".graff", "views")): Promise<string> {
+ return readSnapshot(id, root);
+}
diff --git a/apps/native/package.json b/apps/native/package.json
index bf171ed5..705b1c8b 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -31,6 +31,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: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 --git a/apps/native/playwright.views.config.ts b/apps/native/playwright.views.config.ts
new file mode 100644
index 00000000..a3f14e51
--- /dev/null
+++ b/apps/native/playwright.views.config.ts
@@ -0,0 +1,5 @@
+import {defineConfig} from "@playwright/test";
+// GRAFF_DESKTOP_TOKEN is cleared for the same reason the Electron visual
+// harnesses clear it: proxy.ts gates /api/* on the token the desktop renderer
+// receives, and a spec drives those routes without it.
+export default defineConfig({testDir:"./e2e",testMatch:"views.pw.ts",workers:1,use:{channel:"chrome",baseURL:"http://localhost:3018",headless:true},webServer:{command:"GRAFF_VISUAL_TESTS=1 GRAFF_DESKTOP_TOKEN= bunx next dev --port 3018",url:"http://localhost:3018",timeout:120000,reuseExistingServer:false},reporter:"list"});
diff --git a/docs/adr/0104-model-drawn-pages-render-in-an-opaque-frame.md b/docs/adr/0104-model-drawn-pages-render-in-an-opaque-frame.md
new file mode 100644
index 00000000..58668a22
--- /dev/null
+++ b/docs/adr/0104-model-drawn-pages-render-in-an-opaque-frame.md
@@ -0,0 +1,40 @@
+# 0104. 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 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.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8e6721b5..19cea926 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -114,6 +114,7 @@ record only when you need the evidence or the edge cases.
| [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. |
## When to write one
diff --git a/docs/rendered-views.md b/docs/rendered-views.md
new file mode 100644
index 00000000..77274d28
--- /dev/null
+++ b/docs/rendered-views.md
@@ -0,0 +1,76 @@
+# 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)):
+
+- **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.
+
+## 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
+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 --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 09121b07..57b8cfdf 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -75,3 +75,4 @@
{"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": "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 --git a/examples/edge-worker/src/remote.ts b/examples/edge-worker/src/remote.ts
index f461fb48..3edca6ba 100644
--- a/examples/edge-worker/src/remote.ts
+++ b/examples/edge-worker/src/remote.ts
@@ -10,7 +10,7 @@
export const HARNESS_VERSION = "0.13";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "alibaba/qwen3.8-27b" | "anthropic/claude-sonnet-4.6" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "gemini-3-flash-preview" | "gemini-3.1-flash-lite" | "gemini-3.1-pro-preview" | "gemini-3.5-flash" | "gemini-3.5-flash-lite" | "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash" | "gemma-4-26b-a4b-it" | "gemma-4-31b" | "gemma-4-31b-it" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5-turbo" | "glm-5.2" | "glm-5.3" | "glm-5.3-flash" | "glm-5v-turbo" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-6-astra" | "gpt-oss-120b" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-k2.7-code" | "kimi-k3" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "muse-spark-1.2" | "muse-spark-1.2-contributor" | "openai/gpt-oss-120b" | (string & {});
-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";
+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "render_html" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
/** Events streamed by the bridge (same `--json` contract as the stdio SDK).
@@ -522,4 +522,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat
}
export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "alibaba/qwen3.8-27b", "anthropic/claude-sonnet-4.6", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "gemini-3-flash-preview", "gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemma-4-26b-a4b-it", "gemma-4-31b", "gemma-4-31b-it", "glm-4.5", "glm-4.7", "glm-5", "glm-5-turbo", "glm-5.2", "glm-5.3", "glm-5.3-flash", "glm-5v-turbo", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-astra", "gpt-oss-120b", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-k2.7-code", "kimi-k3", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "muse-spark-1.2", "muse-spark-1.2-contributor", "openai/gpt-oss-120b"];
-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];
+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "render_html", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];
diff --git a/lean-proofs/Graff/ToolCatalog.lean b/lean-proofs/Graff/ToolCatalog.lean
index 1b7d1a9e..f01a4000 100644
--- a/lean-proofs/Graff/ToolCatalog.lean
+++ b/lean-proofs/Graff/ToolCatalog.lean
@@ -23,7 +23,7 @@ deriving Repr, BEq
def localTools : List String :=
["bash", "bash_output", "bash_kill", "read_file", "edit_file",
- "write_file", "codedb", "read_tool_result", "imagegen"]
+ "write_file", "codedb", "read_tool_result", "render_html", "imagegen"]
def leanTools : List String :=
["bash", "read_file", "edit_file", "write_file", "codedb",
@@ -34,7 +34,8 @@ def optionalTools : List String :=
def baseTools : List String :=
["bash", "bash_output", "bash_kill", "read_file", "edit_file",
- "write_file", "webfetch", "skill", "codedb", "read_tool_result"]
+ "write_file", "webfetch", "skill", "codedb", "read_tool_result",
+ "render_html"]
def metaTools : List String :=
["todo_write", "todo_read", "eval", "note_constraint", "ask_user",
diff --git a/scripts/test-render-html.py b/scripts/test-render-html.py
new file mode 100644
index 00000000..abda0111
--- /dev/null
+++ b/scripts/test-render-html.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""Offline engine integration: render_html -> one private snapshot -> model-safe text.
+
+Mirrors scripts/test-mcp-apps.py for the model's own drawing surface. The
+checks that matter are the ones the GUI depends on: the result text carries
+the opaque `[Rendered view](.../.graff/views/<id>.html)` marker (the exact
+shape apps/native/lib/mcp-apps.ts matches), the file is the model's page
+byte-for-byte with no host wrapper, it is private, and the page does not come
+back to the model a second time.
+"""
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import tempfile
+
+sys.path.insert(0, str(Path(__file__).parent / "eval"))
+from mock_model import ScriptedModel
+
+PORT = 1234
+SENTINEL = "retry-flow-sentinel-7f3a"
+PAGE = f'<!doctype html><meta charset="utf-8"><h1>{SENTINEL}</h1><style>h1{{color:#059669}}</style><script>document.title="interactive"</script>'
+MARKER = re.compile(r"\[Rendered view\]\(([^\r\n]*?/\.graff/views/[a-f0-9]{32}\.html)\)")
+
+
+def run(graff: Path, script: list, prompt: str) -> tuple[str, list, ScriptedModel]:
+ model = ScriptedModel(script)
+ model.start(PORT)
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-view-fixture-") as temp:
+ root = Path(temp)
+ (root / ".harness").mkdir()
+ (root / ".harness/settings.json").write_text('{"skills":{"codedbpro":false,"muonry":false}}')
+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY")}
+ env.update(LMSTUDIO_API_KEY="local", GRAFF_NO_TELEMETRY="1", GRAFF_FLEET="off",
+ GRAFF_NO_SMOLIFY="1", GRAFF_NO_CODEDB_GUARD="1", GRAFF_BEHAVIOR_TRACE="0")
+ done = subprocess.run([str(graff), "--json", "--yolo", "--old", "--model", "lmstudio"],
+ input=json.dumps({"type": "user", "text": prompt}) + "\n",
+ cwd=root, env=env, text=True, capture_output=True, timeout=120)
+ assert done.returncode == 0, done.stderr[-2000:]
+ return done.stdout, model.requests, model
+ finally:
+ model.stop()
+
+
+def case_renders(graff: Path):
+ out, requests, _ = run(graff, [{"tool": "render_html", "arguments": {"html": PAGE}},
+ {"text": "Drawn above."}],
+ "Draw the retry flow.")
+ match = MARKER.search(out)
+ assert match, "view marker absent: " + out[-3000:]
+ snapshot = Path(match.group(1))
+ try:
+ # Verbatim: no host document, no injected script around the model's page.
+ assert snapshot.read_text() == PAGE, "the snapshot is not the model's page verbatim"
+ if os.name != "nt":
+ assert snapshot.stat().st_mode & 0o777 == 0o600, "snapshot is not private"
+ assert snapshot.parent.stat().st_mode & 0o777 == 0o700, "snapshot directory is not private"
+ assert snapshot.parent.name == "views" and snapshot.parent.parent.name == ".graff"
+ # The page is the model's own argument exactly once - never echoed back
+ # as a second copy in the result the model reads.
+ body = json.dumps(requests)
+ assert body.count(SENTINEL) == 1, f"the page came back to the model {body.count(SENTINEL)} times"
+ assert "[Rendered view](" in body, "the model never saw the marker"
+ assert str(snapshot) in body, "the model never saw the saved path"
+ print("PASS engine: page saved verbatim under .graff/views at 0600, marker carries the path, page not echoed back")
+ finally:
+ snapshot.unlink(missing_ok=True)
+
+
+def case_refuses_oversize(graff: Path):
+ views = Path.home() / ".graff" / "views"
+ before = set(views.iterdir()) if views.is_dir() else set()
+ out, _, _ = run(graff, [{"tool": "render_html", "arguments": {"html": "<p>" + "x" * (1024 * 1024 + 16) + "</p>"}},
+ {"text": "Too big."}],
+ "Draw something enormous.")
+ assert "limit is 1024 KB" in out, "an oversized page was not refused with its limit: " + out[-2000:]
+ after = set(views.iterdir()) if views.is_dir() else set()
+ assert after == before, f"an oversized page still landed on disk: {sorted(after - before)}"
+ print("PASS engine: an oversized page is refused and writes nothing")
+
+
+if __name__ == "__main__":
+ binary = Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve()
+ case_renders(binary)
+ case_refuses_oversize(binary)
diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.py
index 93b08e65..7e64ec4c 100644
--- a/sdk/py/harness_sdk.py
+++ b/sdk/py/harness_sdk.py
@@ -14,7 +14,7 @@ import urllib.request
from typing import Iterator, List, Literal, Optional, TypedDict, Union
MODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "alibaba/qwen3.8-27b", "anthropic/claude-sonnet-4.6", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "gemini-3-flash-preview", "gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemma-4-26b-a4b-it", "gemma-4-31b", "gemma-4-31b-it", "glm-4.5", "glm-4.7", "glm-5", "glm-5-turbo", "glm-5.2", "glm-5.3", "glm-5.3-flash", "glm-5v-turbo", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-astra", "gpt-oss-120b", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-k2.7-code", "kimi-k3", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "muse-spark-1.2", "muse-spark-1.2-contributor", "openai/gpt-oss-120b"]
-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"]
+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "render_html", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"]
PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "google", "minimax", "xiaomi", "kilo", "groq", "cerebras", "mistral", "kimi", "moonshot", "xai", "zai", "meta", "vercel", "openrouter", "fugu", "fireworks", "mlx", "lmstudio", "codex"]
diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.ts
index 98db5bbb..df70a3a7 100644
--- a/sdk/ts/harness.ts
+++ b/sdk/ts/harness.ts
@@ -12,7 +12,7 @@ import type { Readable, Writable } from "node:stream";
export const HARNESS_VERSION = "0.13";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "alibaba/qwen3.8-27b" | "anthropic/claude-sonnet-4.6" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "gemini-3-flash-preview" | "gemini-3.1-flash-lite" | "gemini-3.1-pro-preview" | "gemini-3.5-flash" | "gemini-3.5-flash-lite" | "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash" | "gemma-4-26b-a4b-it" | "gemma-4-31b" | "gemma-4-31b-it" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5-turbo" | "glm-5.2" | "glm-5.3" | "glm-5.3-flash" | "glm-5v-turbo" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-6-astra" | "gpt-oss-120b" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-k2.7-code" | "kimi-k3" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "muse-spark-1.2" | "muse-spark-1.2-contributor" | "openai/gpt-oss-120b" | (string & {});
-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";
+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "render_html" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
/** Events streamed by `harness --json` (one JSON object per stdout line), each
@@ -675,4 +675,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {
}
export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "alibaba/qwen3.8-27b", "anthropic/claude-sonnet-4.6", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "gemini-3-flash-preview", "gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemma-4-26b-a4b-it", "gemma-4-31b", "gemma-4-31b-it", "glm-4.5", "glm-4.7", "glm-5", "glm-5-turbo", "glm-5.2", "glm-5.3", "glm-5.3-flash", "glm-5v-turbo", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-astra", "gpt-oss-120b", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-k2.7-code", "kimi-k3", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "muse-spark-1.2", "muse-spark-1.2-contributor", "openai/gpt-oss-120b"];
-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];
+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "render_html", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];
diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.ts
index f461fb48..3edca6ba 100644
--- a/sdk/ts/remote.ts
+++ b/sdk/ts/remote.ts
@@ -10,7 +10,7 @@
export const HARNESS_VERSION = "0.13";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "alibaba/qwen3.8-27b" | "anthropic/claude-sonnet-4.6" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "gemini-3-flash-preview" | "gemini-3.1-flash-lite" | "gemini-3.1-pro-preview" | "gemini-3.5-flash" | "gemini-3.5-flash-lite" | "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash" | "gemma-4-26b-a4b-it" | "gemma-4-31b" | "gemma-4-31b-it" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5-turbo" | "glm-5.2" | "glm-5.3" | "glm-5.3-flash" | "glm-5v-turbo" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-6-astra" | "gpt-oss-120b" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-k2.7-code" | "kimi-k3" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "muse-spark-1.2" | "muse-spark-1.2-contributor" | "openai/gpt-oss-120b" | (string & {});
-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";
+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "render_html" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "google" | "minimax" | "xiaomi" | "kilo" | "groq" | "cerebras" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "meta" | "vercel" | "openrouter" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
/** Events streamed by the bridge (same `--json` contract as the stdio SDK).
@@ -522,4 +522,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat
}
export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "alibaba/qwen3.8-27b", "anthropic/claude-sonnet-4.6", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "gemini-3-flash-preview", "gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.8-flash", "gemma-4-26b-a4b-it", "gemma-4-31b", "gemma-4-31b-it", "glm-4.5", "glm-4.7", "glm-5", "glm-5-turbo", "glm-5.2", "glm-5.3", "glm-5.3-flash", "glm-5v-turbo", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6-astra", "gpt-oss-120b", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-k2.7-code", "kimi-k3", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "muse-spark-1.2", "muse-spark-1.2-contributor", "openai/gpt-oss-120b"];
-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];
+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "render_html", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];
diff --git a/spec/kernels/tool_catalog.json b/spec/kernels/tool_catalog.json
index 7d7726ba..12977ed7 100644
--- a/spec/kernels/tool_catalog.json
+++ b/spec/kernels/tool_catalog.json
@@ -12,7 +12,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"meta": [
"todo_write",
@@ -46,6 +47,7 @@
"write_file",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"lean": [
@@ -81,6 +83,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"todo_write",
"todo_read",
"eval",
@@ -120,7 +123,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"blocked": [
"imagegen"
@@ -147,6 +151,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"todo_write",
"todo_read",
"eval",
@@ -187,7 +192,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"blocked": [
"imagegen"
@@ -214,6 +220,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"todo_write",
"todo_read",
"eval",
@@ -254,7 +261,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"blocked": [
"imagegen"
@@ -281,6 +289,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"todo_write",
"todo_read",
"eval",
@@ -322,7 +331,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"blocked": [
"imagegen"
@@ -349,6 +359,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"todo_write",
"todo_read",
"eval",
@@ -388,6 +399,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"blocked": []
@@ -413,6 +425,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"todo_write",
"todo_read",
"eval",
@@ -453,6 +466,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"blocked": []
@@ -478,6 +492,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"todo_write",
"todo_read",
"eval",
@@ -518,6 +533,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"blocked": []
@@ -543,6 +559,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"todo_write",
"todo_read",
"eval",
@@ -584,6 +601,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"blocked": []
@@ -632,7 +650,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"blocked": [
"imagegen"
@@ -682,7 +701,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"blocked": [
"imagegen"
@@ -732,7 +752,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"blocked": [
"imagegen"
@@ -782,7 +803,8 @@
"webfetch",
"skill",
"codedb",
- "read_tool_result"
+ "read_tool_result",
+ "render_html"
],
"blocked": [
"imagegen"
@@ -831,6 +853,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"blocked": []
@@ -878,6 +901,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"blocked": []
@@ -925,6 +949,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"blocked": []
@@ -972,6 +997,7 @@
"skill",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen"
],
"blocked": []
@@ -1013,6 +1039,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1039,6 +1066,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1080,6 +1108,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1106,6 +1135,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1147,6 +1177,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1173,6 +1204,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1215,6 +1247,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1241,6 +1274,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1281,6 +1315,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1307,6 +1342,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1348,6 +1384,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1374,6 +1411,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1415,6 +1453,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1441,6 +1480,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1483,6 +1523,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1509,6 +1550,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1536,6 +1578,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1562,6 +1605,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1589,6 +1633,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1615,6 +1660,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1642,6 +1688,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1668,6 +1715,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1695,6 +1743,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1721,6 +1770,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1748,6 +1798,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1774,6 +1825,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1801,6 +1853,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1827,6 +1880,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1854,6 +1908,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1880,6 +1935,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1907,6 +1963,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
},
@@ -1933,6 +1990,7 @@
"imagegen",
"read_file",
"read_tool_result",
+ "render_html",
"write_file"
]
}
diff --git a/spec/kernels/tool_catalog.md b/spec/kernels/tool_catalog.md
index c734fd9a..736dcb3d 100644
--- a/spec/kernels/tool_catalog.md
+++ b/spec/kernels/tool_catalog.md
@@ -22,11 +22,11 @@ run the keep-list.
| Set | Names |
|---|---|
-| base | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `webfetch` `skill` `codedb` `read_tool_result` |
+| base | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `webfetch` `skill` `codedb` `read_tool_result` `render_html` |
| meta (root) | `todo_write` `todo_read` `eval` `note_constraint` `ask_user` `attempt_completion` `load_tool_schemas` `mcp_search_tools` `mcp_select_tool` `clock_sleep` |
| root extras | `subagent` `workflow` `agent_output` `learn_candidate` `peer_message` `workspace` |
| optional | `imagegen` |
-| local (`#330`) | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `codedb` `read_tool_result` `imagegen` |
+| local (`#330`) | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `codedb` `read_tool_result` `render_html` `imagegen` |
| lean keep | `bash` `read_file` `edit_file` `write_file` `codedb` `subagent` `attempt_completion` `load_tool_schemas` |
`webfetch`, every meta tool except the lean keepers, and every `mcp__*`
diff --git a/spec/ref/tool_catalog.py b/spec/ref/tool_catalog.py
index 4f09fdde..2f19c768 100644
--- a/spec/ref/tool_catalog.py
+++ b/spec/ref/tool_catalog.py
@@ -19,6 +19,7 @@ LOCAL_TOOLS = (
"write_file",
"codedb",
"read_tool_result",
+ "render_html",
"imagegen",
)
LEAN_TOOLS = (
@@ -43,6 +44,7 @@ BASE_TOOLS = (
"skill",
"codedb",
"read_tool_result",
+ "render_html",
)
META_TOOLS = (
"todo_write",
diff --git a/src/exec.zig b/src/exec.zig
index a8d6c4b7..4948c966 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -67,6 +67,7 @@ const native_fold = @import("native_fold.zig"); // folded native power tools: la
const stageReadFileImage = @import("read_image.zig").stage;
const input_util = @import("input_util.zig");
const imagegen = @import("imagegen.zig"); // #352: the codex-gated image tool (advertising lives in schema.zig/tool_gates.zig)
+const html_view = @import("html_view.zig"); // the model's own drawing surface: one HTML page, rendered inline in the desktop transcript
const local_tools = @import("local_tools.zig");
fn learningArgv(argv: *[10][]const u8, exe_path: []const u8, contribute: bool) usize {
@@ -368,6 +369,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
}
// Loads one SKILL.md body (or lists them). Rescans on every call, so a
// skill written this session is loadable without a restart.
+ if (std.mem.eql(u8, call.name, html_view.tool_name)) return html_view.exec(ctx, input);
if (std.mem.eql(u8, call.name, "skill")) return skill_docs.execSkill(gpa, io, input);
// #352: codex-gated. execImagegen answers a call that was never advertised
// (an unavailable session) with the same honest error it gives the model.
diff --git a/src/html_view.zig b/src/html_view.zig
new file mode 100644
index 00000000..b7ce16e4
--- /dev/null
+++ b/src/html_view.zig
@@ -0,0 +1,156 @@
+//! `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), .{});
+ 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);
+}
diff --git a/src/main.zig b/src/main.zig
index 3fe54731..6390c500 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -563,7 +563,7 @@ const agentJobsReap = subagent.agentJobsReap; // #276 P0-3: background subagents
const workflow = @import("workflow_test.zig"); // the engine's tests live here (workflow.zig hit the 600-line cap)
const exec = @import("exec.zig");
test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)
- _ = @import("mcp_apps.zig");
+ _ = .{ @import("mcp_apps.zig"), @import("html_view.zig") };
_ = @import("main_test.zig");
_ = @import("http_client.zig");
_ = @import("http_client_tests.zig");
diff --git a/src/no_local_tools.zig b/src/no_local_tools.zig
index f3a93cdd..fd96d3fc 100644
--- a/src/no_local_tools.zig
+++ b/src/no_local_tools.zig
@@ -49,6 +49,10 @@ pub const gated_tools = [_][]const u8{
// write_file would otherwise still be handed a way to run a process and
// land bytes on disk.
"imagegen",
+ // render_html lands model-authored bytes under the user's own ~/.graff
+ // views directory on THIS host: not a workspace write, but still a host
+ // write an embedder removed bash and write_file to be rid of.
+ "render_html",
};
/// A name test only, independent of whether the gate is on, so the comptime
@@ -200,8 +204,9 @@ test "#330: the gated set is exactly the host-touching built-ins; webfetch, meta
defer enabled = saved;
for (gated_tools) |tool| try std.testing.expect(isLocalTool(tool));
- try std.testing.expectEqual(@as(usize, 9), gated_tools.len);
+ try std.testing.expectEqual(@as(usize, 10), gated_tools.len);
try std.testing.expect(isLocalTool("imagegen")); // #352: optional, but still a local spawn+write
+ try std.testing.expect(isLocalTool("render_html")); // writes the snapshot under the host's own $HOME
for ([_][]const u8{ "webfetch", "skill", "subagent", "workflow", "todo_write", "eval", "mcp__sandbox__exec", "mcp__sandbox__bash" }) |tool|
try std.testing.expect(!isLocalTool(tool));
diff --git a/src/schema.zig b/src/schema.zig
index b7e43ace..5f1d1522 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -111,6 +111,7 @@ pub const base_specs = [_]ToolSpec{
,
},
.{ .name = result_read.tool_name, .desc = result_read.tool_desc, .schema = result_read.tool_schema },
+ @import("html_view.zig").spec,
};
// Meta tools act on the agent's own state, not the outside world; the