Skip to content

feat(agents): summarize visuals on mobile until the webview renderer - #688

Merged
nixuuu merged 1 commit into
feat/agent-visuals-webfrom
feat/agent-visuals-mobile
Nov 14, 2026
Merged

nixuuu merged 1 commit into
feat/agent-visuals-webfrom
feat/agent-visuals-mobile

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

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. 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.

Mobile shows a visual's title, version and where to open it, under the
reply like image galleries. No spec is read or run and no native code changes;
the iOS and Android fingerprints stay the same.
@nixuuu
nixuuu force-pushed the feat/agent-visuals-mobile branch from cdef4a3 to 38eca6a Compare November 14, 2026 01:36
@nixuuu
nixuuu marked this pull request as ready for review November 14, 2026 01:37
@nixuuu
nixuuu merged commit bcc07e0 into dev Nov 14, 2026
11 checks passed
@nixuuu
nixuuu deleted the feat/agent-visuals-mobile 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
…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
Replaces the mobile text-only visual card (#688) with an interactive
renderer in `react-native-webview` **14.0.1** (the version SDK 58 pins).
It ships in the same native build as #659. Do not merge it alone into a
released build: it changes the native fingerprint.

## How it works
- **Same document and CSP as the web.** The app reads the spec with
`GetVisual` (Connect), validates it again and compiles it with
`compileVisual` in frame mode. The WebView gets `source={{ html }}` with
**no `baseUrl`** (an opaque `about:blank` document). It holds a trusted
shell (`@canopy/domain/visual-shell`) that mounts the visual in `<iframe
sandbox="allow-scripts" srcdoc>`, like the web.
- **Shared nonce.** A srcdoc frame inherits its parent's CSP on top of
its own. Headless Chromium showed the kit blocked under the shell's
policy until both documents used the same per-mount nonce.
- **Frame-scoped messaging.** The RN bridge may be reachable from every
frame: Android injects its `WebMessageListener` with `*`, and iOS
exposes `webkit.messageHandlers` to all frames. So the shell wraps each
port message in a per-mount **token envelope** that the frame never
sees. The app drops anything without the token and anything over 8 KiB
plus the envelope. The rest goes through `VisualFrameInbox` (new in
`@canopy/domain/visuals`), which the web `frame-host.ts` now uses too:
10 msg/s, 4 heights/s, strict parser, local state checked against the
spec. Host messages (theme, visibility, reduced motion) go in through
`postMessage` with the same token. The shell accepts them only when
there is no `event.source`, so a frame can't forge them.
- **Locked WebView** (`SandboxedWebView.tsx`):
  - No file, content or universal access.
- `incognito`, no shared or third-party cookies, no DOM storage (the kit
doesn't use it), no cache.
- No new windows: `setSupportMultipleWindows={false}`, a no-op
`onOpenWindow`, `javaScriptCanOpenWindowsAutomatically={false}`. The
shell also disables `window.open`, `alert`, `confirm` and `prompt`.
- No media, geolocation, zoom, link previews or debugging. No
`injectedJavaScript`.
- `originWhitelist={["*"]}` sends every URL to
`onShouldStartLoadWithRequest`. The library's default list would pass
other schemes to `Linking`. That callback allows only the first
top-frame `about:blank` and the child's `about:srcdoc`.
- **Theme** comes from the app theme (light and dark), with Interface
size as the scale, and updates live through host messages.
- **Budget:**
  - At most 1 live WebView in the app.
- A visual mounts lazily when it is on screen and the slot is free.
"Open visual" takes the slot unless the other visual is in full screen.
- Off screen it pauses at once and is released after 5 s. A backgrounded
app releases it at once.
- The last height stays reserved, and a new mount starts at that height.
- Spec cache: LRU, 16 entries / 2 MiB. Control state: 64 entries / 256
KiB in `Paths.cache`.
- **Host chrome at parity:** title, "Version N", "Open full screen" and
"Visual actions". The actions are "Save HTML" (Android, chosen
directory) or "Share HTML" (iOS), "Copy spec", "Cite visual" and the
version list. Full screen uses the same slot, and a hardware Escape
closes it.
- **Old binaries:** `TurboModuleRegistry.get("RNCWebViewModule")` is
checked before the renderer is imported (lazily), so on a build without
the module the JS never touches the native component. Those builds keep
#688's `VisualSummary` card.
- `compileVisualExport` now builds the "Download HTML" file for both the
web BFF route and mobile.

## Verified statically
- `bun install`, `gen:check`, `typecheck`, `lint` (oxlint),
`format:check`, `check:tmp`: 2974 pass, 175 skip, 0 fail, nothing left
in the temp dir. Web build passes.
- New `packages/domain/src/visuals/host.test.ts`:
- The envelope rejects a wrong or missing token, oversized input and
malformed JSON.
  - The inbox enforces its limits and validates state.
- The token is never in the frame document, and the title and spec stay
inert.
- Mounting refuses a newer or revoked kit and a spec that doesn't parse.
- Headless Chromium (Blink, the same engine as Android System WebView),
not committed. From the sandboxed frame:
  - `window.parent.ReactNativeWebView` → SecurityError.
- `window.open` → blocked (no `allow-popups`); `alert` → ignored (no
`allow-modals`).
- `top.location` → SecurityError; `localStorage` and `document.cookie` →
SecurityError; origin `null`.
- A forged token envelope posted to the parent was **not** relayed. The
real `ready` was relayed.
- `expo export` for iOS and Android passes; the shell is in the Hermes
bundle.
- `expo prebuild --no-install --clean` in a temp copy passes:
- No change to Info.plist or app permissions. The library manifest only
merges a non-exported `RNCWebViewFileProvider` and payment `<queries>`;
we turn payment requests off and have no file inputs.
  - The webview is autolinked (`rncoreAutolinkingConfig`).
- **Combined native build (this PR on dev with #659 merged)**,
re-checked on head `e332d33`:
- `bun install --frozen-lockfile` is clean, the mobile typecheck passes,
and `expo export` passes for iOS (3320 modules) and Android (3314
modules).
- `expo prebuild --no-install --clean` in a temp copy passes, and both
sides apply together:
- Autolinking resolves `expo-video`, `canopy-media-stream`,
`canopy-file-intake` and `canopy-pinned-fetch` (Expo modules) plus
`react-native-webview` (RN community).
- #659's `media-network` plugin writes
`res/xml/canopy_media_network.xml`, and `expo-video` adds no
`UIBackgroundModes`.
    - Android permissions and Info.plist keys are unchanged.
  - **Fingerprint** (`@expo/fingerprint`):

    | Platform | dev with #659 | This PR (#659 + webview) |
    | --- | --- | --- |
| iOS | `5a2f1ebbf02efbeb8f57f05a91e105b8f4f7c935` |
`138e0c6b171c82b4933e86808cdfef56da73b8c6` |
| Android | `43b7842311f5520084c7fcfcbce1b1df23da45ec` |
`906dc944f94eb8333fa384ed9f198834fdd30d13` |

The "dev with #659" values come from a temporary worktree that shared
this checkout's `node_modules`. Use the right-hand column for the
scheduled native build.
- `expo lint` on the new files reports the same rule patterns that
already fail across the app (`react-hooks/refs` for `viewport.ref`,
`set-state-in-effect` for claiming the slot). Mobile ESLint is not a CI
gate and already reports 104 errors on dev.

## Security review follow-ups (P3)
- A remount (new shell and token) starts unloaded again: the loaded
state is stored per mount token, so on iOS `allowInitialLoad` no longer
blocks the new `about:blank` (`VisualWebView.tsx`).
- Unpairing, an expired pairing and a new pairing clear the spec cache
and `visual-state.json`, in memory and on disk (`clearVisualCaches` in
`session.tsx`). A read started before a clear can't restore old entries.
- `docs/agent-visuals.md` (mobile section) records the accepted residual
risks: bridge flooding from frame code, and unchecked child-frame
http(s) navigation on Android (the sandbox and CSP stay the boundary).
- Re-checked: oxlint, format, `bun run typecheck`, mobile `tsc`, and
`expo export` for iOS and Android. JS-only change, so the fingerprints
are unchanged.

## Needs on-device checks (the device host is broken)
- **Sandbox boundary on both platforms:** the frame can't reach the
native bridge. The token makes direct calls harmless, but confirm that
Android `WebMessageListener` and iOS `webkit.messageHandlers` calls from
the frame are dropped. Also confirm that no file or content URL loads.
- **Navigation block:** on Android, `shouldOverrideUrlLoading` doesn't
see http(s) navigations of child frames, and it allows the load if JS
doesn't answer within 250 ms. The sandbox and CSP remain the boundary
there; the kit never navigates.
- **Message validation end to end:** heights, saved state restored after
remount, Escape in full screen.
- **Layout:** scrolling inside the iframe within the timeline (iOS
`scrollEnabled={false}` on the shell, Android `nestedScrollEnabled`).
Light and dark, theme changes while open, phone width, long titles.
- **Behaviour:** memory of one WebView (target ≤64 MiB),
VoiceOver/TalkBack, Save/Share HTML, and the fallback card on a build
without the module.

## Copy audit (docs/copy.md §8)
| Text | Check |
|---|---|
| Open visual / Open full screen / Visual actions | Verb first, sentence
case, same as web. |
| Save HTML (Android) / Share HTML (iOS) | Verb matches what the
platform does (save to a chosen folder or share), like "Save image" /
"Share image". |
| Copy spec / Cite visual / Version N / Latest | Same as web; "visual"
per the glossary. |
| Loading visual… / Shown in full screen. | Ongoing action with an
ellipsis; a short status. |
| Couldn't open this visual. + Retry | What happened; the button is the
action. |
| Update Canopy to open this visual. | One idea, says what to do. |
| Close another visual to open this one. | Imperative, says what to do.
|
| Couldn't save/share the HTML. Try again. / Couldn't copy the spec. Try
again. / Couldn't cite this visual. Try again. | What happened, then
what to do. |
| Spec copied | Short status, no period. |

No new glossary terms.
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