Skip to content

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

fix(ai): show the chat's agent on the page it edited (#1073)

Danila Poyarkov4c8fc2be07c9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index daad2598d..50869a6e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -91,11 +91,10 @@
- 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, and watch what the AI chat builds take shape on their own canvas while its JSX streams, not only once it is done.
+- 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, on whichever page those are, and an MCP agent leaves when its session ends. While the chat streams JSX, its cursor moves through the elements as they appear and outlines them. People's and agents' cursors glide to each new position instead of jumping. In a shared room, collaborators see each other's agents in the color of the person running them, and watch what the AI chat builds take shape on their own canvas while its JSX streams, not only once it is done.
- Copy the document's variables as a CSS stylesheet or a Tailwind v4 theme from the variables dialog, or print them with `openpencil tokens`. Each collection's default mode goes in `:root` (or `@theme`, with a `@custom-variant` per mode), other modes override under their condition, `[data-theme="dark"]` unless the mode names a selector or `@media` query, and aliases stay `var()` references that follow the mode. Variables CSS cannot express, such as booleans, are named instead of written.
- Import and export variables, text styles, and effect styles as W3C design tokens. **Export as design tokens** in the variables dialog's copy menu and `openpencil tokens --format dtcg --out <folder>` write one file per collection mode in the shape Figma imports, typography and shadow tokens for styles, and a DTCG resolver for tools such as Style Dictionary. **Import design tokens** reads files from Figma, a resolver with its files, Tokens Studio themes, or a zip of them, shows where each collection and mode goes before anything changes, updates variables and styles by name without deleting any, and undoes in one step; agents and MCP clients import with the `import_design_tokens` tool, and `design_to_tokens` takes `format: "dtcg"`.
- Edit variables as design tokens in the redesigned variables dialog, opened from View → Variables…, the command palette, or the Design panel, and expandable to most of the window. Collections and the groups inside them are listed in a sidebar with counts; picking a group, a type filter, or a search, which matches names, CSS names, descriptions, and values with the command palette's typo-tolerant matching, narrows the list, which shows each variable's type, CSS name, and a value per mode. Names and number or text values edit in place, rows reorder by dragging, and Shift- or Cmd-clicking selects several to duplicate, move into a group, or delete from the context menu, the Delete key, or the side panel. Selecting one edits its name, CSS name (checked against CSS before it is saved), unit, per-mode values or CSS expressions such as `clamp()`, scopes, description, and publishing, and points a value at another variable of the same type or detaches it again. The collection settings rename and delete the collection, add, rename, duplicate, delete, and choose the default mode, and choose when each mode applies in plain words, such as *System is in dark mode* or *Screen is narrower than 640px*, with the CSS it writes shown underneath and a custom selector or `@media`, `@supports`, or `@container` query when no preset fits. Manually switched modes use an attribute named after the collection, such as `data-theme`, or one the collection names to match an existing codebase; it is saved in `.fig` files and used by exported code. The active collection's stylesheet updates live below the list, and copying offers CSS or a Tailwind v4 theme. Undo and redo work in the dialog as they do on the canvas, with one step per change and one per color picker session, while a field with uncommitted text keeps its own undo. The dialog lays out by its own width: in a narrow window or on a phone it shows one mode at a time and opens a variable, the collection settings, or the stylesheet over the list.
-- 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.
- Jump between pages from the command palette: it lists the pages you visited recently in the tab, **Go to page…** lists every page, and typing a page name finds it.
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.ts
index 48046d772..9f97c71e4 100644
--- a/src/app/ai/tools/index.ts
+++ b/src/app/ai/tools/index.ts
@@ -21,6 +21,7 @@ import { aiToolDefinitions } from './catalog'
import { recordToolChange } from './changes/capture'
import { createMutex } from './mutex'
import {
+ markRunChange,
markRunWork,
moveRunToPage,
recordRunBaseline,
@@ -111,6 +112,9 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost
// The change record is a review aid; the edit and its undo entry already stand.
console.warn('Could not record AI tool change', error)
}
+ // The agent shows where it edited, even on another page; layers the result names
+ // refine this once the call returns.
+ markRunChange(store, change)
}
try {
// `switch_page` moves the run, and the user's view with it.
diff --git a/src/app/ai/tools/run.ts b/src/app/ai/tools/run.ts
index f25d6a430..cc201b6f2 100644
--- a/src/app/ai/tools/run.ts
+++ b/src/app/ai/tools/run.ts
@@ -1,4 +1,4 @@
-import type { PageSnapshot } from '@open-pencil/core/editor'
+import type { DocumentChange, PageSnapshot } from '@open-pencil/core/editor'
import type { StepBudget } from '@open-pencil/core/tools'
import type { UndoEntry } from '@open-pencil/scene-graph/undo'
@@ -84,6 +84,25 @@ export function markRunWork(store: EditorStore, nodeIds: string[]): void {
run.agent.update({ status: 'editing', ...placement })
}
+/**
+ * Point the run's agent at the layers a call changed, on whichever page they are, for calls such
+ * as `eval` whose result names none. Only the outermost of them are outlined.
+ */
+export function markRunChange(store: EditorStore, change: DocumentChange): void {
+ const { graph } = store
+ const layers = new Set(
+ [...change.created.map((node) => node.id), ...change.updated.map((update) => update.id)].filter(
+ // Pages and the document root are where the agent works, not what it works on.
+ (id) => id !== graph.rootId && graph.getNode(id)?.type !== 'CANVAS'
+ )
+ )
+ const outermost = [...layers].filter((id) => {
+ const parentId = graph.getNode(id)?.parentId
+ return !parentId || !layers.has(parentId)
+ })
+ markRunWork(store, outermost)
+}
+
export function recordStep(store?: EditorStore): void {
getRunState(store).currentSteps++
}
diff --git a/src/app/automation/agents.ts b/src/app/automation/agents.ts
index 696a7e069..4fda748a2 100644
--- a/src/app/automation/agents.ts
+++ b/src/app/automation/agents.ts
@@ -105,13 +105,6 @@ export function touchedNodeIds(store: EditorStore, args: unknown, result: unknow
})
}
-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)
@@ -129,12 +122,10 @@ export function agentFinished(
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)
+ const placement = agentPlacement(store, work.nodeIds, work.pageId)
agent.handle.update({
status: work.edited ? 'editing' : 'thinking',
- pageId,
+ pageId: work.pageId,
...placement
})
restartTimers(store, session.session, agent)
diff --git a/src/app/presence/registry.ts b/src/app/presence/registry.ts
index 66c80034a..e647a4903 100644
--- a/src/app/presence/registry.ts
+++ b/src/app/presence/registry.ts
@@ -384,18 +384,23 @@ export function addAgent(store: EditorStore, kind: AgentKind, model?: string): A
}
/**
- * 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.
+ * Where an agent shows it is working on `nodeIds`: on the page they are on, whichever page the
+ * agent started from, with its cursor at their top-left corner 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 {
+ fallbackPageId: string
+): Pick<AgentPresence, 'pageId' | 'cursor' | 'selection' | 'outline'> | null {
const present = nodeIds.filter((id) => store.graph.getNode(id))
const bounds = computeContentBounds(store.graph, present)
if (!bounds) return null
+ const [first] = present
+ const pageId =
+ (first && store.graph.closest(first, (node) => node.type === 'CANVAS')?.id) ?? fallbackPageId
return {
+ pageId,
cursor: { x: bounds.minX, y: bounds.minY, pageId },
selection: present,
outline: undefined
diff --git a/tests/app/ai/tools/run.test.ts b/tests/app/ai/tools/run.test.ts
index 2ac5f2ef2..5203c33d5 100644
--- a/tests/app/ai/tools/run.test.ts
+++ b/tests/app/ai/tools/run.test.ts
@@ -162,6 +162,40 @@ test("the agent's switch_page moves the run and the user's view", async () => {
})
})
+test.each([{ followAgents: false }, { followAgents: true }])(
+ 'the agent shows on the page a script edited, and only following takes the view there (%p)',
+ async ({ followAgents }) => {
+ await withStore(async (store, { a, b }) => {
+ appPreferences.value.chat.followAgents = followAgents
+ aiToolOverrides.value = { ...aiToolOverrides.value, eval: true }
+ const card = store.graph.createNode('FRAME', b, { name: 'Card', x: 40, y: 20, width: 80 })
+ const title = store.graph.createNode('TEXT', card.id, { name: 'Title', text: 'Hi' })
+ let during: ReturnType<typeof presenceOf>['agents']['value'] = []
+ let followPage = presenceOf(store).followPage
+ await runMessage(store, [
+ {
+ toolName: 'eval',
+ input: {
+ code: `const card = figma.getNodeById('${card.id}'); card.opacity = 0.5; figma.getNodeById('${title.id}').visible = false`
+ }
+ },
+ async (editor) => {
+ during = presenceOf(editor).agents.value
+ followPage = presenceOf(editor).followPage
+ }
+ ])
+
+ expect(during).toMatchObject([
+ { status: 'editing', pageId: b, cursor: { x: 40, y: 20, pageId: b }, selection: [card.id] }
+ ])
+ expect(runPageId(store)).toBe(a)
+ // Following switches pages as it does for any followed agent; without it the view stays.
+ expect(followPage).toBe(followAgents ? b : null)
+ if (!followAgents) expect(store.state.currentPageId).toBe(a)
+ })
+ }
+)
+
test('a run falls back to the page on screen when its page is deleted', async () => {
await withStore(async (store, { a, b }) => {
await runMessage(store, [])