Skip to content

feat(agents): add the visual spec, validator and sandboxed kit compiler - #682

Merged
nixuuu merged 1 commit into
devfrom
feat/agent-visuals-spec
Nov 14, 2026
Merged

nixuuu merged 1 commit into
devfrom
feat/agent-visuals-spec

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

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
nixuuu force-pushed the feat/agent-visuals-spec branch from 9ef291a to 0961491 Compare November 14, 2026 00:50
@nixuuu
nixuuu marked this pull request as ready for review November 14, 2026 01:36
@nixuuu
nixuuu merged commit 9495aa0 into dev Nov 14, 2026
12 checks passed
@nixuuu
nixuuu deleted the feat/agent-visuals-spec branch November 14, 2026 01:48
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
…685)

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`.
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
nixuuu added a commit that referenced this pull request Nov 14, 2026
Improve the default appearance of agent visuals with Canopy theme
tokens, compact spacing, designed list rows, quiet device chrome and
readable sequence steps.

Related: #682

The reported banking composition now has a thin rounded phone bezel, a
status hint and balanced proportions. Transfer/BLIK previews no longer
sit in dashed placeholder boxes. Transaction rows align signed values on
the right. Login participant headers share the first grid row, columns
fit their container, future messages remain readable, the current
message is highlighted, and reset uses the same button treatment as
navigation.

The development gallery uses the production compiler and sandbox to show
every component in realistic compositions at 360px and 960px, in light
and dark themes. It includes the reported banking/login composition,
long labels, button states and all device artboards. Previously there
was no complete kit gallery.

List row fields are additive within schema v1; stored string lists
remain supported. Rendering still uses textContent and the CSP/security
model is unchanged.

Sequence-only next/previous controls now derive their numeric range from
the message count; previously a sequence starting at zero could remain
at zero unless another control established its range. Explicit numeric
values accepted by stored v1 specs remain valid.

Validation (all passed, with nice and temporary outputs under /var/tmp):

- `bun install`, `bun run gen:check`, `bun run typecheck`, `bun run
lint`, `bun run format:check`.
- `bun test packages/domain/src/visuals
tests/integration/visuals.test.ts
tests/integration/visual-harnesses.test.ts`: 27 tests passed, including
additive row validation, unsafe/oversized fields, stored v1
compatibility, and bounded sequence navigation/reset.
- `bun run --filter @canopy/web build` and Expo Android/iOS exports.
- Native fingerprints compared against dev: iOS
`138e0c6b171c82b4933e86808cdfef56da73b8c6`, Android
`906dc944f94eb8333fa384ed9f198834fdd30d13`; both unchanged.

Browser review ran on the requested review machine in the isolated PR
directory, using loopback port 5397 and a single fixture server. The
fixture needs no gateway, database or containers. The server, tunnel,
review checkout and temporary files were removed afterwards. No
screenshots or run artifacts are committed.

Compared the dev kit with the updated kit using the gallery's stored-v1
banking fixture. At a 320px viewport, the previous sequence had 336px of
content in a 296px column; the updated sequence measures 296px/296px,
with aligned headers and legible future messages. Reviewed light/dark at
phone and desktop widths, long merchant/branch names, signed amounts,
wrapping segmented options, next/reset sequence controls, loading/danger
button preview, before/after switching, device artboards and both chart
types. The same compiled HTML used by mobile fits the phone viewport.
Native WebView/device execution was not part of this browser review.

Copy audit (§8): “Reset” keeps its verb; its visual treatment changes
from ghost to secondary. Gallery headings use sentence case and concise
descriptions; Polish text is retained as screenshot/sample fixture data.
Positive/negative values include explicit signs. Checked short/long
content at phone and desktop widths. No new glossary terms or product
error/empty states; meaning does not rely on colour alone.
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