Skip to content

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

docs: record inline generative UI visualizations

zszz3bdafc1b71c2d
diff --git a/docs/adr/README.md b/docs/adr/README.md
index bae232b03..ba1e13e74 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -385,3 +385,4 @@ Each ADR includes:
| local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |
| 0332 | [macOS keeps its translucent window surface with an opaque opt-out](0332-macos-opaque-window-surface.md) | Accepted (D665, amended by D666 and D667; supersedes the macOS vibrancy window backing from D348; issue #1064) |
+| gen-ui-inline-visualization | [Inline generative UI visualizations](gen-ui-inline-visualization.md) | Proposed (D671) |
diff --git a/docs/adr/gen-ui-inline-visualization.md b/docs/adr/gen-ui-inline-visualization.md
new file mode 100644
index 000000000..b2978d4fe
--- /dev/null
+++ b/docs/adr/gen-ui-inline-visualization.md
@@ -0,0 +1,184 @@
+# ADR: Inline generative UI visualizations
+
+- Status: Proposed
+- Related: D671, D114 (session scratch root), ADR 0092 (plugin-owned panel surface)
+
+## Context
+
+Models can explain dynamic systems, tunable parameters, and spatial
+relationships far better with a small interactive page than with prose,
+Markdown tables, or Mermaid. PI-Desktop cannot show such a page in the
+transcript: assistant text renders through Markdown only, the transcript has no
+embedded frames, and MCP Apps `ui://` resources are not supported.
+
+Codex and ZCode solve the same problem the same way. The model writes an HTML
+*fragment* to a host-owned, per-session directory and references it from the
+final reply. The host validates the file, wraps it in a host shell with a
+strict Content Security Policy and theme variables, and renders it in an
+isolated frame inside the message. PI-Desktop adopts that architecture and
+adapts ZCode's Apache-2.0 visualize kit (stylesheet, tooltip and tab runtime,
+and a condensed skill text); the Codex text is proprietary and is not used.
+Attribution lives in `apps/desktop/resources/gen-ui/NOTICE.md`.
+
+This record covers the first version: an inline card with theming,
+self-reported height, and an expanded view. Interactive state, follow-up
+messages, external links, tweak panels, icons, and image export are
+deferred.
+
+## Decision
+
+### Reference syntax
+
+The model ends its reply with one standalone line per visualization:
+
+```text
+::visualize{"path":"/abs/path/to/chart.html","title":"Optional title"}
+```
+
+The renderer parses references only in completed (non-streaming) assistant
+messages and ignores lines inside fenced or indented code blocks. A malformed
+line stays plain text. The model-facing contract lives in a first-party
+built-in skill, `pi-desktop/visualize`, adapted from ZCode's visualize skill
+with the host API, tweaks, calendar, export, and CDN guidance removed.
+
+### Storage root (Rust host-core)
+
+1. Each local session gets `<data_dir>/visualizations/<sessionId>/` as an
+ additional containment root for `Read`, `Write`, and `Edit`, addressed by
+ absolute path only, with the same lexical and symlink defenses as the D114
+ scratch root.
+2. Before adding the root, the single optional `scratch_root` parameter that
+ threads through path resolution is generalized into an ordered list of
+ contained roots. That step is behavior-preserving and lands first, so the
+ new root does not become a second parallel path.
+3. `Write` and `Edit` into the visualization root accept only `.html` files.
+ `Read` is unrestricted inside the root so the model can revise a fragment.
+4. Writes there auto-allow without a permission card under the same conditions
+ as scratch (local workspace only; contract and Plan modes still deny), and
+ the root is never treated as an external path. Files there are not recorded
+ as artifacts and not snapshotted for review.
+5. The directory is created lazily and removed with its session (session
+ delete and project removal). The startup sweep removes only directories of
+ sessions that no longer exist; unlike scratch it never expires live
+ sessions by age, because transcripts keep pointing at these files.
+6. Forks copy only the fragments their transcript references into
+ `visualizations/<childId>/` and rewrite those paths, like referenced pasted
+ files in scratch. Cards always resolve against the owning session, so a
+ transcript cannot load another session's files, and deleting the parent
+ leaves the child's cards intact.
+
+### Model guidance (agent runtime and Electron Main)
+
+The absolute directory path is advertised in the system prompt beside the
+scratch directory, and the `pi-desktop/visualize` skill is active by default
+(users can disable it like other built-in skills; a disabled skill also
+withholds the directory from the prompt). Remote-host sessions get
+neither the directory nor the skill (neither in the runtime nor in the `/`
+menu or a send-time `/skill:` mention): their tools write on the remote
+machine, which Electron Main cannot read. The card's "unavailable" state is only a
+fallback for older messages.
+
+### Serving (Electron Main)
+
+1. Main registers a `pi-genui:` scheme through the single
+ `registerSchemesAsPrivileged` call site as `standard` and `secure` only —
+ no Fetch API support, no CORS, no `Access-Control-Allow-Origin` header — so
+ no other renderer context, including renderer plugins, can read another
+ session's visualization.
+2. The card URL is `pi-genui://session/<sessionId>/<file>.html`. The renderer derives
+ it from the trailing `visualizations/<sessionId>/<file>.html` segment of the
+ referenced path and never loads the absolute path. Main resolves the file
+ against the *current* data directory, so references survive data-directory
+ relocation, which does not rewrite message text.
+3. The handler accepts `GET` only, validates the session ID against
+ `[A-Za-z0-9_-]` and the file name as a single path component ending in
+ `.html`, and rejects symlinks, non-regular files, files over 2 MB, and
+ complete HTML documents (a leading `<!doctype`, `<html`, `<head`, or
+ `<body`).
+4. Main wraps the fragment in a host shell: the kit stylesheet
+ (`resources/gen-ui/visualize.css`, which defines the agent-facing tokens
+ such as `--foreground` and `--viz-series-1` from MCP Apps-style
+ `--color-*` host variables), a small host runtime that reports content
+ height and applies theme updates, the fragment, and then the kit runtime
+ (tooltips and tabs). Bundled libraries (D3 7.9.0, Floating UI 1.7.x) are
+ referenced by their pinned CDN URLs; the shell rewrites exactly those URLs
+ to `pi-genui://assets/<file>`, which serves only files listed in
+ `resources/gen-ui/vendor/manifest.json`. The response carries the CSP and a deny-all
+ `Permissions-Policy` as HTTP headers, plus `X-Content-Type-Options: nosniff`
+ and `Cache-Control: no-store`.
+5. The guest CSP is `default-src 'none'`; `script-src` allows
+ `'unsafe-inline'` and `pi-genui://assets` only, `style-src`
+ `'unsafe-inline'` only; `img-src`, `font-src`, and `media-src` allow
+ `data:` and `blob:`; `connect-src`, `frame-src`, `form-action`, and
+ `base-uri` are `'none'`. No CDN is allowed: an allowlisted
+ module CDN can proxy arbitrary code, doubles as an exfiltration channel, and
+ makes rendering contact the network. `webrtc 'block'` is also sent, but
+ Chromium does not enforce it today: a guest can still open an
+ `RTCPeerConnection` and send STUN packets to an address it chooses. This
+ residual channel is accepted for v1 (the guest only sees what the model
+ wrote into it) and is tracked as a follow-up; the main window itself uses
+ WebRTC for live voice, so a process-wide WebRTC policy is not an option.
+6. Permission request and check handlers deny every request from a
+ `pi-genui:` origin.
+
+### Main window
+
+`apps/desktop/index.html` adds exactly `frame-src pi-genui:` to its CSP. The
+parent's `frame-src` also governs where the frame may navigate, so a
+visualization cannot replace itself with a remote page outside its own CSP.
+
+### Rendering (renderer)
+
+1. The assistant message bubble splits references out of the message content
+ before Markdown rendering and renders one card per reference. The shared
+ Markdown component is unchanged, so plugin READMEs, file previews, and tool
+ rows never show cards.
+2. The card is `<iframe sandbox="allow-scripts" loading="lazy">` without
+ `allow-same-origin`; the guest has an opaque origin and cannot reach the
+ host DOM, storage, or preload bridge.
+3. The renderer accepts only `{ type: "pi-genui:size", height }` and
+ `{ type: "pi-genui:wheel", deltaX, deltaY, deltaMode }` messages whose
+ `event.source` is that card's frame. Height is clamped to 120–2000 px
+ (initially 240 px). A wheel report is replayed as an untrusted `wheel`
+ event on the frame element: the guest is an out-of-process frame whose
+ input never reaches the transcript, so without it a scroll that chains out
+ of a card reads as programmatic and follow mode pulls the reader back. The
+ renderer posts `{ type: "pi-genui:theme", vars, colorScheme }` (host
+ design tokens mapped to `--color-*` names) when the resolved theme
+ changes and `{ type: "pi-genui:view", view }` on load.
+4. Expanding opens a modal with a fresh frame for the same URL. Moving an
+ iframe in the DOM reloads it anyway, and this version has no guest state to
+ lose. The `expanded` view centers the fragment in the dialog.
+5. A missing, invalid, or remote file renders an "unavailable" card with a
+ localized reason; the rest of the message renders normally. Serving errors
+ reach the card as a fixed code (`pi-genui:error`), never as text or paths.
+6. The number of simultaneously live frames is bounded so hidden session panes
+ do not accumulate pages.
+
+## Consequences
+
+- The transcript can show interactive pages without giving them host
+ capabilities, network access, or same-origin access.
+- host-core gains a small module mirroring the scratch lifecycle and a
+ behavior-preserving generalization of contained roots.
+- Plan mode cannot produce visualizations because it exposes no `Write` or
+ `Edit` tools.
+- Visualizations can use only the bundled libraries; any other library or
+ remote asset is blocked. The kit adds about 380 KB to the app resources.
+- Data-directory relocation and forks keep working; a fork owns copies of the
+ fragments it references, so deleting the parent does not break its cards.
+- A guest can still reach the network through WebRTC ICE until Chromium
+ enforces `webrtc 'block'` (see Serving item 5).
+
+## Alternatives
+
+- **Store fragments under `scratch/<sessionId>/visualizations/`.** About a third
+ of the change, but it changes D114's "scratch is temporary" meaning and still
+ needs a sweep exception. Rejected for unclear ownership.
+- **One `<webview>` per card (ZCode).** Process-level isolation, but requires
+ the webview tag, lifecycle management, and size syncing. An opaque-origin
+ sandboxed iframe behind a strict CSP is sufficient for this version.
+- **Declarative JSON component trees (A2UI).** Safer, but limited to predefined
+ components, which loses the expressiveness that motivates the feature.
+- **MCP Apps `ui://` first.** Standard, but tied to MCP tool results; it can
+ reuse this sandbox later.
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
index da447d18c..7a9422e55 100644
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@ -4,3 +4,8 @@
1.1.0 to 1.3.0. Preserve Desktop compatibility patches, omit foreign-model
thinking from replay, reject malformed final tool JSON before execution, and
expose the user-run discriminator to trusted extension startup handlers.
+- Render inline interactive visualizations in the transcript. Local sessions
+ get a builtin `visualize` skill; the model writes an HTML fragment to the
+ session's visualization directory and references it with a `::visualize`
+ line, which the transcript shows as a sandboxed, theme-aware card with an
+ expanded view.
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 5cc4eddff..e85f1a6ee 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -287,6 +287,41 @@ as binary content.
- A session lookup/storage error fails the tool request; it must never be
treated as a missing legacy session or redirected to the selected workspace.
+## 4b.1 Session visualization directory (D671)
+
+Inline visualizations (ADR `gen-ui-inline-visualization`) are HTML fragments the
+model writes for the transcript to render. They live in a third host-owned
+root, separate from scratch so that scratch keeps its 7-day sweep while a
+visualization lives as long as its session:
+
+```text
+<data_dir>/visualizations/<sessionId>/
+```
+
+- **Availability.** Local sessions only. A remote-workspace session gets no
+ directory, no prompt line, and no `pi-desktop/visualize` skill.
+- **Addressing.** Absolute paths only; the path is advertised in the system
+ prompt next to the scratch directory. Relative paths never resolve here.
+- **Containment.** `resolve_tool_path` checks the workspace, scratch, and
+ visualization roots in that order with the same lexical + symlink defense.
+- **Content.** `Write`/`Edit` accept only a single-component file name ending in
+ `.html`; anything else in this root fails with a tool error. `Read` is
+ allowed.
+- **Permissions.** `Write`/`Edit` inside the root auto-allow without a card,
+ under the same conditions as scratch. Plan and Goal expose no Write/Edit, so
+ contract modes cannot write here. Results carry `root: "visualization"`, are
+ not recorded as artifacts, and are not review-snapshotted.
+- **Lifecycle.** Created lazily on the first write. Deleted with
+ `session.delete`. The startup sweep removes only directories whose session
+ no longer exists; it never removes by age.
+- **Rendering.** A standalone `::visualize{"path":"<absolute path>","title":"…"}`
+ line outside code blocks renders as an inline card after the turn completes.
+ The renderer derives `pi-genui://session/<sessionId>/<file>` from the path
+ suffix and never sends the absolute path to Main. Main serves only regular,
+ non-symlink fragments up to 2 MB below the current data directory, rejects
+ full documents, and wraps the fragment in a host shell with a strict CSP
+ (no network, frames, or forms); the frame is `sandbox="allow-scripts"`.
+
## 4c. Message-owned review snapshots and rollback
`Write` and `Edit` are the structured review boundary. For a successful
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index 3d7cc6472..eed60a812 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -112,7 +112,7 @@ This does not recreate an unavailable custom storage volume during startup.
Rust's offline `--relocate-data <old-root> <copied-root>` mode owns structured
path relocation in the copied SQLite index, transcripts/revisions/checkpoints,
outbox, installed plugin registry and agent capability metadata. It does not boot
-RPC, upgrade schemas, recover turns, or sweep scratch. It changes only known
+RPC, upgrade schemas, recover turns, or sweep scratch or visualizations. It changes only known
path-bearing fields under the old root. External projects, dev/builtin plugins,
narrative text, commands, source code, secrets, and arbitrary plugin-private formats
are preserved. Credentials and their machine key migrate as bytes with their
@@ -190,11 +190,14 @@ to an absolute path before it reaches host-core as a child-process variable.
├── review-changes/<sessionId>/<snapshotId>/
│ ├── before # bounded pre-tool bytes, when reversible
│ └── meta.json # path, hashes, diff state, and ownership
- └── scratch/<sessionId>/ # per-session agent temp files (D114), including
- # composer pasted files under pasted/ and replayed/
- # image fallbacks — deleted
- # with the session; startup sweep removes orphans
- # and stale dirs
+ ├── scratch/<sessionId>/ # per-session agent temp files (D114), including
+ │ # composer pasted files under pasted/ and replayed/
+ │ # image fallbacks — deleted
+ │ # with the session; startup sweep removes orphans
+ │ # and stale dirs
+ └── visualizations/<sessionId>/ # inline visualization .html fragments (D671) —
+ # deleted with the session; startup sweep removes
+ # orphans only, never by age
```
One database file keeps cross-entity writes transactional (e.g. session +
@@ -706,6 +709,11 @@ CREATE INDEX idx_session_import_origins_plugin
later-message inputs outside a bounded fork, and other scratch outputs are
excluded. Missing expired inputs stay missing; no cross-session read grant
is added. Handled fork failures remove copied inputs and child transcripts.
+- Forks copy only the `visualizations/<sourceId>/` fragments the copied
+ transcript references into `visualizations/<childId>/` and rewrite those
+ `::visualize` paths; unreferenced fragments stay behind. Cards always load
+ from the owning session's directory, so deleting the source session does not
+ affect the fork (D671).
### 4.6 turns — one row per agent run
@@ -1202,8 +1210,8 @@ CREATE INDEX idx_artifacts_time ON artifacts(updated_at DESC);
Upserted by host-core in the same transaction as the `tool_execute` audit row
whenever Write/Edit (or a plugin tool declaring file effects) succeeds —
repeat edits update `op`/`updated_at`, keeping one row per file per session.
-Writes into the session scratch directory (D114) are excluded: artifacts list
-workspace deliverables only.
+Writes into the session scratch directory (D114) or the session visualization
+directory (D671) are excluded: artifacts list workspace deliverables only.
### 4.11 scheduled_tasks + task_runs — automations
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index a73dde68a..b0d1997ca 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -121,6 +121,7 @@ does not turn temporary thread pressure into a host process exit.
|---|---|---|
| `WORKSPACE_REQUIRED` | no | no workspace bound |
| `PATH_OUTSIDE_WORKSPACE` | no | path escapes sandbox before an explicit outside-path permission decision, or a prompt attachment is outside its session scratch/project/attachment roots |
+| `VISUALIZATION_HTML_ONLY` | no | a Write/Edit into the session visualization directory is not a direct-child `.html` fragment |
| `WORKSPACE_PATH_DENIED` | no | an explicit `Read`/`Write`/`Edit` path hit the always-on security denylist (private keys, `.env` files, credential bundles, `.git/objects`); an outside-path grant does not lift it (spec 15 §3) |
| `READ_PATH_IS_DIRECTORY` | no | `Read` was given a directory; the result carries a `Glob` suggestion |
| `TOOL_BINARY_CONTENT` | no | `Read` refused to dump a binary file into the model context |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index e7ebdf2cf..4174bb753 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -18604,3 +18604,29 @@ host-created files. The full app's file-preview viewer is covered separately.
`composer-suggestion-state.test.mjs`, `composer-suggestion-relay.test.mjs`,
and `plugin-composer-suggestion.test.mjs`; the rendered journey remains a
manual/Electron check when this surface changes.
+
+### E2E-GENUI-inline-visualization-card: a visualization renders inline and stays sandboxed
+
+- **Preconditions**: The app is running with a local Agent session and the
+ builtin `pi-desktop/visualize` skill enabled. A second session uses a remote
+ workspace.
+- **Steps**: 1) Ask for an interactive chart (for example "show a slider that
+ changes a sine wave's frequency"). 2) Wait for the turn to finish, then drag
+ the slider. 3) Switch the app theme between light and dark. 4) Press the
+ card's expand button, then Esc. 5) Ask the model to write a non-`.html` file
+ into the visualization directory, and to write a fragment that calls
+ `fetch("https://example.com")`. 6) Fork the session, then delete the source
+ session. 7) Repeat step 1 in the remote session.
+- **Expected**:
+ - No permission card appears for the fragment write. While streaming, the
+ reply shows plain text; after completion the `::visualize` line is
+ replaced by a card whose height fits the content (at most 2000 px).
+ - The slider works; theme changes recolor the card without a reload.
+ - Expand opens a large modal copy; Esc closes it and the inline card keeps
+ its state.
+ - The non-`.html` write fails with a tool error; the network call fails and
+ nothing leaves the machine; the frame cannot open popups or navigate.
+ - The fork shows the same card until the source session is deleted, then an
+ "unavailable" card. The source's `visualizations/<sessionId>/` directory is
+ removed with it.
+ - The remote session gets no visualization directory or skill.
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index da0a75865..e3f8ab2c4 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -334,6 +334,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.
| D620 | pi-ai built-in API-key services are named presets | **Add fifteen named endpoint presets — Ant Ling, Baseten, Cerebras, Hugging Face, Meta (`responses`), MiniMax (International), Moonshot AI (International), NVIDIA, OpenCode Zen, Vercel AI Gateway, Qwen Token Plan (`alibaba-token-plan`), Qwen Token Plan (China), Xiaomi Token Plan (China / Europe / Singapore) — to `NAMED_ENDPOINT_PRESETS`, each at its published host, with the pi-ai provider id kept as an alias wherever the models.dev key differs. Eight built-in providers remain exceptions with a recorded reason: Amazon Bedrock, Azure OpenAI, Cloudflare AI Gateway, Cloudflare Workers AI, Google Vertex AI (account- or region-scoped URLs), GitHub Copilot and OpenAI Codex (vendor-account rows), and Radius (`pi_messages` is account-only here). `packages/agent-runtime/src/pi-ai-provider-sync.test.ts` fails on a pi-ai upgrade that leaves a provider neither covered nor excepted. No protocol, storage, or IPC change.** | Every other pi-ai capability was already reachable, but the API-key half of the service catalog was hand-maintained and had drifted from the library's own provider list (ADR 0307). |
| D668 | One process disclosure per turn, with three transcript display modes | **Amend D661 / the `turn-process-and-thinking-display` ADR. A turn renders exactly one top-level process disclosure holding every pre-answer row; the answer stays outside it. `AppSettings.transcriptDisplayMode` selects the layout: `flat` renders no nested activity groups, `command-first` renders `Bash`/run rows as standalone rows beside activity groups, and `fully-folded` (the default for absent or invalid values) keeps commands inside their groups and lets only ordinary assistant progress text split them. The mode is read while rendering, so switching repaints immediately - the projection cache is keyed by messages and compactions only. The disclosure header reports failed / stopped / running / finished with precedence in that order and never echoes the current item, and the disclosure shares one left edge with the levels it reveals. `transcriptDisplayMode` joins the portable application fields; `keepCommandsExpanded` is deprecated, retained only for persisted-settings compatibility, and no longer exposed or read for rendering. No host protocol, persistence schema, permission, or plugin contract change. See the amended ADR, `04-ux/06-settings-ia.md`, `04-ux/08-component-spec.md`, `04-ux/09-interaction-patterns.md`, and E2E-CHAT-turn-process-and-thinking-display.** | Chronological segmentation split one turn into several sibling disclosures above the answer, and the boolean command-folding preference could only express two layouts; a three-mode setting covers flat, command-first, and the released grouped view without changing what a tool received or stored. |
| D669 | `@` queries search past a truncated file index | **Amend D124: while the 8000-entry `fs/index` snapshot is truncated, a non-empty `@` query is also searched over the root's full listing through the read-only Electron channel `pi-desktop/fs/search` once typing pauses, and its best 50 rows merge with the local matches. A complete index never searches. Remote sessions keep their snapshot. No host RPC, storage, or schema change.** | The shallowest-8000-entry index left a script several folders down matching no query at all, even though the truncation note invited the reader to refine it (issue #1781). |
+| D671 | Inline generative UI visualizations | **Amend D114: local sessions get a second host-owned contained root `<data_dir>/visualizations/<sessionId>/` for `.html` fragments only (Read/Write/Edit, auto-allowed like scratch, never in remote or contract sessions). A standalone `::visualize{"path","title"}` reply line renders the fragment inline through a sandboxed `pi-genui://session/<sid>/<file>` iframe (`sandbox="allow-scripts"`, strict CSP, no network). Builtin skill `pi-desktop/visualize`. No schema change.** | Interactive explanations need an embedded page; ADR gen-ui-inline-visualization. |
## M0. Model catalog decisions
@@ -7918,3 +7919,31 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
and closed payloads. See `04-ux/08-component-spec.md`,
`04-ux/09-interaction-patterns.md`, and
E2E-CHAT-turn-process-and-thinking-display.
+
+## 2026-10-22 — Inline generative UI visualizations (D671)
+
+- Models explain dynamic systems, tunable parameters, and spatial relations
+ better with a small interactive page than with prose or Mermaid, but the
+ transcript renders Markdown only.
+- Local sessions get `<data_dir>/visualizations/<sessionId>/`, a second
+ contained root next to scratch (D114). Write/Edit accept only `.html`
+ fragments there, without a permission prompt; the directory is removed with
+ its session and orphan directories are swept at startup, never by age.
+ Remote-workspace and contract sessions get neither the root nor the skill.
+- A standalone `::visualize{"path":"…","title":"…"}` line outside code blocks
+ becomes an inline card once the turn completes. Main serves the fragment
+ through `pi-genui://session/<sessionId>/<file>` inside a host shell with a
+ strict CSP (no network, no frames, no forms) and a sandboxed iframe
+ (`allow-scripts` only); the URL is derived from the path suffix, so data-dir
+ relocation does not break old references. Cards always load from the
+ owning session; forks copy the fragments they reference. Theme and height
+ travel by `postMessage`. WebRTC ICE is not blocked by Chromium yet and is a
+ documented residual risk.
+- The shell embeds a stylesheet and tooltip/tab runtime adapted from ZCode's
+ Apache-2.0 visualize kit, plus offline D3 7.9.0 and Floating UI served from
+ `pi-genui://assets` (pinned CDN URLs are rewritten; any other remote URL is
+ blocked). The skill is a condensed adaptation of ZCode's.
+- v1 has no widget state, follow-up messages, CDN access, icons, or tweak
+ panel.
+ See ADR `gen-ui-inline-visualization`, `03-runtime/03-tools-and-permissions.md`
+ §4b.1, `03-runtime/04-data-storage.md`, and E2E-GENUI-inline-visualization-card.
diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
index 0eab90abf..131cea39c 100644
--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md
@@ -219,6 +219,35 @@ Electron 主要低于 `<data_dir>/scratch/<sessionId>/pasted/` 之前的
- 会话 lookup/storage 错误使工具请求失败;它绝不能是
被视为丢失的旧会话或重定向到选定的工作区。
+## 4b.1 会话可视化目录(D671)
+
+内联可视化(ADR `gen-ui-inline-visualization`)是模型写出、由转录区渲染的 HTML 片段。
+它们放在第三个由宿主拥有的根目录中,与 scratch 分开,这样 scratch 保留 7 天清理,
+而可视化与会话同生命周期:
+
+```text
+<data_dir>/visualizations/<sessionId>/
+```
+
+- **可用范围。** 仅本地会话。远程工作区会话没有该目录、没有提示行,也没有
+ `pi-desktop/visualize` skill。
+- **寻址。** 只接受绝对路径;路径在系统提示中与 scratch 目录一起给出。相对路径
+ 永远不会解析到这里。
+- **包含校验。** `resolve_tool_path` 依次检查工作区、scratch、可视化三个根目录,
+ 使用相同的词法 + 符号链接防护。
+- **内容。** `Write`/`Edit` 只接受以 `.html` 结尾的单层文件名;该根目录下的其他目标
+ 返回工具错误。允许 `Read`。
+- **权限。** 在该根目录内的 `Write`/`Edit` 与 scratch 条件相同,免确认自动允许。
+ Plan 和 Goal 不提供 Write/Edit,因此合约模式无法写入这里。结果带
+ `root: "visualization"`,不记为工件,也不做审核快照。
+- **生命周期。** 首次写入时延迟创建。随 `session.delete` 删除。启动清理只删除会话已
+ 不存在的目录,从不按时间删除。
+- **渲染。** 代码块之外单独一行 `::visualize{"path":"<绝对路径>","title":"…"}` 会在
+ 回合完成后渲染为内联卡片。渲染层由路径后缀推导出
+ `pi-genui://session/<sessionId>/<file>`,从不把绝对路径发给 Main。Main 只提供当前
+ 数据目录下不超过 2 MB 的普通非符号链接片段,拒绝完整文档,并把片段包进带严格 CSP
+ (无网络、子框架、表单)的宿主外壳;框架为 `sandbox="allow-scripts"`。
+
## 4c。消息拥有的审核快照和回滚
`Write` 和 `Edit` 是结构化审核边界。对于一个成功的
diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.md
index 60132669b..94f093322 100644
--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md
+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md
@@ -64,12 +64,15 @@ host-core 之前被解析为绝对路径。
├── review-changes/<sessionId>/<snapshotId>/
│ ├── before # bounded pre-tool bytes, when reversible
│ └── meta.json # path, hashes, diff state, and ownership
- └── scratch/<sessionId>/ # per-session agent temp files (D114), including
- # composer pasted files under pasted/ — deleted
- # with the session; startup sweep removes orphans
-
- # with the session; startup sweep removes orphans
- # and stale dirs
+ ├── scratch/<sessionId>/ # per-session agent temp files (D114), including
+ │ # composer pasted files under pasted/ — deleted
+ │ # with the session; startup sweep removes orphans
+
+ │ # with the session; startup sweep removes orphans
+ │ # and stale dirs
+ └── visualizations/<sessionId>/ # inline visualization .html fragments (D671) —
+ # deleted with the session; startup sweep removes
+ # orphans only, never by age
```
一个数据库文件保持跨实体写入事务性(例如会话+
@@ -459,6 +462,9 @@ CREATE INDEX idx_session_import_origins_plugin
删除原任务不会删除子任务的副本。未引用文件、截断点之后独有的输入和其他
scratch 输出不复制;已过期的文件仍不可用,不新增跨任务读取授权。
分支失败时清理已复制的输入及子任务转录本。
+- 分支只把复制的转录本所引用的 `visualizations/<sourceId>/` 片段复制到
+ `visualizations/<childId>/`,并改写这些 `::visualize` 路径;未引用的片段不复制。
+ 卡片总是从所属会话的目录加载,所以删除原会话不影响分支(D671)。
### 4.6 turns — 每次 agent 运行一行
@@ -896,7 +902,7 @@ CREATE INDEX idx_artifacts_time ON artifacts(updated_at DESC);
由 host-core 在与 `tool_execute` 审计行相同的事务中更新插入
每当 Write/Edit(或声明文件效果的插件工具)成功时 -
重复编辑更新 Write/Edit/`op`,每个会话每个文件保留一行。
-写入会话暂存目录 (D114) 被排除:工件列表
+写入会话暂存目录 (D114) 或会话可视化目录 (D671) 被排除:工件列表
仅工作区可交付成果。
### 4.11 scheduled_tasks + task_runs — 自动化
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 49365f018..52d49ea4a 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -123,6 +123,7 @@ stdio 与 Tokio 的动态阻塞池隔离,因此后一种情况
|---|---|---|
| `WORKSPACE_REQUIRED` | 不 | 无工作空间限制 |
| `PATH_OUTSIDE_WORKSPACE` | 不 | 在显式外部路径权限决策之前路径逃逸沙箱,或提示词附件位于其会话 scratch/project/attachment 根目录之外 |
+| `VISUALIZATION_HTML_ONLY` | 不 | 写入会话可视化目录的 Write/Edit 目标不是该目录下直接一层的 `.html` 片段 |
| `WORKSPACE_PATH_DENIED` | 不 | 显式的 `Read`/`Write`/`Edit` 路径命中了始终开启的安全拒绝名单(私钥、`.env` 文件、凭证包、`.git/objects`);外部路径授权不会解除它(规格 15 §3) |
| `READ_PATH_IS_DIRECTORY` | 不 | `Read` 拿到的是目录;结果附带一条 `Glob` 建议 |
| `TOOL_BINARY_CONTENT` | 不 | `Read` 拒绝把二进制文件倾倒进模型上下文 |
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index 50bb3987a..44ee3d882 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -337,6 +337,7 @@
| D620 | pi-ai 内置的 API-key 服务成为命名预设 | **向 `NAMED_ENDPOINT_PRESETS` 新增十五条命名预设——Ant Ling、Baseten、Cerebras、Hugging Face、Meta(`responses`)、MiniMax(国际)、Moonshot AI(国际)、NVIDIA、OpenCode Zen、Vercel AI Gateway、Qwen Token 套餐(`alibaba-token-plan`)、Qwen Token 套餐(中国)、小米 Token 套餐(中国/欧洲/新加坡)——各自使用官方主机名;models.dev 键与 pi-ai 提供方 id 不同的那几条,把 pi-ai id 保留为别名。八个内置提供方仍作例外并写明原因:Amazon Bedrock、Azure OpenAI、Cloudflare AI Gateway、Cloudflare Workers AI、Google Vertex AI(URL 里带账户或区域),GitHub Copilot 与 OpenAI Codex(以厂商账号行提供),以及 Radius(这里的 `pi_messages` 仅限账号)。pi-ai 升级后若某提供方既未被覆盖也不在例外中,`packages/agent-runtime/src/pi-ai-provider-sync.test.ts` 会失败。不改协议、存储或 IPC。** | pi-ai 其他能力本就可达,但服务目录的 API-key 一半靠手工维护,已经跟库自带的提供方列表脱节(ADR 0307)。 |
| D668 | 每回合一个过程披露,并提供三种转录显示模式 | **修订 D661 / `turn-process-and-thinking-display` ADR:每个回合渲染一个顶层过程披露,包含回答前的全部行;回答留在披露之外。`AppSettings.transcriptDisplayMode` 选择布局:`flat` 不渲染嵌套活动组,`command-first` 将 `Bash`/run 行作为活动组旁的独立行,`fully-folded`(缺失或无效值的默认)让命令留在所属组内,且只有普通助手进度文字会拆分活动组。该模式在渲染时读取,因此切换后立即重绘——投影缓存只以消息和压缩为键。披露标题按失败/停止/执行中/已完成的优先级报告,且绝不回显当前条目;披露与它展开的层级共用一条左边缘。`transcriptDisplayMode` 加入可移植应用字段;`keepCommandsExpanded` 已弃用,仅为持久化设置兼容性保留,不再暴露,也不再参与渲染读取。无 Host 协议、持久化 schema、权限或插件契约变更。见修订后的 ADR、`04-ux/06-settings-ia.md`、`04-ux/08-component-spec.md`、`04-ux/09-interaction-patterns.md` 与 E2E-CHAT-turn-process-and-thinking-display。** | 按时间顺序的分段把同一回合拆成答案上方多个并列披露,而布尔命令折叠偏好只能表达两种布局;三种模式覆盖平铺、命令优先与已发布的分组视图,且不改变工具收到的内容或持久化内容。 |
| D669 | `@` 查询越过被截断的文件索引 | **修订 D124:8000 条的 `fs/index` 快照被截断时,非空的 `@` 查询会在输入停顿后,通过只读的 Electron 通道 `pi-desktop/fs/search` 在该根目录的完整清单中搜索,最好的 50 行与本地匹配合并。完整的索引从不搜索。远程会话保持使用快照。不改变主机 RPC、存储或 schema。** | 只保留最浅 8000 条的索引,会让深几层目录里的脚本对任何查询都匹配不到,而截断提示还在邀请用户细化查询(issue #1781)。 |
+| D671 | 对话内联生成式 UI 可视化 | **修订 D114:本地会话新增第二个由宿主拥有的受控根目录 `<data_dir>/visualizations/<sessionId>/`,仅用于 `.html` 片段(Read/Write/Edit,与 scratch 一样免确认,远程会话和合约会话中不提供)。回复中单独一行 `::visualize{"path","title"}` 会通过沙箱化的 `pi-genui://session/<sid>/<file>` iframe(`sandbox="allow-scripts"`、严格 CSP、无网络)内联渲染该片段。内置 skill `pi-desktop/visualize`。不改变 schema。** | 交互式讲解需要内嵌页面;见 ADR gen-ui-inline-visualization。 |
## M0. 模型目录决策
@@ -5528,3 +5529,24 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
`apps/desktop/test/composer-deep-file-search-user-path.test.mjs` 覆盖。见
`03-runtime/01-ipc-protocol.md` §13c、`04-ux/08-component-spec.md` §11.8 与
E2E-COMPOSER-deep-file-mentions。
+
+## 2026-10-22 —— 对话内联生成式 UI 可视化(D671)
+
+- 讲解动态系统、可调参数和空间关系时,小型交互页面比文字或 Mermaid 更清楚,但转录区
+ 只渲染 Markdown。
+- 本地会话获得 `<data_dir>/visualizations/<sessionId>/`,作为 scratch(D114)之外的
+ 第二个受控根目录。Write/Edit 在其中只接受 `.html` 片段,不弹权限确认;目录随会话
+ 删除,启动时只清理孤儿目录,从不按时间清理。远程工作区会话和合约会话既没有该目录,
+ 也没有该 skill。
+- 代码块之外单独一行 `::visualize{"path":"…","title":"…"}` 会在回合完成后变成内联卡片。
+ Main 通过 `pi-genui://session/<sessionId>/<file>` 提供片段,外包一层带严格 CSP(无网络、
+ 无子框架、无表单)的宿主外壳,并放在沙箱 iframe(仅 `allow-scripts`)中;URL 由路径
+ 后缀推导,因此数据目录迁移不会破坏旧引用。卡片总是从所属会话加载;分支会复制其引用
+ 的片段。主题和高度通过 `postMessage` 传递。Chromium 尚未拦截 WebRTC ICE,这是已记录
+ 的残留风险。
+- 外壳内嵌改编自 ZCode Apache-2.0 visualize 套件的样式表和 tooltip/标签页运行时,以及
+ 从 `pi-genui://assets` 提供的离线 D3 7.9.0 与 Floating UI(固定版本的 CDN 地址会被
+ 改写,其他远程地址一律拦截)。skill 是 ZCode skill 的精简改编。
+- v1 不支持控件状态、后续消息、CDN、图标库和微调面板。
+ 见 ADR `gen-ui-inline-visualization`、`03-runtime/03-tools-and-permissions.md`
+ §4b.1、`03-runtime/04-data-storage.md` 与 E2E-GENUI-inline-visualization-card。