Skip to content

feat(agents): show sandboxed interactive visuals on web and desktop - #685

Merged
nixuuu merged 1 commit into
feat/agent-visuals-workerfrom
feat/agent-visuals-web
Nov 14, 2026
Merged

nixuuu merged 1 commit into
feat/agent-visuals-workerfrom
feat/agent-visuals-web

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Web and desktop renderer for visuals (docs/agent-visuals.md §4, ui-api.md "Visuals").

  • The visual item shows under the reply, outside folded work (reply-items.ts, shared with image galleries).
  • frame-host.ts: <iframe sandbox="allow-scripts" referrerpolicy="no-referrer" allow=""> via srcdoc, compiled per mount with a fresh nonce and instance. One MessagePort goes to that frame's window after load (exactly once). After that, only parsed messages are read: 10/s, heights 4/s, one height change per animation frame, clamped to 160–720 px. Theme (Appearance, light/dark, Interface size) and reduced motion reach the frame through the port.
  • Lazy and bounded: the spec loads via the BFF only when the visual is visible and a slot is free (2 frames, 1 on narrow screens; LRU of 16 specs / 2 MiB). "Open visual" takes the oldest unfocused slot. Leaving the view pauses at once and removes the frame after 5 s; a hidden window removes it at once. The last height stays reserved. The compiler and kit load lazily.
  • Local control state is validated against the spec and cached only in this device's localStorage (64 entries / 256 KiB, per version).
  • Host chrome: "Version N", "Open full screen" (dialog with the same sandbox), "Download HTML" (BFF compiles the export; served as attachment + text/plain + nosniff + CSP sandbox), "Copy spec", "Cite visual" (a text citation with title, version, visual:<id>@<n> and description) and a version picker. A new version replaces the view, unless the frame has focus: then "A new version is available." with "Reload".
  • Desktop: srcdoc frames inherit the window CSP, so DocumentPolicy admits exactly the kit script's hash (KIT_SCRIPT_CSP). Verified in Chromium: without it the kit is blocked; with it the kit runs; frame-src 'none' doesn't block srcdoc. No preload or IPC is exposed to the subframe, and window-open and navigation guards are unchanged.

Browser review (disposable stack on the review host, SQL fixture, headless Chromium through an SSH tunnel; cleaned up afterwards): light and dark, 1280 px and 390 px. Checked: short, typical and long titles (truncation), two versions with the picker, slot limit and eviction, toggles and segmented controls without layout shift (card box unchanged), full screen with controls and tabs, menu, HTML download headers. Electron itself was not launched; the CSP inheritance was verified in Chromium with the exact desktop policy.

Review fixes:

  • Every menu action (Download HTML, Copy spec, Cite visual) uses the version on screen: a picked older version, or the one kept while "A new version is available." waits. The header title, description and full-screen title follow the same version.
  • Escape inside the frame closes full screen (the kit's escape message).
  • The actions menu is a bottom sheet on phones, so it stays in the viewport even when the card header sits under the thread bar.
  • ?version= outside uint32 returns 400.
  • document-policy.ts explains that the kit hash also applies to the main window, because srcdoc frames inherit its policy.

Re-checked in the browser on the review host: Escape closes full screen; Version 1 picked → header "Version 1", its title, download ?version=1; phone (dark) sheet fully visible; a ±1e308 chart draws at the axis edge.

Copy audit (docs/copy.md §8):

Text Check
Version N, Version N (latest), Versions Sentence case; no repeat of the title.
Open full screen, Download HTML, Copy spec, Cite visual, Open visual, Reload, Retry, Reset, Previous, Next, Show data / Hide data Verbs first; "Cite" per the glossary.
Couldn't cite this visual. Try again. Toast pattern, says what to do.
Couldn't open this visual. + Retry What happened, then the action; no sandbox/API jargon. Kit fallback aligned to the same wording.
Update Canopy to open this visual. Says what to do.
A new version is available. + Reload One idea, one action.
Close another visual to open this one. Shown only when every slot holds focus; says what to do.
Shown in full screen. Placeholder while the dialog is open (was "Open in full screen.", changed: it read like an action).
Spec copied / Couldn't copy the spec. Try again. Toast pattern.
Glossary "visual" added (banned: widget, app, embed, applet). No humour.

Mobile: #688 shows a text-only summary card; the interactive WebView renderer comes later with a native build.


Stack #686 (merge together: gh stack merge 686 --squash): #682 spec/kit → #683 gateway → #684 worker → #685 web/desktop → #688 mobile fallback.

Merge order: this stack merges first; migration 0139_thread_visuals follows dev's 0138, and the drafts stack moves to 0140. 0139 keeps every tool value of 0138 (show_images, import_image_reply) and adds render_visual. Item.visual = 26 follows image_gallery = 25.

Visual items render under the reply in an opaque-origin srcdoc frame with
the pinned kit, a per-mount nonce and one MessagePort. Frames mount lazily,
are bounded to two (one on narrow screens), pause offscreen and follow the
appearance. Host chrome offers full screen, HTML download, copy spec, cite
and version history. The desktop policy admits exactly the kit script.
@nixuuu
nixuuu force-pushed the feat/agent-visuals-web branch from aff170f to fd74414 Compare November 14, 2026 01:36
@nixuuu
nixuuu marked this pull request as ready for review November 14, 2026 01:36
@nixuuu
nixuuu merged commit 9884569 into dev Nov 14, 2026
11 checks passed
@nixuuu
nixuuu deleted the feat/agent-visuals-web branch November 14, 2026 01:48
nixuuu added a commit that referenced this pull request Nov 14, 2026
…er (#682)

Implements the visual spec v1, its validator and the trusted kit from
docs/agent-visuals.md (§3, §4).

- `packages/domain/src/visuals`: Effect Schema for the component tree
(26 components: layout, content, controls, comparisons, flow/sequence,
charts). Strict decoding: unknown fields, components and tokens are
path-named errors. Limits are checked from cheapest to most expensive:
128 KiB serialized, raw nesting without recursion, 300 nodes, 12 levels,
32 KiB text, tables 100×12, diagrams 40/80, charts 200 points / 6
series, 8 actions per button, 32 state keys.
- State domains come from the controls bound to each key. References
(`*_from`, `when`, `set` values, highlight/step keys) are checked before
storage. `validVisualState` validates cached state.
- `visual-kit/`: a DOM runtime that renders with `textContent` only and
never parses markup. `bun run gen` bundles it with the pinned Bun into
`src/visuals/gen/kit.ts` (ASCII-only), and `gen:check` covers it. It
exports the script's CSP hash for hosts whose policy srcdoc frames
inherit.
- `compile.ts`: one self-contained document with the §4 CSP (everything
`'none'` except nonced kit script/styles), an escaped title and the spec
as inert JSON (`<`, `>`, `&`, U+2028/9 escaped). Limit 2 MiB.
- `protocol.ts`: frame messages `ready`, `height`, `local_state`,
`render_error` and `escape` (Escape only, so the host can close full
screen; no other input is forwarded); handshake (instance + nonce,
parent window only), message parsers for both sides, rate windows and
height clamping. Theme tokens accept only hex or `color-mix` of hex
colours.

- Charts clamp the axis to ±1e15, so finite extremes like ±1e308 draw at
the edge instead of producing NaN coordinates; the data table shows the
values as given.

Tests: `packages/domain/src/visuals/spec.test.ts` covers unknown fields
and code-like fields, node, depth, text and size limits, a 10 000-level
hostile nesting, references, XSS in title, text and serialization, mount
identifiers, foreign state and protocol parsing.

Measured (headless Chromium, loaded host, max spec of 295 nodes and 200
chart points): validation 9 ms, compile 0.4 ms, 59 KB HTML. Two frames
ready in ~275 ms. Local interaction p95 50 ms (two-rAF measurement;
budget 100 ms). One 84 ms long task during the initial render of the max
spec; none during interaction. Memory (USS of the browser tree, median
of 3): +10.2 MiB for one frame, +16.4 MiB for two (budget 32 MiB). RSS
shows +146 MiB for the first frame because Chromium starts a separate
renderer for sandboxed frames; that is mostly shared library pages.

---
Stack #686 (merge together: `gh stack merge 686 --squash`): #682
spec/kit → #683 gateway → #684 worker → #685 web/desktop → #688 mobile
fallback.

**Merge order:** this stack merges first; migration
`0139_thread_visuals` follows dev's 0138, and the drafts stack moves to
0140. 0139 keeps every tool value of 0138 (`show_images`,
`import_image_reply`) and adds `render_visual`. `Item.visual = 26`
follows `image_gallery = 25`.
nixuuu added a commit that referenced this pull request Nov 14, 2026
Gateway side of visuals (docs/agent-visuals.md §5).

- `render_visual` joins `AGENT_BUS_TOOLS`: providers get `spec` as an
object plus a compact catalogue, state rules, an example and the limits
in the description. The bus decoder rejects oversized arguments before
parsing, then validates the spec fully.
- `core/visual-publication.ts`, `store/visuals.ts`: needs a running
turn, the pinned worker with `thread_visuals_v1` (older workers get
"Update this computer to show visuals in Canopy.") and a non-archived
thread. One transaction stores the immutable version, upserts the
`visual-<id>` item in its original place, writes the `item_completed`
event, call record and audit, and applies the per-turn limits (10
visuals, 1 MiB). Updates require `visual_id` + `expected_version` of the
same thread; a mismatch is a conflict naming the current version. Replay
by call ID returns the same result. The call record stores no spec.
- `Item.visual = 26` is a small manifest; the spec never travels in
events or `WatchThread`. `GetVisual` is owner-scoped (the visual's own
thread or a fork showing it) and routes to the thread's home like
`GetThreadBlob`. `MovedThread.visuals_json = 4` carries versions on
thread moves. Worker events that create or change visual items are
quarantined.
- `Welcome.thread_visuals_v1 = 7` tells workers this gateway executes
`render_visual`.
- Migration `0139_thread_visuals` (see merge order below).

Tests: `tests/integration/visuals.test.ts` (persistence, manifest-only
item, replay, versioning in place, conflict, foreign visual, owner
scoping, strict validation, per-turn limit, old worker refusal, forged
item quarantine), and an extended `computer-moves.test.ts` (a visual
stays readable after a move). `packages/db` schema list updated.

---
Stack #686 (merge together: `gh stack merge 686 --squash`): #682
spec/kit → #683 gateway → #684 worker → #685 web/desktop → #688 mobile
fallback.

**Merge order:** this stack merges first; migration
`0139_thread_visuals` follows dev's 0138, and the drafts stack moves to
0140. 0139 keeps every tool value of 0138 (`show_images`,
`import_image_reply`) and adds `render_visual`. `Item.visual = 26`
follows `image_gallery = 25`.
nixuuu added a commit that referenced this pull request Nov 14, 2026
Workers announce `thread_visuals_v1`. No adapter code changes: Claude
(`mcp__canopy__render_visual`), Codex (dynamic tool in `canopy`) and
Grok (local HTTP MCP) build their tool lists from `AGENT_BUS_TOOLS` and
forward `AgentToolCall` to the gateway. The tool is offered at both
levels, so side threads can publish in their own thread. As with other
bus tools, Codex threads created earlier don't get it after resume.

On a gateway without `Welcome.thread_visuals_v1`, the worker answers
`render_visual` itself with "Update Canopy on the gateway computer to
show visuals." instead of relaying "unknown agent bus tool"
(`runtime/tool-gates.ts`).

The model guidance lives in the tool description (catalogue, state,
example, limits; controls never contact the agent; `ask_user` for
decisions), with no extra system prompt.

Tests: `tests/integration/visual-harnesses.test.ts` drives each adapter
(scripted Codex app-server, Claude in-process MCP, Grok HTTP MCP)
through gRPC into PostgreSQL, plus the old-gateway refusal.
`support/bus-app-server.ts` takes the tool name as an argument (as the
image stack does). Live tests: none added; no provider credentials were
used.

---
Stack #686 (merge together: `gh stack merge 686 --squash`): #682
spec/kit → #683 gateway → #684 worker → #685 web/desktop → #688 mobile
fallback.

**Merge order:** this stack merges first; migration
`0139_thread_visuals` follows dev's 0138, and the drafts stack moves to
0140. 0139 keeps every tool value of 0138 (`show_images`,
`import_image_reply`) and adds `render_visual`. `Item.visual = 26`
follows `image_gallery = 25`.
nixuuu added a commit that referenced this pull request Nov 14, 2026
…688)

Mobile fallback for visuals, with no native code (docs/mobile.md
"Visuals agenta").

- `VisualSummary` shows the visual's title, "Version N" and "Open this
visual on web or desktop.", styled like the other timeline cards
(surface, ring, 12 px radius, medium title, muted meta). The description
goes into the accessibility label. The spec is never read or run.
- Visual items stay under the reply when the turn's work is folded, like
image galleries (`TimelineTurn.tsx`).
- Fingerprints are unchanged (`@expo/fingerprint fingerprint:generate`):
iOS `74705db3a68907bc28379bb9b1080a227bc0755b`, Android
`7d38be8f5c9bf842d62060c75820a206f99c87e3`, before and after.
- `expo export` succeeds for iOS and Android; mobile typecheck and
ESLint are clean. Device checks remain blocked (device host), so there
are no on-device screenshots.

The interactive renderer needs `react-native-webview` (the linked
`@expo/dom-webview` can't meet the §4 boundary). Per the plan it ships
later, in one native build with #659.

**Copy audit (docs/copy.md §8):**
| Text | Check |
|---|---|
| Version N | Sentence case, tabular digits, no repeat of the title. |
| Open this visual on web or desktop. | One idea, verb first, says where
it works; no jargon about WebViews or sandboxes. |
| Accessibility label "Visual: <title>, version N. <description> Open
this visual on web or desktop." | Reads the same facts in order;
"visual" per the glossary. |


---
Stack #686 (merge together: `gh stack merge 686 --squash`): #682
spec/kit → #683 gateway → #684 worker → #685 web/desktop → #688 mobile
fallback.

**Merge order:** this stack merges first; migration
`0139_thread_visuals` follows dev's 0138, and the drafts stack moves to
0140. 0139 keeps every tool value of 0138 (`show_images`,
`import_image_reply`) and adds `render_visual`. `Item.visual = 26`
follows `image_gallery = 25`.
nixuuu added a commit that referenced this pull request Nov 14, 2026
## Problem

On web and desktop, the thread stops scrolling while the cursor is over
an interactive visual, then jumps once the cursor leaves it. The user's
recording shows this.

## Root cause

Wheel and touch input over the sandboxed visual frame goes to the
frame's document. The frame can't scroll, so the scroll chains to the
thread feed, but the feed never gets the `wheel` event. `ScrollIntent`
labels that scroll `unattributed` and `settle()` treats it as a layout
change. It then restores the reading anchor, or the end when following,
and every step is undone.

## Fix

- The kit reports `hover`: a bare boolean that says whether the pointer
is over the frame. It carries no coordinates and forwards no other
events. The kit sends at most 4 per second, and the last report always
carries the current state. `VisualFrameInbox` parses it, checks the
type, and rate-limits it with its own window (`hoversPerSecond`).
- The web host turns that state into an event on the frame element.
While a frame is hovered, the feed counts a scroll under it as the
reader's. A `pointermove` in the feed's own document clears the state,
and so does unmounting the frame.
- The kit document is scrollable only when the host caps the frame below
its content (`overflow: hidden` otherwise). A document that can scroll
even 1px captures a whole wheel gesture. The height is now measured from
the bounding box and rounded up. `ready` includes the body padding too,
so the frame no longer hops 24px after mount.
- Security model unchanged: `allow-scripts` only, same CSP, port-only
channel.
- Mobile: the native list scrolls the WebView (`scrollEnabled={false}`),
so mobile doesn't have this problem. Mobile ignores the new message.

A per-gesture message didn't work: in Chromium (site-per-process), the
feed's scroll event can arrive before the frame's message, even with a
non-passive listener. The hover state arrives long before any wheel.

## Verification

Chromium with `--site-per-process`, on the `/dev/long-thread` feed with
a local fixture (not committed) that adds a tabs + stats + chart visual
every third turn. I measured how far a row moved on screen for each
wheel step:

| Scenario | `dev` | this branch |
| --- | --- | --- |
| 120 × −40 px, cursor fixed over visuals while they pass | 0 px on all
120 steps (frozen) | same as the margin run |
| 120 × +40 px, over visuals | 0 px on all 120 steps | 4800 / 4800 px, 0
off-steps |
| Following the end, 30 × −20 px starting over a visual | – | 600 / 600
px, 0 off-steps |
| Same scroll with the cursor on the feed margin (control) | baseline |
identical to the run over visuals |

- Light and dark both checked.
- The odd −360…−400 px step in the "up" runs also happens over the
margin and on `dev`: it is the virtual feed measuring rows above, not
the frames.
- Inside a fitting frame: `overflowY: hidden`, scrollHeight equals
innerHeight (719).
- Not checked in Electron itself. It runs the same Chromium engine with
site isolation, which the runs above enable.

Checks: `bun install`, `gen:check`, `typecheck`, `lint`, `format:check`,
`check:tmp`, the web build, `expo export` for Android and iOS.

## Copy audit (docs/copy.md §8)

No UI text changed.

Fixes: #685
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant