Skip to content

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

fix(editor): undo agent edits to other pages, pages, and variables (#1059)

Danila Poyarkov5ca546a2c6aa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57a9ac545..daad2598d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -166,6 +166,7 @@
- Design lint reports far fewer false positives in `openpencil lint` and the app: `no-hardcoded-colors` flags only colors that match a color variable and names it, `no-deeply-nested` flags only the layer that crosses the depth limit, `touch-target-size` checks the WCAG 2.2 AA minimum of 24 × 24 in the Recommended preset (Strict and Accessibility keep 44 × 44), matches control names as whole words (a layer named "Rectangle" is no longer a call to action) and ignores icons and controls inside other controls, `consistent-spacing` accepts multiples of 4, `color-contrast` checks text bound to color variables, and layers inside instances are checked once through their main component. The Recommended preset reports unbound colors, deep nesting, mixed text styles, and off-scale spacing as suggestions instead of warnings. Lint messages carry the measured values in `data`.
- Keep the Share button labeled Share while you are in a room, instead of turning it into a Connected status; a green dot on your avatar shows the room is live.
- Show Flatten, Outline text, and Outline stroke in the canvas context menu without icons, like every other item there.
+- The AI chat starts with more tools turned on: comments (`get_comments`, `add_comment`, `reply_to_comment`, `resolve_comment`), variables (`list_variables`, `create_collection`, `create_variable`, `set_variable`, `bind_variable`), `lint` and `lint_fix`, `export_image` to look at its result, and `list_pages` and `create_page`. Before, it could reach these only through `eval` or after turning them on under Settings → Tool access, so when asked for a comment, it drew a note layer instead. Tools you turned off stay off.
- Keep an AI chat working on the page where it started when you switch to another page, instead of sending its next edits to whichever page is on screen. When the AI switches pages itself, your view follows.
- `openpencil://` and web `?node=` links select the layer on another page when the current page has none, switching to that page.
- Generate Tailwind JSX with the same class mapping as Tailwind HTML export, so both describe a design the same way, and write opaque colors as hex in HTML, CSS, and Tailwind output. `openpencil export -f jsx --style tailwind` now exports a whole page when no `--node` is given.
@@ -205,6 +206,7 @@
- Draw what a mask masks through the mask's opacity and layer blur, as Figma does, so a half-transparent or blurred mask fades or softens its layers instead of masking them fully. An outline mask ignores how opaque its fill is, and a luminance mask counts its opacity twice, as in Figma.
- Import SVG files that start with an XML declaration or doctype, such as Illustrator and Inkscape exports, instead of reporting no supported elements.
- Keep `fill-opacity` and `stroke-opacity` when importing SVG instead of drawing those paints opaque.
+- Keep an AI chat going when a script it runs through `eval` returns layers or pages inside an object or list, or values such as `NaN` or a `Map`; the reply used to stop with an invalid-prompt error. The model now gets such results as JSON.
- Use an API key saved in Settings for the open AI chat right away, including when asking again after a failed request, instead of only after reloading; the failure's notice closes once the request is sent again.
- Renaming a section title on the canvas keeps the title's size, weight, and place. Section titles draw in Inter SemiBold rather than an emboldened regular weight, and labels that are not rotated sit on whole pixels, so they stay crisp.
- Save HTML imported with `openpencil import` with its layout applied: layers in a flex container sit where its padding and gap place them instead of all at the top left (#788).
@@ -268,7 +270,7 @@
- Read and set `componentPropertyReferences` in the plugin API with property keys such as `Label#prop:1a2b`, as `componentPropertyDefinitions` lists them and Figma uses them, instead of internal property ids.
- Open Figma files that use slots with each instance's own slot content instead of its component's default, keep slot properties, their settings, and instance content when saving back to `.fig`, and keep an instance's slot content, and that of instances nested in it with the same names, when you switch its variant or swap it.
- Report a failed MCP `save_file` or `new_document` save as an error instead of success, and ask for a path rather than opening a Save dialog when the document has never been saved.
-- Undo layers that MCP clients and the CLI create, delete, or rearrange in the running app, including `render` and `eval` changes, with Edit → Undo. Previously only their property edits were undoable.
+- Undo layers that MCP clients and the CLI create, delete, or rearrange in the running app, including `render` and `eval` changes, with Edit → Undo. Previously only their property edits were undoable. Undoing these and AI chat edits also reverts what they change on other pages, the pages themselves, and variables and collections, which undo used to leave as they were; an edit that lands while a colour picker is open becomes its own undo step instead of joining the picker's.
- Save a `.fig` file that was opened and not edited yet. In the app the save never finished, and MCP `save_file` timed out without writing the file.
- Show the text, visibility, or swapped component an instance sets when the component gains that layer after the instance was placed, instead of the component's default ([#849](https://github.com/open-pencil/open-pencil/issues/849)).
- Show `.fig` thumbnails in the desktop app's recent files, which the app was not permitted to read.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index df35fc654..14f8c2f49 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -8,7 +8,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do
- Content an author wrote (design JSX, HTML, `.pen`) gets its sizes and positions from `layoutAuthoredNodes` in `packages/core/src/layout.ts`, which measures text that resizes to its content wherever it sits and then lays out the pages involved; renderers and readers of authored formats call it, while `.fig` keeps the geometry it stores (`packages/core/tests/layout/authored.test.ts`).
- HTML is styled by whoever has a CSS runtime and built into layers by `sceneGraphFromStyledHTML` (`packages/core/src/io/formats/html/layers.ts`), which browser builds may bundle. `readHTMLDocument` and `headlessHTMLReader` use the headless CSS runtime, which cannot be bundled for browsers, so they stay out of `BUILTIN_IO_FORMATS` and the CLI registers the reader (`packages/core/tests/io/formats/html/import.test.ts`).
- Copies of part of a document, such as previews, history snapshots, and exports, come from `extractPageContext` or `extractExportGraph` in `packages/core/src/io/subgraph.ts`, not another copier. Pass `componentSets` when instances must switch variant and `shareTables` for a read-only view rebuilt often (`packages/core/tests/io/subgraph.test.ts`).
-- Undo for structural AI and MCP edits records only the layers an edit touches with `capturePageChange`, whose capture shares unchanged values instead of deep-copying the page, since a page copy per tool call grows memory with every call. It relies on every change emitting a graph event and on values being replaced rather than written into, apart from the child lists, source metadata, and override maps it copies (`packages/core/tests/editor/history/page-change.test.ts`).
+- Undo for structural AI and MCP edits records only what an edit touches with `captureDocumentChange`: the edit's page is copied up front, and another page or the document node the first time `SceneGraph.observeNodeChanges` reports it about to change, so code that writes into a node directly calls `willChangeNode` first. Copies share values rather than deep-copying, so values must be replaced rather than written into, apart from the child lists, source metadata, and override maps it copies; comments on the document node stay out of undo (`packages/core/tests/editor/history/document-change.test.ts`).
## Layout
diff --git a/packages/core/src/editor/bridges/undo.ts b/packages/core/src/editor/bridges/undo.ts
index ba420d796..9d4c87ee5 100644
--- a/packages/core/src/editor/bridges/undo.ts
+++ b/packages/core/src/editor/bridges/undo.ts
@@ -31,8 +31,9 @@ export function createUndoBridge(
},
snapshotPage: undoActions.snapshotPage,
restorePageFromSnapshot: undoActions.restorePageFromSnapshot,
- capturePageChange: undoActions.capturePageChange,
- restorePageChange: undoActions.restorePageChange,
- pushUndoEntry: undoActions.pushUndoEntry
+ captureDocumentChange: undoActions.captureDocumentChange,
+ restoreDocumentChange: undoActions.restoreDocumentChange,
+ pushUndoEntry: undoActions.pushUndoEntry,
+ pushUndoStep: undoActions.pushUndoStep
}
}
diff --git a/packages/core/src/editor/history/atomic-tool.ts b/packages/core/src/editor/history/atomic-tool.ts
index e67e0a1d5..7089cfd16 100644
--- a/packages/core/src/editor/history/atomic-tool.ts
+++ b/packages/core/src/editor/history/atomic-tool.ts
@@ -14,7 +14,7 @@ import { diffFields, type FieldChanges } from './diff'
// Capture property changes across pages. Component synchronization remains editor-owned.
const MAX_TRANSACTION_NODES = 10_000
-type MutationEditor = Pick<Editor, 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoEntry'>
+type MutationEditor = Pick<Editor, 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoStep'>
function changes<T extends object>(
before: Map<string, T>,
@@ -108,7 +108,7 @@ export function executeAtomicTool(
nodeChanges.some((change) => Object.keys(change.after).some((key) => key !== 'source'))
if (!contentChanged && nodeChanges.length) replay(nodeChanges, [], 'before')
if (contentChanged) {
- editor.pushUndoEntry({
+ editor.pushUndoStep({
label: `${options.label ?? 'Agent'}: ${def.name}`,
inverse: () => replay(nodeChanges, variableChanges, 'before'),
forward: () => replay(nodeChanges, variableChanges, 'after')
diff --git a/packages/core/src/editor/history/document-change.ts b/packages/core/src/editor/history/document-change.ts
new file mode 100644
index 000000000..82aeaebee
--- /dev/null
+++ b/packages/core/src/editor/history/document-change.ts
@@ -0,0 +1,369 @@
+import { isEqual } from 'es-toolkit'
+
+import {
+ cloneInstanceOverrideState,
+ createSceneMutationImpact,
+ recordSceneMutations,
+ withLiveComments,
+ type FigmaSourcePayload,
+ type SceneGraph,
+ type SceneNode,
+ type SourceMetadata,
+ type Variable,
+ type VariableCollection
+} from '@open-pencil/scene-graph'
+
+import type { EditorContext } from '#core/editor/types'
+import { computeAllLayouts } from '#core/layout'
+
+import { diffFields, type FieldChanges } from './diff'
+
+type Side = 'before' | 'after'
+
+/**
+ * The fields an edit changed on a layer that exists on both sides. Source metadata is compared
+ * a level down and its `.fig` payload a level below that, so marking a field edited keeps that
+ * change rather than the layer's whole `.fig` record.
+ */
+interface LayerUpdate {
+ id: string
+ fields: FieldChanges<SceneNode> | null
+ source: FieldChanges<SourceMetadata> | null
+ fig: FieldChanges<FigmaSourcePayload> | null
+}
+
+/** A parent's children in one state, listed parents first. */
+interface ChildList {
+ id: string
+ childIds: string[]
+}
+
+/** A variable or collection on each side of an edit; `null` on the side it does not exist. */
+interface RecordChange<T> {
+ id: string
+ before: T | null
+ after: T | null
+}
+
+/**
+ * What one edit did to the document: copies of only the layers, variables, and collections it
+ * created, deleted, or changed, on any page, so an undo step costs what the edit touched rather
+ * than a copy of the document. Comments on the document node are left out, as undo never takes
+ * them back.
+ */
+export interface DocumentChange {
+ /** The page the edit ran on, which a review of it shows. */
+ pageId: string
+ /** Pages whose layers the edit changed, laid out again when it is undone or redone. */
+ pageIds: string[]
+ /** Layers as the edit left them, parents first. */
+ created: SceneNode[]
+ /** Layers as they were before the edit removed them, parents first. */
+ deleted: SceneNode[]
+ /** Fields the edit changed on layers that exist in both states, children aside. */
+ updated: LayerUpdate[]
+ /** Child lists that differ between the states, each side's parents first. */
+ children: Record<Side, ChildList[]>
+ variables: RecordChange<Variable>[]
+ collections: RecordChange<VariableCollection>[]
+}
+
+/** Layers by id: the live graph's, or those captured before the edit. */
+type Lookup = Pick<ReadonlyMap<string, SceneNode>, 'get' | 'size'>
+
+const NESTED_FIELDS: ReadonlySet<keyof SceneNode> = new Set(['childIds', 'parentId', 'source'])
+const SOURCE_PAYLOAD: ReadonlySet<keyof SourceMetadata> = new Set(['fig'])
+
+function diffLayer(id: string, previous: SceneNode, current: SceneNode): LayerUpdate | null {
+ const update: LayerUpdate = {
+ id,
+ fields: diffFields(id, previous, current, NESTED_FIELDS),
+ source: diffFields(id, previous.source, current.source, SOURCE_PAYLOAD),
+ fig: diffFields(id, previous.source.fig, current.source.fig)
+ }
+ return update.fields || update.source || update.fig ? update : null
+}
+
+function withChanges<T extends object>(value: T, changes: FieldChanges<T> | null, side: Side): T {
+ if (!changes) return value
+ const result = { ...value, ...structuredClone(changes[side]) }
+ for (const key of changes.absent[side]) Reflect.deleteProperty(result, key)
+ return result
+}
+
+/**
+ * `editedFields` marking plugin data edited as `live` does. The mark makes `.fig` export write
+ * the document node's comments, so it follows them rather than undo.
+ */
+function markedLike(editedFields: string[], live: SceneNode): string[] {
+ const marked = live.source.editedFields.includes('pluginData')
+ if (editedFields.includes('pluginData') === marked) return editedFields
+ return marked
+ ? [...editedFields, 'pluginData']
+ : editedFields.filter((field) => field !== 'pluginData')
+}
+
+/** The document node holding the comments of `live`, as undo never takes them back. */
+function withCommentsOf(root: SceneNode, live: SceneNode): SceneNode {
+ return {
+ ...root,
+ pluginData: withLiveComments(root.pluginData, live.pluginData),
+ source: { ...root.source, editedFields: markedLike(root.source.editedFields, live) }
+ }
+}
+
+function restoreLayer(graph: SceneGraph, update: LayerUpdate, side: Side): void {
+ const node = graph.getNode(update.id)
+ if (!node) return
+ const changes: Partial<SceneNode> = update.fields ? structuredClone(update.fields[side]) : {}
+ if (update.source || update.fig) {
+ changes.source = {
+ ...withChanges(node.source, update.source, side),
+ fig: withChanges(node.source.fig, update.fig, side)
+ }
+ }
+ if (node.id === graph.rootId) {
+ if (changes.pluginData)
+ changes.pluginData = withLiveComments(changes.pluginData, node.pluginData)
+ if (changes.source) {
+ changes.source.editedFields = markedLike(changes.source.editedFields, node)
+ }
+ }
+ graph.restoreNodeProperties(update.id, changes, update.fields?.absent[side] ?? [])
+}
+
+/**
+ * A copy that keeps the layer's values as they are now. Values are replaced, never written into
+ * (`materialize-instance.ts` in `@open-pencil/fig`), so sharing them is safe; the graph edits
+ * child lists, source metadata, and override maps in place, so those are copied.
+ */
+function captureNode(node: SceneNode): SceneNode {
+ const { source, instanceOverrides } = node
+ return {
+ ...node,
+ childIds: [...node.childIds],
+ source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },
+ instanceOverrides: cloneInstanceOverrideState(instanceOverrides)
+ }
+}
+
+/** Copies a page's layers not copied yet; a layer moved in from another page keeps its copy. */
+function capturePage(graph: SceneGraph, pageId: string, captured: Map<string, SceneNode>): void {
+ const stack = [pageId]
+ for (let id = stack.pop(); id !== undefined; id = stack.pop()) {
+ const node = graph.getNode(id)
+ if (!node) continue
+ if (!captured.has(id)) captured.set(id, captureNode(node))
+ stack.push(...node.childIds)
+ }
+}
+
+/**
+ * A layer and its ancestors, nearest first. Like `SceneGraph.closest`, the walk visits at most as
+ * many layers as there are, so a parent cycle in bad data cannot hang it.
+ */
+function* lineage(nodes: Lookup, id: string): Generator<SceneNode> {
+ let node = nodes.get(id)
+ for (let steps = 0; node && steps < nodes.size; steps++) {
+ yield node
+ node = node.parentId ? nodes.get(node.parentId) : undefined
+ }
+}
+
+function pageOf(nodes: Lookup, id: string): string | null {
+ for (const node of lineage(nodes, id)) if (node.type === 'CANVAS') return node.id
+ return null
+}
+
+function depthIn(nodes: Lookup, id: string): number {
+ let depth = 0
+ for (const node of lineage(nodes, id)) if (node.parentId) depth++
+ return depth
+}
+
+/** Adds one touched layer to the change, given its state on each side, if it has one. */
+function recordLayer(
+ change: DocumentChange,
+ id: string,
+ previous: SceneNode | undefined,
+ current: SceneNode | undefined
+): void {
+ if (previous && !isEqual(previous.childIds, current?.childIds ?? [])) {
+ change.children.before.push({ id, childIds: previous.childIds })
+ }
+ if (current && !isEqual(current.childIds, previous?.childIds ?? [])) {
+ change.children.after.push({ id, childIds: [...current.childIds] })
+ }
+ if (!previous) {
+ if (current) change.created.push(structuredClone(current))
+ } else if (!current) {
+ change.deleted.push(structuredClone(previous))
+ } else {
+ const update = diffLayer(id, previous, current)
+ if (update) change.updated.push(update)
+ }
+}
+
+function diffRecords<T>(previous: Map<string, T>, current: Map<string, T>): RecordChange<T>[] {
+ const ids = new Set([...previous.keys(), ...current.keys()])
+ return [...ids].flatMap((id) => {
+ const before = previous.get(id) ?? null
+ const after = current.get(id) ?? null
+ return isEqual(before, after) ? [] : [{ id, before, after: structuredClone(after) }]
+ })
+}
+
+/** Restores records in place where they exist, as views may hold them, as atomic tools do. */
+function restoreRecords<T extends object>(
+ target: Map<string, T>,
+ changes: RecordChange<T>[],
+ side: Side
+): void {
+ for (const change of changes) {
+ const value = change[side]
+ const existing = target.get(change.id)
+ if (!value) {
+ target.delete(change.id)
+ } else if (existing) {
+ for (const key of Object.keys(existing)) {
+ if (!Object.hasOwn(value, key)) Reflect.deleteProperty(existing, key)
+ }
+ Object.assign(existing, structuredClone(value))
+ } else {
+ target.set(change.id, structuredClone(value))
+ }
+ }
+}
+
+/**
+ * Starts recording an edit made from `pageId`. Call the returned function once the edit is
+ * done, also when it failed, to stop recording and get what the edit changed.
+ *
+ * The page is copied up front, so values written into its layers in place are kept too. Another
+ * page, or the document node, is copied the first time the edit is about to change it.
+ */
+export function captureDocumentChange(graph: SceneGraph, pageId: string): () => DocumentChange {
+ const captured = new Map<string, SceneNode>()
+ const capturedPages = new Set([pageId])
+ const created = new Set<string>()
+ capturePage(graph, pageId, captured)
+ const variables = structuredClone(graph.variables)
+ const collections = structuredClone(graph.variableCollections)
+ const impact = createSceneMutationImpact()
+ const unbindEvents = recordSceneMutations(graph, impact)
+ const unobserve = graph.observeNodeChanges({
+ created: (node) => created.add(node.id),
+ before: (node) => {
+ if (captured.has(node.id) || created.has(node.id)) return
+ const page = pageOf(graph.nodes, node.id)
+ if (page && !capturedPages.has(page)) {
+ capturedPages.add(page)
+ capturePage(graph, page, captured)
+ }
+ if (!captured.has(node.id)) captured.set(node.id, captureNode(node))
+ }
+ })
+
+ return () => {
+ unobserve()
+ unbindEvents()
+ const change: DocumentChange = {
+ pageId,
+ pageIds: [],
+ created: [],
+ deleted: [],
+ updated: [],
+ children: { before: [], after: [] },
+ variables: diffRecords(variables, graph.variables),
+ collections: diffRecords(collections, graph.variableCollections)
+ }
+ const pageIds = new Set<string>()
+ const touched = new Set([
+ ...impact.changedNodeIds,
+ ...impact.previousParentIds,
+ ...impact.currentParentIds
+ ])
+ for (const id of touched) {
+ const previous = captured.get(id)
+ // A layer changed without telling observers has no state to go back to.
+ if (!previous && !created.has(id)) continue
+ const current = graph.getNode(id)
+ // Comments are never part of an undo step.
+ const kept =
+ previous && current && id === graph.rootId ? withCommentsOf(previous, current) : previous
+ recordLayer(change, id, kept, current)
+ for (const page of [pageOf(captured, id), pageOf(graph.nodes, id)])
+ if (page) pageIds.add(page)
+ }
+ change.pageIds = [...pageIds]
+ const byDepth = (nodes: Lookup) => (a: { id: string }, b: { id: string }) =>
+ depthIn(nodes, a.id) - depthIn(nodes, b.id)
+ change.created.sort(byDepth(graph.nodes))
+ change.children.after.sort(byDepth(graph.nodes))
+ change.deleted.sort(byDepth(captured))
+ change.children.before.sort(byDepth(captured))
+ return change
+ }
+}
+
+export function isEmptyDocumentChange(change: DocumentChange): boolean {
+ return (
+ change.created.length === 0 &&
+ change.deleted.length === 0 &&
+ change.updated.length === 0 &&
+ change.children.before.length === 0 &&
+ change.children.after.length === 0 &&
+ change.variables.length === 0 &&
+ change.collections.length === 0
+ )
+}
+
+/**
+ * Puts what an edit touched back as it was on one side of it. The graph must be as the other
+ * side left it; what the edit did not touch is left alone, and so are comments. A graph that
+ * holds only part of the document, such as one page, gets the part of the change it has room
+ * for.
+ */
+export function applyDocumentChange(graph: SceneGraph, change: DocumentChange, side: Side): void {
+ const restored = side === 'before' ? change.deleted : change.created
+ const removed = side === 'before' ? change.created : change.deleted
+ restoreRecords(graph.variableCollections, change.collections, side)
+ restoreRecords(graph.variables, change.variables, side)
+ graph.preserveSourceMetadataDuring(() => {
+ for (const node of restored) {
+ const { parentId, childIds: _childIds, ...fields } = structuredClone(node)
+ if (!parentId || !graph.getNode(parentId)) continue
+ graph.createNode(node.type, parentId, { ...fields, childIds: [] })
+ }
+ // Parents come first, so a layer never moves under one of its own descendants.
+ for (const { id, childIds } of change.children[side]) {
+ for (const [index, childId] of childIds.entries()) {
+ if (graph.getNode(id)?.childIds[index] !== childId) graph.insertChildAt(childId, id, index)
+ }
+ }
+ // Layers that survive have moved out of the removed ones by now.
+ for (const node of removed) graph.deleteNode(node.id)
+ for (const update of change.updated) restoreLayer(graph, update, side)
+ })
+ graph.clearAbsPosCache()
+}
+
+/** Undoes or redoes an edit in the editor, whichever page is on screen. */
+export function restoreDocumentChange(
+ ctx: EditorContext,
+ change: DocumentChange,
+ side: Side
+): void {
+ applyDocumentChange(ctx.graph, change, side)
+ const pageIds = new Set(change.pageIds)
+ // Bound values follow their variables, so the page on screen is laid out again.
+ if (change.variables.length > 0) pageIds.add(ctx.state.currentPageId)
+ for (const pageId of pageIds) {
+ if (ctx.graph.getNode(pageId)) computeAllLayouts(ctx.graph, pageId)
+ }
+ if (pageIds.has(ctx.state.currentPageId)) {
+ ctx.setSelectedIds(new Set())
+ ctx.state.hoveredNodeId = null
+ }
+ ctx.requestRender()
+}
diff --git a/packages/core/src/editor/history/page-change.ts b/packages/core/src/editor/history/page-change.ts
deleted file mode 100644
index 664144365..000000000
--- a/packages/core/src/editor/history/page-change.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-import { isEqual } from 'es-toolkit'
-
-import {
- cloneInstanceOverrideState,
- createSceneMutationImpact,
- recordSceneMutations,
- type FigmaSourcePayload,
- type SceneGraph,
- type SceneNode,
- type SourceMetadata
-} from '@open-pencil/scene-graph'
-
-import type { EditorContext } from '#core/editor/types'
-import { computeAllLayouts } from '#core/layout'
-
-import { diffFields, type FieldChanges } from './diff'
-
-type Side = 'before' | 'after'
-
-/**
- * The fields an edit changed on a layer that exists on both sides. Source metadata is compared
- * a level down and its `.fig` payload a level below that, so marking a field edited keeps that
- * change rather than the layer's whole `.fig` record.
- */
-interface LayerUpdate {
- id: string
- fields: FieldChanges<SceneNode> | null
- source: FieldChanges<SourceMetadata> | null
- fig: FieldChanges<FigmaSourcePayload> | null
-}
-
-/** A parent's children in one state, listed parents first. */
-interface ChildList {
- id: string
- childIds: string[]
-}
-
-/**
- * What one edit did to a page: copies of only the layers it created, deleted, or changed, so an
- * undo step costs what the edit touched rather than a copy of the whole page.
- */
-export interface PageChange {
- pageId: string
- /** Layers as the edit left them, parents first. */
- created: SceneNode[]
- /** Layers as they were before the edit removed them, parents first. */
- deleted: SceneNode[]
- /** Fields the edit changed on layers that exist in both states, children aside. */
- updated: LayerUpdate[]
- /** Child lists that differ between the states, each side's parents first. */
- children: Record<Side, ChildList[]>
-}
-
-const NESTED_FIELDS: ReadonlySet<keyof SceneNode> = new Set(['childIds', 'parentId', 'source'])
-const SOURCE_PAYLOAD: ReadonlySet<keyof SourceMetadata> = new Set(['fig'])
-
-function diffLayer(id: string, previous: SceneNode, current: SceneNode): LayerUpdate | null {
- const update: LayerUpdate = {
- id,
- fields: diffFields(id, previous, current, NESTED_FIELDS),
- source: diffFields(id, previous.source, current.source, SOURCE_PAYLOAD),
- fig: diffFields(id, previous.source.fig, current.source.fig)
- }
- return update.fields || update.source || update.fig ? update : null
-}
-
-function withChanges<T extends object>(value: T, changes: FieldChanges<T> | null, side: Side): T {
- if (!changes) return value
- const result = { ...value, ...structuredClone(changes[side]) }
- for (const key of changes.absent[side]) Reflect.deleteProperty(result, key)
- return result
-}
-
-function restoreLayer(graph: SceneGraph, update: LayerUpdate, side: Side): void {
- const node = graph.getNode(update.id)
- if (!node) return
- const changes: Partial<SceneNode> = update.fields ? structuredClone(update.fields[side]) : {}
- if (update.source || update.fig) {
- changes.source = {
- ...withChanges(node.source, update.source, side),
- fig: withChanges(node.source.fig, update.fig, side)
- }
- }
- graph.restoreNodeProperties(update.id, changes, update.fields?.absent[side] ?? [])
-}
-
-/**
- * A copy that keeps the layer's values as they are now. Values are replaced, never written into
- * (`materialize-instance.ts` in `@open-pencil/fig`), so sharing them is safe; the graph edits
- * child lists, source metadata, and override maps in place, so those are copied.
- */
-function captureNode(node: SceneNode): SceneNode {
- const { source, instanceOverrides } = node
- return {
- ...node,
- childIds: [...node.childIds],
- source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },
- instanceOverrides: cloneInstanceOverrideState(instanceOverrides)
- }
-}
-
-function capturePage(graph: SceneGraph, pageId: string): Map<string, SceneNode> {
- const captured = new Map<string, SceneNode>()
- const stack = [pageId]
- for (let id = stack.pop(); id !== undefined; id = stack.pop()) {
- const node = graph.getNode(id)
- if (!node) continue
- captured.set(id, captureNode(node))
- stack.push(...node.childIds)
- }
- return captured
-}
-
-function depthIn(nodes: (id: string) => SceneNode | undefined, id: string, pageId: string) {
- let depth = 0
- for (let node = nodes(id); node && node.id !== pageId; node = nodes(node.parentId ?? '')) depth++
- return depth
-}
-
-function isOnPage(graph: SceneGraph, node: SceneNode, pageId: string): boolean {
- for (let current: SceneNode | undefined = node; current;) {
- if (current.id === pageId) return true
- current = current.parentId ? graph.getNode(current.parentId) : undefined
- }
- return false
-}
-
-/** Adds one touched layer to the change, given its state on each side, if it has one. */
-function recordLayer(
- change: PageChange,
- id: string,
- previous: SceneNode | undefined,
- current: SceneNode | undefined
-): void {
- if (previous && !isEqual(previous.childIds, current?.childIds ?? [])) {
- change.children.before.push({ id, childIds: previous.childIds })
- }
- if (current && !isEqual(current.childIds, previous?.childIds ?? [])) {
- change.children.after.push({ id, childIds: [...current.childIds] })
- }
- if (!previous) {
- if (current) change.created.push(structuredClone(current))
- } else if (!current) {
- change.deleted.push(structuredClone(previous))
- } else {
- const update = diffLayer(id, previous, current)
- if (update) change.updated.push(update)
- }
-}
-
-/**
- * Starts recording an edit to a page. Call the returned function once the edit is done, also
- * when it failed, to stop recording and get what the edit changed.
- */
-export function capturePageChange(graph: SceneGraph, pageId: string): () => PageChange {
- const captured = capturePage(graph, pageId)
- const impact = createSceneMutationImpact()
- const unbind = recordSceneMutations(graph, impact)
-
- return () => {
- unbind()
- const change: PageChange = {
- pageId,
- created: [],
- deleted: [],
- updated: [],
- children: { before: [], after: [] }
- }
- const touched = new Set([
- ...impact.changedNodeIds,
- ...impact.previousParentIds,
- ...impact.currentParentIds
- ])
- const beforeDepth = (id: string) => depthIn((key) => captured.get(key), id, pageId)
- const afterDepth = (id: string) => depthIn((key) => graph.getNode(key), id, pageId)
- for (const id of touched) {
- const live = graph.getNode(id)
- const current = live && isOnPage(graph, live, pageId) ? live : undefined
- recordLayer(change, id, captured.get(id), current)
- }
- const byDepth = (depth: (id: string) => number) => (a: { id: string }, b: { id: string }) =>
- depth(a.id) - depth(b.id)
- change.created.sort(byDepth(afterDepth))
- change.children.after.sort(byDepth(afterDepth))
- change.deleted.sort(byDepth(beforeDepth))
- change.children.before.sort(byDepth(beforeDepth))
- return change
- }
-}
-
-export function isEmptyPageChange(change: PageChange): boolean {
- return (
- change.created.length === 0 &&
- change.deleted.length === 0 &&
- change.updated.length === 0 &&
- change.children.before.length === 0 &&
- change.children.after.length === 0
- )
-}
-
-/**
- * Puts the layers an edit touched back as they were on one side of it. The graph must be as the
- * other side left it; layers the edit did not touch are left alone.
- */
-export function applyPageChange(graph: SceneGraph, change: PageChange, side: Side): void {
- const restored = side === 'before' ? change.deleted : change.created
- const removed = side === 'before' ? change.created : change.deleted
- graph.preserveSourceMetadataDuring(() => {
- for (const node of restored) {
- const { parentId, childIds: _childIds, ...fields } = structuredClone(node)
- graph.createNode(node.type, parentId ?? change.pageId, { ...fields, childIds: [] })
- }
- // Parents come first, so a layer never moves under one of its own descendants.
- for (const { id, childIds } of change.children[side]) {
- for (const [index, childId] of childIds.entries()) {
- if (graph.getNode(id)?.childIds[index] !== childId) graph.insertChildAt(childId, id, index)
- }
- }
- // Layers that survive have moved out of the removed ones by now.
- for (const node of removed) graph.deleteNode(node.id)
- for (const update of change.updated) restoreLayer(graph, update, side)
- })
- graph.clearAbsPosCache()
-}
-
-/** Undoes or redoes an edit in the editor, whichever page is on screen. */
-export function restorePageChange(ctx: EditorContext, change: PageChange, side: Side): void {
- if (!ctx.graph.getNode(change.pageId)) return
- applyPageChange(ctx.graph, change, side)
- computeAllLayouts(ctx.graph, change.pageId)
- if (change.pageId === ctx.state.currentPageId) {
- ctx.setSelectedIds(new Set())
- ctx.state.hoveredNodeId = null
- }
- ctx.requestRender()
-}
diff --git a/packages/core/src/editor/history/snapshot-graph.ts b/packages/core/src/editor/history/snapshot-graph.ts
index 8f72e31d8..79102fa7b 100644
--- a/packages/core/src/editor/history/snapshot-graph.ts
+++ b/packages/core/src/editor/history/snapshot-graph.ts
@@ -1,8 +1,10 @@
+import { uniq } from 'es-toolkit/array'
+
import type { SceneGraph } from '@open-pencil/scene-graph'
import { extractPageContext } from '#core/io/subgraph'
-import { applyPageChange, type PageChange } from './page-change'
+import { applyDocumentChange, type DocumentChange } from './document-change'
import type { PageSnapshot } from './snapshot'
function pageContext(source: SceneGraph, pageId: string, nodeIds: string[]): SceneGraph {
@@ -31,19 +33,23 @@ export function graphFromPageSnapshot(
}
/**
- * A standalone copy of the document with the change's page on one side of the change. The
- * source must be as the change left it, as it is right after the edit. Other pages are left
- * empty.
+ * A standalone copy of the document with the pages a change touched, and the page it ran on, on
+ * one side of the change. The source must be as the change left it, as it is right after the
+ * edit. Other pages are left empty.
*/
-export function graphFromPageChange(
+export function graphFromDocumentChange(
source: SceneGraph,
- change: PageChange,
+ change: DocumentChange,
side: 'before' | 'after'
): SceneGraph | null {
- const page = source.getNode(change.pageId)
- if (!page) return null
- const graph = pageContext(source, page.id, page.childIds)
- if (side === 'before') applyPageChange(graph, change, 'before')
+ // A page's own id brings its whole subtree; a layer moved between pages can then move back.
+ const pageIds = uniq([change.pageId, ...change.pageIds]).filter((id) => source.getNode(id))
+ // A change that removed every page it touched still needs one to build on; the past side
+ // brings the removed ones back.
+ const host = pageIds[0] ?? source.getPages()[0]?.id
+ if (!host) return null
+ const graph = pageContext(source, host, pageIds)
+ if (side === 'before') applyDocumentChange(graph, change, 'before')
graph.clearAbsPosCache()
return graph
}
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index f6e804210..8d9d7d81d 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -23,10 +23,9 @@ export {
} from './state/view'
export { createDefaultEditorState, createEditor } from './create'
export { executeAtomicTool } from './history/atomic-tool'
-export type { PageChange } from './history/page-change'
-export { isEmptyPageChange } from './history/page-change'
+export { isEmptyDocumentChange, type DocumentChange } from './history/document-change'
export type { PageSnapshot } from './history/snapshot'
-export { graphFromPageChange, graphFromPageSnapshot } from './history/snapshot-graph'
+export { graphFromDocumentChange, graphFromPageSnapshot } from './history/snapshot-graph'
export type { ClipboardPayload, ClipboardSnapshot } from './clipboard/copy'
export { resolvePasteTarget } from './clipboard/paste/target'
export { playIslandRoots } from './play/islands'
diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.ts
index ce5f15430..72db8f1ac 100644
--- a/packages/core/src/editor/undo.ts
+++ b/packages/core/src/editor/undo.ts
@@ -10,10 +10,10 @@ import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
import { assertNodeEditable } from './capabilities'
import {
- capturePageChange as startPageChange,
- restorePageChange as applyPageChangeToEditor,
- type PageChange
-} from './history/page-change'
+ captureDocumentChange as startDocumentChange,
+ restoreDocumentChange as applyDocumentChangeToEditor,
+ type DocumentChange
+} from './history/document-change'
import { collectNodePositions, pushPositionUndo } from './history/position'
import {
restorePageFromSnapshot as restorePageSnapshot,
@@ -252,19 +252,27 @@ export function createUndoActions(ctx: EditorContext) {
restorePageSnapshot(ctx, snapshot)
}
- /** Starts recording an edit to a page; the returned function ends it with what changed. */
- function capturePageChange(pageId = ctx.state.currentPageId): () => PageChange {
- return startPageChange(ctx.graph, pageId)
+ /**
+ * Starts recording an edit made from a page, wherever in the document it lands; the returned
+ * function ends it with what changed.
+ */
+ function captureDocumentChange(pageId = ctx.state.currentPageId): () => DocumentChange {
+ return startDocumentChange(ctx.graph, pageId)
}
- function restorePageChange(change: PageChange, side: 'before' | 'after') {
- applyPageChangeToEditor(ctx, change, side)
+ function restoreDocumentChange(change: DocumentChange, side: 'before' | 'after') {
+ applyDocumentChangeToEditor(ctx, change, side)
}
function pushUndoEntry(entry: UndoEntry) {
ctx.undo.push(entry)
}
+ /** Records an agent's edit as its own step, even while the user is in the middle of one. */
+ function pushUndoStep(entry: UndoEntry) {
+ ctx.undo.pushStep(entry)
+ }
+
return {
commitMove,
commitMoveWithReparent,
@@ -277,8 +285,9 @@ export function createUndoActions(ctx: EditorContext) {
redoAction,
snapshotPage,
restorePageFromSnapshot,
- capturePageChange,
- restorePageChange,
- pushUndoEntry
+ captureDocumentChange,
+ restoreDocumentChange,
+ pushUndoEntry,
+ pushUndoStep
}
}
diff --git a/packages/core/src/tools/analyze/eval/index.ts b/packages/core/src/tools/analyze/eval/index.ts
index 53f2ed717..69ed86759 100644
--- a/packages/core/src/tools/analyze/eval/index.ts
+++ b/packages/core/src/tools/analyze/eval/index.ts
@@ -7,7 +7,7 @@ import { compileScript } from './wrap'
export const evalCode = defineTool({
name: 'eval',
description:
- 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is the Figma Plugin API; the `openpencil` global adds what Figma has no API for, such as component behaviours (`openpencil.setBehaviour`, `openpencil.getBehaviour`, `openpencil.behaviourKinds`) and slots (`openpencil.createSlot`).',
+ 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is the Figma Plugin API; the `openpencil` global adds what Figma has no API for, such as component behaviours (`openpencil.setBehaviour`, `openpencil.getBehaviour`, `openpencil.behaviourKinds`), slots (`openpencil.createSlot`), and comments (`openpencil.getComments`, `openpencil.getComment`, `openpencil.addComment`, and each comment’s `reply` and `resolve`).',
execution: { kind: 'async', mutation: 'document' },
capabilities: ['document:read', 'document:write', 'code:execute'],
availability: 'eval',
@@ -16,12 +16,15 @@ export const evalCode = defineTool({
}),
execute: async (figma, { code }) => {
- const result = await compileScript(code)(figma)
- if (result && typeof result === 'object') {
- const toJSON = Reflect.get(result, 'toJSON')
- if (typeof toJSON === 'function') return toJSON.call(result)
- }
- if (result !== undefined && result !== null) return result
- return { ok: true, message: 'Code executed (no return value)' }
+ const result: unknown = await compileScript(code)(figma)
+ // `null` is a result, such as a lookup that found nothing; only nothing returned is not.
+ if (result === undefined) return { ok: true, message: 'Code executed (no return value)' }
+ // JSON has no text for these; their description is the closest.
+ if (typeof result === 'function' || typeof result === 'symbol') return String(result)
+ // Callers read a result as JSON: MCP and the CLI print it, and the AI chat's model takes
+ // nothing else. So a script gets back what printing shows: nodes, even inside objects, as
+ // their JSON, `NaN` as null, and a `Map` as `{}`.
+ const json = JSON.stringify(result)
+ return JSON.parse(json) as unknown
}
})
diff --git a/packages/core/tests/editor/history/atomic-tools.test.ts b/packages/core/tests/editor/history/atomic-tools.test.ts
index 9e4045580..32a717144 100644
--- a/packages/core/tests/editor/history/atomic-tools.test.ts
+++ b/packages/core/tests/editor/history/atomic-tools.test.ts
@@ -14,7 +14,7 @@ function setup() {
graph,
runLayoutForNode: () => undefined,
requestRender: () => undefined,
- pushUndoEntry: undo.push.bind(undo)
+ pushUndoStep: undo.pushStep.bind(undo)
}
const rectangle = figma.createRectangle()
const tool = (name: string): ToolDef => {
diff --git a/packages/core/tests/editor/history/document-change.test.ts b/packages/core/tests/editor/history/document-change.test.ts
new file mode 100644
index 000000000..5ac12e6ee
--- /dev/null
+++ b/packages/core/tests/editor/history/document-change.test.ts
@@ -0,0 +1,271 @@
+import { describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import {
+ createEditor,
+ graphFromDocumentChange,
+ isEmptyDocumentChange
+} from '@open-pencil/core/editor'
+import { readComments, writeComments, type CommentThread } from '@open-pencil/scene-graph'
+
+function setup() {
+ const editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const card = editor.graph.createNode('FRAME', pageId, { name: 'Card', width: 200, height: 120 })
+ const title = editor.graph.createNode('TEXT', card.id, { name: 'Title', text: 'Hello' })
+ const badge = editor.graph.createNode('RECTANGLE', card.id, { name: 'Badge', width: 24 })
+ const other = editor.graph.createNode('FRAME', pageId, { name: 'Other', x: 400 })
+ return { editor, pageId, card, title, badge, other }
+}
+
+type Editor = ReturnType<typeof setup>['editor']
+
+/** Every page, the document node, and the variables, as copies. */
+function documentState(editor: Editor) {
+ const { graph } = editor
+ return {
+ root: structuredClone(graph.getNode(graph.rootId)),
+ pages: graph.getPages().map((page) => editor.snapshotPage(page.id)),
+ variables: structuredClone(graph.variables),
+ collections: structuredClone(graph.variableCollections)
+ }
+}
+
+/** Records an edit, then checks that undo and redo bring back each side exactly. */
+function roundTrip(editor: Editor, edit: () => void) {
+ const before = documentState(editor)
+ const finish = editor.captureDocumentChange(editor.state.currentPageId)
+ edit()
+ const change = finish()
+ const after = documentState(editor)
+
+ editor.restoreDocumentChange(change, 'before')
+ expect(documentState(editor)).toEqual(before)
+ editor.restoreDocumentChange(change, 'after')
+ expect(documentState(editor)).toEqual(after)
+ return change
+}
+
+function thread(id: string, pageId: string): CommentThread {
+ return {
+ id,
+ pageId,
+ x: 0,
+ y: 0,
+ author: 'Ada',
+ text: id,
+ createdAt: '2026-10-08T10:00:00.000Z',
+ updatedAt: '2026-10-08T10:00:00.000Z',
+ resolved: false,
+ replies: []
+ }
+}
+
+describe('document changes', () => {
+ test('undo and redo restore created, edited, and deleted layers', () => {
+ const { editor, card, title, badge } = setup()
+ roundTrip(editor, () => {
+ editor.graph.updateNode(title.id, { text: 'Changed', x: 12 })
+ editor.graph.deleteNode(badge.id)
+ const added = editor.graph.createNode('FRAME', card.id, { name: 'Added' })
+ editor.graph.createNode('TEXT', added.id, { name: 'Inner', text: 'New' })
+ })
+ })
+
+ test('undo and redo restore moves, including nesting two layers the other way round', () => {
+ const { editor, pageId, card, title, other } = setup()
+ roundTrip(editor, () => {
+ editor.graph.insertChildAt(title.id, other.id, 0)
+ editor.graph.reorderChild(other.id, pageId, 0)
+ })
+ roundTrip(editor, () => {
+ editor.graph.reparentNode(other.id, card.id)
+ })
+ roundTrip(editor, () => {
+ editor.graph.reparentNode(card.id, pageId)
+ editor.graph.reparentNode(other.id, pageId)
+ editor.graph.reparentNode(card.id, other.id)
+ })
+ })
+
+ test('layers that survive a removed parent are moved back out first', () => {
+ const { editor, pageId, card, other } = setup()
+ roundTrip(editor, () => {
+ const wrapper = editor.graph.createNode('FRAME', pageId, { name: 'Wrapper' })
+ editor.graph.reparentNode(card.id, wrapper.id)
+ editor.graph.reparentNode(other.id, wrapper.id)
+ })
+ })
+
+ test('keeps copies of only the layers the edit touched', () => {
+ const { editor, pageId, card, title, badge, other } = setup()
+ const finish = editor.captureDocumentChange(pageId)
+ editor.graph.updateNode(title.id, { text: 'Changed' })
+ editor.graph.createNode('RECTANGLE', other.id, { name: 'New' })
+ const change = finish()
+
+ expect(change.updated.map((update) => update.id)).toEqual([title.id])
+ expect(change.updated[0]?.fields?.after).toEqual({ text: 'Changed' })
+ // Marking the field edited keeps that list, not the layer's whole source metadata.
+ expect(change.updated[0]?.source?.after).toEqual({ editedFields: ['text'] })
+ expect(change.updated[0]?.fig).toBeNull()
+ expect(change.created.map((node) => node.name)).toEqual(['New'])
+ expect(change.children.after.map((list) => list.id)).toEqual([other.id])
+
+ // Undo edits the layers in place, leaving untouched ones as they are.
+ const untouched = editor.graph.getNode(badge.id)
+ const edited = editor.graph.getNode(title.id)
+ editor.restoreDocumentChange(change, 'before')
+ expect(editor.graph.getNode(badge.id)).toBe(expectDefined(untouched, 'badge'))
+ expect(editor.graph.getNode(title.id)).toBe(expectDefined(edited, 'title'))
+ expect(editor.graph.getNode(card.id)?.childIds).toEqual([title.id, badge.id])
+ })
+
+ test('an edit that changes nothing is empty', () => {
+ const { editor, pageId } = setup()
+ const finish = editor.captureDocumentChange(pageId)
+ expect(isEmptyDocumentChange(finish())).toBe(true)
+ })
+
+ test('builds standalone graphs of both sides of an edit', () => {
+ const { editor, pageId, title, badge } = setup()
+ const finish = editor.captureDocumentChange(pageId)
+ editor.graph.updateNode(title.id, { text: 'Changed' })
+ editor.graph.deleteNode(badge.id)
+ const change = finish()
+
+ const before = expectDefined(graphFromDocumentChange(editor.graph, change, 'before'), 'before')
+ const after = expectDefined(graphFromDocumentChange(editor.graph, change, 'after'), 'after')
+ expect(before.getNode(title.id)?.text).toBe('Hello')
+ expect(before.getNode(badge.id)?.name).toBe('Badge')
+ expect(after.getNode(title.id)?.text).toBe('Changed')
+ expect(after.getNode(badge.id)).toBeUndefined()
+ // Building the past side leaves the document alone.
+ expect(editor.graph.getNode(title.id)?.text).toBe('Changed')
+ expect(editor.graph.getNode(badge.id)).toBeUndefined()
+ })
+
+ test('the past side of a move to another page keeps the layer on its first page', () => {
+ const { editor, pageId, card } = setup()
+ const second = editor.graph.addPage('Second')
+ const finish = editor.captureDocumentChange(pageId)
+ editor.graph.reparentNode(card.id, second.id)
+ const change = finish()
+
+ const before = expectDefined(graphFromDocumentChange(editor.graph, change, 'before'), 'before')
+ const after = expectDefined(graphFromDocumentChange(editor.graph, change, 'after'), 'after')
+ expect(before.getNode(card.id)?.parentId).toBe(pageId)
+ expect(before.getNode(pageId)?.childIds).toContain(card.id)
+ expect(after.getNode(pageId)?.childIds).not.toContain(card.id)
+ })
+
+ test('the past side of removing the page the edit ran on brings that page back', () => {
+ const { editor, pageId, card } = setup()
+ editor.graph.addPage('Second')
+ const finish = editor.captureDocumentChange(pageId)
+ editor.graph.deleteNode(pageId)
+ const change = finish()
+
+ const before = expectDefined(graphFromDocumentChange(editor.graph, change, 'before'), 'before')
+ const after = expectDefined(graphFromDocumentChange(editor.graph, change, 'after'), 'after')
+ expect(before.getNode(pageId)?.childIds).toContain(card.id)
+ expect(after.getNode(pageId)).toBeUndefined()
+ })
+
+ test('a parent cycle in bad data does not hang recording', () => {
+ const { editor, pageId, card, title } = setup()
+ // Nothing in the graph's API makes a cycle; a damaged file can.
+ expectDefined(editor.graph.getNode(card.id), 'card').parentId = title.id
+ const finish = editor.captureDocumentChange(pageId)
+ editor.graph.updateNode(title.id, { text: 'Changed' })
+ expect(isEmptyDocumentChange(finish())).toBe(false)
+ })
+
+ test('undo and redo restore layers on other pages', () => {
+ const { editor } = setup()
+ const second = editor.graph.addPage('Second')
+ const card = editor.graph.createNode('FRAME', second.id, { name: 'Card' })
+ const label = editor.graph.createNode('TEXT', card.id, { name: 'Label', text: 'Hi' })
+ const change = roundTrip(editor, () => {
+ editor.graph.updateNode(label.id, { text: 'Changed' })
+ editor.graph.createNode('RECTANGLE', card.id, { name: 'Added' })
+ })
+ expect(change.pageIds).toEqual([second.id])
+ })
+
+ test('undo and redo restore a layer moved to another page', () => {
+ const { editor, card } = setup()
+ const second = editor.graph.addPage('Second')
+ roundTrip(editor, () => editor.graph.reparentNode(card.id, second.id))
+ })
+
+ test('undo and redo restore added, renamed, moved, and removed pages', () => {
+ const { editor, pageId } = setup()
+ const second = editor.graph.addPage('Second')
+ editor.graph.createNode('FRAME', second.id, { name: 'On second' })
+ roundTrip(editor, () => {
+ editor.graph.addPage('Added')
+ editor.graph.updateNode(pageId, { name: 'Renamed' })
+ editor.graph.insertChildAt(pageId, editor.graph.rootId, 1)
+ })
+ roundTrip(editor, () => editor.graph.deleteNode(second.id))
+ })
+
+ test('undo and redo restore variables, collections, and bindings', () => {
+ const { editor, title } = setup()
+ const collection = editor.graph.createCollection('Colors')
+ const brand = editor.graph.createVariable('Brand', 'COLOR', collection.id, {
+ r: 1,
+ g: 0,
+ b: 0,
+ a: 1
+ })
+ roundTrip(editor, () => {
+ const faded = editor.graph.createVariable('Faded', 'FLOAT', collection.id, 0.5)
+ brand.name = 'Primary'
+ editor.graph.bindVariable(title.id, 'opacity', faded.id)
+ })
+ roundTrip(editor, () => editor.graph.removeVariable(brand.id))
+ roundTrip(editor, () => editor.graph.removeCollection(collection.id))
+ })
+
+ test('a layer created and then edited is undone as created', () => {
+ const { editor, pageId } = setup()
+ const second = editor.graph.addPage('Second')
+ const change = roundTrip(editor, () => {
+ const added = editor.graph.createNode('FRAME', second.id, { name: 'New' })
+ editor.graph.updateNode(added.id, { name: 'Renamed' })
+ editor.graph.reparentNode(added.id, pageId)
+ })
+ expect(change.created.map((node) => node.name)).toEqual(['Renamed'])
+ expect(change.updated).toEqual([])
+ })
+
+ test('comments are never part of a change, and undo leaves them as they are', () => {
+ const { editor, pageId } = setup()
+ const { graph } = editor
+ const finishComment = editor.captureDocumentChange(pageId)
+ writeComments(graph, [thread('first', pageId)])
+ expect(isEmptyDocumentChange(finishComment())).toBe(true)
+
+ // A step that renames the document and comments as it goes.
+ const finish = editor.captureDocumentChange(pageId)
+ graph.updateNode(graph.rootId, { name: 'Renamed' })
+ writeComments(graph, [thread('first', pageId), thread('second', pageId)])
+ const change = finish()
+ // Someone comments after the step.
+ writeComments(graph, [
+ thread('first', pageId),
+ thread('second', pageId),
+ thread('third', pageId)
+ ])
+
+ editor.restoreDocumentChange(change, 'before')
+ expect(graph.getNode(graph.rootId)?.name).toBe('Document')
+ expect(readComments(graph).map((entry) => entry.id)).toEqual(['first', 'second', 'third'])
+ editor.restoreDocumentChange(change, 'after')
+ expect(graph.getNode(graph.rootId)?.name).toBe('Renamed')
+ expect(readComments(graph)).toHaveLength(3)
+ })
+})
diff --git a/packages/core/tests/editor/history/page-change.test.ts b/packages/core/tests/editor/history/page-change.test.ts
deleted file mode 100644
index c88ddaa46..000000000
--- a/packages/core/tests/editor/history/page-change.test.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import { expectDefined } from '#core-tests/helpers/assert'
-
-import { createEditor, graphFromPageChange, isEmptyPageChange } from '@open-pencil/core/editor'
-
-function setup() {
- const editor = createEditor()
- const pageId = editor.state.currentPageId
- const card = editor.graph.createNode('FRAME', pageId, { name: 'Card', width: 200, height: 120 })
- const title = editor.graph.createNode('TEXT', card.id, { name: 'Title', text: 'Hello' })
- const badge = editor.graph.createNode('RECTANGLE', card.id, { name: 'Badge', width: 24 })
- const other = editor.graph.createNode('FRAME', pageId, { name: 'Other', x: 400 })
- return { editor, pageId, card, title, badge, other }
-}
-
-/** Records an edit, then checks that undo and redo bring back each side exactly. */
-function roundTrip(editor: ReturnType<typeof setup>['editor'], edit: () => void) {
- const pageId = editor.state.currentPageId
- const before = editor.snapshotPage(pageId)
- const finish = editor.capturePageChange(pageId)
- edit()
- const change = finish()
- const after = editor.snapshotPage(pageId)
-
- editor.restorePageChange(change, 'before')
- expect(editor.snapshotPage(pageId)).toEqual(before)
- editor.restorePageChange(change, 'after')
- expect(editor.snapshotPage(pageId)).toEqual(after)
- return change
-}
-
-describe('page changes', () => {
- test('undo and redo restore created, edited, and deleted layers', () => {
- const { editor, card, title, badge } = setup()
- roundTrip(editor, () => {
- editor.graph.updateNode(title.id, { text: 'Changed', x: 12 })
- editor.graph.deleteNode(badge.id)
- const added = editor.graph.createNode('FRAME', card.id, { name: 'Added' })
- editor.graph.createNode('TEXT', added.id, { name: 'Inner', text: 'New' })
- })
- })
-
- test('undo and redo restore moves, including nesting two layers the other way round', () => {
- const { editor, pageId, card, title, other } = setup()
- roundTrip(editor, () => {
- editor.graph.insertChildAt(title.id, other.id, 0)
- editor.graph.reorderChild(other.id, pageId, 0)
- })
- roundTrip(editor, () => {
- editor.graph.reparentNode(other.id, card.id)
- })
- roundTrip(editor, () => {
- editor.graph.reparentNode(card.id, pageId)
- editor.graph.reparentNode(other.id, pageId)
- editor.graph.reparentNode(card.id, other.id)
- })
- })
-
- test('layers that survive a removed parent are moved back out first', () => {
- const { editor, pageId, card, other } = setup()
- roundTrip(editor, () => {
- const wrapper = editor.graph.createNode('FRAME', pageId, { name: 'Wrapper' })
- editor.graph.reparentNode(card.id, wrapper.id)
- editor.graph.reparentNode(other.id, wrapper.id)
- })
- })
-
- test('keeps copies of only the layers the edit touched', () => {
- const { editor, pageId, card, title, badge, other } = setup()
- const finish = editor.capturePageChange(pageId)
- editor.graph.updateNode(title.id, { text: 'Changed' })
- editor.graph.createNode('RECTANGLE', other.id, { name: 'New' })
- const change = finish()
-
- expect(change.updated.map((update) => update.id)).toEqual([title.id])
- expect(change.updated[0]?.fields?.after).toEqual({ text: 'Changed' })
- // Marking the field edited keeps that list, not the layer's whole source metadata.
- expect(change.updated[0]?.source?.after).toEqual({ editedFields: ['text'] })
- expect(change.updated[0]?.fig).toBeNull()
- expect(change.created.map((node) => node.name)).toEqual(['New'])
- expect(change.children.after.map((list) => list.id)).toEqual([other.id])
-
- // Undo edits the layers in place, leaving untouched ones as they are.
- const untouched = editor.graph.getNode(badge.id)
- const edited = editor.graph.getNode(title.id)
- editor.restorePageChange(change, 'before')
- expect(editor.graph.getNode(badge.id)).toBe(expectDefined(untouched, 'badge'))
- expect(editor.graph.getNode(title.id)).toBe(expectDefined(edited, 'title'))
- expect(editor.graph.getNode(card.id)?.childIds).toEqual([title.id, badge.id])
- })
-
- test('an edit that changes nothing is empty', () => {
- const { editor, pageId } = setup()
- const finish = editor.capturePageChange(pageId)
- expect(isEmptyPageChange(finish())).toBe(true)
- })
-
- test('builds standalone graphs of both sides of an edit', () => {
- const { editor, pageId, title, badge } = setup()
- const finish = editor.capturePageChange(pageId)
- editor.graph.updateNode(title.id, { text: 'Changed' })
- editor.graph.deleteNode(badge.id)
- const change = finish()
-
- const before = expectDefined(graphFromPageChange(editor.graph, change, 'before'), 'before')
- const after = expectDefined(graphFromPageChange(editor.graph, change, 'after'), 'after')
- expect(before.getNode(title.id)?.text).toBe('Hello')
- expect(before.getNode(badge.id)?.name).toBe('Badge')
- expect(after.getNode(title.id)?.text).toBe('Changed')
- expect(after.getNode(badge.id)).toBeUndefined()
- // Building the past side leaves the document alone.
- expect(editor.graph.getNode(title.id)?.text).toBe('Changed')
- expect(editor.graph.getNode(badge.id)).toBeUndefined()
- })
-})
diff --git a/packages/core/tests/tools/analyze/eval.test.ts b/packages/core/tests/tools/analyze/eval.test.ts
new file mode 100644
index 000000000..ebb413965
--- /dev/null
+++ b/packages/core/tests/tools/analyze/eval.test.ts
@@ -0,0 +1,44 @@
+import { expect, test } from 'bun:test'
+
+import { toolModelMessageSchema } from 'ai'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { evalCode } from '#core/tools/analyze/eval'
+
+function run(code: string) {
+ return evalCode.execute(new FigmaAPI(new SceneGraph()), { code })
+}
+
+test('returns what a script returns as the JSON it prints as', async () => {
+ const result = await run(
+ 'return { page: figma.createPage(), width: NaN, list: [1, undefined], byId: new Map([["a", 1]]) }'
+ )
+
+ expect(result).toMatchObject({ width: null, list: [1, null], byId: {} })
+ expect(result).toHaveProperty('page.type', 'CANVAS')
+})
+
+test('a script result makes a tool message the AI SDK accepts in the next prompt', async () => {
+ // The AI adapter sends results other than images to the model as JSON.
+ const output = await run('return figma.root.children')
+ const message = {
+ role: 'tool',
+ content: [
+ {
+ type: 'tool-result',
+ toolCallId: 'call',
+ toolName: 'eval',
+ output: { type: 'json', value: output }
+ }
+ ]
+ }
+ expect(toolModelMessageSchema.safeParse(message).success).toBe(true)
+})
+
+test('reports a script with no result, keeps a null one, and describes a function', async () => {
+ expect(await run('const x = 1')).toEqual({ ok: true, message: 'Code executed (no return value)' })
+ expect(await run('return figma.getNodeById("missing")')).toBeNull()
+ expect(await run('return () => 1')).toBe('() => 1')
+})
diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.md
index fffc5b2e6..2b5d03493 100644
--- a/packages/docs/programmable/ai-chat.md
+++ b/packages/docs/programmable/ai-chat.md
@@ -28,7 +28,7 @@ The built-in AI captures this limit when each message starts. Stopping, remainin
## Tool access
-Open **Settings → Tool access** to choose which tools direct AI model connections can use. Search by name or description, expand read-only or side-effect groups, and toggle individual tools or an entire group. Group switches affect all tools in that group, not only search results. **Restore defaults** restores the compact default tool set; extended tools such as `create_component` can be enabled individually.
+Open **Settings → Tool access** to choose which tools direct AI model connections can use. Search by name or description, expand read-only or side-effect groups, and toggle individual tools or an entire group. Group switches affect all tools in that group, not only search results. **Restore defaults** restores the default tool set: the core editing and inspection tools, the library tools (`get_components`, `list_libraries`, `insert_library_component`), comments, variables, `lint` and `lint_fix`, `export_image`, `list_pages`, and `create_page`. Extended tools such as `create_component` can be enabled individually.
Preferences are saved locally and apply to the next message, including in an existing conversation. They do not change an already-running request. Enabling many tools increases the schemas sent to the model.
diff --git a/packages/scene-graph/src/comments/document.ts b/packages/scene-graph/src/comments/document.ts
index df1ef91ef..ea84faa6d 100644
--- a/packages/scene-graph/src/comments/document.ts
+++ b/packages/scene-graph/src/comments/document.ts
@@ -1,7 +1,12 @@
import type { SceneGraph } from '../index'
-import { readPluginData, withPluginData } from '../plugin-data/field'
+import {
+ isPluginDataEntry,
+ readPluginData,
+ withoutPluginData,
+ withPluginData
+} from '../plugin-data/field'
import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
-import type { CommentThread } from '../types'
+import type { CommentThread, PluginDataEntry } from '../types'
const { comments } = OPEN_PENCIL_PLUGIN_DATA
@@ -30,3 +35,17 @@ export function writeComments(graph: SceneGraph, threads: readonly CommentThread
)
})
}
+
+/**
+ * `entries` holding the comments of `live` instead of their own. Undo and redo restore the
+ * document node with this, so they leave comments as they are now.
+ */
+export function withLiveComments(
+ entries: readonly PluginDataEntry[],
+ live: readonly PluginDataEntry[]
+): PluginDataEntry[] {
+ return [
+ ...withoutPluginData(entries, [comments]),
+ ...live.filter((entry) => isPluginDataEntry(entry, comments))
+ ]
+}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 3d11644df..8740b2b69 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -113,6 +113,7 @@ import type {
DocumentColorSpace,
EnabledLibraryBinding,
NodeType,
+ NodeChangeObserver,
SceneGraphEventHandlers,
SceneNode,
SourceMetadata,
@@ -183,6 +184,7 @@ export class SceneGraph {
private absPosCache = new Map<string, Vector>()
private previewMutationDepth = 0
private previewObservers: NodePreviewObserver[] = []
+ private readonly changeObservers = new Set<NodeChangeObserver>()
private sourceMetadataPreservationDepth = 0
private importedStateApplicationDepth = 0
private layoutMutationDepth = 0
@@ -220,6 +222,23 @@ export class SceneGraph {
return bindNodeEvents(this.emitter, handlers)
}
+ /**
+ * Tells `observer` about each node an edit adds and, before it changes, each node it is about
+ * to change, so a recorder can keep the node as it was. Unlike node events these are never
+ * buffered. Graph methods report the nodes they change; code that writes into a node directly
+ * reports it with `willChangeNode` first.
+ */
+ observeNodeChanges(observer: NodeChangeObserver): () => void {
+ this.changeObservers.add(observer)
+ return () => this.changeObservers.delete(observer)
+ }
+
+ /** Tells `observeNodeChanges` observers that `node` is about to change. */
+ willChangeNode(node: SceneNode | undefined): void {
+ if (!node) return
+ for (const observer of this.changeObservers) observer.before(node)
+ }
+
countDescendants(nodeId: string): number {
const node = this.nodes.get(nodeId)
if (!node) return 0
@@ -467,6 +486,7 @@ export class SceneGraph {
private registerNode(node: SceneNode, parentId: string | null): SceneNode {
node.parentId = parentId
this.nodes.set(node.id, node)
+ for (const observer of this.changeObservers) observer.created(node)
if (node.type === 'INSTANCE' && node.componentId) {
let set = this.instanceIndex.get(node.componentId)
if (!set) {
@@ -485,7 +505,9 @@ export class SceneGraph {
createNode(type: NodeType, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode {
const node = createDefaultNode(() => this.generateEntityId(), type, overrides)
- this.nodes.get(parentId)?.childIds.push(node.id)
+ const parent = this.nodes.get(parentId)
+ this.willChangeNode(parent)
+ parent?.childIds.push(node.id)
return this.registerNode(node, parentId)
}
createNodeWithId(
@@ -497,7 +519,10 @@ export class SceneGraph {
const node = createDefaultNode(() => id, type, overrides)
node.id = id
const parent = parentId ? this.nodes.get(parentId) : undefined
- if (parent && !parent.childIds.includes(id)) parent.childIds.push(id)
+ if (parent && !parent.childIds.includes(id)) {
+ this.willChangeNode(parent)
+ parent.childIds.push(id)
+ }
return this.registerNode(node, parentId)
}
@@ -640,6 +665,7 @@ export class SceneGraph {
absent: readonly (keyof SceneNode)[] = []
): void {
const { id } = node
+ this.willChangeNode(node)
// Include removed keys in cache invalidation and update notifications.
if (absent.length) {
changes = { ...changes }
@@ -690,6 +716,9 @@ export class SceneGraph {
if (node.parentId === newParentId) return
const oldParentId = node.parentId
+ this.willChangeNode(node)
+ this.willChangeNode(oldParent)
+ this.willChangeNode(newParent)
this.absPosCache.clear()
const oldParentWorld = this.parentWorldMatrix(oldParent)
@@ -726,6 +755,9 @@ export class SceneGraph {
const oldParent = previousParentId ? this.nodes.get(previousParentId) : undefined
const newParent = this.nodes.get(parentId)
if (!newParent || this.isDescendant(parentId, nodeId)) return
+ this.willChangeNode(node)
+ this.willChangeNode(oldParent)
+ this.willChangeNode(newParent)
// Remove from old parent
if (oldParent) {
@@ -755,6 +787,9 @@ export class SceneGraph {
if (!node || !newParent || childId === parentId || this.isDescendant(parentId, childId)) return
const previousParentId = node.parentId
const oldParent = previousParentId ? this.getNode(previousParentId) : undefined
+ this.willChangeNode(node)
+ this.willChangeNode(oldParent)
+ this.willChangeNode(newParent)
if (oldParent) {
oldParent.childIds = oldParent.childIds.filter((id) => id !== childId)
}
@@ -768,9 +803,11 @@ export class SceneGraph {
deleteNode(id: string): void {
const node = this.nodes.get(id)
if (!node || id === this.rootId) return
+ this.willChangeNode(node)
if (node.parentId) {
const parent = this.nodes.get(node.parentId)
+ this.willChangeNode(parent)
if (parent) {
parent.childIds = parent.childIds.filter((cid) => cid !== id)
}
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 0843df1b5..df8e60856 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -33,6 +33,14 @@ export type SceneGraphEventHandlers = Partial<{
) => void
}>
+/** Hears about nodes as an edit adds and changes them, synchronously and before each change. */
+export interface NodeChangeObserver {
+ /** A node is about to change and is still as it was. */
+ before: (node: SceneNode) => void
+ /** A node was just added. */
+ created: (node: SceneNode) => void
+}
+
export type DocumentColorSpace = 'srgb' | 'display-p3'
export interface FigmaSourcePayload {
diff --git a/packages/scene-graph/src/undo.ts b/packages/scene-graph/src/undo.ts
index ca1811b1f..48a819d04 100644
--- a/packages/scene-graph/src/undo.ts
+++ b/packages/scene-graph/src/undo.ts
@@ -55,6 +55,16 @@ export class UndoManager {
this.pushUndoEntry(entry)
}
+ /**
+ * Records an entry as a step of its own, outside the batches being built, such as an agent's
+ * edit made while a colour picker is open. Batches settle first, so the step follows the
+ * changes they hold so far.
+ */
+ pushStep(entry: UndoEntry): void {
+ this.settle()
+ this.pushUndoEntry(entry)
+ }
+
/**
* Registers a hook that commits an edit still being coalesced, such as a run of picker changes.
* Undo and redo run every hook first, so they act on the newest change.
diff --git a/packages/scene-graph/src/variables.ts b/packages/scene-graph/src/variables.ts
index 782605068..a4f8731df 100644
--- a/packages/scene-graph/src/variables.ts
+++ b/packages/scene-graph/src/variables.ts
@@ -39,6 +39,7 @@ export function removeVariable(graph: SceneGraph, id: string): void {
for (const node of graph.nodes.values()) {
const hadBinding = Object.values(node.boundVariables).includes(id)
if (!hadBinding) continue
+ graph.willChangeNode(node)
node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<
string,
string
@@ -399,6 +400,7 @@ export function bindVariable(
throw new Error(`Unknown binding field "${field}"`)
}
+ graph.willChangeNode(node)
node.boundVariables = { ...node.boundVariables, [field]: variableId }
assignVariableBindingUnits(graph, node, field)
markBoundVariablesOverrideOnInstance(graph, nodeId, field)
@@ -412,6 +414,7 @@ export function unbindVariable(graph: SceneGraph, nodeId: string, field: string)
const node = graph.nodes.get(nodeId)
if (!node) return
if (!(field in node.boundVariables)) return
+ graph.willChangeNode(node)
node.boundVariables = omit(node.boundVariables, [field])
node.variableBindingScales = omit(node.variableBindingScales, [field])
markBoundVariablesOverrideOnInstance(graph, nodeId, field)
diff --git a/packages/scene-graph/tests/undo/batch.test.ts b/packages/scene-graph/tests/undo/batch.test.ts
index c191b2255..3873107af 100644
--- a/packages/scene-graph/tests/undo/batch.test.ts
+++ b/packages/scene-graph/tests/undo/batch.test.ts
@@ -73,3 +73,26 @@ test('a pending batch that will settle counts as undoable', () => {
expect(undo.canUndo).toBe(true)
expect(undo.undo()).toBe('Change fill')
})
+
+// An agent's edit lands while a picker is still coalescing: it is a step of its own, after the
+// picker's changes so far, rather than part of the picker's step.
+test('a step pushed during a settling batch stays its own step, in order', () => {
+ const undo = new UndoManager()
+ const noop = () => undefined
+ const entry = (label: string) => ({ label, forward: noop, inverse: noop })
+ undo.beginBatch('Change fill')
+ undo.push(entry('Picker'))
+ undo.onBeforeHistory(() => {
+ if (!undo.isBatching) return
+ undo.commitBatch()
+ undo.beginBatch('Change fill')
+ })
+
+ undo.pushStep(entry('Agent: set_fill'))
+ undo.push(entry('Picker again'))
+
+ expect(undo.undo()).toBe('Change fill')
+ expect(undo.undo()).toBe('Agent: set_fill')
+ expect(undo.undo()).toBe('Change fill')
+ expect(undo.canUndo).toBe(false)
+})
diff --git a/src/app/ai/tools/catalog.ts b/src/app/ai/tools/catalog.ts
index 5545975d7..4522c82e5 100644
--- a/src/app/ai/tools/catalog.ts
+++ b/src/app/ai/tools/catalog.ts
@@ -7,7 +7,24 @@ const defaultNames = new Set([
...CORE_TOOLS.map((tool) => tool.name),
'get_components',
'list_libraries',
- 'insert_library_component'
+ 'insert_library_component',
+ // Scripts cannot discover comments, so without these the model fakes them with layers.
+ 'get_comments',
+ 'add_comment',
+ 'reply_to_comment',
+ 'resolve_comment',
+ // Design JSX references variables but cannot create them, and `eval` names differ from Figma's.
+ 'list_variables',
+ 'create_collection',
+ 'create_variable',
+ 'set_variable',
+ 'bind_variable',
+ 'lint',
+ 'lint_fix',
+ // Lets the model look at what it built.
+ 'export_image',
+ 'list_pages',
+ 'create_page'
])
export const aiToolDefinitions = ALL_TOOLS.filter((tool) => isToolExposed(tool, 'ai'))
diff --git a/src/app/ai/tools/changes/capture.ts b/src/app/ai/tools/changes/capture.ts
index 856929ddd..ab79cf0c4 100644
--- a/src/app/ai/tools/changes/capture.ts
+++ b/src/app/ai/tools/changes/capture.ts
@@ -1,8 +1,13 @@
import { diffLines, type ChangeObject } from 'diff'
-import { compact } from 'es-toolkit/array'
+import { compact, uniq } from 'es-toolkit/array'
-import { graphFromPageChange, isEmptyPageChange, type PageChange } from '@open-pencil/core/editor'
+import {
+ graphFromDocumentChange,
+ isEmptyDocumentChange,
+ type DocumentChange
+} from '@open-pencil/core/editor'
import { diffPageLayersJSX } from '@open-pencil/core/tools'
+import type { SceneGraph } from '@open-pencil/scene-graph'
import { changePreviewSize } from '@/app/ai/chat/preferences'
import type { EditorStore } from '@/app/editor/active-store'
@@ -46,24 +51,34 @@ export function clipChangedJSX(before: string, after: string): [string, string]
return [clip(before), clip(after)]
}
+/** The first page, the call's own one first, whose layers the change added, removed, or changed. */
+function changedPage(before: SceneGraph, after: SceneGraph, change: DocumentChange) {
+ for (const pageId of uniq([change.pageId, ...change.pageIds])) {
+ const layers = diffPageLayersJSX(before, after, pageId)
+ if (layers.length > 0) return { pageId, layers }
+ }
+ return null
+}
+
/**
- * Records what a finished call changed on its page, called right after it while the page is as
- * the call left it. The structural diff is immediate; images render afterwards from frozen
- * copies of both states, so later edits cannot leak into them.
+ * Records what a finished call changed, called right after it while the document is as the call
+ * left it. The review shows one page: the one the call ran on when its layers changed, otherwise
+ * the first other page whose layers did. The structural diff is immediate; images render
+ * afterwards from frozen copies of both states, so later edits cannot leak into them.
*/
export function recordToolChange(
store: EditorStore,
toolCallId: string,
- pageChange: PageChange
+ documentChange: DocumentChange
): ToolChange | null {
- if (isEmptyPageChange(pageChange)) return null
- const beforeGraph = graphFromPageChange(store.graph, pageChange, 'before')
- const afterGraph = graphFromPageChange(store.graph, pageChange, 'after')
- const { pageId } = pageChange
+ if (isEmptyDocumentChange(documentChange)) return null
+ const beforeGraph = graphFromDocumentChange(store.graph, documentChange, 'before')
+ const afterGraph = graphFromDocumentChange(store.graph, documentChange, 'after')
if (!beforeGraph || !afterGraph) return null
// The same JSX diff `diff_jsx` returns decides which layers changed.
- const layers = diffPageLayersJSX(beforeGraph, afterGraph, pageId)
- if (layers.length === 0) return null
+ const shown = changedPage(beforeGraph, afterGraph, documentChange)
+ if (!shown) return null
+ const { pageId, layers } = shown
const nodeIds = layers.map((layer) => layer.id)
const [jsxBefore, jsxAfter] = clipChangedJSX(
joinJSX(layers.map((layer) => layer.before)),
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.ts
index e3cb0885b..48046d772 100644
--- a/src/app/ai/tools/index.ts
+++ b/src/app/ai/tools/index.ts
@@ -1,6 +1,6 @@
import { tool } from 'ai'
-import { graphFromPageSnapshot, isEmptyPageChange } from '@open-pencil/core/editor'
+import { graphFromPageSnapshot, isEmptyDocumentChange } from '@open-pencil/core/editor'
import type { FigmaAPI } from '@open-pencil/core/figma-api'
import {
registerComponentCatalog,
@@ -87,17 +87,17 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost
recordRunBaseline(store, store.snapshotPage(pageId))
}
const undoBefore = store.undo.peekUndo()
- const finishChange = store.capturePageChange(pageId)
+ const finishChange = store.captureDocumentChange(pageId)
try {
return await runTool(def, figma, args, pageId)
} finally {
const change = finishChange()
// Atomic tools record their own undo entry; an edit that changed nothing records none.
- if (!isAtomicTool(def) && !isEmptyPageChange(change)) {
- store.pushUndoEntry({
+ if (!isAtomicTool(def) && !isEmptyDocumentChange(change)) {
+ store.pushUndoStep({
label: `AI: ${def.name}`,
- forward: () => store.restorePageChange(change, 'after'),
- inverse: () => store.restorePageChange(change, 'before')
+ forward: () => store.restoreDocumentChange(change, 'after'),
+ inverse: () => store.restoreDocumentChange(change, 'before')
})
}
// Every entry the run pushes belongs to its turn; atomic and page edits both label
diff --git a/src/app/automation/bridge/eval-handler.ts b/src/app/automation/bridge/eval-handler.ts
index 3d5325812..7d62cb458 100644
--- a/src/app/automation/bridge/eval-handler.ts
+++ b/src/app/automation/bridge/eval-handler.ts
@@ -2,7 +2,7 @@ import type { FigmaAPI } from '@open-pencil/core/figma-api'
import { compileScript } from '@open-pencil/core/tools'
import type { AutomationTarget } from '@/app/automation/bridge/target'
-import { automationUndoLabel, executeWithPageUndo } from '@/app/automation/execution/editor'
+import { automationUndoLabel, executeWithDocumentUndo } from '@/app/automation/execution/editor'
import { ensureGraphFonts } from '@/app/editor/fonts'
type FigmaFactory = (store: AutomationTarget['store'], pageId?: string) => FigmaAPI
@@ -13,7 +13,7 @@ export function createAutomationEvalHandler(makeFigma: FigmaFactory) {
if (!code) throw new Error('Missing "code" in args')
const figma = makeFigma(target.store, target.pageId)
const run = compileScript(code)
- const result = await executeWithPageUndo(
+ const result = await executeWithDocumentUndo(
target.store,
target.pageId,
automationUndoLabel('eval'),
diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.ts
index fdbcd3fed..b9397628e 100644
--- a/src/app/automation/bridge/tool-handlers.ts
+++ b/src/app/automation/bridge/tool-handlers.ts
@@ -20,7 +20,7 @@ import {
AUTOMATION_UNDO_LABEL,
automationUndoLabel,
executeAtomicEditorTool,
- executeWithPageUndo
+ executeWithDocumentUndo
} from '@/app/automation/execution/editor'
import { ensureGraphFonts } from '@/app/editor/fonts'
import { useLibraryService } from '@/app/libraries'
@@ -82,7 +82,7 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
)
// View tools (selection, viewport, pages) leave the document and its history alone.
result = toolChangesDocument(def)
- ? await executeWithPageUndo(store, pageId, automationUndoLabel(def.name), mutate)
+ ? await executeWithDocumentUndo(store, pageId, automationUndoLabel(def.name), mutate)
: await mutate()
} else {
result = await def.execute(figma, toolArgs)
diff --git a/src/app/automation/execution/editor.ts b/src/app/automation/execution/editor.ts
index 07dd9e676..238c96685 100644
--- a/src/app/automation/execution/editor.ts
+++ b/src/app/automation/execution/editor.ts
@@ -1,4 +1,4 @@
-import { executeAtomicTool, isEmptyPageChange } from '@open-pencil/core/editor'
+import { executeAtomicTool, isEmptyDocumentChange } from '@open-pencil/core/editor'
import type { FigmaAPI } from '@open-pencil/core/figma-api'
import type { ToolDef } from '@open-pencil/core/tools'
@@ -42,26 +42,27 @@ export async function executeAtomicEditorTool(
}
/**
- * Run a structural edit as one undo step by recording what it changes on its page, as the AI
- * chat does, so `undo` reverts what an automation client created, moved, or deleted.
+ * Run a structural edit as one undo step by recording what it changes in the document, as the
+ * AI chat does, so `undo` reverts what an automation client created, moved, or deleted on any
+ * page, and the variables it changed.
*/
-export async function executeWithPageUndo<T>(
+export async function executeWithDocumentUndo<T>(
store: EditorStore,
pageId: string,
label: string,
run: () => Promise<T>
): Promise<T> {
- const finishChange = store.capturePageChange(pageId)
+ const finishChange = store.captureDocumentChange(pageId)
try {
return await run()
} finally {
const change = finishChange()
// Read-only scripts and no-op edits must not leave empty steps in the user's history.
- if (!isEmptyPageChange(change)) {
- store.pushUndoEntry({
+ if (!isEmptyDocumentChange(change)) {
+ store.pushUndoStep({
label,
- forward: () => store.restorePageChange(change, 'after'),
- inverse: () => store.restorePageChange(change, 'before')
+ forward: () => store.restoreDocumentChange(change, 'after'),
+ inverse: () => store.restoreDocumentChange(change, 'before')
})
}
}
diff --git a/src/theme/comments.ts b/src/theme/comments.ts
index d5aa73ab1..05f1cd486 100644
--- a/src/theme/comments.ts
+++ b/src/theme/comments.ts
@@ -13,7 +13,7 @@ export const comments = tv({
pins: 'absolute top-0 left-0',
// A 32px speech bubble whose square corner points at the commented spot, as Figma draws it;
// hovering opens it in place into a preview of the comment.
- pin: 'group/pin pointer-events-auto absolute flex -translate-y-full cursor-pointer touch-none items-start rounded-2xl rounded-bl-none bg-panel p-1 text-left shadow-md ring-1 ring-black/10 outline-none select-none hover:shadow-lg focus-visible:ring-2 focus-visible:ring-accent data-[active]:ring-2 data-[active]:ring-accent data-[draft]:pointer-events-none data-[draft]:size-8 data-[draft]:bg-accent data-[dragging]:cursor-grabbing data-[dragging]:shadow-lg data-[resolved]:grayscale',
+ pin: 'group/pin pointer-events-auto absolute flex w-max -translate-y-full cursor-pointer touch-none items-start rounded-2xl rounded-bl-none bg-panel p-1 text-left shadow-md ring-1 ring-black/10 outline-none select-none hover:shadow-lg focus-visible:ring-2 focus-visible:ring-accent data-[active]:ring-2 data-[active]:ring-accent data-[draft]:pointer-events-none data-[draft]:size-8 data-[draft]:bg-accent data-[dragging]:cursor-grabbing data-[dragging]:shadow-lg data-[resolved]:grayscale',
// Grows from nothing to its content's size, so the bubble opens smoothly in both directions.
pinPreview:
'grid grid-cols-[0fr] grid-rows-[0fr] opacity-0 transition-[grid-template-columns,grid-template-rows,opacity] duration-150 ease-out group-hover/pin:grid-cols-[1fr] group-hover/pin:grid-rows-[1fr] group-hover/pin:opacity-100 group-focus-visible/pin:grid-cols-[1fr] group-focus-visible/pin:grid-rows-[1fr] group-focus-visible/pin:opacity-100 motion-reduce:transition-none',
diff --git a/tests/app/ai/tools/changes/capture.test.ts b/tests/app/ai/tools/changes/capture.test.ts
index effc44455..6c1340d8f 100644
--- a/tests/app/ai/tools/changes/capture.test.ts
+++ b/tests/app/ai/tools/changes/capture.test.ts
@@ -65,6 +65,18 @@ test('records the layers a call changed with their JSX before and after', async
expect(change?.images).toBeUndefined()
})
+test('records a call that changed only another page on that page', async () => {
+ const second = store.graph.addPage('Settings')
+ const card = store.graph.createNode('FRAME', second.id, { name: 'Profile', width: 100 })
+
+ await execute('set_fill', { id: card.id, color: '#ff0000' }, 'other-page-call')
+
+ const change = readToolChange('other-page-call')
+ expect(change?.pageId).toBe(second.id)
+ expect(change?.nodeIds).toEqual([card.id])
+ expect(change?.jsx.after).toContain('#FF0000')
+})
+
test('records nothing for calls that leave the page as it was', async () => {
const card = store.graph.createNode('FRAME', store.state.currentPageId, { name: 'Card' })
await execute('get_node', { id: card.id }, 'read-call')
diff --git a/tests/app/automation/bridge/handlers.test.ts b/tests/app/automation/bridge/handlers.test.ts
index 86e9b92c3..747b68b98 100644
--- a/tests/app/automation/bridge/handlers.test.ts
+++ b/tests/app/automation/bridge/handlers.test.ts
@@ -218,6 +218,40 @@ describe('undo and redo', () => {
expect(graph.getNode(frame.id)?.childIds).toEqual([placeholder.id])
})
+ test('undo reverts a script’s edits to other pages, pages, and variables', async () => {
+ const tab = createTab()
+ const graph = tab.store.graph
+ const otherPage = graph.addPage('Other')
+ const card = graph.createNode('FRAME', otherPage.id, { name: 'Card', width: 200, height: 200 })
+ const pages = graph.getPages().map((page) => page.id)
+ await request('eval', {
+ document_id: tab.id,
+ code: `
+ const other = figma.root.children.find((page) => page.name === 'Other')
+ other.findOne((node) => node.name === 'Card').name = 'Renamed'
+ other.name = 'Renamed page'
+ figma.createPage().name = 'Added'
+ const colors = figma.createVariableCollection('Colors')
+ figma.createVariable('Brand', 'COLOR', colors.id)
+ `
+ })
+ expect(graph.getNode(card.id)?.name).toBe('Renamed')
+ expect(graph.variables.size).toBe(1)
+
+ const undone = await request('undo', { document_id: tab.id })
+ expect(undone.result).toMatchObject({ applied: true, label: 'Agent: eval' })
+ expect(graph.getNode(card.id)?.name).toBe('Card')
+ expect(graph.getNode(otherPage.id)?.name).toBe('Other')
+ expect(graph.getPages().map((page) => page.id)).toEqual(pages)
+ expect(graph.variables.size).toBe(0)
+ expect(graph.variableCollections.size).toBe(0)
+
+ await request('redo', { document_id: tab.id })
+ expect(graph.getNode(card.id)?.name).toBe('Renamed')
+ expect(graph.getPages().map((page) => page.name)).toEqual(['Page 1', 'Renamed page', 'Added'])
+ expect(graph.variables.size).toBe(1)
+ })
+
test('a read-only eval leaves the history unchanged', async () => {
const tab = createTab()
await request('eval', { document_id: tab.id, code: 'return figma.currentPage.name' })
diff --git a/tests/app/comments/session.test.ts b/tests/app/comments/session.test.ts
index 8535386f3..e3adc2811 100644
--- a/tests/app/comments/session.test.ts
+++ b/tests/app/comments/session.test.ts
@@ -5,7 +5,7 @@ import { FigmaAPI } from '@open-pencil/core/figma-api'
import { ALL_TOOLS } from '@open-pencil/core/tools'
import { readComments, writeComments, type CommentThread } from '@open-pencil/scene-graph'
-import { executeWithPageUndo } from '@/app/automation/execution/editor'
+import { executeWithDocumentUndo } from '@/app/automation/execution/editor'
import { useComments } from '@/app/comments/use'
import { setActiveEditorStore } from '@/app/editor/active-store'
import { createEditorStore } from '@/app/editor/session/create'
@@ -140,7 +140,7 @@ test('an agent’s comment is not an undo step either, as comments stay out of u
const addComment = ALL_TOOLS.find((tool) => tool.name === 'add_comment')
if (!addComment) throw new Error('add_comment missing')
- await executeWithPageUndo(store, store.state.currentPageId, 'Agent: add_comment', () =>
+ await executeWithDocumentUndo(store, store.state.currentPageId, 'Agent: add_comment', () =>
Promise.resolve(addComment.execute(figma, { text: 'Tighten the spacing', x: 4, y: 4 }))
)
await Promise.resolve()
diff --git a/tests/engine/app/settings/ai-tool-access.test.ts b/tests/engine/app/settings/ai-tool-access.test.ts
index f3175144a..db11844aa 100644
--- a/tests/engine/app/settings/ai-tool-access.test.ts
+++ b/tests/engine/app/settings/ai-tool-access.test.ts
@@ -29,6 +29,26 @@ test('AI catalog includes exposed extended tools while preserving compact defaul
expect(defaults).toContain('get_components')
expect(defaults).toContain('list_libraries')
expect(defaults).toContain('insert_library_component')
+ for (const name of [
+ 'get_comments',
+ 'add_comment',
+ 'reply_to_comment',
+ 'resolve_comment',
+ 'list_variables',
+ 'create_collection',
+ 'create_variable',
+ 'set_variable',
+ 'bind_variable',
+ 'lint',
+ 'lint_fix',
+ 'export_image',
+ 'list_pages',
+ 'create_page'
+ ]) {
+ expect(defaults).toContain(name)
+ }
+ // Moving the view stays the user's choice.
+ expect(defaults).not.toContain('switch_page')
expect(defaults).not.toContain('create_component')
expect(enabledAIToolDefinitions({ create_component: true }).map((tool) => tool.name)).toContain(
'create_component'