Skip to content

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

feat(collab): show MCP agents, follow streamed JSX, and follow your agents as they work (#725)

Victor Wads690c1247e403
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0b0a8d74e..821ebd172 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,9 +47,10 @@
- See which layer the code is about in the Code tab's Design JSX and Tailwind JSX: the element around the cursor marks its opening and closing tag and shows its layer on the canvas as a tinted box, apart from canvas hover, and design issues are underlined on the property that causes them, including while you edit Design JSX live.
- 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.
- 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.
- 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.
-- 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. A frame in their color and a “Following …” bar show whom you follow; Escape, clicking, scrolling, zooming, or switching pages stops it. Your own avatar renames your agents and leaves the room.
- See where the built-in AI chat is working: while it replies, a cursor whose outlined label shows a sparkle and a callsign such as *Fern* marks the layers it edits. In a shared room, collaborators see each other's agents in the color of the person running them.
- See which pages people and AI agents are working on: the Pages panel marks those pages in their colors and, on hover, shows who is there with what their agents are doing and a button to follow them; the command palette names who is there, and the chat offers **Go to page** while its reply works on a page you're not viewing. On phones, the room pill shows the people in the room as avatars beside the room's status.
- Hide, lock, and constrain layers in design JSX with `visible={false}`, `locked`, and `constraints={{ horizontal, vertical }}`, set italic text with `italic`, and describe strokes fully with `strokes`, `strokeWeights`, `strokeCap`, `strokeJoin`, and the node-level `dashPattern`. JSX export now writes these together with stacked, gradient, and image fills, every effect, absolutely positioned children, size limits, vertical text alignment, masks, and variable bindings, so rendering exported JSX reproduces them and `diff_jsx` reports changes to them.
diff --git a/packages/core/src/canvas/overlays/presence.ts b/packages/core/src/canvas/overlays/presence.ts
index 81a46cca6..068eb6775 100644
--- a/packages/core/src/canvas/overlays/presence.ts
+++ b/packages/core/src/canvas/overlays/presence.ts
@@ -19,12 +19,24 @@ const LABEL_SPARKLE_RADIUS = 4
const LABEL_SPARKLE_GAP = 3
function drawSelection(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph, cursor: PresenceCursor) {
- if (!cursor.selection?.length) return
+ if (!cursor.selection?.length && !cursor.outline?.length) return
const { r: red, g, b } = cursor.color
r.auxStroke.setColor(r.ck.Color4f(red, g, b, 0.6))
r.auxStroke.setStrokeWidth(1.5)
r.auxStroke.setPathEffect(null)
- for (const nodeId of cursor.selection) {
+ // Outlines of what is not a layer yet, such as JSX an agent is still streaming.
+ for (const rect of cursor.outline ?? []) {
+ canvas.drawRect(
+ r.ck.XYWHRect(
+ rect.x * r.zoom + r.panX,
+ rect.y * r.zoom + r.panY,
+ rect.width * r.zoom,
+ rect.height * r.zoom
+ ),
+ r.auxStroke
+ )
+ }
+ for (const nodeId of cursor.selection ?? []) {
const node = graph.getNode(nodeId)
if (!node) continue
// Map the corners through the node's world matrix, as the shape is rendered, so the
diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.ts
index 7a8f4674b..17bffbddd 100644
--- a/packages/core/src/canvas/renderer/types.ts
+++ b/packages/core/src/canvas/renderer/types.ts
@@ -18,6 +18,8 @@ export type MeasurementMode = 'off' | 'shallow' | 'deep'
/** Where a collaborator or an agent is working, in world coordinates. */
export interface PresenceCursor {
+ /** Who it is, kept between updates; editors use it to glide a cursor rather than jump it. */
+ id?: string
kind: 'person' | 'agent'
name: string
/** A person's color, or the color of the person who runs the agent. */
@@ -25,6 +27,8 @@ export interface PresenceCursor {
x: number
y: number
selection?: string[]
+ /** Outlines in world coordinates of what is not a layer yet, such as streamed JSX. */
+ outline?: Rect[]
}
export interface RenderOverlays {
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 29acefb0c..56605543b 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -458,6 +458,11 @@ export const DEFAULT_AI_MODEL =
AI_PROVIDERS.find((provider) => provider.id === DEFAULT_AI_PROVIDER)?.defaultModel ?? ''
export const AUTOMATION_HTTP_PORT = 7600
+/**
+ * Request header the app's own ACP and Pi harness chats send to the MCP server, so their sessions
+ * show as those agents rather than as an outside MCP client.
+ */
+export const MCP_AGENT_HEADER = 'x-openpencil-agent'
export const GOOGLE_FONTS_API_KEY = 'AIzaSyD1tYDR_dUEiV-Tw1vksEhZbUytgKW5pc8'
diff --git a/packages/core/src/design-jsx/preview/stage.ts b/packages/core/src/design-jsx/preview/stage.ts
index 086a3c2df..6933636f7 100644
--- a/packages/core/src/design-jsx/preview/stage.ts
+++ b/packages/core/src/design-jsx/preview/stage.ts
@@ -15,6 +15,8 @@ export interface StagedJSXPreview {
graph: SceneGraph
pageId: string
nodeIds: string[]
+ /** The roots the JSX rendered, in source order, even when `nodeIds` names their owner. */
+ renderedIds: string[]
/** Existing page child to replace visually, without changing the source graph. */
replaceId?: string
/** Page insertion slot when the preview adds new top-level nodes. */
@@ -67,6 +69,7 @@ export async function stageJSXPreview(
graph,
pageId,
nodeIds: owner && graph.getNode(owner) ? [owner] : results.map((result) => result.id),
+ renderedIds: results.map((result) => result.id),
replaceId: owner,
insertIndex: placement.insertIndex
}
diff --git a/packages/docs/de/programmable/collaboration.md b/packages/docs/de/programmable/collaboration.md
index a51c12eb6..86b4a57f5 100644
--- a/packages/docs/de/programmable/collaboration.md
+++ b/packages/docs/de/programmable/collaboration.md
@@ -30,12 +30,14 @@ Räume werden nicht auf einem Server gespeichert: Die Datei liegt auf den Gerät
- **Dokument:** Änderungen an Formen, Text, Eigenschaften und Anordnung;
- **Zeiger:** Position, Name und Farbe jedes Teilnehmers;
- **Auswahl:** ausgewählte Objekte der anderen Teilnehmer;
-- **Agenten:** Der integrierte AI-Chat erscheint als Zeiger an den Ebenen, die er bearbeitet; seine umrandete Beschriftung zeigt ein Funkelsymbol und einen Rufnamen wie *Fern*. Zeiger und Umrandung haben die Farbe der Person, die den Agenten ausführt, sodass erkennbar ist, wem er gehört. Geteilt werden nur Name, Art, Modell, Status, Seite, Position und bearbeitete Ebenen, niemals Prompts oder Antworten.
+- **Agenten:** Der integrierte AI-Chat, ACP- und Pi-Harness-Chats und jeder verbundene MCP-Client erscheinen als Zeiger an den Ebenen, die sie lesen oder bearbeiten; ihre umrandete Beschriftung zeigt ein Funkelsymbol und einen Rufnamen wie *Fern*. Während der Chat JSX streamt, wandert sein Zeiger durch die Elemente, sobald sie erscheinen, und umrandet sie. Zeiger und Umrandung haben die Farbe der Person, die den Agenten ausführt, sodass erkennbar ist, wem er gehört. Geteilt werden nur Name, Art, Modell, Status, Seite, Position und bearbeitete Ebenen, niemals Prompts oder Antworten.
## Ansichtsverfolgung
Ein Klick auf einen Avatar folgt der Ansicht dieses Teilnehmers. Position und Zoom werden angepasst, und ein Rahmen in dessen Farbe mit einer Leiste „Du folgst …“ zeigt, wem Sie folgen. Zum Beenden klicken Sie erneut auf den Avatar, drücken <kbd>Esc</kbd> oder klicken, scrollen, zoomen oder wechseln selbst die Seite.
+Deinen eigenen Agenten, dem AI-Chat und MCP-Clients wie Claude Code oder Cursor, folgt die Ansicht automatisch, während sie arbeiten, sodass im Blick bleibt, was sie bearbeiten. Abschalten lässt sich das mit dem Fadenkreuz-Symbol oben im AI-Panel. Beendest du das Folgen, während ein Agent arbeitet, bleibt er bis zum Ende seiner Arbeit unbeachtet und wird beim nächsten Durchlauf wieder verfolgt.
+
Ein Avatar zählt die Agenten, die die Person ausführt. Beim Daraufzeigen erscheinen alle Agenten, ihre Tätigkeit und die jeweilige Seite; mit **Folgen** neben einem Agenten bleiben die Seite und die Ebenen, die er bearbeitet, im Blick. Die Verfolgung läuft zwischen seinen Antworten weiter und endet, wenn er den Raum verlässt. Die Schaltfläche nach den Avataren listet alle Personen im Raum mit ihren Agenten auf und ist per Tastatur bedienbar. Ihr eigener Avatar listet Ihre Agenten auf – ein Klick benennt einen Agenten um – und enthält **Raum verlassen**.
Das Teilen-Panel listet alle Personen im Raum mit den Agenten auf, die sie ausführen, mit ihrer Tätigkeit und der jeweiligen Seite. Einem Agenten folgen Sie auf dieselbe Weise, um die Seite und die Ebenen, die er bearbeitet, im Blick zu behalten; die Verfolgung läuft zwischen seinen Antworten weiter und endet, wenn er den Raum verlässt. Mit einem Doppelklick auf einen eigenen Agenten benennen Sie ihn um.
diff --git a/packages/docs/es/programmable/collaboration.md b/packages/docs/es/programmable/collaboration.md
index 50d53f577..c5088b684 100644
--- a/packages/docs/es/programmable/collaboration.md
+++ b/packages/docs/es/programmable/collaboration.md
@@ -19,12 +19,14 @@ Quien abre el enlace entra en la misma sala. El documento inicial se sincroniza
- **Presencia:** nombre, color, selección y página activa;
- **Cursores:** posición de cada participante;
- **Vista:** posibilidad de seguir el encuadre de otra persona;
-- **Agentes:** el chat con AI integrado aparece como un cursor sobre las capas que edita, con una etiqueta con contorno que muestra una chispa y un nombre en clave como *Fern*. El cursor y el contorno tienen el color de la persona que lo ejecuta, para que se sepa de quién es el agente. Solo se comparten su nombre, tipo, modelo, estado, página, posición y capas editadas, nunca los prompts ni las respuestas.
+- **Agentes:** el chat con AI integrado, los chats de ACP y Pi harness y cada cliente MCP conectado aparecen como cursores sobre las capas que leen o editan, con una etiqueta con contorno que muestra una chispa y un nombre en clave como *Fern*. Mientras el chat transmite JSX, su cursor recorre los elementos a medida que aparecen y los contornea. El cursor y el contorno tienen el color de la persona que ejecuta el agente, para que se sepa de quién es. Solo se comparten su nombre, tipo, modelo, estado, página, posición y capas editadas, nunca los prompts ni las respuestas.
## Modo seguimiento
Haz clic en el avatar de un participante en la barra superior para seguir su vista. Tu lienzo se desplaza y amplía para coincidir con la suya, y un marco de su color con una barra «Siguiendo a …» indica a quién sigues. Para dejar de seguir, vuelve a hacer clic en el avatar, pulsa <kbd>Esc</kbd>, o haz clic, desplázate, haz zoom o cambia de página por tu cuenta.
+Tus propios agentes, el chat de IA y clientes MCP como Claude Code o Cursor, se siguen automáticamente mientras trabajan, para mantener a la vista lo que editan. Desactívalo con el botón de la mira en la parte superior del panel de IA. Si dejas de seguir a un agente mientras trabaja, no se vuelve a seguir hasta que termine; en su siguiente ejecución se sigue de nuevo.
+
Un avatar cuenta los agentes que ejecuta esa persona. Pasa el cursor por encima para ver cada agente, qué hace y en qué página, y haz clic en **Seguir** junto a un agente para mantener a la vista la página y las capas que edita; el seguimiento continúa entre sus respuestas y termina cuando se va. El botón situado después de los avatares enumera a todos los presentes en la sala con sus agentes y funciona con el teclado. Tu propio avatar enumera tus agentes —haz clic en uno para cambiarle el nombre— y ofrece **Salir de la sala**.
El panel para compartir enumera a todos los presentes en la sala con los agentes que ejecutan, qué hace cada uno y en qué página. Sigue a un agente del mismo modo para mantener a la vista la página y las capas que edita; el seguimiento continúa entre sus respuestas y termina cuando se va. Haz doble clic en uno de tus agentes para cambiarle el nombre.
diff --git a/packages/docs/fr/programmable/collaboration.md b/packages/docs/fr/programmable/collaboration.md
index 8554100e8..39cf513a3 100644
--- a/packages/docs/fr/programmable/collaboration.md
+++ b/packages/docs/fr/programmable/collaboration.md
@@ -17,12 +17,14 @@ Ouvrez le menu de collaboration, créez une salle et partagez le lien. L’ident
- **Présence :** nom, couleur, sélection et page active ;
- **Curseurs :** position de chaque participant ;
- **Vue :** possibilité de suivre le cadrage d’une autre personne ;
-- **Agents :** le chat AI intégré apparaît sous la forme d’un curseur sur les calques qu’il modifie, son étiquette cerclée affichant une étincelle et un nom de code tel que *Fern*. Le curseur et le contour ont la couleur de la personne qui l’utilise, ce qui permet de savoir à qui appartient l’agent. Seuls son nom, son type, son modèle, son état, sa page, sa position et les calques modifiés sont partagés, jamais les instructions ni les réponses.
+- **Agents :** le chat AI intégré, les chats ACP et Pi harness et chaque client MCP connecté apparaissent sous la forme de curseurs sur les calques qu’ils lisent ou modifient, leur étiquette cerclée affichant une étincelle et un nom de code tel que *Fern*. Pendant que le chat diffuse du JSX, son curseur parcourt les éléments à mesure qu’ils apparaissent et les entoure. Le curseur et le contour ont la couleur de la personne qui utilise l’agent, ce qui permet de savoir à qui il appartient. Seuls son nom, son type, son modèle, son état, sa page, sa position et les calques modifiés sont partagés, jamais les instructions ni les réponses.
## Mode suivi
Cliquez sur l’avatar d’une personne dans la barre supérieure pour suivre sa vue. Votre zone de travail se déplace et zoome comme la sienne, et un cadre de sa couleur avec une barre « Vous suivez … » indique qui vous suivez. Cliquez de nouveau sur l’avatar, appuyez sur <kbd>Esc</kbd>, ou cliquez, faites défiler, zoomez ou changez de page vous-même pour arrêter.
+Vos propres agents, le chat IA et les clients MCP comme Claude Code ou Cursor, sont suivis automatiquement pendant qu’ils travaillent, pour garder en vue ce qu’ils modifient. Désactivez-le avec le bouton en forme de viseur en haut du panneau IA. Si vous arrêtez de suivre un agent pendant qu’il travaille, il n’est plus suivi jusqu’à la fin de son travail, puis l’est de nouveau à sa prochaine exécution.
+
Un avatar compte les agents que cette personne utilise. Survolez-le pour voir chaque agent, ce qu’il fait et sur quelle page, puis cliquez sur **Suivre** à côté d’un agent pour garder à l’écran la page et les calques qu’il modifie ; le suivi se poursuit entre ses réponses et s’arrête quand il s’en va. Le bouton placé après les avatars énumère toutes les personnes de la salle avec leurs agents et fonctionne au clavier. Votre propre avatar énumère vos agents — cliquez sur l’un d’eux pour le renommer — et propose **Quitter la salle**.
Le panneau de partage énumère toutes les personnes de la salle avec les agents qu’elles utilisent, ce que fait chaque agent et sur quelle page. Suivez un agent de la même manière pour garder à l’écran la page et les calques qu’il modifie ; le suivi se poursuit entre ses réponses et s’arrête quand il s’en va. Double-cliquez sur l’un de vos agents pour le renommer.
diff --git a/packages/docs/it/programmable/collaboration.md b/packages/docs/it/programmable/collaboration.md
index e56e31eac..3632a8bc2 100644
--- a/packages/docs/it/programmable/collaboration.md
+++ b/packages/docs/it/programmable/collaboration.md
@@ -17,12 +17,14 @@ Apri il menu di collaborazione, crea una stanza e condividi il link. L’identif
- **Presenza:** nome, colore, selezione e pagina attiva;
- **Cursori:** posizione di ogni partecipante;
- **Vista:** possibilità di seguire l’inquadratura di un’altra persona;
-- **Agenti:** la chat AI integrata compare come cursore sui livelli che sta modificando, con un’etichetta contornata che mostra una scintilla e un nome in codice come *Fern*. Cursore e contorno hanno il colore di chi lo esegue, così si capisce a chi appartiene l’agente. Vengono condivisi solo nome, tipo, modello, stato, pagina, posizione e livelli modificati, mai richieste o risposte.
+- **Agenti:** la chat AI integrata, le chat ACP e Pi harness e ogni client MCP collegato compaiono come cursori sui livelli che leggono o modificano, con un’etichetta contornata che mostra una scintilla e un nome in codice come *Fern*. Mentre la chat trasmette JSX, il suo cursore percorre gli elementi man mano che compaiono e li contorna. Cursore e contorno hanno il colore di chi esegue l’agente, così si capisce a chi appartiene. Vengono condivisi solo nome, tipo, modello, stato, pagina, posizione e livelli modificati, mai richieste o risposte.
## Modalità di seguito
Fai clic sull’avatar di un partecipante nella barra superiore per seguire la sua inquadratura. L’area di lavoro si sposta e cambia zoom come la sua vista, e una cornice del suo colore con una barra «Stai seguendo …» indica chi stai seguendo. Per smettere, fai di nuovo clic sull’avatar, premi <kbd>Esc</kbd> oppure fai clic, scorri, cambia zoom o pagina.
+I tuoi agenti, la chat AI e i client MCP come Claude Code o Cursor, vengono seguiti automaticamente mentre lavorano, così ciò che modificano resta in vista. Puoi disattivarlo con il pulsante a mirino in alto nel pannello AI. Se smetti di seguire un agente mentre lavora, non viene più seguito finché non ha finito e torna a esserlo alla sua esecuzione successiva.
+
Un avatar conta gli agenti eseguiti da quella persona. Passaci sopra il puntatore per vedere ogni agente, cosa sta facendo e su quale pagina, e fai clic su **Segui** accanto a un agente per tenere in vista la pagina e i livelli che sta modificando; il seguito continua tra una risposta e l’altra e termina quando l’agente se ne va. Il pulsante dopo gli avatar elenca tutti i presenti nella stanza con i rispettivi agenti e funziona anche da tastiera. Il tuo avatar elenca i tuoi agenti (fai clic su uno per rinominarlo) e contiene **Esci dalla stanza**.
Il pannello di condivisione elenca tutti i presenti nella stanza con gli agenti che eseguono, cosa fa ciascun agente e su quale pagina. Segui un agente allo stesso modo per tenere in vista la pagina e i livelli che sta modificando. Fai doppio clic su un tuo agente per rinominarlo.
diff --git a/packages/docs/pl/programmable/collaboration.md b/packages/docs/pl/programmable/collaboration.md
index 1aaf66371..005c470a3 100644
--- a/packages/docs/pl/programmable/collaboration.md
+++ b/packages/docs/pl/programmable/collaboration.md
@@ -30,12 +30,14 @@ Pokoje nie są przechowywane na serwerze: plik znajduje się na urządzeniach os
- **Dokument:** figury, tekst, właściwości i układ są aktualizowane po każdej zmianie.
- **Kursory:** widoczne są położenie, nazwa i kolor każdego uczestnika.
- **Zaznaczenie:** obiekty wybrane przez innych są widoczne dla wszystkich.
-- **Agenci:** wbudowany czat AI pojawia się jako kursor przy edytowanych warstwach, a jego obrysowana etykieta zawiera iskrę i kryptonim, na przykład *Fern*. Kursor i obrys mają kolor osoby, która go uruchomiła, więc widać, czyj to agent. Udostępniane są tylko nazwa, rodzaj, model, stan, strona, położenie i edytowane warstwy agenta, nigdy prompty ani odpowiedzi.
+- **Agenci:** wbudowany czat AI, czaty ACP i Pi harness oraz każdy połączony klient MCP pojawiają się jako kursory przy warstwach, które czytają lub edytują, a ich obrysowana etykieta zawiera iskrę i kryptonim, na przykład *Fern*. Gdy czat strumieniuje JSX, jego kursor przechodzi przez elementy w miarę ich pojawiania się i je obrysowuje. Kursor i obrys mają kolor osoby, która uruchomiła agenta, więc widać, czyj to agent. Udostępniane są tylko nazwa, rodzaj, model, stan, strona, położenie i edytowane warstwy agenta, nigdy prompty ani odpowiedzi.
## Tryb śledzenia
Kliknij awatar uczestnika na górnym pasku, aby śledzić jego widok. Położenie i skala obszaru roboczego będą odpowiadać jego widokowi, a ramka w kolorze uczestnika z paskiem „Obserwujesz: …” pokazuje, kogo śledzisz. Aby przestać, kliknij awatar ponownie, naciśnij <kbd>Esc</kbd> albo sam kliknij, przewiń, zmień powiększenie lub przełącz stronę.
+Twoi agenci, czat AI i klienci MCP, tacy jak Claude Code czy Cursor, są śledzeni automatycznie podczas pracy, więc to, co edytują, pozostaje w widoku. Wyłączysz to przyciskiem z celownikiem u góry panelu AI. Jeśli przestaniesz śledzić agenta w trakcie jego pracy, nie będzie śledzony do jej końca, a przy następnym uruchomieniu znów będzie.
+
Awatar pokazuje liczbę agentów uruchomionych przez daną osobę. Najedź na niego, aby zobaczyć każdego agenta, jego bieżące działanie i stronę, a następnie kliknij **Obserwuj** przy agencie, aby mieć w widoku stronę i warstwy, które edytuje; śledzenie trwa między jego odpowiedziami i kończy się, gdy agent odejdzie. Przycisk za awatarami wyświetla wszystkich uczestników pokoju wraz z ich agentami i działa z klawiatury. Twój awatar wyświetla Twoich agentów — kliknij jednego, aby zmienić jego nazwę — i zawiera polecenie **Opuść pokój**.
Panel udostępniania wyświetla wszystkich uczestników pokoju wraz z ich agentami, tym, co każdy z nich robi, i stroną, na której pracuje. Agenta śledzisz tak samo: strona i warstwy, które edytuje, pozostają w widoku; śledzenie trwa między jego odpowiedziami i kończy się, gdy agent odejdzie. Kliknij dwukrotnie własnego agenta, aby zmienić jego nazwę.
diff --git a/packages/docs/programmable/collaboration.md b/packages/docs/programmable/collaboration.md
index 6a3811085..6de614d0b 100644
--- a/packages/docs/programmable/collaboration.md
+++ b/packages/docs/programmable/collaboration.md
@@ -30,12 +30,14 @@ Rooms are not stored on a server: the file lives on the devices of the people wh
- **Document changes** — every edit (shapes, text, properties, layout) syncs instantly
- **Cursors** — see where each collaborator is pointing, with their name and color
- **Selections** — highlighted selections are visible to everyone
-- **Agents** — the built-in AI chat appears as a cursor at the layers it is editing, its outlined label showing a sparkle and a callsign such as *Fern*. The cursor and outline have the color of the person running it, so you can tell whose agent it is. Only its name, kind, model, status, page, position, and edited layers are shared, never prompts or replies.
+- **Agents** — the built-in AI chat, ACP and Pi harness chats, and every connected MCP client appear as cursors at the layers they read or edit, each outlined label showing a sparkle and a callsign such as *Fern*. While the chat streams JSX, its cursor moves through the elements as they appear and outlines them. The cursor and outline have the color of the person running the agent, so you can tell whose agent it is. Only its name, kind, model, status, page, position, and edited layers are shared, never prompts or replies.
## Follow Mode
Click a collaborator's avatar in the top bar to follow their viewport. Your canvas pans and zooms to match their view, and a frame in their color with a “Following …” bar shows whom you follow. Click the avatar again, press <kbd>Esc</kbd>, or click, scroll, zoom, or switch pages yourself to stop.
+Your own agents, the AI chat and MCP clients such as Claude Code or Cursor, are followed automatically while they work, so what they edit stays in view. Turn this off with the crosshair button at the top of the AI panel. If you stop following an agent while it works, it is left alone until it finishes and followed again on its next run.
+
An avatar counts the agents that person runs. Hover over it to see each agent, what it is doing, and on which page, and click **Follow** next to an agent to keep the page and layers it is editing in view; following continues between its replies and stops when it leaves. The button after the avatars lists everyone in the room with their agents, and works from the keyboard. Your own avatar lists your agents — click one to rename it — and has **Leave room**.
The share panel lists everyone in the room with the agents they run, what each agent is doing, and on which page. Follow an agent the same way to keep the page and layers it is editing in view; following continues between its replies and stops when it leaves. Double-click one of your own agents to rename it.
diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.md
index c30529f2c..ddbb0fb00 100644
--- a/packages/docs/programmable/mcp-server.md
+++ b/packages/docs/programmable/mcp-server.md
@@ -153,6 +153,8 @@ Endpoints are available over both active transports:
`undo` and `redo` step back through the agent's own changes, and `activate_document` brings a tab to the front when the user should see it.
+Each MCP session shows in the app as an agent with a callsign, like the built-in chat: its cursor and outline sit on the layers each tool reads or changes, it rests after a quiet spell and leaves when the session ends, and people can follow it from their avatar. Collaborators in a shared room see it too.
+
Most tools accept optional `document_id` and `page_id` fields. Pass them explicitly for agent workflows instead of relying on the visible active tab/page. `create_page` only creates a page; call `switch_page` separately when the workflow should change the active page.
## AI Agent Skill
diff --git a/packages/docs/ru/programmable/collaboration.md b/packages/docs/ru/programmable/collaboration.md
index aa59b3833..17245ab1c 100644
--- a/packages/docs/ru/programmable/collaboration.md
+++ b/packages/docs/ru/programmable/collaboration.md
@@ -30,12 +30,14 @@ description: Одновременное редактирование напря
- **Документ:** фигуры, текст, свойства и компоновка обновляются после каждого изменения.
- **Указатели:** видны положение, имя и цвет каждого участника.
- **Выделение:** выбранные другими участниками объекты видны всем.
-- **Агенты:** встроенный чат с ИИ отображается как указатель у слоёв, которые он редактирует; на его контурной подписи есть значок-искорка и позывной, например *Fern*. Указатель и контур имеют цвет того, кто его запустил, так что видно, чей это агент. Передаются только имя, тип, модель, состояние, страница, положение и изменяемые слои — но не запросы и ответы.
+- **Агенты:** встроенный чат с ИИ, чаты ACP и Pi harness и каждый подключённый клиент MCP отображаются как указатели у слоёв, которые они читают или редактируют; на их контурной подписи есть значок-искорка и позывной, например *Fern*. Пока чат передаёт JSX потоком, его указатель проходит по элементам по мере их появления и обводит их. Указатель и контур имеют цвет того, кто запустил агента, так что видно, чей это агент. Передаются только имя, тип, модель, состояние, страница, положение и изменяемые слои — но не запросы и ответы.
## Режим слежения
Щёлкните аватар участника на верхней панели, чтобы следовать за его областью просмотра. Положение и масштаб вашего холста будут повторять его вид, а рамка его цвета с панелью «Вы следуете за …» показывает, за кем вы следите. Чтобы остановить слежение, снова щёлкните аватар, нажмите <kbd>Esc</kbd> либо сами щёлкните по холсту, прокрутите его, измените масштаб или переключите страницу.
+За вашими собственными агентами — чатом ИИ и MCP-клиентами вроде Claude Code или Cursor — вид следует автоматически, пока они работают, так что то, что они правят, остаётся на виду. Отключить это можно кнопкой с прицелом вверху панели ИИ. Если вы перестанете следовать за агентом во время работы, за ним не будут следовать до конца его работы, а при следующем запуске — снова.
+
На аватаре отображается число агентов, которых запустил этот участник. Наведите на него указатель, чтобы увидеть каждого агента, чем он занят и на какой странице, и нажмите **Следовать** рядом с агентом, чтобы страница и слои, которые он редактирует, оставались в поле зрения. Слежение продолжается между его ответами и прекращается, когда агент уходит. Кнопка после аватаров показывает всех участников комнаты с их агентами и доступна с клавиатуры. Ваш собственный аватар перечисляет ваших агентов — щёлкните по одному, чтобы переименовать, — и содержит пункт **Покинуть комнату**.
Панель «Поделиться» перечисляет всех участников комнаты с запущенными ими агентами, показывает, чем занят каждый агент и на какой странице. Следуйте за агентом так же, чтобы страница и слои, которые он редактирует, оставались в поле зрения; слежение продолжается между его ответами и прекращается, когда агент уходит. Дважды щёлкните своего агента, чтобы переименовать его.
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index 0135285ee..52432d3ee 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -8,6 +8,8 @@ import { resolveCommand } from 'package-manager-detector/commands'
import { detect, getUserAgent } from 'package-manager-detector/detect'
import { WebSocketServer, type WebSocket } from 'ws'
+import { MCP_AGENT_HEADER } from '@open-pencil/core/constants'
+
import { bearerToken, isAuthorized, mcpRequestToken } from '#mcp/auth'
import { createBrowserRPCBridge } from '#mcp/browser-rpc'
import { MCP_CORS_HEADERS, MCP_CORS_METHODS, MCP_EXPOSED_HEADERS } from '#mcp/http-options'
@@ -17,7 +19,12 @@ import { createMCPSessionManager } from '#mcp/server/sessions'
import { createToolDescriptors } from '#mcp/tool/manifest'
import type { ToolDescriptor, ToolPolicy } from '#mcp/tool/metadata'
import { applyToolPolicy } from '#mcp/tool/policy'
-import { registerTools } from '#mcp/tool/registration'
+import {
+ MCP_AGENT_KINDS,
+ registerTools,
+ type MCPAgentKind,
+ type MCPAgentSession
+} from '#mcp/tool/registration'
import packageJSON from '../package.json' with { type: 'json' }
import {
@@ -58,7 +65,18 @@ function mcpInstallCommand(): Promise<string> {
export { fail, ok, type MCPContent, type MCPResult } from '#mcp/result'
-export { registerTools, type RegisterToolsOptions, type RPCSender } from '#mcp/tool/registration'
+export {
+ MCP_AGENT_KINDS,
+ registerTools,
+ type MCPAgentKind,
+ type MCPAgentSession,
+ type RegisterToolsOptions,
+ type RPCSender
+} from '#mcp/tool/registration'
+
+function agentKindFromHeader(value: string | undefined): MCPAgentKind {
+ return MCP_AGENT_KINDS.find((kind) => kind === value) ?? 'mcp'
+}
export interface ServerOptions {
/** TCP port for the HTTP + WebSocket server. Ignored when `withTcp` is false. When set to 0 with `withTcp: true`, binds to an ephemeral port. Defaults to 7600. */
@@ -217,7 +235,10 @@ function createHonoApp(options: {
mcpSessions.touch(sessionId, existing)
return existing.handleRequest(c.req.raw)
}
- const transport = await mcpSessions.resolveTransport(undefined)
+ const transport = await mcpSessions.resolveTransport(
+ undefined,
+ agentKindFromHeader(c.req.header(MCP_AGENT_HEADER))
+ )
if ('error' in transport) {
if (transport.error === 'closed') {
return c.json({ error: 'MCP server is shutting down' }, 503)
@@ -315,8 +336,19 @@ function buildServerContext(options: ServerOptions) {
const mcpSessions = createMCPSessionManager({
serverVersion: MCP_VERSION,
- registerTools: (mcpServer: McpServer) =>
- registerTools(mcpServer, { policy: toolPolicy, mcpRoot, sendRPC: sendToBrowser })
+ registerTools: (mcpServer: McpServer, agentSession: MCPAgentSession) =>
+ registerTools(mcpServer, {
+ policy: toolPolicy,
+ mcpRoot,
+ sendRPC: sendToBrowser,
+ agentSession
+ }),
+ onSessionClosed: (sessionId) => {
+ // Best-effort: the app may be gone already, and then it shows no agents anyway.
+ sendToBrowser({ command: 'agent_session_closed', args: { session: sessionId } }).catch(
+ () => undefined
+ )
+ }
})
const browserRPC = createBrowserRPCBridge({
authToken,
diff --git a/packages/mcp/src/server/sessions.ts b/packages/mcp/src/server/sessions.ts
index afc73182e..6e5b741dc 100644
--- a/packages/mcp/src/server/sessions.ts
+++ b/packages/mcp/src/server/sessions.ts
@@ -2,6 +2,8 @@ import { randomUUID } from 'node:crypto'
import { McpServer, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'
+import type { MCPAgentKind, MCPAgentSession } from '#mcp/tool/registration'
+
export type MCPTransport = {
handleRequest: (request: Request) => Promise<Response>
close: () => Promise<void>
@@ -15,7 +17,9 @@ type MCPSession = {
type MCPSessionManagerOptions = {
serverVersion: string
- registerTools: (server: McpServer) => void
+ registerTools: (server: McpServer, session: MCPAgentSession) => void
+ /** Told when a session ends, so the app stops showing its agent. */
+ onSessionClosed?: (sessionId: string) => void
}
const MAX_MCP_SESSIONS = 10
@@ -61,12 +65,14 @@ async function closeSession(session: MCPSession): Promise<void> {
export function createMCPSessionManager({
serverVersion,
- registerTools
+ registerTools,
+ onSessionClosed
}: MCPSessionManagerOptions) {
const sessions = new Map<string, MCPSession>()
const closing = new Set<Promise<void>>()
- function scheduleClose(session: MCPSession): Promise<void> {
+ function scheduleClose(session: MCPSession, id?: string): Promise<void> {
+ if (id) onSessionClosed?.(id)
const task = closeSession(session).finally(() => closing.delete(task))
closing.add(task)
return task
@@ -87,7 +93,7 @@ export function createMCPSessionManager({
for (const [id, session] of sessions) {
if (now - session.lastSeen > MCP_SESSION_TTL_MS) {
sessions.delete(id)
- void scheduleClose(session)
+ void scheduleClose(session, id)
}
}
}
@@ -95,14 +101,14 @@ export function createMCPSessionManager({
const creating = new Map<string, Promise<MCPTransport>>()
let closed = false
- async function createSession(id: string): Promise<MCPTransport> {
+ async function createSession(id: string, kind: MCPAgentKind): Promise<MCPTransport> {
if (closed) throw new Error('Session manager is closed')
const inFlight = creating.get(id)
if (inFlight) return inFlight
const promise = (async () => {
const server = new McpServer({ name: 'open-pencil', version: serverVersion })
- registerTools(server)
+ registerTools(server, { id, kind })
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: () => id,
@@ -142,7 +148,8 @@ export function createMCPSessionManager({
}
function resolveTransport(
- sessionId: string | undefined
+ sessionId: string | undefined,
+ kind: MCPAgentKind = 'mcp'
): Promise<MCPTransport | { error: 'too_many' | 'closed' }> {
if (closed) return Promise.resolve({ error: 'closed' })
cleanupExpired()
@@ -163,7 +170,7 @@ export function createMCPSessionManager({
if (sessions.size + creating.size + closing.size >= MAX_MCP_SESSIONS) {
return Promise.resolve({ error: 'too_many' })
}
- return createSession(sessionId ?? randomUUID()).catch((e) => {
+ return createSession(sessionId ?? randomUUID(), kind).catch((e) => {
// If the manager was closed during session creation, return the structured
// error instead of letting the throw escape as a route-level 500.
if (closed) return { error: 'closed' as const }
@@ -200,14 +207,14 @@ export function createMCPSessionManager({
const session = sessions.get(sessionId)
if (!session) return
sessions.delete(sessionId)
- void scheduleClose(session)
+ void scheduleClose(session, sessionId)
}
async function clear() {
closed = true
// Collect sessions before awaiting in-flight creations so new sessions
// can't be added during shutdown.
- const all = [...sessions.values()]
+ const all = [...sessions]
sessions.clear()
// Wait for in-flight session creations to finish (they will check
// `closed` and clean up without storing the session).
@@ -216,7 +223,10 @@ export function createMCPSessionManager({
creating.clear()
// Await both previously-scheduled closes (from cleanupExpired/deleteSession)
// and closes for sessions still alive at clear() time.
- await Promise.allSettled([...closing, ...all.map(scheduleClose)])
+ await Promise.allSettled([
+ ...closing,
+ ...all.map(([id, session]) => scheduleClose(session, id))
+ ])
}
return { clear, deleteSession, getExistingTransport, notifyToolsChanged, resolveTransport, touch }
diff --git a/packages/mcp/src/stdio.ts b/packages/mcp/src/stdio.ts
index cf259f90c..4acc03185 100644
--- a/packages/mcp/src/stdio.ts
+++ b/packages/mcp/src/stdio.ts
@@ -1,4 +1,6 @@
#!/usr/bin/env node
+import { randomUUID } from 'node:crypto'
+
import { McpServer } from '@modelcontextprotocol/server'
import { StdioServerTransport } from '@modelcontextprotocol/server/stdio'
@@ -81,7 +83,13 @@ const bridge = createStdioRPCBridge({
})
const mcpServer = new McpServer({ name: 'open-pencil', version: MCP_VERSION })
-registerTools(mcpServer, { policy: toolPolicy, mcpRoot, sendRPC: bridge.sendRPC })
+// One client per process: its tool calls show as one agent in the app.
+registerTools(mcpServer, {
+ policy: toolPolicy,
+ mcpRoot,
+ sendRPC: bridge.sendRPC,
+ agentSession: { id: randomUUID(), kind: 'mcp' }
+})
const transport = new StdioServerTransport()
mcpServer.connect(transport).catch((err) => {
diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.ts
index ca465c94e..3cb1c8730 100644
--- a/packages/mcp/src/tool/registration.ts
+++ b/packages/mcp/src/tool/registration.ts
@@ -53,10 +53,21 @@ function withTarget<T extends object>(body: T, res: RPCResponse): T & { target?:
return res.target ? { ...body, target: res.target } : body
}
+/** Who sends a session's tool calls: any MCP client, or an ACP or Pi harness chat in the app. */
+export const MCP_AGENT_KINDS = ['mcp', 'acp', 'harness'] as const
+export type MCPAgentKind = (typeof MCP_AGENT_KINDS)[number]
+
+/** The session tool calls come from, so the app can show the client as an agent at work. */
+export interface MCPAgentSession {
+ id: string
+ kind: MCPAgentKind
+}
+
export interface RegisterToolsOptions {
policy: ToolPolicy
mcpRoot?: string | null
sendRPC: RPCSender
+ agentSession?: MCPAgentSession
}
function toolAnnotations(effect: ToolEffect): ToolAnnotations {
@@ -71,7 +82,16 @@ function descriptorByName(descriptors: readonly ToolDescriptor[]): Map<string, T
}
export function registerTools(mcpServer: McpServer, options: RegisterToolsOptions): void {
- const { policy, sendRPC } = options
+ const { policy, sendRPC, agentSession } = options
+ // Sent with each tool call: the session, and the client's name once it has introduced itself.
+ const agent = () =>
+ agentSession
+ ? {
+ session: agentSession.id,
+ kind: agentSession.kind,
+ client: mcpServer.server.getClientVersion()?.name
+ }
+ : undefined
const resolvedRoot = options.mcpRoot ? resolve(options.mcpRoot) : null
const descriptors = descriptorByName(createToolDescriptors(resolvedRoot !== null))
const register = <InputArgs extends v.GenericSchema>(
@@ -106,7 +126,7 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOption
const { target, args: toolArgs } = splitAutomationTarget(args)
const result = await sendRPC({
command: 'tool',
- args: { ...target, name: def.name, args: toolArgs }
+ args: { ...target, name: def.name, args: toolArgs, agent: agent() }
})
const res = result as { ok?: boolean; result?: unknown; error?: string }
if (res.ok === false) return fail(new Error(res.error))
diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.json
index c31fa45e7..83ddecef9 100644
--- a/packages/vue/src/i18n/locales/de/ai.json
+++ b/packages/vue/src/i18n/locales/de/ai.json
@@ -155,6 +155,8 @@
"latest": "Neu",
"chatHistory": "Chatverlauf",
"newChat": "Neuer Chat",
+ "followAgents": "Agenten bei der Arbeit folgen",
+ "stopFollowingAgents": "Agenten bei der Arbeit nicht mehr folgen",
"allChats": "Alle Chats",
"renameChat": "Umbenennen",
"deleteChat": "Löschen",
diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.json
index 55821796d..2cf2072ee 100644
--- a/packages/vue/src/i18n/locales/es/ai.json
+++ b/packages/vue/src/i18n/locales/es/ai.json
@@ -155,6 +155,8 @@
"modelsTitle": "Modelos",
"chatHistory": "Historial de chats",
"newChat": "Nuevo chat",
+ "followAgents": "Seguir a los agentes mientras trabajan",
+ "stopFollowingAgents": "Dejar de seguir a los agentes mientras trabajan",
"allChats": "Todos los chats",
"renameChat": "Renombrar",
"deleteChat": "Eliminar",
diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.json
index 5de61ddfa..a25b0b2d8 100644
--- a/packages/vue/src/i18n/locales/fr/ai.json
+++ b/packages/vue/src/i18n/locales/fr/ai.json
@@ -155,6 +155,8 @@
"latest": "Nouveau",
"chatHistory": "Historique des discussions",
"newChat": "Nouvelle discussion",
+ "followAgents": "Suivre les agents pendant qu’ils travaillent",
+ "stopFollowingAgents": "Ne plus suivre les agents pendant qu’ils travaillent",
"allChats": "Toutes les discussions",
"renameChat": "Renommer",
"deleteChat": "Supprimer",
diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.json
index 1f4b0b98d..09fba4881 100644
--- a/packages/vue/src/i18n/locales/it/ai.json
+++ b/packages/vue/src/i18n/locales/it/ai.json
@@ -155,6 +155,8 @@
"modelsTitle": "Modelli",
"chatHistory": "Cronologia chat",
"newChat": "Nuova chat",
+ "followAgents": "Segui gli agenti mentre lavorano",
+ "stopFollowingAgents": "Smetti di seguire gli agenti mentre lavorano",
"allChats": "Tutte le chat",
"renameChat": "Rinomina",
"deleteChat": "Elimina",
diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.json
index b01cac945..bc18a013a 100644
--- a/packages/vue/src/i18n/locales/ja/ai.json
+++ b/packages/vue/src/i18n/locales/ja/ai.json
@@ -155,6 +155,8 @@
"modelsTitle": "モデル",
"chatHistory": "チャット履歴",
"newChat": "新しいチャット",
+ "followAgents": "作業中のエージェントを追従",
+ "stopFollowingAgents": "作業中のエージェントの追従を停止",
"allChats": "すべてのチャット",
"renameChat": "名前を変更",
"deleteChat": "削除",
diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.json
index afd231958..5d35ab5c7 100644
--- a/packages/vue/src/i18n/locales/pl/ai.json
+++ b/packages/vue/src/i18n/locales/pl/ai.json
@@ -155,6 +155,8 @@
"latest": "Nowy",
"chatHistory": "Historia czatów",
"newChat": "Nowy czat",
+ "followAgents": "Śledź agentów podczas pracy",
+ "stopFollowingAgents": "Przestań śledzić agentów podczas pracy",
"allChats": "Wszystkie czaty",
"renameChat": "Zmień nazwę",
"deleteChat": "Usuń",
diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.json
index 2c01980cc..86fa8e811 100644
--- a/packages/vue/src/i18n/locales/ru/ai.json
+++ b/packages/vue/src/i18n/locales/ru/ai.json
@@ -155,6 +155,8 @@
"latest": "Новая",
"chatHistory": "История чатов",
"newChat": "Новый чат",
+ "followAgents": "Следовать за агентами во время работы",
+ "stopFollowingAgents": "Не следовать за агентами во время работы",
"allChats": "Все чаты",
"renameChat": "Переименовать",
"deleteChat": "Удалить",
diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.json
index ab4415fd2..e52f5564c 100644
--- a/packages/vue/src/i18n/locales/zh-cn/ai.json
+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json
@@ -155,6 +155,8 @@
"modelsTitle": "模型",
"chatHistory": "聊天记录",
"newChat": "新建聊天",
+ "followAgents": "工作时跟随智能体",
+ "stopFollowingAgents": "停止在工作时跟随智能体",
"allChats": "所有聊天",
"renameChat": "重命名",
"deleteChat": "删除",
diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.ts
index 3bbf4b58f..a0107bc1b 100644
--- a/packages/vue/src/i18n/messages/ai.ts
+++ b/packages/vue/src/i18n/messages/ai.ts
@@ -23,6 +23,8 @@ export const aiMessageDefaults = {
chatActions: 'Conversation actions',
chatHistory: 'Conversation history',
newChat: 'New chat',
+ followAgents: 'Follow agents as they work',
+ stopFollowingAgents: 'Stop following agents as they work',
allChats: 'All chats',
renameChat: 'Rename',
deleteChat: 'Delete',
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index d90ebf174..3498d991a 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -266,9 +266,8 @@ The CLI defaults the filesystem root to the home directory on Windows and the cu
2. **Query** — `get_page_tree`, `find_nodes`, `query_nodes`, `get_node`, `list_pages`, `get_current_page`.
3. **Inspect** — `get_jsx`, `diff_jsx`, `diff_create`, `diff_visual`, `describe`, `export_image`, `export_svg`, `export_pdf`.
4. **Modify** — `render`, `batch_update`, `update_node`, `set_fill`, `set_layout`, `create_shape`, `import_svg`, etc.
-5. **Navigate** — after creating or editing visible canvas content, call `select_nodes` and `viewport_zoom_to_fit { id }` (or `node_bounds` + `viewport_set`) so the user can see the result in the running editor.
-6. **Save/export** — `save_file`, `export_image`, `export_svg`, `export_pdf`, or CLI `export`.
-7. **Close** — `close_file { document_id, unsaved }` closes a document tab after the workflow. With unsaved changes it fails unless `unsaved` is `"save"` or `"discard"`; automation never prompts in the app.
+5. **Save/export** — `save_file`, `export_image`, `export_svg`, `export_pdf`, or CLI `export`.
+6. **Close** — `close_file { document_id, unsaved }` closes a document tab after the workflow. With unsaved changes it fails unless `unsaved` is `"save"` or `"discard"`; automation never prompts in the app.
Use `undo` / `redo { document_id }` to step back your own changes. They refuse when the newest step was made by the user in the editor; never work around that. `get_settings` and `update_settings { settings }` read and change editor preferences such as theme, language, and snapping; they never expose credentials, models, or tool access.
@@ -295,7 +294,7 @@ Discover available tools and their arguments from the connected server or browse
- **`describe`** — semantic analysis of role, visual style, layout, and design issues.
- **`batch_update`** — apply multiple node updates efficiently.
- **`export_image` / `export_svg` / `export_pdf`** — visual verification and deliverables.
-- **`viewport_zoom_to_fit` / `viewport_set` / `viewport_get`** — keep the live editor focused on the created or edited design.
+- **`viewport_zoom_to_fit` / `viewport_set` / `viewport_get`** — move the user's view only when they ask to be shown something.
- **`get_codegen_prompt`** — retrieve OpenPencil's current JSX/codegen guidance.
- **`undo` / `redo`** — revert or reapply your newest change; they refuse to touch the user's edits.
- **`list_documents` / `activate_document`** — discover open tabs and show the one you worked on.
@@ -313,8 +312,7 @@ Use the `render` tool for JSX strings. Use only the APIs exposed by the installe
- Use `tree --depth 2` or `query_nodes` to avoid overwhelming output on large files.
- Export specific nodes with `--node` for faster visual checks.
- Use `export_image` after changes to verify visual quality.
-- After creating a visible design, select it and zoom the editor to it: `select_nodes { ids: [id] }` then `viewport_zoom_to_fit { id }`.
-- If zoom-to-fit is unavailable in a client, use `node_bounds` to calculate the center and call `viewport_set { x, y, zoom }`.
+- The running editor shows each MCP session as an agent at the layers its tools touch, and follows it while it works when the user has Follow agents on. Leave the user's selection and view alone unless they ask to be shown something.
- Use `analyze colors --similar` to find near-duplicate colors.
- Use `openpencil tool call` for MCP tools without a dedicated CLI command, and `eval` for Figma Plugin API operations not covered by any tool.
- Use `--json` when piping CLI output to scripts.
diff --git a/src/AGENTS.md b/src/AGENTS.md
index 7fe7906e5..3c74c2c56 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -26,6 +26,7 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr
- Collaboration lives under `src/app/collab/**` on Trystero, Yjs, and awareness; preserve crypto-safe room IDs and peer cleanup.
- 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`).
- 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 d23005c47..b905199e8 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -23,7 +23,14 @@ 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, recordStep, runPageId, startRun } from '@/app/ai/tools'
+import {
+ createAITools,
+ endRun,
+ markRunPreview,
+ recordStep,
+ runPageId,
+ startRun
+} from '@/app/ai/tools'
import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'
import { aiToolOverrides } from '@/app/ai/tools/preferences'
import { diagnosticErrorDetails } from '@/app/diagnostics'
@@ -111,7 +118,12 @@ export function createToolLoopTransport({
diagnosticContext = {}
}: ToolLoopTransportOptions) {
const tools = createAITools(store, diagnosticContext)
- const preview = createCanvasJSXPreview(store, () => runPageId(store))
+ // While JSX streams, the chat's agent moves through the elements as they appear.
+ const preview = createCanvasJSXPreview(
+ store,
+ () => runPageId(store),
+ (focus) => markRunPreview(store, focus)
+ )
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 6755f4571..07e32abec 100644
--- a/src/app/ai/preview/canvas.ts
+++ b/src/app/ai/preview/canvas.ts
@@ -1,15 +1,23 @@
import type { CanvasKit, SkPicture } from 'canvaskit-wasm'
+import { uniq } from 'es-toolkit/array'
import { watch } from 'vue'
-import { recordJSXPreview, stageJSXPreview } from '@open-pencil/core/design-jsx'
+import {
+ recordJSXPreview,
+ stageJSXPreview,
+ type StagedJSXPreview
+} from '@open-pencil/core/design-jsx'
+import { computeContentBounds } from '@open-pencil/core/io'
import type { JSXPreviewNode } from '@open-pencil/design-jsx'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import {
getActiveEditorStoreOrNull,
useActiveEditorStoreRef,
type EditorStore
} from '@/app/editor/active-store'
+import { MAX_OUTLINE } from '@/app/presence/schema'
import { createJSXPreviewController, type PreviewArtifact } from './controller'
import type { RenderPreviewInput } from './input'
@@ -21,6 +29,48 @@ interface PreviewTarget {
const MAX_RENDERED_PREVIEW_NODES = 500
+/** Where streamed JSX is being built, in world coordinates: its newest element, and outlines. */
+export interface PreviewFocus {
+ cursor: Vector
+ outline: Rect[]
+}
+
+function nodeRect(graph: SceneGraph, nodeId: string): Rect | null {
+ const bounds = computeContentBounds(graph, [nodeId])
+ if (!bounds) return null
+ return {
+ x: bounds.minX,
+ y: bounds.minY,
+ width: bounds.maxX - bounds.minX,
+ height: bounds.maxY - bounds.minY
+ }
+}
+
+/** The element that appeared last: the source's last element is the end of the last-child chain. */
+function newestElement(graph: SceneGraph, rootIds: readonly string[]): string | undefined {
+ const rootId = rootIds.at(-1)
+ let node = rootId ? graph.getNode(rootId) : undefined
+ while (node) {
+ const last = node.childIds.at(-1)
+ const child = last ? graph.getNode(last) : undefined
+ if (!child) return node.id
+ node = child
+ }
+ return undefined
+}
+
+/** The cursor at the newest element's trailing corner, and outlines of the JSX and that element. */
+export function previewFocus(staged: Pick<StagedJSXPreview, 'graph' | 'renderedIds'>) {
+ const newest = newestElement(staged.graph, staged.renderedIds)
+ const newestRect = newest ? nodeRect(staged.graph, newest) : null
+ if (!newest || !newestRect) return null
+ const outlined = uniq([...staged.renderedIds, newest]).slice(-MAX_OUTLINE)
+ const outline = outlined.flatMap((id) => nodeRect(staged.graph, id) ?? [])
+ // The trailing corner, where content grows, so the agent's name sits beside what it writes.
+ const cursor = { x: newestRect.x + newestRect.width, y: newestRect.y + newestRect.height }
+ return { cursor, outline } satisfies PreviewFocus
+}
+
function countNodes(tree: JSXPreviewNode): number {
return (
1 +
@@ -35,7 +85,12 @@ function countNodes(tree: JSXPreviewNode): number {
* 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.
*/
-export function createCanvasJSXPreview(store: EditorStore, pageId: () => string) {
+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
+) {
let subscriptions: (() => void)[] = []
function isCurrent(target: PreviewTarget): boolean {
@@ -104,6 +159,7 @@ export function createCanvasJSXPreview(store: EditorStore, pageId: () => string)
throw error
}
if (pictures.size === 0) return null
+ const focus = previewFocus(staged)
const id = crypto.randomUUID()
const attached = new Set<EditorStore['canvasRenderers'][number]>()
let disposed = false
@@ -122,6 +178,7 @@ export function createCanvasJSXPreview(store: EditorStore, pageId: () => string)
attached.add(canvasRenderer)
}
store.requestRepaint()
+ if (focus) onFocus?.(focus)
},
dispose() {
if (disposed) return
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.ts
index 20543f9f1..71cdfb3c6 100644
--- a/src/app/ai/tools/index.ts
+++ b/src/app/ai/tools/index.ts
@@ -33,6 +33,7 @@ import {
export {
didHitStepLimit,
endRun,
+ markRunPreview,
recordStep,
runAgentId,
runPageId,
diff --git a/src/app/ai/tools/run.ts b/src/app/ai/tools/run.ts
index cad523dd6..4456961ad 100644
--- a/src/app/ai/tools/run.ts
+++ b/src/app/ai/tools/run.ts
@@ -1,12 +1,12 @@
import type { PageSnapshot } from '@open-pencil/core/editor'
-import { computeContentBounds } from '@open-pencil/core/io'
import type { StepBudget } from '@open-pencil/core/tools'
import type { UndoEntry } from '@open-pencil/scene-graph/undo'
import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'
+import type { PreviewFocus } from '@/app/ai/preview/canvas'
import { getActiveEditorStore } from '@/app/editor/active-store'
import type { EditorStore } from '@/app/editor/active-store'
-import { addAgent, type AgentHandle } from '@/app/presence/registry'
+import { addAgent, agentPlacement, type AgentHandle } from '@/app/presence/registry'
class RunState {
currentSteps = 0
@@ -55,19 +55,33 @@ export function startRun(store: EditorStore, maxSteps: number, model?: string):
/** The reply finished, failed, or was stopped: the agent stays listed but leaves the canvas. */
export function endRun(store: EditorStore): void {
- getRunState(store).agent?.update({ status: 'idle', cursor: undefined, selection: undefined })
+ getRunState(store).agent?.update({
+ status: 'idle',
+ cursor: undefined,
+ selection: undefined,
+ outline: undefined
+ })
+}
+
+/**
+ * Point the run's agent at JSX it is still streaming: the element that appeared last, with
+ * outlines of what it builds, until the tool runs and `markRunWork` names the real layers.
+ */
+export function markRunPreview(store: EditorStore, focus: PreviewFocus): void {
+ getRunState(store).agent?.update({
+ status: 'editing',
+ cursor: { ...focus.cursor, pageId: runPageId(store) },
+ selection: undefined,
+ outline: focus.outline
+ })
}
/** Point the run's agent at nodes a tool just created or changed. */
export function markRunWork(store: EditorStore, nodeIds: string[]): void {
const run = getRunState(store)
- const bounds = computeContentBounds(store.graph, nodeIds)
- if (!run.agent || !bounds) return
- run.agent.update({
- status: 'editing',
- cursor: { x: bounds.minX, y: bounds.minY, pageId: runPageId(store) },
- selection: nodeIds
- })
+ const placement = agentPlacement(store, nodeIds, runPageId(store))
+ if (!run.agent || !placement) return
+ run.agent.update({ status: 'editing', ...placement })
}
export function recordStep(store?: EditorStore): void {
diff --git a/src/app/automation/agents.ts b/src/app/automation/agents.ts
new file mode 100644
index 000000000..696a7e069
--- /dev/null
+++ b/src/app/automation/agents.ts
@@ -0,0 +1,147 @@
+import * as v from 'valibot'
+
+import { isUnknownRecord } from '@/app/automation/bridge/target'
+import type { EditorStore } from '@/app/editor/active-store'
+import { addAgent, agentPlacement, type AgentHandle } from '@/app/presence/registry'
+import { MAX_NAME_LENGTH } from '@/app/presence/schema'
+
+/** After this long without a tool call, a session's agent rests and leaves the canvas. */
+export const MCP_AGENT_IDLE_MS = 20_000
+/** A session that never says goodbye, such as one whose client crashed, is dropped after this. */
+export const MCP_AGENT_GONE_MS = 10 * 60_000
+const MAX_SESSION_ID = 128
+/** Argument and result fields that name the layers a tool works on. */
+const NODE_ID_FIELDS = ['id', 'ids', 'node_id', 'node_ids', 'parent_id', 'root_id', 'target_id']
+const NODE_LIST_FIELDS = ['results', 'selection', 'nodes']
+
+const agentSessionSchema = v.object({
+ session: v.pipe(v.string(), v.minLength(1), v.maxLength(MAX_SESSION_ID)),
+ kind: v.picklist(['mcp', 'acp', 'harness']),
+ client: v.fallback(
+ v.optional(v.pipe(v.string(), v.trim(), v.maxLength(MAX_NAME_LENGTH))),
+ undefined
+ )
+})
+
+/** The MCP session a tool call came from, as the MCP server forwards it. */
+export type AgentSession = v.InferOutput<typeof agentSessionSchema>
+
+export function readAgentSession(value: unknown): AgentSession | null {
+ const result = v.safeParse(agentSessionSchema, value)
+ return result.success ? result.output : null
+}
+
+interface SessionAgent {
+ handle: AgentHandle
+ idleTimer?: ReturnType<typeof setTimeout>
+ goneTimer?: ReturnType<typeof setTimeout>
+}
+
+/** Each session's agent in every document it works in; tool calls name their document. */
+const sessions = new Map<string, Map<EditorStore, SessionAgent>>()
+
+function sessionAgent(store: EditorStore, session: AgentSession): SessionAgent {
+ let agents = sessions.get(session.session)
+ if (!agents) {
+ agents = new Map()
+ sessions.set(session.session, agents)
+ }
+ let agent = agents.get(store)
+ if (!agent) {
+ agent = { handle: addAgent(store, session.kind, session.client || undefined) }
+ agents.set(store, agent)
+ }
+ return agent
+}
+
+function remove(sessionId: string, store: EditorStore): void {
+ const agents = sessions.get(sessionId)
+ const agent = agents?.get(store)
+ if (!agents || !agent) return
+ clearTimeout(agent.idleTimer)
+ clearTimeout(agent.goneTimer)
+ agent.handle.remove()
+ agents.delete(store)
+ if (agents.size === 0) sessions.delete(sessionId)
+}
+
+function restartTimers(store: EditorStore, sessionId: string, agent: SessionAgent): void {
+ clearTimeout(agent.idleTimer)
+ clearTimeout(agent.goneTimer)
+ agent.idleTimer = setTimeout(() => {
+ agent.handle.update({ status: 'idle', cursor: undefined, selection: undefined })
+ }, MCP_AGENT_IDLE_MS)
+ agent.goneTimer = setTimeout(() => remove(sessionId, store), MCP_AGENT_GONE_MS)
+}
+
+function collectIds(value: unknown, ids: Set<string>): void {
+ if (!isUnknownRecord(value)) return
+ const record = value
+ for (const field of NODE_ID_FIELDS) {
+ const entry = record[field]
+ if (typeof entry === 'string') ids.add(entry)
+ else if (Array.isArray(entry)) {
+ for (const item of entry) if (typeof item === 'string') ids.add(item)
+ }
+ }
+ for (const field of NODE_LIST_FIELDS) {
+ const list = record[field]
+ if (!Array.isArray(list)) continue
+ for (const item of list) {
+ if (isUnknownRecord(item) && typeof item.id === 'string') ids.add(item.id)
+ }
+ }
+}
+
+/** The layers a tool call works on: what its arguments name, then what its result names. */
+export function touchedNodeIds(store: EditorStore, args: unknown, result: unknown): string[] {
+ const ids = new Set<string>()
+ collectIds(args, ids)
+ collectIds(result, ids)
+ return [...ids].filter((id) => {
+ const node = store.graph.getNode(id)
+ // Pages and the document root are where the agent is, not what it works on.
+ return node !== undefined && node.type !== 'CANVAS' && id !== store.graph.rootId
+ })
+}
+
+function pageOf(store: EditorStore, nodeId: string): string | undefined {
+ let node = store.graph.getNode(nodeId)
+ while (node && node.type !== 'CANVAS')
+ node = node.parentId ? store.graph.getNode(node.parentId) : undefined
+ return node?.id
+}
+
+/** A session started a tool call on `pageId`: its agent shows it is at work there. */
+export function agentStarted(store: EditorStore, session: AgentSession, pageId: string): void {
+ const agent = sessionAgent(store, session)
+ agent.handle.update({ status: 'thinking', pageId })
+ restartTimers(store, session.session, agent)
+}
+
+/**
+ * A session's tool call finished: its agent points at the layers the call read or changed, so
+ * people see the context it works with, and edits show as editing.
+ */
+export function agentFinished(
+ store: EditorStore,
+ session: AgentSession,
+ work: { pageId: string; nodeIds: readonly string[]; edited: boolean }
+): void {
+ const agent = sessionAgent(store, session)
+ const first = work.nodeIds[0]
+ const pageId = (first && pageOf(store, first)) || work.pageId
+ const placement = agentPlacement(store, work.nodeIds, pageId)
+ agent.handle.update({
+ status: work.edited ? 'editing' : 'thinking',
+ pageId,
+ ...placement
+ })
+ restartTimers(store, session.session, agent)
+}
+
+/** The MCP server says a session ended: its agents leave every document. */
+export function endAgentSession(sessionId: string): void {
+ // Removing entries while iterating a Map is safe: visited ones stay visited.
+ for (const store of sessions.get(sessionId)?.keys() ?? []) remove(sessionId, store)
+}
diff --git a/src/app/automation/bridge/handlers.ts b/src/app/automation/bridge/handlers.ts
index 5757f2818..27997f45c 100644
--- a/src/app/automation/bridge/handlers.ts
+++ b/src/app/automation/bridge/handlers.ts
@@ -1,5 +1,6 @@
import type { FigmaAPI } from '@open-pencil/core/figma-api'
+import { endAgentSession } from '@/app/automation/agents'
import {
handleActivateDocument,
handleGetSettings,
@@ -76,6 +77,11 @@ export function createAutomationCommandHandlers(makeFigma: FigmaFactory) {
if (command === 'list_documents') {
return { ok: true, result: { documents: listAutomationDocuments(store) } }
}
+ if (command === 'agent_session_closed') {
+ const session = isUnknownRecord(args) ? args.session : undefined
+ if (typeof session === 'string') endAgentSession(session)
+ return { ok: true, result: null }
+ }
if (command === 'get_settings') return handleGetSettings()
if (command === 'update_settings') return handleUpdateSettings(args)
diff --git a/src/app/automation/bridge/server.ts b/src/app/automation/bridge/server.ts
index b78a50bd4..831c22b7f 100644
--- a/src/app/automation/bridge/server.ts
+++ b/src/app/automation/bridge/server.ts
@@ -8,8 +8,10 @@ import * as v from 'valibot'
import { randomHex } from '@open-pencil/scene-graph/random'
+import { endAgentSession, readAgentSession } from '@/app/automation/agents'
import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'
import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'
+import { isUnknownRecord } from '@/app/automation/bridge/target'
import type { EditorStore } from '@/app/editor/active-store'
/** Requests from the MCP bridge; other message types (such as the register prompt) are ignored. */
@@ -24,6 +26,13 @@ const AutomationRequestJSON = v.pipe(
})
)
+/**
+ * The connections each MCP session's calls came over, across bridges: restarting MCP opens a new
+ * bridge while the old socket is still closing, and that close must not end a session the new
+ * connection carries, so a session ends only with its last connection.
+ */
+const sessionSockets = new Map<string, Set<WebSocket>>()
+
export function connectAutomation(
getStore: () => EditorStore,
authToken: string | null = null,
@@ -69,6 +78,12 @@ export function connectAutomation(
return
}
const msg = parsed.output
+ const session = isUnknownRecord(msg.args) ? readAgentSession(msg.args.agent) : null
+ if (session) {
+ const sockets = sessionSockets.get(session.session) ?? new Set<WebSocket>()
+ sockets.add(socket)
+ sessionSockets.set(session.session, sockets)
+ }
try {
const result = await handleRequest(msg.id, msg.command, msg.args)
if (socket.readyState !== WebSocket.OPEN) return
@@ -91,6 +106,13 @@ export function connectAutomation(
socket.onclose = (event) => {
if (ws === socket) ws = null
+ // Sessions that reached the app only over this connection cannot any more, so their agents
+ // leave; ones that also came another way, such as over a newer connection, stay.
+ for (const [id, sockets] of sessionSockets) {
+ if (!sockets.delete(socket) || sockets.size > 0) continue
+ sessionSockets.delete(id)
+ endAgentSession(id)
+ }
if (intentionalDisconnect || event.code === 1000) return
console.warn('[Automation] WebSocket closed:', `code=${event.code} reason=${event.reason}`)
scheduleReconnect()
diff --git a/src/app/automation/bridge/test-hooks.ts b/src/app/automation/bridge/test-hooks.ts
new file mode 100644
index 000000000..24be670be
--- /dev/null
+++ b/src/app/automation/bridge/test-hooks.ts
@@ -0,0 +1,9 @@
+import { exposeAutomationRequests } from '@/app/browser-bridge'
+
+import { makeFigmaFromStore } from './figma-factory'
+import { createAutomationCommandHandlers } from './handlers'
+
+/** Lets browser tests send MCP requests through the same handler the bridge uses. */
+export function exposeAutomationTestRequests() {
+ exposeAutomationRequests(createAutomationCommandHandlers(makeFigmaFromStore).handleRequest)
+}
diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.ts
index c23672d65..6bb907c40 100644
--- a/src/app/automation/bridge/tool-handlers.ts
+++ b/src/app/automation/bridge/tool-handlers.ts
@@ -9,6 +9,12 @@ import {
} from '@open-pencil/core/tools'
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
+import {
+ agentFinished,
+ agentStarted,
+ readAgentSession,
+ touchedNodeIds
+} from '@/app/automation/agents'
import type { AutomationTarget } from '@/app/automation/bridge/target'
import {
AUTOMATION_UNDO_LABEL,
@@ -25,7 +31,7 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
async function handleToolRender(
target: AutomationTarget,
toolArgs: Record<string, unknown>
- ): Promise<unknown> {
+ ): Promise<{ id: string; name: string; type: string; children: string[] }> {
const store = target.store
const tree = toolArgs.tree as Parameters<typeof renderTree>[1]
const parentId = (toolArgs.parent_id as string | undefined) ?? target.pageId
@@ -47,10 +53,7 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
)
store.requestRender()
store.flashNodes([result.id])
- return {
- ok: true,
- result: { id: result.id, name: result.name, type: result.type, children: result.childIds }
- }
+ return { id: result.id, name: result.name, type: result.type, children: result.childIds }
}
return async function handleTool(target: AutomationTarget, args: unknown): Promise<unknown> {
@@ -58,8 +61,27 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
const toolArgs = (args as { args?: Record<string, unknown> }).args ?? {}
if (!toolName) throw new Error('Missing "name" in args')
+ // A call from an MCP session shows as that session's agent, working where the call works.
+ const session = readAgentSession((args as { agent?: unknown }).agent)
+ if (session) agentStarted(target.store, session, target.pageId)
+ const response = await runTool(target, toolName, toolArgs)
+ if (session) {
+ agentFinished(target.store, session, {
+ pageId: target.pageId,
+ nodeIds: touchedNodeIds(target.store, toolArgs, response.result),
+ edited: response.edited
+ })
+ }
+ return { ok: true, result: response.result }
+ }
+
+ async function runTool(
+ target: AutomationTarget,
+ toolName: string,
+ toolArgs: Record<string, unknown>
+ ): Promise<{ result: unknown; edited: boolean }> {
if (toolName === 'render' && toolArgs.tree) {
- return handleToolRender(target, toolArgs)
+ return { result: await handleToolRender(target, toolArgs), edited: true }
}
const def = ALL_TOOLS.find((t) => t.name === toolName && isToolExposed(t, 'mcp'))
@@ -97,7 +119,7 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
store.requestRender()
store.flashNodes(extractNodeIds(result))
}
- return { ok: true, result }
+ return { result, edited: def.mutates }
}
}
diff --git a/src/app/browser-bridge.ts b/src/app/browser-bridge.ts
index d61cf55ef..ac10b569f 100644
--- a/src/app/browser-bridge.ts
+++ b/src/app/browser-bridge.ts
@@ -25,6 +25,8 @@ export interface OpenPencilTestHooks {
peerSelections: () => Array<string[] | undefined>
status: () => RoomStatus | null
}
+ /** Sends a request through the MCP bridge's command handler, as an MCP client's call arrives. */
+ automation?: (command: string, args: unknown) => Promise<unknown>
}
export interface OpenPencilWindowAPI {
@@ -77,6 +79,20 @@ export function exposeCollaborationActions(
}
}
+/** Test runs send MCP requests the way the bridge delivers them, without a separate server. */
+export function exposeAutomationRequests(
+ handleRequest: (store: EditorStore, command: string, args: unknown) => Promise<unknown>
+) {
+ if (!IS_BROWSER || !import.meta.env.DEV) return
+ if (!appRuntimeConfig.test) return
+ const testHooks = (windowAPI().test ??= {})
+ testHooks.automation = async (command, args) => {
+ const store = windowAPI().getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ return handleRequest(store, command, args)
+ }
+}
+
export function exposeChatTransportOverride(
setChatTransport: (factory: () => ChatTransport<UIMessage>) => void
) {
diff --git a/src/app/integrations/mcp/pi.ts b/src/app/integrations/mcp/pi.ts
index cffbaa21b..3d80cacc8 100644
--- a/src/app/integrations/mcp/pi.ts
+++ b/src/app/integrations/mcp/pi.ts
@@ -1,4 +1,4 @@
-import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'
+import { AUTOMATION_HTTP_PORT, MCP_AGENT_HEADER } from '@open-pencil/core/constants'
import { getAutomationAuthToken } from '@/app/automation/mcp/spawn'
import { describeDiagnosticError, recordMCPConnectionFailure } from '@/app/diagnostics'
@@ -49,7 +49,11 @@ export async function buildPiMCPServers(options?: {
...Object.fromEntries(entries),
'open-pencil': {
url: `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/mcp`,
- ...(authorizationToken ? { headers: { Authorization: `Bearer ${authorizationToken}` } } : {}),
+ // The Pi harness chat's tool calls show as its agent rather than an outside MCP client.
+ headers: {
+ [MCP_AGENT_HEADER]: 'harness',
+ ...(authorizationToken ? { Authorization: `Bearer ${authorizationToken}` } : {})
+ },
auth: false
}
}
diff --git a/src/app/integrations/mcp/runtime.ts b/src/app/integrations/mcp/runtime.ts
index d2b9de96d..63d87e1ac 100644
--- a/src/app/integrations/mcp/runtime.ts
+++ b/src/app/integrations/mcp/runtime.ts
@@ -1,6 +1,6 @@
import type { McpServer } from '@agentclientprotocol/sdk'
-import { AUTOMATION_HTTP_PORT } from '@open-pencil/core/constants'
+import { AUTOMATION_HTTP_PORT, MCP_AGENT_HEADER } from '@open-pencil/core/constants'
import { describeDiagnosticError, recordMCPConnectionFailure } from '@/app/diagnostics'
import { appCredentialServices } from '@/app/settings/credentials/app'
@@ -16,9 +16,13 @@ export function builtInMCPServer(options: BuiltInMCPServerOptions): McpServer {
type: 'http',
name: 'open-pencil',
url: `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/mcp`,
- headers: options.authorizationToken
- ? [{ name: 'Authorization', value: `Bearer ${options.authorizationToken}` }]
- : []
+ // An ACP chat's tool calls show as an ACP agent rather than an outside MCP client.
+ headers: [
+ { name: MCP_AGENT_HEADER, value: 'acp' },
+ ...(options.authorizationToken
+ ? [{ name: 'Authorization', value: `Bearer ${options.authorizationToken}` }]
+ : [])
+ ]
}
}
diff --git a/src/app/presence/cursor-motion.ts b/src/app/presence/cursor-motion.ts
new file mode 100644
index 000000000..2a20f6098
--- /dev/null
+++ b/src/app/presence/cursor-motion.ts
@@ -0,0 +1,135 @@
+import type { PresenceCursor } from '@open-pencil/core/canvas'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+import type { EditorStore } from '@/app/editor/active-store'
+import { animationsEnabled } from '@/app/shell/motion'
+
+import { CURSOR_GLIDE_MS, FOLLOW_GLIDE_MS, glideAt, retarget, type Glide } from './motion'
+
+/** A cursor with the identity it keeps between updates, so it can glide rather than jump. */
+export type TrackedCursor = PresenceCursor & { id: string }
+
+interface ViewGlide {
+ center: Glide
+ fromZoom: number
+ toZoom: number
+ /** Applies one step; the registry marks it as following's own viewport change. */
+ move: (x: number, y: number, zoom: number) => void
+}
+
+interface Motion {
+ targets: TrackedCursor[]
+ glides: Map<string, Glide>
+ view: ViewGlide | null
+ frame: number | null
+}
+
+const motions = new WeakMap<EditorStore, Motion>()
+
+function motionOf(store: EditorStore): Motion {
+ let motion = motions.get(store)
+ if (!motion) {
+ motion = { targets: [], glides: new Map(), view: null, frame: null }
+ motions.set(store, motion)
+ }
+ return motion
+}
+
+function canAnimate(): boolean {
+ return animationsEnabled.value && typeof requestAnimationFrame === 'function'
+}
+
+function schedule(store: EditorStore, motion: Motion): void {
+ if (motion.frame !== null) return
+ motion.frame = requestAnimationFrame(() => {
+ motion.frame = null
+ step(store, motion, performance.now())
+ })
+}
+
+/** Draws every cursor where its glide is now, moves a following view, and asks for the next frame. */
+function step(store: EditorStore, motion: Motion, now: number): void {
+ let moving = false
+ store.state.presenceCursors = motion.targets.map((cursor) => {
+ const glide = motion.glides.get(cursor.id)
+ if (!glide) return cursor
+ const { point, done } = glideAt(glide, now)
+ if (!done) moving = true
+ return { ...cursor, x: point.x, y: point.y }
+ })
+ store.requestRepaint()
+ const view = motion.view
+ if (view) {
+ const { point, done } = glideAt(view.center, now)
+ const t = done ? 1 : (now - view.center.start) / view.center.duration
+ // Zoom changes by ratio, so it eases evenly whether it doubles or halves.
+ const zoom = view.fromZoom * (view.toZoom / view.fromZoom) ** Math.min(1, Math.max(0, t))
+ view.move(point.x, point.y, zoom)
+ if (done) motion.view = null
+ else moving = true
+ }
+ if (moving) schedule(store, motion)
+}
+
+/**
+ * Show people's and agents' cursors at `targets`. Each one glides from where it is drawn now;
+ * a new one appears in place. With animations off, they move at once.
+ */
+export function showCursors(store: EditorStore, targets: TrackedCursor[]): void {
+ const motion = motionOf(store)
+ const now = performance.now()
+ const animate = canAnimate()
+ const ids = new Set(targets.map((cursor) => cursor.id))
+ for (const id of motion.glides.keys()) if (!ids.has(id)) motion.glides.delete(id)
+ for (const cursor of targets) {
+ const to = { x: cursor.x, y: cursor.y }
+ const previous = animate ? motion.glides.get(cursor.id) : undefined
+ motion.glides.set(cursor.id, retarget(previous, to, now, CURSOR_GLIDE_MS))
+ }
+ motion.targets = targets
+ step(store, motion, now)
+}
+
+/** The world point at the center of the view. */
+function viewCenter(store: EditorStore): Vector {
+ const screen = store.viewportCanvasCenter()
+ return {
+ x: (screen.x - store.state.panX) / store.state.zoom,
+ y: (screen.y - store.state.panY) / store.state.zoom
+ }
+}
+
+/**
+ * Pan the view so `point` is centered, at `zoom`, gliding there from where it looks now. `move`
+ * applies each step. With animations off, the view moves at once.
+ */
+export function glideViewTo(
+ store: EditorStore,
+ point: Vector,
+ zoom: number,
+ move: (x: number, y: number, zoom: number) => void
+): void {
+ const motion = motionOf(store)
+ if (!canAnimate()) {
+ motion.view = null
+ move(point.x, point.y, zoom)
+ return
+ }
+ const now = performance.now()
+ const current = motion.view
+ ? { center: glideAt(motion.view.center, now).point, zoom: store.state.zoom }
+ : { center: viewCenter(store), zoom: store.state.zoom }
+ if (current.center.x === point.x && current.center.y === point.y && current.zoom === zoom) return
+ motion.view = {
+ center: { from: current.center, to: point, start: now, duration: FOLLOW_GLIDE_MS },
+ fromZoom: current.zoom,
+ toZoom: zoom,
+ move
+ }
+ schedule(store, motion)
+}
+
+/** Stop a view glide in place, as when following ends. */
+export function stopViewGlide(store: EditorStore): void {
+ motionOf(store).view = null
+}
diff --git a/src/app/presence/motion.ts b/src/app/presence/motion.ts
new file mode 100644
index 000000000..b5bbf10ed
--- /dev/null
+++ b/src/app/presence/motion.ts
@@ -0,0 +1,48 @@
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+/** How long a cursor takes to glide to where its owner last moved it. */
+export const CURSOR_GLIDE_MS = 180
+/** How long the view takes to pan to where the followed person or agent went. */
+export const FOLLOW_GLIDE_MS = 260
+
+/** A move from one point to another that started at `start` and lasts `duration` ms. */
+export interface Glide {
+ from: Vector
+ to: Vector
+ start: number
+ duration: number
+}
+
+/** Fast start, gentle stop, so a cursor catches up quickly and settles without overshooting. */
+export function easeOutCubic(t: number): number {
+ const clamped = Math.min(1, Math.max(0, t))
+ return 1 - (1 - clamped) ** 3
+}
+
+/** Where a glide is at `now`, and whether it has arrived. */
+export function glideAt(glide: Glide, now: number): { point: Vector; done: boolean } {
+ const t = glide.duration > 0 ? (now - glide.start) / glide.duration : 1
+ const k = easeOutCubic(t)
+ return {
+ point: {
+ x: glide.from.x + (glide.to.x - glide.from.x) * k,
+ y: glide.from.y + (glide.to.y - glide.from.y) * k
+ },
+ done: t >= 1
+ }
+}
+
+/**
+ * A glide to `to` that starts wherever the previous one is now, so frequent updates never make a
+ * cursor jump back. Without a previous glide the point simply appears at `to`.
+ */
+export function retarget(
+ previous: Glide | undefined,
+ to: Vector,
+ now: number,
+ duration: number
+): Glide {
+ if (!previous) return { from: to, to, start: now, duration: 0 }
+ if (previous.to.x === to.x && previous.to.y === to.y) return previous
+ return { from: glideAt(previous, now).point, to, start: now, duration }
+}
diff --git a/src/app/presence/registry.ts b/src/app/presence/registry.ts
index 33891bed6..66c80034a 100644
--- a/src/app/presence/registry.ts
+++ b/src/app/presence/registry.ts
@@ -1,14 +1,16 @@
import { shallowRef, type ShallowRef } from 'vue'
-import type { PresenceCursor } from '@open-pencil/core/canvas'
import { AI_ACTIVE_COLOR } from '@open-pencil/core/constants'
+import { computeContentBounds } from '@open-pencil/core/io'
import type { Color } from '@open-pencil/scene-graph/primitives'
import { randomHex } from '@open-pencil/scene-graph/random'
import type { RemotePeer } from '@/app/collab/types'
import type { EditorStore } from '@/app/editor/active-store'
+import { appPreferences } from '@/app/settings/preferences/store'
import { pickCallsign } from './callsigns'
+import { glideViewTo, showCursors, stopViewGlide, type TrackedCursor } from './cursor-motion'
import { MAX_NAME_LENGTH } from './schema'
import type { AgentKind, AgentPresence, FollowTarget, PersonPoint } from './types'
@@ -30,6 +32,8 @@ interface Presence {
switching: string | null
/** True while following centers the view; any other viewport change is yours. */
moving: boolean
+ /** Our agents the person stopped following mid-work; following them again waits until they rest. */
+ declined: Set<string>
}
const presences = new WeakMap<EditorStore, Presence>()
@@ -44,7 +48,8 @@ export function presenceOf(store: EditorStore): Presence {
following: shallowRef(null),
followPage: null,
switching: null,
- moving: false
+ moving: false,
+ declined: new Set()
}
presences.set(store, presence)
store.onEditorEvent('page:changed', () => {
@@ -54,7 +59,7 @@ export function presenceOf(store: EditorStore): Presence {
// Zooming or fitting the view yourself, by any shortcut or menu, ends following. A page
// switch restores that page's viewport without this event, so only centering is ours.
store.onEditorEvent('viewport:changed', () => {
- if (presence.following.value && !presence.moving) stopFollowing(store)
+ if (presence.following.value && !presence.moving) stopFollowing(store, true)
})
return presence
}
@@ -113,21 +118,33 @@ export function presenceByPage(store: EditorStore): Map<string, PagePresenceEntr
return byPage
}
-function agentCursor(agent: AgentPresence, color: Color, pageId: string): PresenceCursor[] {
+function agentCursor(agent: AgentPresence, color: Color, pageId: string): TrackedCursor[] {
if (agent.status === 'idle' || agent.cursor?.pageId !== pageId) return []
const { x, y } = agent.cursor
- return [{ kind: 'agent', name: agent.name, color, x, y, selection: agent.selection }]
+ return [
+ {
+ id: `agent:${agent.id}`,
+ kind: 'agent',
+ name: agent.name,
+ color,
+ x,
+ y,
+ selection: agent.selection,
+ outline: agent.outline
+ }
+ ]
}
/** Draw everyone working on the page on screen: people, their agents, and ours. */
export function refreshCursors(store: EditorStore): void {
const { agents, peers } = presenceOf(store)
const pageId = store.state.currentPageId
- store.state.presenceCursors = [
- ...peers.value.flatMap((peer): PresenceCursor[] => [
+ showCursors(store, [
+ ...peers.value.flatMap((peer): TrackedCursor[] => [
...(peer.cursor?.pageId === pageId
? [
{
+ id: `person:${peer.clientId}`,
kind: 'person' as const,
name: peer.name,
color: peer.color,
@@ -139,8 +156,43 @@ export function refreshCursors(store: EditorStore): void {
...peer.agents.flatMap((agent) => agentCursor(agent, peer.color, pageId))
]),
...agents.value.flatMap((agent) => agentCursor(agent, localAgentColor(store), pageId))
- ]
- store.requestRepaint()
+ ])
+ autoFollow(store)
+ keepFollowing(store)
+}
+
+/** An agent in a run: following it starts here and waits for its first cursor. */
+function isWorking(agent: AgentPresence): boolean {
+ return agent.status !== 'idle'
+}
+
+/**
+ * With Follow agents on, the view follows our agents while they work: whichever starts first
+ * when nobody is followed, and the next one at work once the followed agent rests. Following
+ * starts with the run, so leaving the page or moving the view while the agent thinks counts as
+ * stopping, and an agent the person stopped following is left alone until it rests.
+ */
+function autoFollow(store: EditorStore): void {
+ const presence = presenceOf(store)
+ const working = presence.agents.value.filter(isWorking)
+ for (const id of presence.declined) {
+ if (!working.some((agent) => agent.id === id)) presence.declined.delete(id)
+ }
+ if (!appPreferences.value.chat.followAgents) return
+ const target = presence.following.value
+ if (target?.kind === 'person') return
+ if (target && working.some((agent) => agent.id === target.agentId)) return
+ // A followed agent of someone else's is theirs to stop; only a resting one of ours hands over.
+ if (target && !presence.agents.value.some((agent) => agent.id === target.agentId)) return
+ const next = working.find((agent) => !presence.declined.has(agent.id))
+ if (!next) return
+ presence.following.value = { kind: 'agent', agentId: next.id }
+ presence.followPage = store.state.currentPageId
+}
+
+/** Starts following our agents at work right away, for when Follow agents is turned on. */
+export function followWorkingAgents(store: EditorStore): void {
+ autoFollow(store)
keepFollowing(store)
}
@@ -187,22 +239,35 @@ function keepFollowing(store: EditorStore): void {
})
return
}
- presence.moving = true
- try {
- store.centerOn(point.x, point.y, point.zoom)
- } finally {
- presence.moving = false
- }
+ glideViewTo(store, point, point.zoom ?? store.state.zoom, (x, y, zoom) => {
+ // Following ended while the view was on its way: leave it where the person left it.
+ if (!presence.following.value) return
+ presence.moving = true
+ try {
+ store.centerOn(x, y, zoom)
+ } finally {
+ presence.moving = false
+ }
+ })
}
/** A page change following did not make is yours, so it ends following, even of a resting agent. */
function stopIfLeftFollowedPage(store: EditorStore): void {
const presence = presenceOf(store)
if (presence.following.value && store.state.currentPageId !== presence.followPage) {
+ declineFollowed(presence)
presence.following.value = null
}
}
+/** The person stopped following an agent of ours at work: auto-follow leaves it until it rests. */
+function declineFollowed(presence: Presence): void {
+ const target = presence.following.value
+ if (target?.kind !== 'agent') return
+ const agent = presence.agents.value.find((entry) => entry.id === target.agentId)
+ if (agent && isWorking(agent)) presence.declined.add(agent.id)
+}
+
/** Who the view follows, for showing it: their name, an agent's owner, and the color. */
export interface FollowedLabel {
kind: FollowTarget['kind']
@@ -229,20 +294,22 @@ export function followedLabel(store: EditorStore): FollowedLabel | null {
return null
}
-/** Follow a person or an agent, or stop following with null. */
/** Stop following; a follow switch still loading is overtaken, so it does not land later. */
-function stopFollowing(store: EditorStore): void {
+function stopFollowing(store: EditorStore, byPerson: boolean): void {
const presence = presenceOf(store)
+ if (byPerson) declineFollowed(presence)
presence.following.value = null
+ stopViewGlide(store)
if (presence.switching) {
presence.switching = null
void store.switchPage(store.state.currentPageId)
}
}
+/** Follow a person or an agent, or stop following with null. */
export function follow(store: EditorStore, target: FollowTarget | null): void {
if (!target) {
- stopFollowing(store)
+ stopFollowing(store, true)
return
}
const presence = presenceOf(store)
@@ -315,3 +382,22 @@ export function addAgent(store: EditorStore, kind: AgentKind, model?: string): A
remove: () => replace(null)
}
}
+
+/**
+ * Where an agent shows it is working on `nodeIds`: its cursor at their top-left corner on
+ * `pageId`, and their outlines. Null when none of them is in the document.
+ */
+export function agentPlacement(
+ store: EditorStore,
+ nodeIds: readonly string[],
+ pageId: string
+): Pick<AgentPresence, 'cursor' | 'selection' | 'outline'> | null {
+ const present = nodeIds.filter((id) => store.graph.getNode(id))
+ const bounds = computeContentBounds(store.graph, present)
+ if (!bounds) return null
+ return {
+ cursor: { x: bounds.minX, y: bounds.minY, pageId },
+ selection: present,
+ outline: undefined
+ }
+}
diff --git a/src/app/presence/schema.ts b/src/app/presence/schema.ts
index 59836a12a..dba8bae35 100644
--- a/src/app/presence/schema.ts
+++ b/src/app/presence/schema.ts
@@ -8,6 +8,8 @@ import { AGENT_KINDS, AGENT_STATUSES } from './types'
/** Bounds on what a peer can publish, so a broken or hostile peer cannot flood rendering. */
export const MAX_AGENTS_PER_PEER = 16
const MAX_SELECTION = 256
+/** Outlines an agent draws around JSX it is still streaming. */
+export const MAX_OUTLINE = 32
export const MAX_NAME_LENGTH = 40
const MAX_ID = 64
@@ -25,6 +27,11 @@ const personPoint = v.object({
zoom: lenient(v.pipe(finite, v.minValue(0.02), v.maxValue(256)))
})
const selection = v.pipe(v.array(id), v.maxLength(MAX_SELECTION))
+const extent = v.pipe(finite, v.minValue(0))
+const outline = v.pipe(
+ v.array(v.object({ x: finite, y: finite, width: extent, height: extent })),
+ v.maxLength(MAX_OUTLINE)
+)
const agent = v.object({
id,
@@ -34,7 +41,8 @@ const agent = v.object({
status: v.picklist(AGENT_STATUSES),
pageId: lenient(id),
cursor: lenient(point),
- selection: lenient(selection)
+ selection: lenient(selection),
+ outline: lenient(outline)
})
const peerState = v.object({
diff --git a/src/app/presence/types.ts b/src/app/presence/types.ts
index 6040e9c73..dab183938 100644
--- a/src/app/presence/types.ts
+++ b/src/app/presence/types.ts
@@ -1,3 +1,5 @@
+import type { Rect } from '@open-pencil/scene-graph/primitives'
+
export const AGENT_KINDS = ['chat', 'acp', 'harness', 'mcp'] as const
export type AgentKind = (typeof AGENT_KINDS)[number]
@@ -31,4 +33,6 @@ export interface AgentPresence {
/** Where the agent last worked, derived from the nodes it touched. */
cursor?: PresencePoint
selection?: string[]
+ /** Outlines, in world coordinates on the cursor's page, of what is not a layer yet. */
+ outline?: Rect[]
}
diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.ts
index a64cd45dd..7199ce1b4 100644
--- a/src/app/settings/preferences/store.ts
+++ b/src/app/settings/preferences/store.ts
@@ -40,6 +40,8 @@ export interface AppPreferences {
reasoningDisplay: ReasoningDisplay
maxAgentSteps: number
changePreviewSize: ChangePreviewSize
+ /** Whether the view follows our AI agents while they work. */
+ followAgents: boolean
}
version: 1
recovery: {
@@ -62,7 +64,8 @@ export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {
chat: {
reasoningDisplay: 'collapsed',
maxAgentSteps: DEFAULT_AGENT_STEPS,
- changePreviewSize: 'medium'
+ changePreviewSize: 'medium',
+ followAgents: true
},
version: 1,
recovery: { enabled: true },
@@ -96,7 +99,11 @@ const appPreferencesSchema = section({
v.pipe(v.unknown(), v.transform(resolveAgentStepLimit)),
defaults.chat.maxAgentSteps
),
- changePreviewSize: v.fallback(v.picklist(CHANGE_PREVIEW_SIZES), defaults.chat.changePreviewSize)
+ changePreviewSize: v.fallback(
+ v.picklist(CHANGE_PREVIEW_SIZES),
+ defaults.chat.changePreviewSize
+ ),
+ followAgents: v.fallback(v.boolean(), defaults.chat.followAgents)
}),
version: v.fallback(v.literal(1), 1),
recovery: section({ enabled: v.fallback(v.boolean(), defaults.recovery.enabled) }),
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index fe8525df5..db3f9ff21 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -22,6 +22,7 @@ import ChatHistory from '@/components/chat/ChatHistory.vue'
import ChatInput from '@/components/chat/ChatInput.vue'
import ChatRunLocation from '@/components/chat/ChatRunLocation.vue'
import ChatTranscript from '@/components/chat/ChatTranscript.vue'
+import FollowAgentsToggle from '@/components/chat/FollowAgentsToggle.vue'
import ProviderSetup from '@/components/chat/ProviderSetup.vue'
const { isConfigured, ensureChat, history, chatFailure, clearChatFailure } = useAIChat()
@@ -197,7 +198,9 @@ function handleStop() {
@select="historyAction(() => history.open($event))"
@rename="renameConversation"
@delete="historyAction(() => history.remove($event))"
- />
+ >
+ <template #actions><FollowAgentsToggle /></template>
+ </ChatHistory>
<p v-if="history.storageError.value" role="alert" class="px-3 py-2 text-xs text-red-400">
{{ ai.chatStorageFailed }}
</p>
diff --git a/src/components/chat/ChatHistory.vue b/src/components/chat/ChatHistory.vue
index 25fed0c01..acd79a207 100644
--- a/src/components/chat/ChatHistory.vue
+++ b/src/components/chat/ChatHistory.vue
@@ -160,6 +160,7 @@ function closeMenu(event: Event) {
</PopoverContent>
</PopoverPortal>
</PopoverRoot>
+ <slot name="actions" />
<IconButton :label="ai.newChat" :disabled="disabled" size="sm" @click="emit('create')"
><icon-lucide-plus :class="styles.icon()"
/></IconButton>
diff --git a/src/components/chat/FollowAgentsToggle.vue b/src/components/chat/FollowAgentsToggle.vue
new file mode 100644
index 000000000..bfbaa3ac0
--- /dev/null
+++ b/src/components/chat/FollowAgentsToggle.vue
@@ -0,0 +1,30 @@
+<script setup lang="ts">
+import { useAIMessages } from '@open-pencil/vue'
+
+import { useActiveEditorStoreRef } from '@/app/editor/active-store'
+import { followWorkingAgents } from '@/app/presence/registry'
+import { appPreferences } from '@/app/settings/preferences/store'
+import IconButton from '@/components/ui/button/IconButton.vue'
+
+/** Whether the view follows our AI agents while they work, from the chat's header. */
+const ai = useAIMessages()
+const tabStore = useActiveEditorStoreRef()
+
+function toggle() {
+ const on = !appPreferences.value.chat.followAgents
+ appPreferences.value.chat.followAgents = on
+ if (on && tabStore.value) followWorkingAgents(tabStore.value)
+}
+</script>
+
+<template>
+ <IconButton
+ :label="appPreferences.chat.followAgents ? ai.stopFollowingAgents : ai.followAgents"
+ :active="appPreferences.chat.followAgents"
+ size="sm"
+ data-test-id="chat-follow-agents"
+ @click="toggle"
+ >
+ <icon-lucide-locate-fixed class="size-3.5" />
+ </IconButton>
+</template>
diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vue
index f807c1cec..3c13173d8 100644
--- a/src/views/WorkspaceView.vue
+++ b/src/views/WorkspaceView.vue
@@ -7,6 +7,7 @@ import { useRoute, useRouter } from 'vue-router'
import { useI18n } from '@open-pencil/vue'
import { offerAISetupOnFirstRun } from '@/app/ai/models/settings/onboarding/dialog'
+import { exposeAutomationTestRequests } from '@/app/automation/bridge/test-hooks'
import { startMCPRuntime, stopMCPRuntime } from '@/app/automation/mcp/runtime'
import { startWebMCP } from '@/app/automation/webmcp/runtime'
import { exposeCollaborationActions } from '@/app/browser-bridge'
@@ -87,6 +88,7 @@ useDocumentDrop()
const collab = useCollab()
provide(COLLAB_KEY, collab)
exposeCollaborationActions(collab, joinRoomFromInput)
+exposeAutomationTestRequests()
syncRoomRoute(router, route)
useEventListener(
diff --git a/tests/app/ai/preview/canvas.test.ts b/tests/app/ai/preview/canvas.test.ts
new file mode 100644
index 000000000..111e94a34
--- /dev/null
+++ b/tests/app/ai/preview/canvas.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { previewFocus } from '@/app/ai/preview/canvas'
+import { MAX_OUTLINE } from '@/app/presence/schema'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+function page(graph: SceneGraph) {
+ return expectDefined(graph.getPages()[0], 'page').id
+}
+
+describe('streamed JSX focus', () => {
+ test('points at the element that appeared last and outlines what the JSX builds', () => {
+ const graph = new SceneGraph()
+ const card = graph.createNode('FRAME', page(graph), { x: 100, y: 50, width: 300, height: 200 })
+ graph.createNode('TEXT', card.id, { x: 16, y: 16, width: 100, height: 20 })
+ const footer = graph.createNode('FRAME', card.id, { x: 16, y: 120, width: 268, height: 60 })
+ const button = graph.createNode('RECTANGLE', footer.id, { x: 8, y: 8, width: 80, height: 32 })
+
+ const focus = expectDefined(previewFocus({ graph, renderedIds: [card.id] }), 'focus')
+ // The source's last element: the button, the last child of the card's last child. The
+ // cursor sits at its trailing corner, where content grows.
+ expect(focus.cursor).toEqual({ x: 204, y: 210 })
+ expect(focus.outline).toEqual([
+ { x: 100, y: 50, width: 300, height: 200 },
+ { x: 124, y: 178, width: 80, height: 32 }
+ ])
+ expect(button.id).toBeString()
+ })
+
+ test('a lone element is both the cursor and the outline, and outlines stay bounded', () => {
+ const graph = new SceneGraph()
+ const roots = Array.from({ length: MAX_OUTLINE + 4 }, (_, index) =>
+ graph.createNode('RECTANGLE', page(graph), { x: index * 10, y: 0, width: 8, height: 8 })
+ )
+ const focus = expectDefined(
+ previewFocus({ graph, renderedIds: roots.map((root) => root.id) }),
+ 'focus'
+ )
+ expect(focus.cursor).toEqual({ x: (MAX_OUTLINE + 3) * 10 + 8, y: 8 })
+ expect(focus.outline).toHaveLength(MAX_OUTLINE)
+ })
+
+ test('nothing rendered yet has no focus', () => {
+ expect(previewFocus({ graph: new SceneGraph(), renderedIds: [] })).toBeNull()
+ })
+})
diff --git a/tests/app/ai/tools/run.test.ts b/tests/app/ai/tools/run.test.ts
index 8d8c93cda..42468328d 100644
--- a/tests/app/ai/tools/run.test.ts
+++ b/tests/app/ai/tools/run.test.ts
@@ -8,13 +8,15 @@ import { toRaw } from 'vue'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { createToolLoopTransport } from '@/app/ai/chat/transports'
-import { runPageId } from '@/app/ai/tools'
+import { endRun, markRunPreview, runPageId, startRun } from '@/app/ai/tools'
import { aiToolOverrides } from '@/app/ai/tools/preferences'
+import { markRunWork } from '@/app/ai/tools/run'
import * as figmaFactory from '@/app/automation/bridge/figma-factory'
import { createEditorStore } from '@/app/editor/session/create'
import { presenceOf } from '@/app/presence/registry'
import { appPreferences } from '@/app/settings/preferences/store'
+import { expectDefined } from '#tests/helpers/assert'
import { MOCK_USAGE } from '#tests/helpers/chat/usage'
type EditorStore = ReturnType<typeof createEditorStore>
@@ -174,3 +176,33 @@ test("shows the chat's agent where its tools work, then takes it off the canvas"
])
})
})
+
+test('the agent moves through streamed JSX, then onto the layers the tool made', () => {
+ const store = createEditorStore()
+ try {
+ startRun(store, 10)
+ markRunPreview(store, {
+ cursor: { x: 40, y: 60 },
+ outline: [{ x: 40, y: 60, width: 100, height: 20 }]
+ })
+ const agent = () => expectDefined(presenceOf(store).agents.value[0], 'agent')
+ expect(agent()).toMatchObject({
+ status: 'editing',
+ cursor: { x: 40, y: 60, pageId: store.state.currentPageId },
+ outline: [{ x: 40, y: 60, width: 100, height: 20 }]
+ })
+
+ const made = store.graph.createNode('RECTANGLE', store.state.currentPageId, {
+ x: 10,
+ y: 20,
+ width: 30,
+ height: 30
+ })
+ markRunWork(store, [made.id])
+ expect(agent()).toMatchObject({ selection: [made.id], outline: undefined })
+ endRun(store)
+ expect(agent()).toMatchObject({ status: 'idle', outline: undefined })
+ } finally {
+ store.preparationController.dispose()
+ }
+})
diff --git a/tests/app/automation/agents.test.ts b/tests/app/automation/agents.test.ts
new file mode 100644
index 000000000..6992f64c3
--- /dev/null
+++ b/tests/app/automation/agents.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, beforeEach, describe, expect, jest, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import {
+ MCP_AGENT_GONE_MS,
+ MCP_AGENT_IDLE_MS,
+ agentFinished,
+ agentStarted,
+ endAgentSession,
+ readAgentSession,
+ touchedNodeIds,
+ type AgentSession
+} from '@/app/automation/agents'
+import { createEditorStore, type EditorStore } from '@/app/editor/session'
+import { presenceOf } from '@/app/presence/registry'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const claude: AgentSession = { session: 'session-1', kind: 'mcp', client: 'claude-code' }
+
+let store: EditorStore
+
+beforeEach(() => {
+ jest.useFakeTimers()
+ store = createEditorStore(new SceneGraph())
+})
+
+afterEach(() => {
+ endAgentSession(claude.session)
+ store.preparationController.dispose()
+ jest.useRealTimers()
+})
+
+function pageId() {
+ return expectDefined(store.graph.getPages()[0], 'page').id
+}
+
+function agents() {
+ return presenceOf(store).agents.value
+}
+
+describe('MCP sessions as agents', () => {
+ test('a session shows as one agent, named by its client, while its tools run', () => {
+ agentStarted(store, claude, pageId())
+ agentStarted(store, claude, pageId())
+ expect(agents()).toHaveLength(1)
+ expect(agents()[0]).toMatchObject({ kind: 'mcp', model: 'claude-code', status: 'thinking' })
+ })
+
+ test('the agent points at what a call reads and what it edits', () => {
+ const card = store.graph.createNode('FRAME', pageId(), { x: 40, y: 60, width: 100, height: 80 })
+ agentStarted(store, claude, pageId())
+ agentFinished(store, claude, {
+ pageId: pageId(),
+ nodeIds: touchedNodeIds(store, { id: card.id }, { name: 'Card' }),
+ edited: false
+ })
+ expect(agents()[0]).toMatchObject({
+ status: 'thinking',
+ cursor: { x: 40, y: 60, pageId: pageId() },
+ selection: [card.id]
+ })
+
+ const made = store.graph.createNode('RECTANGLE', pageId(), { x: 200, y: 10 })
+ agentFinished(store, claude, {
+ pageId: pageId(),
+ nodeIds: touchedNodeIds(store, {}, { results: [{ id: made.id }] }),
+ edited: true
+ })
+ expect(agents()[0]).toMatchObject({ status: 'editing', selection: [made.id] })
+ })
+
+ test('the agent works on the page of the layers it touched', () => {
+ const other = store.graph.addPage('Other')
+ const node = store.graph.createNode('RECTANGLE', other.id, {})
+ agentFinished(store, claude, { pageId: pageId(), nodeIds: [node.id], edited: true })
+ expect(agents()[0]).toMatchObject({ pageId: other.id, cursor: { pageId: other.id } })
+ })
+
+ test('pages and the document are not layers a call works on', () => {
+ const node = store.graph.createNode('RECTANGLE', pageId(), {})
+ expect(
+ touchedNodeIds(store, { ids: [pageId(), store.graph.rootId, node.id, 'missing'] }, null)
+ ).toEqual([node.id])
+ })
+
+ test('a quiet session rests, and one that never says goodbye leaves', () => {
+ agentStarted(store, claude, pageId())
+ jest.advanceTimersByTime(MCP_AGENT_IDLE_MS)
+ expect(agents()[0]).toMatchObject({ status: 'idle', cursor: undefined })
+ jest.advanceTimersByTime(MCP_AGENT_GONE_MS)
+ expect(agents()).toEqual([])
+ })
+
+ test('a session that ends takes its agents out of every document', () => {
+ const second = createEditorStore(new SceneGraph())
+ try {
+ agentStarted(store, claude, pageId())
+ agentStarted(second, claude, expectDefined(second.graph.getPages()[0], 'page').id)
+ endAgentSession(claude.session)
+ expect(agents()).toEqual([])
+ expect(presenceOf(second).agents.value).toEqual([])
+ } finally {
+ second.preparationController.dispose()
+ }
+ })
+
+ test('ACP and harness chats show as their own kinds, and a forwarded session is validated', () => {
+ expect(readAgentSession({ session: 'a', kind: 'acp' })).toMatchObject({ kind: 'acp' })
+ expect(readAgentSession({ session: 'a', kind: 'harness', client: 'pi' })).toMatchObject({
+ kind: 'harness',
+ client: 'pi'
+ })
+ expect(readAgentSession({ session: '', kind: 'mcp' })).toBeNull()
+ expect(readAgentSession({ session: 'a', kind: 'chat' })).toBeNull()
+ expect(readAgentSession(undefined)).toBeNull()
+ })
+})
diff --git a/tests/app/automation/bridge/server.test.ts b/tests/app/automation/bridge/server.test.ts
new file mode 100644
index 000000000..b3163c8e6
--- /dev/null
+++ b/tests/app/automation/bridge/server.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { agentStarted, endAgentSession, type AgentSession } from '@/app/automation/agents'
+import { connectAutomation } from '@/app/automation/bridge/server'
+import { createEditorStore, type EditorStore } from '@/app/editor/session'
+import { presenceOf } from '@/app/presence/registry'
+
+import { expectDefined } from '#tests/helpers/assert'
+import { asDouble } from '#tests/helpers/doubles'
+
+const claude: AgentSession = { session: 'bridge-session', kind: 'mcp', client: 'claude-code' }
+
+/** A browser socket: closing it reports the close later, as the WebSocket close handshake does. */
+class FakeSocket {
+ static readonly OPEN = 1
+ static opened: FakeSocket[] = []
+ readyState = FakeSocket.OPEN
+ onopen: (() => void) | null = null
+ onmessage: ((event: { data: string }) => Promise<void>) | null = null
+ onclose: ((event: { code: number; reason: string }) => void) | null = null
+ onerror: ((event: unknown) => void) | null = null
+ readonly sent: string[] = []
+
+ constructor() {
+ FakeSocket.opened.push(this)
+ }
+
+ send(data: string) {
+ this.sent.push(data)
+ }
+
+ close() {
+ this.readyState = 2
+ }
+
+ /** Reports the close the bridge asked for. */
+ closed() {
+ this.readyState = 3
+ this.onclose?.({ code: 1000, reason: '' })
+ }
+
+ /** Delivers a tool call from the agent's MCP session. */
+ async request(id: string) {
+ await this.onmessage?.({
+ data: JSON.stringify({ type: 'request', id, command: 'unknown', args: { agent: claude } })
+ })
+ }
+}
+
+const RealWebSocket = globalThis.WebSocket
+let store: EditorStore
+
+beforeEach(() => {
+ FakeSocket.opened = []
+ globalThis.WebSocket = asDouble<typeof WebSocket>(FakeSocket)
+ store = createEditorStore(new SceneGraph())
+})
+
+afterEach(() => {
+ endAgentSession(claude.session)
+ store.preparationController.dispose()
+ globalThis.WebSocket = RealWebSocket
+})
+
+function agents() {
+ return presenceOf(store).agents.value
+}
+
+function openBridge() {
+ const bridge = connectAutomation(() => store, 'token', 'ws://automation.test')
+ return { bridge, socket: expectDefined(FakeSocket.opened.at(-1), 'socket') }
+}
+
+describe('automation bridge sessions', () => {
+ test('restarting MCP keeps the agent of a session the new connection carries', async () => {
+ agentStarted(store, claude, expectDefined(store.graph.getPages()[0], 'page').id)
+ const old = openBridge()
+ await old.socket.request('1')
+
+ old.bridge.disconnect()
+ const restarted = openBridge()
+ await restarted.socket.request('2')
+ old.socket.closed()
+ expect(agents()).toHaveLength(1)
+
+ restarted.bridge.disconnect()
+ restarted.socket.closed()
+ expect(agents()).toHaveLength(0)
+ })
+
+ test('a session that only an old connection carried ends with it', async () => {
+ agentStarted(store, claude, expectDefined(store.graph.getPages()[0], 'page').id)
+ const old = openBridge()
+ await old.socket.request('1')
+
+ old.bridge.disconnect()
+ openBridge()
+ old.socket.closed()
+ expect(agents()).toHaveLength(0)
+ })
+})
diff --git a/tests/app/presence/auto-follow.test.ts b/tests/app/presence/auto-follow.test.ts
new file mode 100644
index 000000000..1076c6434
--- /dev/null
+++ b/tests/app/presence/auto-follow.test.ts
@@ -0,0 +1,86 @@
+import 'fake-indexeddb/auto'
+import { afterEach, expect, test } from 'bun:test'
+
+import { createEditorStore } from '@/app/editor/session/create'
+import {
+ addAgent,
+ follow,
+ followWorkingAgents,
+ presenceOf,
+ setPeers
+} from '@/app/presence/registry'
+import { appPreferences } from '@/app/settings/preferences/store'
+
+const stores: ReturnType<typeof createEditorStore>[] = []
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose()
+ appPreferences.value.chat.followAgents = true
+})
+
+function setup() {
+ const store = createEditorStore()
+ stores.push(store)
+ return { store, pageId: store.state.currentPageId }
+}
+
+const following = (store: ReturnType<typeof createEditorStore>) => presenceOf(store).following.value
+
+test('with Follow agents on, the view follows an agent from the start of its run', () => {
+ const { store, pageId } = setup()
+ const agent = addAgent(store, 'mcp')
+ expect(following(store)).toBeNull()
+ agent.update({ status: 'thinking', pageId })
+ expect(following(store)).toEqual({ kind: 'agent', agentId: agent.id })
+})
+
+test('an agent the person stopped following is left alone until it rests', () => {
+ const { store, pageId } = setup()
+ const agent = addAgent(store, 'chat')
+ agent.update({ status: 'editing', cursor: { x: 10, y: 10, pageId } })
+ follow(store, null)
+ agent.update({ cursor: { x: 40, y: 40, pageId } })
+ expect(following(store)).toBeNull()
+
+ agent.update({ status: 'idle', cursor: undefined })
+ agent.update({ status: 'thinking' })
+ expect(following(store)).toEqual({ kind: 'agent', agentId: agent.id })
+})
+
+test('when the followed agent rests, the view moves on to one still at work', () => {
+ const { store, pageId } = setup()
+ const first = addAgent(store, 'chat')
+ const second = addAgent(store, 'mcp')
+ first.update({ status: 'editing', cursor: { x: 10, y: 10, pageId } })
+ second.update({ status: 'editing', cursor: { x: 90, y: 90, pageId } })
+ expect(following(store)).toEqual({ kind: 'agent', agentId: first.id })
+ first.update({ status: 'idle', cursor: undefined })
+ expect(following(store)).toEqual({ kind: 'agent', agentId: second.id })
+})
+
+test('following a person is never taken over by an agent', () => {
+ const { store, pageId } = setup()
+ setPeers(store, [
+ {
+ clientId: 7,
+ name: 'Ana',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ agents: [],
+ cursor: { x: 0, y: 0, pageId }
+ }
+ ])
+ follow(store, { kind: 'person', clientId: 7 })
+ addAgent(store, 'chat').update({ status: 'editing', cursor: { x: 5, y: 5, pageId } })
+ expect(following(store)).toEqual({ kind: 'person', clientId: 7 })
+})
+
+test('with Follow agents off, agents are followed only by clicking Follow', () => {
+ const { store, pageId } = setup()
+ appPreferences.value.chat.followAgents = false
+ const agent = addAgent(store, 'chat')
+ agent.update({ status: 'editing', cursor: { x: 10, y: 10, pageId } })
+ expect(following(store)).toBeNull()
+
+ appPreferences.value.chat.followAgents = true
+ followWorkingAgents(store)
+ expect(following(store)).toEqual({ kind: 'agent', agentId: agent.id })
+})
diff --git a/tests/app/presence/motion.test.ts b/tests/app/presence/motion.test.ts
new file mode 100644
index 000000000..9b96bc574
--- /dev/null
+++ b/tests/app/presence/motion.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'bun:test'
+
+import { easeOutCubic, glideAt, retarget, type Glide } from '@/app/presence/motion'
+
+describe('cursor glides', () => {
+ test('ease out starts fast, ends at rest, and clamps outside its range', () => {
+ expect(easeOutCubic(0)).toBe(0)
+ expect(easeOutCubic(1)).toBe(1)
+ expect(easeOutCubic(0.5)).toBeGreaterThan(0.5)
+ expect(easeOutCubic(-1)).toBe(0)
+ expect(easeOutCubic(2)).toBe(1)
+ })
+
+ test('a glide moves between its points and arrives on time', () => {
+ const glide: Glide = { from: { x: 0, y: 0 }, to: { x: 100, y: 50 }, start: 1000, duration: 200 }
+ expect(glideAt(glide, 1000)).toEqual({ point: { x: 0, y: 0 }, done: false })
+ const half = glideAt(glide, 1100)
+ expect(half.done).toBe(false)
+ expect(half.point.x).toBeCloseTo(87.5)
+ expect(half.point.y).toBeCloseTo(43.75)
+ expect(glideAt(glide, 1200)).toEqual({ point: { x: 100, y: 50 }, done: true })
+ })
+
+ test('a new cursor appears in place, and a moved one glides on from where it is now', () => {
+ const first = retarget(undefined, { x: 10, y: 10 }, 0, 200)
+ expect(glideAt(first, 0)).toEqual({ point: { x: 10, y: 10 }, done: true })
+
+ const moving = retarget(first, { x: 110, y: 10 }, 0, 200)
+ const midway = glideAt(moving, 100).point
+ const redirected = retarget(moving, { x: 110, y: 210 }, 100, 200)
+ // It turns from where it is drawn, never jumping back to where it started.
+ expect(redirected.from).toEqual(midway)
+ expect(retarget(redirected, { x: 110, y: 210 }, 150, 200)).toBe(redirected)
+ })
+})
diff --git a/tests/app/presence/registry.test.ts b/tests/app/presence/registry.test.ts
index 12240028f..d241fcd5b 100644
--- a/tests/app/presence/registry.test.ts
+++ b/tests/app/presence/registry.test.ts
@@ -34,7 +34,16 @@ test('draws active agents on their page, in their owner color', () => {
there.update({ status: 'editing', cursor: { x: 1, y: 1, pageId: other } })
setOwnerColor(store, red)
expect(store.state.presenceCursors).toEqual([
- { kind: 'agent', name: here.name, color: red, x: 5, y: 6, selection: undefined }
+ {
+ id: `agent:${here.id}`,
+ kind: 'agent',
+ name: here.name,
+ color: red,
+ x: 5,
+ y: 6,
+ selection: undefined,
+ outline: undefined
+ }
])
})
@@ -283,3 +292,14 @@ test('keeps people with the same name apart on a page', () => {
?.map((entry) => entry.id)
).toEqual(['person:4', 'person:5'])
})
+
+test('without animation frames, cursors and following move at once', () => {
+ const { store, pageId } = setup()
+ const agent = addAgent(store, 'chat')
+ agent.update({ status: 'editing', cursor: { x: 5, y: 6, pageId } })
+ agent.update({ status: 'editing', cursor: { x: 50, y: 60, pageId } })
+ expect(store.state.presenceCursors.map(({ x, y }) => ({ x, y }))).toEqual([{ x: 50, y: 60 }])
+
+ follow(store, { kind: 'agent', agentId: agent.id })
+ expect(centered(store)).toEqual({ x: 50, y: 60 })
+})
diff --git a/tests/app/presence/schema.test.ts b/tests/app/presence/schema.test.ts
index 966051848..dadaa598d 100644
--- a/tests/app/presence/schema.test.ts
+++ b/tests/app/presence/schema.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { MAX_AGENTS_PER_PEER, parsePeer } from '@/app/presence/schema'
+import { MAX_AGENTS_PER_PEER, MAX_OUTLINE, parsePeer } from '@/app/presence/schema'
const user = { name: 'Ana', color: { r: 1, g: 0, b: 0, a: 1 } }
const agent = {
@@ -55,4 +55,19 @@ describe('parsePeer', () => {
})
expect(parsePeer(7, { user })?.treeFormat).toBeUndefined()
})
+
+ test("reads an agent's outlines of streamed JSX, and drops malformed or too many", () => {
+ const outline = [{ x: 0, y: 10, width: 120, height: 40 }]
+ expect(parsePeer(7, { user, agents: [{ ...agent, outline }] })?.agents[0]?.outline).toEqual(
+ outline
+ )
+ const negative = [{ x: 0, y: 0, width: -5, height: 10 }]
+ expect(
+ parsePeer(7, { user, agents: [{ ...agent, outline: negative }] })?.agents[0]?.outline
+ ).toBeUndefined()
+ const tooMany = Array.from({ length: MAX_OUTLINE + 1 }, () => outline[0])
+ expect(
+ parsePeer(7, { user, agents: [{ ...agent, outline: tooMany }] })?.agents[0]
+ ).toMatchObject({ name: 'Fern', outline: undefined })
+ })
})
diff --git a/tests/e2e/chat/streaming/jsx.spec.ts b/tests/e2e/chat/streaming/jsx.spec.ts
index b7dfeaacb..546f0444a 100644
--- a/tests/e2e/chat/streaming/jsx.spec.ts
+++ b/tests/e2e/chat/streaming/jsx.spec.ts
@@ -176,3 +176,48 @@ for (const outcome of ['cancel', 'error', 'disconnect'] as const) {
}
})
}
+
+test("the chat's agent moves through the streamed elements and outlines them", async ({
+ configuredChat: chat
+}) => {
+ await setupCanvas(chat.page)
+ const stream = await installRenderStream(chat.page, scenario)
+ const agentCursor = () =>
+ chat.page.evaluate(() => {
+ const cursor = window.openPencil
+ ?.getStore?.()
+ .state.presenceCursors.find((entry) => entry.kind === 'agent')
+ return cursor
+ ? {
+ x: cursor.x,
+ y: cursor.y,
+ outlines: cursor.outline?.length ?? 0,
+ selection: cursor.selection
+ }
+ : null
+ })
+ try {
+ await chat.submit('Render a card')
+ await expect.poll(() => stream.evaluate((s) => s.ready())).toBe(true)
+ await stream.evaluate((s) => s.advance())
+ await expect.poll(() => previewKey(chat.page)).not.toBe('')
+ // The text streams first: the cursor sits at its trailing corner, inside the outlined card,
+ // so the agent's name does not cover the text being written.
+ await expect.poll(agentCursor).toMatchObject({ outlines: 2 })
+ const onText = await agentCursor()
+ expect(onText?.x).toBeGreaterThan(100)
+ expect(onText?.y).toBeGreaterThan(100)
+
+ await stream.evaluate((s) => s.advance())
+ // The last element to appear is the button bar below the text.
+ await expect.poll(async () => (await agentCursor())?.y).toBeGreaterThan(130)
+
+ await stream.evaluate((s) => s.complete())
+ await expect(chat.assistantMessage()).toContainText('Rendered.')
+ // Once the tool ran, the agent outlines the real layer instead of the preview.
+ await expect.poll(async () => (await agentCursor())?.outlines ?? 0).toBe(0)
+ } finally {
+ await stream.evaluate((s) => s.dispose())
+ await stream.dispose()
+ }
+})
diff --git a/tests/e2e/collab/agents.spec.ts b/tests/e2e/collab/agents.spec.ts
index 440634c49..ca19ee412 100644
--- a/tests/e2e/collab/agents.spec.ts
+++ b/tests/e2e/collab/agents.spec.ts
@@ -68,3 +68,76 @@ test("a guest's agent shows on their avatar and can be followed until Escape", a
await relay.close()
}
})
+
+test('an MCP session shows as an agent at the layers it touches, to collaborators too', async ({
+ browser
+}) => {
+ // Two peers in a room, a tool call, and following it, stopping, and following again.
+ 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)
+ const nodeId = await host.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ return store.graph.createNode('FRAME', store.state.currentPageId, {
+ name: 'Card',
+ x: 240,
+ y: 160,
+ width: 200,
+ height: 120
+ }).id
+ })
+
+ // A tool call as the MCP bridge delivers it, from a session of an outside client.
+ await host.page.evaluate(
+ (id) =>
+ window.openPencil?.test?.automation?.('tool', {
+ name: 'rename_node',
+ args: { id, name: 'Checkout card' },
+ agent: { session: 'session-1', kind: 'mcp', client: 'claude-code' }
+ }),
+ nodeId
+ )
+ const agent = await host.page.evaluate(() => {
+ const cursor = window.openPencil
+ ?.getStore?.()
+ .state.presenceCursors.find((entry) => entry.kind === 'agent')
+ return cursor ? { name: cursor.name, x: cursor.x, y: cursor.y } : null
+ })
+ expect(agent).toMatchObject({ x: 240, y: 160 })
+ const name = agent?.name ?? ''
+
+ // With Follow agents on, as by default, its owner's view follows it as soon as it works.
+ const frame = host.page.getByTestId('follow-frame')
+ await expect(frame).toContainText(`Following ${name}`)
+ await frame.getByRole('button', { name: 'Stop following' }).click()
+ await expect(frame).toHaveCount(0)
+
+ // Its owner lists it on their avatar and can follow it again like any agent.
+ await host.page.getByTestId('collab-local-avatar').click()
+ const menu = host.page.getByTestId('collab-self-menu')
+ await expect(menu.getByText(name)).toBeVisible()
+ await menu.getByRole('button', { name: `Follow ${name}` }).click()
+ await expect(frame).toContainText(`Following ${name}`)
+
+ // Collaborators see it on its owner's avatar.
+ await expect(guest.page.getByTestId('collab-peer-avatar')).toContainText('1')
+
+ // When the session ends, the agent leaves.
+ await host.page.evaluate(() =>
+ window.openPencil?.test?.automation?.('agent_session_closed', { session: 'session-1' })
+ )
+ await expect(frame).toHaveCount(0)
+ expect(collaborationErrors(host)).toEqual([])
+ } finally {
+ await host?.context.close()
+ await guest?.context.close()
+ await relay.close()
+ }
+})
diff --git a/tests/engine/app/integrations/mcp-connections.test.ts b/tests/engine/app/integrations/mcp-connections.test.ts
index b5d4d85ac..dfd69348a 100644
--- a/tests/engine/app/integrations/mcp-connections.test.ts
+++ b/tests/engine/app/integrations/mcp-connections.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'bun:test'
+import { MCP_AGENT_HEADER } from '@open-pencil/core/constants'
+
import {
buildACPMCPServers,
createMCPConnectionDraft,
@@ -148,7 +150,10 @@ describe('MCP connections', () => {
type: 'http',
name: 'open-pencil',
url: expect.stringContaining('/mcp'),
- headers: [{ name: 'Authorization', value: 'Bearer built-in-token' }]
+ headers: [
+ { name: MCP_AGENT_HEADER, value: 'acp' },
+ { name: 'Authorization', value: 'Bearer built-in-token' }
+ ]
},
{
type: 'http',
@@ -189,7 +194,10 @@ describe('MCP connections', () => {
type: 'http',
name: 'open-pencil',
url: expect.stringContaining('/mcp'),
- headers: [{ name: 'Authorization', value: 'Bearer built-in-token' }]
+ headers: [
+ { name: MCP_AGENT_HEADER, value: 'acp' },
+ { name: 'Authorization', value: 'Bearer built-in-token' }
+ ]
},
{
type: 'http',
diff --git a/tests/engine/app/integrations/pi-mcp.test.ts b/tests/engine/app/integrations/pi-mcp.test.ts
index 0840496f1..ce4b61679 100644
--- a/tests/engine/app/integrations/pi-mcp.test.ts
+++ b/tests/engine/app/integrations/pi-mcp.test.ts
@@ -1,5 +1,7 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+import { MCP_AGENT_HEADER } from '@open-pencil/core/constants'
+
import { replaceMCPConnectionSettings, setMCPConnectionCredential } from '@/app/integrations/mcp'
import { buildPiMCPServers } from '@/app/integrations/mcp/pi'
@@ -39,7 +41,7 @@ describe('Pi MCP configuration', () => {
})
expect(servers['open-pencil']).toEqual({
url: expect.stringContaining('/mcp'),
- headers: { Authorization: 'Bearer built-in-token' },
+ headers: { [MCP_AGENT_HEADER]: 'harness', Authorization: 'Bearer built-in-token' },
auth: false
})
})
diff --git a/tests/engine/mcp/server/index.test.ts b/tests/engine/mcp/server/index.test.ts
index 18c242248..1b4b6fe51 100644
--- a/tests/engine/mcp/server/index.test.ts
+++ b/tests/engine/mcp/server/index.test.ts
@@ -7,6 +7,7 @@ import { join } from 'node:path'
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
+import { MCP_AGENT_HEADER } from '@open-pencil/core/constants'
import { SceneGraph } from '@open-pencil/scene-graph'
import { startServer, type ServerHandle } from '#mcp/server'
@@ -703,3 +704,70 @@ describe('MCP server concurrent startServer', () => {
}
}, 15000)
})
+
+describe('MCP sessions as agents', () => {
+ async function withAgentClient(
+ headers: Record<string, string>,
+ run: (
+ client: Client,
+ browser: MockBrowser,
+ transport: StreamableHTTPClientTransport
+ ) => Promise<void>
+ ) {
+ if (isUnix) await mkdir(SOCKET_DIR, { recursive: true })
+ const handle = await startServer({
+ httpPort: 0,
+ withTcp: true,
+ socketPath: testSocketPath(),
+ authToken: TEST_CLIENT_AUTH_TOKEN,
+ enableEval: false,
+ mcpRoot: null
+ })
+ const httpPort = expectDefined(handle.httpPort, 'TCP port')
+ const browser = await connectMockBrowser(httpPort, new SceneGraph(), TEST_CLIENT_AUTH_TOKEN)
+ try {
+ await waitForBrowserRegistration(httpPort)
+ const client = new Client({ name: 'test-client', version: '0.0.0' })
+ const transport = new StreamableHTTPClientTransport(
+ new URL(`http://127.0.0.1:${httpPort}/mcp`),
+ {
+ requestInit: {
+ headers: { Authorization: `Bearer ${TEST_CLIENT_AUTH_TOKEN}`, ...headers }
+ }
+ }
+ )
+ await client.connect(transport)
+ await run(client, browser, transport)
+ } finally {
+ browser.close()
+ await handle.close()
+ }
+ }
+
+ function agentOf(browser: MockBrowser): unknown {
+ const request = browser.requests.find((item) => item.command === 'tool')
+ return (request?.args as { agent?: unknown } | undefined)?.agent
+ }
+
+ test('a tool call names its session and client, so the app can show it as an agent', async () => {
+ await withAgentClient({}, async (client, browser) => {
+ await client.callTool({ name: 'get_page_tree', arguments: {} })
+ expect(agentOf(browser)).toMatchObject({ kind: 'mcp', client: 'test-client' })
+ expect((agentOf(browser) as { session: unknown }).session).toBeString()
+ })
+ })
+
+ test("the app's ACP chat marks its session, and closing the session tells the app", async () => {
+ await withAgentClient({ [MCP_AGENT_HEADER]: 'acp' }, async (client, browser, transport) => {
+ await client.callTool({ name: 'get_page_tree', arguments: {} })
+ const agent = agentOf(browser) as { session: string; kind: string }
+ expect(agent.kind).toBe('acp')
+
+ await transport.terminateSession()
+ const closed = () => browser.requests.find((item) => item.command === 'agent_session_closed')
+ // The notice reaches the app over its socket after the DELETE is answered.
+ for (let attempt = 0; attempt < 50 && !closed(); attempt++) await Bun.sleep(10)
+ expect(closed()?.args).toEqual({ session: agent.session })
+ })
+ })
+})
diff --git a/tests/helpers/chat/render-preview.ts b/tests/helpers/chat/render-preview.ts
index 2a52f3da3..a9058b0d5 100644
--- a/tests/helpers/chat/render-preview.ts
+++ b/tests/helpers/chat/render-preview.ts
@@ -1,6 +1,9 @@
import type { Page } from '@playwright/test'
+/** Clears the page and fixes the view; rendering snapshots compare it, so agents are not followed. */
export async function setupCanvas(page: Page) {
+ const followAgents = page.getByTestId('chat-follow-agents')
+ if ((await followAgents.getAttribute('aria-pressed')) === 'true') await followAgents.click()
await page.evaluate(() => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('Editor unavailable')