Skip to content

AI-native design editor. Open-source Figma alternative.

feat: show collaborators what the AI chat streams as it builds (#1010)

Danila Poyarkovac724653bdac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 18faf17fe..7cd8dcf23 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -59,7 +59,7 @@
- Fix lint issues outside the app: `openpencil lint --fix -o fixed.fig` binds colors to the variable they match and rounds subpixel geometry, and the `lint` and `lint_fix` tools let MCP clients and AI chat check a page and apply those fixes, plus radius, spacing, text size, group-to-frame, and hidden-layer suggestions on request. Lint messages carry each fix as data in `fix` and `suggestions`.
- Mark layers with errors and warnings on the canvas while you work, and pin those outside the view to the canvas edge in their direction, with matching marks in the Layers panel and error and warning counts in the page list; hover a marker or pin for its issues or click it to open them in Lint, and turn markers on or off with View → Design issues.
- Follow collaborators and their AI agents from the avatars in the toolbar: an avatar counts that person's agents, hovering lists what each is doing and on which page, and clicking follows. The view glides after whoever you follow, a frame in their color and a “Following …” bar show whom you follow, and Escape, clicking, scrolling, zooming, or switching pages stops it. Your own agents, the AI chat and MCP clients alike, are followed automatically while they work; turn this off with the crosshair button at the top of the AI panel. Your own avatar renames your agents and leaves the room.
-- See where AI agents are working: the built-in AI chat, ACP and Pi harness chats, and every MCP client each show a cursor whose outlined label shows a sparkle and a callsign such as *Fern*, at the layers they read or edit, and an MCP agent leaves when its session ends. While the chat streams JSX, its cursor moves through the elements as they appear and outlines them. People's and agents' cursors glide to each new position instead of jumping. In a shared room, collaborators see each other's agents in the color of the person running them.
+- See where AI agents are working: the built-in AI chat, ACP and Pi harness chats, and every MCP client each show a cursor whose outlined label shows a sparkle and a callsign such as *Fern*, at the layers they read or edit, and an MCP agent leaves when its session ends. While the chat streams JSX, its cursor moves through the elements as they appear and outlines them. People's and agents' cursors glide to each new position instead of jumping. In a shared room, collaborators see each other's agents in the color of the person running them, and watch what the AI chat builds take shape on their own canvas while its JSX streams, not only once it is done.
- Copy the document's variables as a CSS stylesheet or a Tailwind v4 theme from the variables dialog, or print them with `openpencil tokens`. Each collection's default mode goes in `:root` (or `@theme`, with a `@custom-variant` per mode), other modes override under their condition, `[data-theme="dark"]` unless the mode names a selector or `@media` query, and aliases stay `var()` references that follow the mode. Variables CSS cannot express, such as booleans, are named instead of written.
- Import and export variables, text styles, and effect styles as W3C design tokens. **Export as design tokens** in the variables dialog's copy menu and `openpencil tokens --format dtcg --out <folder>` write one file per collection mode in the shape Figma imports, typography and shadow tokens for styles, and a DTCG resolver for tools such as Style Dictionary. **Import design tokens** reads files from Figma, a resolver with its files, Tokens Studio themes, or a zip of them, shows where each collection and mode goes before anything changes, updates variables and styles by name without deleting any, and undoes in one step; agents and MCP clients import with the `import_design_tokens` tool, and `design_to_tokens` takes `format: "dtcg"`.
- Edit variables as design tokens in the redesigned variables dialog, opened from View → Variables…, the command palette, or the Design panel, and expandable to most of the window. Collections and the groups inside them are listed in a sidebar with counts; picking a group, a type filter, or a search, which matches names, CSS names, descriptions, and values with the command palette's typo-tolerant matching, narrows the list, which shows each variable's type, CSS name, and a value per mode. Names and number or text values edit in place, rows reorder by dragging, and Shift- or Cmd-clicking selects several to duplicate, move into a group, or delete from the context menu, the Delete key, or the side panel. Selecting one edits its name, CSS name (checked against CSS before it is saved), unit, per-mode values or CSS expressions such as `clamp()`, scopes, description, and publishing, and points a value at another variable of the same type or detaches it again. The collection settings rename and delete the collection, add, rename, duplicate, delete, and choose the default mode, and choose when each mode applies in plain words, such as *System is in dark mode* or *Screen is narrower than 640px*, with the CSS it writes shown underneath and a custom selector or `@media`, `@supports`, or `@container` query when no preset fits. Manually switched modes use an attribute named after the collection, such as `data-theme`, or one the collection names to match an existing codebase; it is saved in `.fig` files and used by exported code. The active collection's stylesheet updates live below the list, and copying offers CSS or a Tailwind v4 theme. Undo and redo work in the dialog as they do on the canvas, with one step per change and one per color picker session, while a field with uncommitted text keeps its own undo. The dialog lays out by its own width: in a narrow window or on a phone it shows one mode at a time and opens a variable, the collection settings, or the stylesheet over the list.
diff --git a/src/AGENTS.md b/src/AGENTS.md
index 0b613beda..3d2b6afcc 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -28,6 +28,7 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr
- A room is a document: every room tab owns its session (`src/app/collab/rooms.ts`, `session.ts`), joining always opens a new tab, and only Share binds an existing document; the collaboration UI reads the active tab's room through `useCollab()` and publishes cursors through the canvas's own tab (`tests/app/collab/session.test.ts`, `tests/e2e/collab/rooms.spec.ts`).
- A shared document records each layer's parent history, order key and page, never `parentId` or `childIds`, and only Share or a room's conversion sets its root in `meta`; local edits are written by `writeLocalPlacement` and remote changes applied by `applySharedTree` in `src/app/collab/shared-tree/sync.ts`, which resolve the tree with `LayerTree` from `src/app/collab/tree/` (`tests/app/collab/random-edits.test.ts`).
- Every agent at work, the built-in chat's and each MCP session's (`src/app/automation/agents.ts`), is registered with `addAgent` in `src/app/presence/registry.ts`, and presence cursors reach the editor only through `showCursors` in `src/app/presence/cursor-motion.ts`, which glides them; never assign `presenceCursors` directly (`tests/app/presence/registry.test.ts`).
+- Agent presence in awareness is metadata only. The one content an agent shares is its streamed `render` JSX, published through `publishAgentPreview` (`src/app/presence/preview-stream.ts`) and sent on the room's `agent-preview` channel by `shareAgentPreviews` (`src/app/collab/agent-preview.ts`), which validates and bounds what peers send and draws it with the chat run's canvas preview; never put prompts or other tool arguments in either (`tests/app/collab/agent-preview.test.ts`).
- Changing how a shared document records data bumps `TREE_FORMAT` and `COLLAB_APP_ID` together, so mismatched builds never meet, and converts saved rooms in `src/app/collab/shared-tree/migration.ts` (`tests/app/collab/shared-tree/migration.test.ts`).
## Browser baseline
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index b905199e8..29ebbe826 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -22,15 +22,8 @@ import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'
import { chatThinkingLevel } from '@/app/ai/chat/thinking'
import { createAIModelRuntime, resolveModelConnectionAPIKey } from '@/app/ai/models'
import type { ThinkingLevel } from '@/app/ai/models/types'
-import { createCanvasJSXPreview } from '@/app/ai/preview/canvas'
-import {
- createAITools,
- endRun,
- markRunPreview,
- recordStep,
- runPageId,
- startRun
-} from '@/app/ai/tools'
+import { createRunPreview } from '@/app/ai/preview/run'
+import { createAITools, endRun, recordStep, startRun } from '@/app/ai/tools'
import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'
import { aiToolOverrides } from '@/app/ai/tools/preferences'
import { diagnosticErrorDetails } from '@/app/diagnostics'
@@ -118,12 +111,9 @@ export function createToolLoopTransport({
diagnosticContext = {}
}: ToolLoopTransportOptions) {
const tools = createAITools(store, diagnosticContext)
- // While JSX streams, the chat's agent moves through the elements as they appear.
- const preview = createCanvasJSXPreview(
- store,
- () => runPageId(store),
- (focus) => markRunPreview(store, focus)
- )
+ // While JSX streams, the chat's agent moves through the elements as they appear, here and
+ // on the screens of everyone else in the room.
+ const preview = createRunPreview(store)
const renderTool = tools.render
renderTool.onInputStart = ({ toolCallId, abortSignal }) => preview.start(toolCallId, abortSignal)
renderTool.onInputDelta = ({ toolCallId, inputTextDelta }) =>
diff --git a/src/app/ai/preview/canvas.ts b/src/app/ai/preview/canvas.ts
index 07e32abec..ae9c26fc1 100644
--- a/src/app/ai/preview/canvas.ts
+++ b/src/app/ai/preview/canvas.ts
@@ -81,6 +81,17 @@ function countNodes(tree: JSXPreviewNode): number {
)
}
+export interface CanvasJSXPreviewOptions {
+ /** Told where each shown preview is being built, so the agent can point there. */
+ onFocus?: (focus: PreviewFocus) => void
+ /**
+ * Show previews only while this document is the active tab, and drop them when another tab
+ * becomes active, as the chat's own preview does. A room shows its peers' previews whenever
+ * the document's canvas is drawn, which is also true of several documents on one page.
+ */
+ activeTabOnly?: boolean
+}
+
/**
* Bind speculative pictures to this editor. Previews belong to `pageId()`, the run's page:
* the renderer shows them only while that page is on screen, so page switches hide them.
@@ -88,14 +99,15 @@ function countNodes(tree: JSXPreviewNode): number {
export function createCanvasJSXPreview(
store: EditorStore,
pageId: () => string,
- /** Told where each shown preview is being built, so the agent can point there. */
- onFocus?: (focus: PreviewFocus) => void
+ { onFocus, activeTabOnly = true }: CanvasJSXPreviewOptions = {}
) {
let subscriptions: (() => void)[] = []
+ const isShown = () => !activeTabOnly || getActiveEditorStoreOrNull() === store
+
function isCurrent(target: PreviewTarget): boolean {
return (
- getActiveEditorStoreOrNull() === store &&
+ isShown() &&
store.graph === target.graph &&
store.graph.getNode(target.pageId)?.type === 'CANVAS'
)
@@ -107,7 +119,7 @@ export function createCanvasJSXPreview(
}
function capture(): PreviewTarget | null {
- if (getActiveEditorStoreOrNull() !== store || !store.renderer) return null
+ if (!isShown() || !store.renderer) return null
if (subscriptions.length === 0) {
subscriptions = [
store.onEditorEvent('graph:replaced', () => controller.clear()),
@@ -116,15 +128,19 @@ export function createCanvasJSXPreview(
store.onEditorEvent('node:updated', () => controller.invalidate()),
store.onEditorEvent('node:deleted', () => controller.invalidate()),
store.onEditorEvent('node:reparented', () => controller.invalidate()),
- store.onEditorEvent('node:reordered', () => controller.invalidate()),
- watch(
- useActiveEditorStoreRef(),
- (active) => {
- if (active !== store) controller.clear()
- },
- { flush: 'sync' }
- )
+ store.onEditorEvent('node:reordered', () => controller.invalidate())
]
+ if (activeTabOnly) {
+ subscriptions.push(
+ watch(
+ useActiveEditorStoreRef(),
+ (active) => {
+ if (active !== store) controller.clear()
+ },
+ { flush: 'sync' }
+ )
+ )
+ }
}
return { graph: store.graph, pageId: pageId() }
}
diff --git a/src/app/ai/preview/run.ts b/src/app/ai/preview/run.ts
new file mode 100644
index 000000000..17da51768
--- /dev/null
+++ b/src/app/ai/preview/run.ts
@@ -0,0 +1,67 @@
+import { useEventListener } from '@vueuse/core'
+
+import { createCanvasJSXPreview } from '@/app/ai/preview/canvas'
+import { markRunPreview, runAgentId, runPageId } from '@/app/ai/tools/run'
+import type { EditorStore } from '@/app/editor/active-store'
+import { publishAgentPreview } from '@/app/presence/preview-stream'
+
+/**
+ * The chat run's preview of streamed `render` input: drawn on this canvas, with the run's agent
+ * pointing at what it builds, and published so a room shows it to everyone else as it streams.
+ */
+export function createRunPreview(store: EditorStore) {
+ const preview = createCanvasJSXPreview(store, () => runPageId(store), {
+ onFocus: (focus) => markRunPreview(store, focus)
+ })
+
+ /** Stops each call's abort listener; the request's signal outlives the calls it covers. */
+ const stopAbortListeners = new Map<string, () => void>()
+
+ function stopAbortListener(callId: string): void {
+ stopAbortListeners.get(callId)?.()
+ stopAbortListeners.delete(callId)
+ }
+
+ return {
+ start(callId: string, signal?: AbortSignal): void {
+ preview.start(callId, signal)
+ const agentId = runAgentId(store)
+ if (!agentId) return
+ publishAgentPreview(store, { type: 'start', agentId, callId, pageId: runPageId(store) })
+ // A stopped call ends its preview here, so it ends everywhere else too.
+ if (signal) {
+ stopAbortListener(callId)
+ stopAbortListeners.set(
+ callId,
+ useEventListener(
+ signal,
+ 'abort',
+ () => {
+ stopAbortListeners.delete(callId)
+ publishAgentPreview(store, { type: 'finish', agentId, callId })
+ },
+ { once: true }
+ )
+ )
+ }
+ },
+ delta(callId: string, text: string): void {
+ preview.delta(callId, text)
+ const agentId = runAgentId(store)
+ if (agentId) publishAgentPreview(store, { type: 'delta', agentId, callId, text })
+ },
+ finish(callId: string): void {
+ stopAbortListener(callId)
+ preview.finish(callId)
+ const agentId = runAgentId(store)
+ if (agentId) publishAgentPreview(store, { type: 'finish', agentId, callId })
+ },
+ clear(): void {
+ for (const stop of stopAbortListeners.values()) stop()
+ stopAbortListeners.clear()
+ preview.clear()
+ const agentId = runAgentId(store)
+ if (agentId) publishAgentPreview(store, { type: 'clear', agentId })
+ }
+ }
+}
diff --git a/src/app/collab/agent-preview.ts b/src/app/collab/agent-preview.ts
new file mode 100644
index 000000000..a17d5f14a
--- /dev/null
+++ b/src/app/collab/agent-preview.ts
@@ -0,0 +1,150 @@
+import * as v from 'valibot'
+
+import { createCanvasJSXPreview } from '@/app/ai/preview/canvas'
+import type { CollabRoomConnection } from '@/app/collab/room/connection'
+import type { EditorStore } from '@/app/editor/active-store'
+import { onAgentPreview, type AgentPreviewEvent } from '@/app/presence/preview-stream'
+
+/** Bounds on what a peer can send, so a broken or hostile one cannot flood the preview. */
+const MAX_ID_LENGTH = 64
+/** A model streams arguments in small pieces; the controller also caps a call's whole input. */
+export const MAX_PREVIEW_DELTA_LENGTH = 16_384
+
+const id = v.pipe(v.string(), v.minLength(1), v.maxLength(MAX_ID_LENGTH))
+const AgentPreviewEventSchema = v.variant('type', [
+ v.object({ type: v.literal('start'), agentId: id, callId: id, pageId: id }),
+ v.object({
+ type: v.literal('delta'),
+ agentId: id,
+ callId: id,
+ text: v.pipe(v.string(), v.maxLength(MAX_PREVIEW_DELTA_LENGTH))
+ }),
+ v.object({ type: v.literal('finish'), agentId: id, callId: id }),
+ v.object({ type: v.literal('clear'), agentId: id })
+])
+const AgentPreviewMessageSchema = v.pipe(v.string(), v.parseJson(), AgentPreviewEventSchema)
+
+const encoder = new TextEncoder()
+const decoder = new TextDecoder()
+
+export function encodeAgentPreview(event: AgentPreviewEvent): Uint8Array {
+ return encoder.encode(JSON.stringify(event))
+}
+
+/**
+ * The messages that carry `event`. A model's chunk can exceed what peers accept, so a long
+ * delta goes as several in order; JSON escapes a surrogate pair split between two of them.
+ */
+export function encodeAgentPreviewMessages(event: AgentPreviewEvent): Uint8Array[] {
+ if (event.type !== 'delta' || event.text.length <= MAX_PREVIEW_DELTA_LENGTH) {
+ return [encodeAgentPreview(event)]
+ }
+ const messages: Uint8Array[] = []
+ for (let offset = 0; offset < event.text.length; offset += MAX_PREVIEW_DELTA_LENGTH) {
+ const text = event.text.slice(offset, offset + MAX_PREVIEW_DELTA_LENGTH)
+ messages.push(encodeAgentPreview({ ...event, text }))
+ }
+ return messages
+}
+
+/** The event a peer sent, or null when it is malformed or out of bounds. */
+export function decodeAgentPreview(data: Uint8Array): AgentPreviewEvent | null {
+ const result = v.safeParse(AgentPreviewMessageSchema, decoder.decode(data))
+ return result.success ? result.output : null
+}
+
+/** What remote previews are drawn with: the same controller the local chat run uses. */
+export interface RemotePreviewController {
+ start(callId: string, signal?: AbortSignal): void
+ delta(callId: string, text: string): void
+ finish(callId: string): void
+ clear(): void
+}
+
+/**
+ * Routes peers' preview events into one controller. Calls are keyed by peer, agent, and call,
+ * so two peers' agents never collide, and everything a peer started ends when it leaves.
+ */
+export function createRemotePreviewRouter(
+ controller: RemotePreviewController,
+ /** Set right before a call starts: the page its preview belongs to. */
+ setPage: (pageId: string) => void
+) {
+ const calls = new Map<string, { peerId: string; agentId: string }>()
+ const key = (peerId: string, agentId: string, callId: string) =>
+ `${peerId}\u0000${agentId}\u0000${callId}`
+
+ function end(callKey: string): void {
+ if (!calls.delete(callKey)) return
+ controller.finish(callKey)
+ }
+
+ function endWhere(match: (call: { peerId: string; agentId: string }) => boolean): void {
+ for (const [callKey, call] of calls) if (match(call)) end(callKey)
+ }
+
+ return {
+ receive(event: AgentPreviewEvent, peerId: string): void {
+ if (event.type === 'clear') {
+ endWhere((call) => call.peerId === peerId && call.agentId === event.agentId)
+ return
+ }
+ const callKey = key(peerId, event.agentId, event.callId)
+ if (event.type === 'start') {
+ end(callKey)
+ calls.set(callKey, { peerId, agentId: event.agentId })
+ setPage(event.pageId)
+ controller.start(callKey)
+ } else if (event.type === 'delta') {
+ // A peer that joined mid-call missed its start; it sees the next call instead.
+ if (calls.has(callKey)) controller.delta(callKey, event.text)
+ } else {
+ end(callKey)
+ }
+ },
+ peerLeft(peerId: string): void {
+ endWhere((call) => call.peerId === peerId)
+ },
+ clear(): void {
+ calls.clear()
+ controller.clear()
+ }
+ }
+}
+
+/**
+ * Show other people's agents building on this canvas as they stream, and send ours to them.
+ * The canvas preview draws only while this document is on screen and the call's page exists.
+ */
+export function shareAgentPreviews(
+ store: EditorStore,
+ connection: Pick<CollabRoomConnection, 'agentPreview' | 'onPeerLeave'>,
+ /** Draws remote previews; the canvas preview the chat run uses unless a test supplies one. */
+ createController: (pageId: () => string) => RemotePreviewController = (pageId) =>
+ createCanvasJSXPreview(store, pageId, { activeTabOnly: false })
+): () => void {
+ const [send, receive] = connection.agentPreview
+ let page = store.state.currentPageId
+ const router = createRemotePreviewRouter(
+ createController(() => page),
+ (pageId) => {
+ page = pageId
+ }
+ )
+ let disposed = false
+ receive((data, peerId) => {
+ if (disposed) return
+ const event = decodeAgentPreview(data)
+ if (event) router.receive(event, peerId)
+ })
+ const stopLocal = onAgentPreview(store, (event) => {
+ for (const message of encodeAgentPreviewMessages(event)) send(message)
+ })
+ const stopLeave = connection.onPeerLeave((peerId) => router.peerLeft(peerId))
+ return () => {
+ disposed = true
+ stopLocal()
+ stopLeave()
+ router.clear()
+ }
+}
diff --git a/src/app/collab/room/connection.ts b/src/app/collab/room/connection.ts
index 18c582bc3..1adda11f7 100644
--- a/src/app/collab/room/connection.ts
+++ b/src/app/collab/room/connection.ts
@@ -3,6 +3,7 @@ import * as awarenessProtocol from 'y-protocols/awareness'
import * as Y from 'yjs'
import { joinCollabRoom, type JoinCollabRoom } from '@/app/collab/transport'
+import type { CollabAction } from '@/app/collab/transport/types'
export type CollabRoomOptions = {
roomId: string
@@ -17,6 +18,10 @@ export type CollabRoomConnection = {
sendYjsUpdate: (data: Uint8Array, peerId?: string) => void
sendAwareness: (data: Uint8Array, peerId?: string) => void
sendSyncStep1: (data: Uint8Array, peerId?: string) => void
+ /** What agents preview while they stream, apart from presence (`app/collab/agent-preview.ts`). */
+ agentPreview: CollabAction
+ /** Follow peers leaving the room; returns the unsubscribe. */
+ onPeerLeave: (handler: (peerId: string) => void) => () => void
}
function awarenessClientIds(data: Uint8Array): number[] {
@@ -47,6 +52,9 @@ export function connectCollabRoom({
const [sendAwareness, getAwareness] = room.makeAction('awareness')
const [sendSyncStep1, getSyncStep1] = room.makeAction('sync-step1')
const [sendSyncReply, getSyncReply] = room.makeAction('sync-reply')
+ const agentPreview = room.makeAction('agent-preview')
+ // A transport keeps one leave handler, so the connection shares it with its users.
+ const leaveHandlers = new Set<(peerId: string) => void>()
const awarenessClientsByPeer = new Map<string, Set<number>>()
@@ -96,7 +104,18 @@ export function connectCollabRoom({
awarenessClientsByPeer.delete(peerId)
awarenessProtocol.removeAwarenessStates(awareness, remoteClients, 'peer-left')
updatePeersList()
+ for (const handler of leaveHandlers) handler(peerId)
})
- return { room, sendYjsUpdate, sendAwareness, sendSyncStep1 }
+ return {
+ room,
+ sendYjsUpdate,
+ sendAwareness,
+ sendSyncStep1,
+ agentPreview,
+ onPeerLeave(handler) {
+ leaveHandlers.add(handler)
+ return () => leaveHandlers.delete(handler)
+ }
+ }
}
diff --git a/src/app/collab/session.ts b/src/app/collab/session.ts
index 1c07b030a..c7e8afb70 100644
--- a/src/app/collab/session.ts
+++ b/src/app/collab/session.ts
@@ -4,6 +4,7 @@ import { IndexeddbPersistence } from 'y-indexeddb'
import * as awarenessProtocol from 'y-protocols/awareness'
import * as Y from 'yjs'
+import { shareAgentPreviews } from '@/app/collab/agent-preview'
import { buildRemotePeers } from '@/app/collab/awareness'
import { useCollabIdentity } from '@/app/collab/identity'
import { publishLocalAgents } from '@/app/collab/local-awareness'
@@ -196,6 +197,7 @@ export function openRoomSession({
if (cursor) awareness.setLocalStateField('cursor', { ...cursor, zoom: viewport.zoom })
})
const stopAgentSync = publishLocalAgents(store, () => awareness, identity.color)
+ const stopAgentPreviews = shareAgentPreviews(store, connection)
const unbindGraphEvents = bindCollabGraphEvents({
store,
getYdoc: () => (disposed ? null : ydoc),
@@ -231,6 +233,7 @@ export function openRoomSession({
stopNameWatch()
stopZoomWatch()
stopAgentSync()
+ stopAgentPreviews()
meta.unobserve(refreshDocument)
unregisterYjsObservers()
// Destroying the awareness can emit a last change; nothing here should react to it.
diff --git a/src/app/presence/preview-stream.ts b/src/app/presence/preview-stream.ts
new file mode 100644
index 000000000..d86806aa7
--- /dev/null
+++ b/src/app/presence/preview-stream.ts
@@ -0,0 +1,30 @@
+import type { EditorStore } from '@/app/editor/active-store'
+
+/**
+ * What a local agent's streamed `render` call shows before it runs, as other people in the
+ * room should see it. Unlike the rest of an agent's presence it carries content: the JSX the
+ * agent is about to commit to the shared document, and nothing else from its tools or prompts.
+ */
+export type AgentPreviewEvent =
+ | { type: 'start'; agentId: string; callId: string; pageId: string }
+ | { type: 'delta'; agentId: string; callId: string; text: string }
+ | { type: 'finish'; agentId: string; callId: string }
+ /** The agent stopped previewing: its step ended, failed, or was stopped. */
+ | { type: 'clear'; agentId: string }
+
+type AgentPreviewListener = (event: AgentPreviewEvent) => void
+
+const listeners = new WeakMap<EditorStore, Set<AgentPreviewListener>>()
+
+/** Tell whoever shares this document, such as a room, what a local agent is previewing. */
+export function publishAgentPreview(store: EditorStore, event: AgentPreviewEvent): void {
+ for (const listener of listeners.get(store) ?? []) listener(event)
+}
+
+/** Follow this document's local agent previews; returns the unsubscribe. */
+export function onAgentPreview(store: EditorStore, listener: AgentPreviewListener): () => void {
+ const set = listeners.get(store) ?? new Set<AgentPreviewListener>()
+ listeners.set(store, set)
+ set.add(listener)
+ return () => set.delete(listener)
+}
diff --git a/src/app/presence/types.ts b/src/app/presence/types.ts
index dab183938..04559557e 100644
--- a/src/app/presence/types.ts
+++ b/src/app/presence/types.ts
@@ -20,7 +20,10 @@ export interface PersonPoint extends PresencePoint {
/** Who to keep in view: a person in the room, or any agent, ours or theirs. */
export type FollowTarget = { kind: 'person'; clientId: number } | { kind: 'agent'; agentId: string }
-/** An agent as its owner publishes it: metadata only, never prompts or tool arguments. */
+/**
+ * An agent as its owner publishes it: metadata only, never prompts or tool arguments. What its
+ * streamed `render` call builds travels apart from presence (`./preview-stream.ts`).
+ */
export interface AgentPresence {
id: string
/** A callsign, unique among the agents in a room, such as "Fern". */
diff --git a/tests/app/ai/preview/run.test.ts b/tests/app/ai/preview/run.test.ts
new file mode 100644
index 000000000..ab7bfcaa2
--- /dev/null
+++ b/tests/app/ai/preview/run.test.ts
@@ -0,0 +1,75 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { createRunPreview } from '@/app/ai/preview/run'
+import { runAgentId, runPageId, startRun } from '@/app/ai/tools/run'
+import { createEditorStore } from '@/app/editor/session'
+import { onAgentPreview, type AgentPreviewEvent } from '@/app/presence/preview-stream'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const stores: ReturnType<typeof createEditorStore>[] = []
+afterEach(() => {
+ for (const store of stores.splice(0)) store.preparationController.dispose()
+})
+
+function recordedRun() {
+ const store = createEditorStore(new SceneGraph())
+ stores.push(store)
+ const events: AgentPreviewEvent[] = []
+ onAgentPreview(store, (event) => events.push(event))
+ return { store, events, preview: createRunPreview(store) }
+}
+
+describe("the chat run's preview", () => {
+ test("publishes the run's streamed render input for the room", () => {
+ const { store, events, preview } = recordedRun()
+ startRun(store, 10)
+ const agentId = expectDefined(runAgentId(store), 'run agent')
+
+ preview.start('call-1')
+ preview.delta('call-1', '{"jsx":"<Frame')
+ preview.finish('call-1')
+ preview.clear()
+
+ expect(events).toEqual([
+ { type: 'start', agentId, callId: 'call-1', pageId: runPageId(store) },
+ { type: 'delta', agentId, callId: 'call-1', text: '{"jsx":"<Frame' },
+ { type: 'finish', agentId, callId: 'call-1' },
+ { type: 'clear', agentId }
+ ])
+ })
+
+ test('ends a stopped call for the room too', () => {
+ const { store, events, preview } = recordedRun()
+ startRun(store, 10)
+ const agentId = expectDefined(runAgentId(store), 'run agent')
+ const stop = new AbortController()
+
+ preview.start('call-1', stop.signal)
+ stop.abort()
+
+ expect(events.at(-1)).toEqual({ type: 'finish', agentId, callId: 'call-1' })
+ })
+
+ test('a call that finished publishes nothing more when its request stops later', () => {
+ const { store, events, preview } = recordedRun()
+ startRun(store, 10)
+ const request = new AbortController()
+
+ preview.start('call-1', request.signal)
+ preview.finish('call-1')
+ request.abort()
+
+ expect(events.filter((event) => event.type === 'finish')).toHaveLength(1)
+ })
+
+ test('publishes nothing before a run has an agent', () => {
+ const { events, preview } = recordedRun()
+ preview.start('call-1')
+ preview.delta('call-1', '<Frame')
+ preview.clear()
+ expect(events).toEqual([])
+ })
+})
diff --git a/tests/app/collab/agent-preview.test.ts b/tests/app/collab/agent-preview.test.ts
new file mode 100644
index 000000000..b89cf2545
--- /dev/null
+++ b/tests/app/collab/agent-preview.test.ts
@@ -0,0 +1,172 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { Awareness } from 'y-protocols/awareness'
+import * as Y from 'yjs'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import {
+ createRemotePreviewRouter,
+ decodeAgentPreview,
+ encodeAgentPreview,
+ encodeAgentPreviewMessages,
+ MAX_PREVIEW_DELTA_LENGTH,
+ shareAgentPreviews,
+ type RemotePreviewController
+} from '@/app/collab/agent-preview'
+import { connectCollabRoom } from '@/app/collab/room/connection'
+import { createEditorStore } from '@/app/editor/session'
+import { publishAgentPreview, type AgentPreviewEvent } from '@/app/presence/preview-stream'
+
+import { createMemoryRooms } from '#tests/helpers/collab/memory-transport'
+
+const ROOM = 'cccccccccccccccccccccccccccccccc'
+
+/** Records what a remote preview controller is asked to draw. */
+function recordingController() {
+ const log: string[] = []
+ const controller: RemotePreviewController = {
+ start: (callId) => log.push(`start ${callId}`),
+ delta: (callId, text) => log.push(`delta ${callId} ${text}`),
+ finish: (callId) => log.push(`finish ${callId}`),
+ clear: () => log.push('clear')
+ }
+ return { log, controller }
+}
+
+/** Call keys name the peer, the agent, and the call. */
+const callKey = (peerId: string, agentId: string, callId: string) =>
+ `${peerId}\u0000${agentId}\u0000${callId}`
+
+describe('agent preview messages', () => {
+ test('carry every event kind through encoding', () => {
+ const events: AgentPreviewEvent[] = [
+ { type: 'start', agentId: 'a1', callId: 'c1', pageId: '0:1' },
+ { type: 'delta', agentId: 'a1', callId: 'c1', text: '{"jsx":"<Frame' },
+ { type: 'finish', agentId: 'a1', callId: 'c1' },
+ { type: 'clear', agentId: 'a1' }
+ ]
+ for (const event of events) expect(decodeAgentPreview(encodeAgentPreview(event))).toEqual(event)
+ })
+
+ test('reject what a broken or hostile peer could send', () => {
+ const encode = (value: unknown) => new TextEncoder().encode(JSON.stringify(value))
+ expect(decodeAgentPreview(new TextEncoder().encode('not json'))).toBeNull()
+ expect(decodeAgentPreview(encode({ type: 'start', agentId: 'a1', callId: 'c1' }))).toBeNull()
+ expect(decodeAgentPreview(encode({ type: 'run', agentId: 'a1' }))).toBeNull()
+ expect(decodeAgentPreview(encode({ type: 'clear', agentId: 'x'.repeat(65) }))).toBeNull()
+ expect(
+ decodeAgentPreview(
+ encode({
+ type: 'delta',
+ agentId: 'a1',
+ callId: 'c1',
+ text: 'x'.repeat(MAX_PREVIEW_DELTA_LENGTH + 1)
+ })
+ )
+ ).toBeNull()
+ })
+})
+
+test('a delta longer than peers accept goes as several that rejoin intact', () => {
+ // A surrogate pair straddles the first split, as an emoji in streamed text can.
+ const text = `${'x'.repeat(MAX_PREVIEW_DELTA_LENGTH - 1)}😀${'y'.repeat(MAX_PREVIEW_DELTA_LENGTH)}`
+ const messages = encodeAgentPreviewMessages({ type: 'delta', agentId: 'a1', callId: 'c1', text })
+
+ expect(messages).toHaveLength(3)
+ const decoded = messages.map((message) => decodeAgentPreview(message))
+ expect(decoded.every((event) => event?.type === 'delta')).toBe(true)
+ expect(decoded.map((event) => (event?.type === 'delta' ? event.text : '')).join('')).toBe(text)
+})
+
+describe('remote preview routing', () => {
+ test("keeps each peer's agents apart and draws a call on its page", () => {
+ const { log, controller } = recordingController()
+ const pages: string[] = []
+ const router = createRemotePreviewRouter(controller, (pageId) => pages.push(pageId))
+
+ router.receive({ type: 'start', agentId: 'a1', callId: 'c1', pageId: '0:1' }, 'peer-1')
+ router.receive({ type: 'start', agentId: 'a1', callId: 'c1', pageId: '0:2' }, 'peer-2')
+ router.receive({ type: 'delta', agentId: 'a1', callId: 'c1', text: '<Frame' }, 'peer-2')
+ router.receive({ type: 'finish', agentId: 'a1', callId: 'c1' }, 'peer-1')
+
+ expect(pages).toEqual(['0:1', '0:2'])
+ expect(log).toEqual([
+ `start ${callKey('peer-1', 'a1', 'c1')}`,
+ `start ${callKey('peer-2', 'a1', 'c1')}`,
+ `delta ${callKey('peer-2', 'a1', 'c1')} <Frame`,
+ `finish ${callKey('peer-1', 'a1', 'c1')}`
+ ])
+ })
+
+ test('ignores a call it joined midway, and ends calls on clear or when the peer leaves', () => {
+ const { log, controller } = recordingController()
+ const router = createRemotePreviewRouter(controller, () => undefined)
+
+ router.receive({ type: 'delta', agentId: 'a1', callId: 'missed', text: 'x' }, 'peer-1')
+ router.receive({ type: 'start', agentId: 'a1', callId: 'c1', pageId: '0:1' }, 'peer-1')
+ router.receive({ type: 'start', agentId: 'a2', callId: 'c2', pageId: '0:1' }, 'peer-1')
+ router.receive({ type: 'clear', agentId: 'a1' }, 'peer-1')
+ router.peerLeft('peer-1')
+
+ expect(log).toEqual([
+ `start ${callKey('peer-1', 'a1', 'c1')}`,
+ `start ${callKey('peer-1', 'a2', 'c2')}`,
+ `finish ${callKey('peer-1', 'a1', 'c1')}`,
+ `finish ${callKey('peer-1', 'a2', 'c2')}`
+ ])
+ })
+})
+
+describe('agent previews in a room', () => {
+ const cleanups: (() => void)[] = []
+ afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup()
+ })
+
+ function connect(rooms: ReturnType<typeof createMemoryRooms>) {
+ const ydoc = new Y.Doc()
+ const awareness = new Awareness(ydoc)
+ const connection = connectCollabRoom({
+ roomId: ROOM,
+ ydoc,
+ awareness,
+ updatePeersList: () => undefined,
+ joinRoom: rooms.join
+ })
+ const store = createEditorStore(new SceneGraph())
+ cleanups.push(() => {
+ store.preparationController.dispose()
+ awareness.destroy()
+ ydoc.destroy()
+ })
+ return { connection, store }
+ }
+
+ test("show the host's streamed render input on the guest, and end it when the host leaves", async () => {
+ const rooms = createMemoryRooms()
+ const host = connect(rooms)
+ const guest = connect(rooms)
+ const { log, controller } = recordingController()
+ const stopHost = shareAgentPreviews(
+ host.store,
+ host.connection,
+ () => recordingController().controller
+ )
+ const stopGuest = shareAgentPreviews(guest.store, guest.connection, () => controller)
+ cleanups.push(stopHost, stopGuest)
+ await rooms.settle()
+
+ publishAgentPreview(host.store, { type: 'start', agentId: 'a1', callId: 'c1', pageId: '0:1' })
+ publishAgentPreview(host.store, { type: 'delta', agentId: 'a1', callId: 'c1', text: '<Frame' })
+ await rooms.settle()
+ expect(log).toHaveLength(2)
+ expect(log[0]).toStartWith('start ')
+ expect(log[1]).toEndWith(' <Frame')
+
+ await host.connection.room.leave()
+ await rooms.settle()
+ expect(log).toHaveLength(3)
+ expect(log[2]).toStartWith('finish ')
+ })
+})
diff --git a/tests/e2e/collab/agent-preview.spec.ts b/tests/e2e/collab/agent-preview.spec.ts
new file mode 100644
index 000000000..9deeb9097
--- /dev/null
+++ b/tests/e2e/collab/agent-preview.spec.ts
@@ -0,0 +1,71 @@
+import { expect, test } from '@playwright/test'
+
+import { routeModelCatalog } from '#tests/helpers/chat/catalog'
+import { ChatHarness } from '#tests/helpers/chat/harness'
+import { documentState, previewKey } from '#tests/helpers/chat/render-preview'
+import { installRenderStream } from '#tests/helpers/chat/render-stream'
+import { routeVisionModel } from '#tests/helpers/chat/vision'
+import {
+ collaborationErrors,
+ connect,
+ createPeer,
+ share,
+ startRelay,
+ type Peer
+} from '#tests/helpers/collab/room'
+
+const scenario = {
+ jsx: '<Frame name="Shared card" w={280} h={180} bg="#20242f" p={20}><Text size={24} color="#ffffff">Streaming preview</Text></Frame>',
+ placement: { x: 80, y: 80 },
+ pauseAfter: ['>Streaming']
+}
+
+test("collaborators see the AI chat's streamed JSX on their own canvas before it commits", async ({
+ browser
+}) => {
+ test.setTimeout(90_000)
+ const relay = await startRelay()
+ let host: Peer | null = null
+ let guest: Peer | null = null
+ try {
+ host = await createPeer(browser, 'Host', relay.url)
+ guest = await createPeer(browser, 'Guest', relay.url)
+ await share(host)
+ await connect(guest)
+ await expect
+ .poll(() => host?.page.evaluate(() => window.openPencil?.test?.collab?.peerCount()))
+ .toBe(1)
+
+ await routeModelCatalog(host.page)
+ await routeVisionModel(host.page)
+ const chat = new ChatHarness(host.page)
+ await chat.configureOpenRouter('sk-or-test-key-12345')
+ const stream = await installRenderStream(host.page, scenario)
+ const guestPage = guest.page
+ try {
+ await chat.submit('Render a card')
+ await expect.poll(() => stream.evaluate((s) => s.ready())).toBe(true)
+ await stream.evaluate((s) => s.advance())
+
+ // Mid-stream, the guest draws the card from the streamed JSX, though nothing is committed.
+ await expect.poll(() => previewKey(host?.page ?? guestPage)).not.toBe('')
+ await expect.poll(() => previewKey(guestPage)).not.toBe('')
+ expect((await documentState(guestPage)).children).toEqual([])
+
+ // Once the tool runs, the preview gives way to the committed card on both screens.
+ await stream.evaluate((s) => s.complete())
+ await expect(chat.assistantMessage()).toContainText('Rendered.')
+ await expect.poll(() => previewKey(guestPage)).toBe('')
+ await expect.poll(async () => (await documentState(guestPage)).children.length).toBe(1)
+ expect(collaborationErrors(host)).toEqual([])
+ expect(collaborationErrors(guest)).toEqual([])
+ } finally {
+ await stream.evaluate((s) => s.dispose())
+ await stream.dispose()
+ }
+ } finally {
+ await host?.context.close()
+ await guest?.context.close()
+ await relay.close()
+ }
+})