AI-native design editor. Open-source Figma alternative.
perf: record atomic agent edits by the layers they touch (#1639)
Valery Komarov8753f84194e1
diff --git a/changes/1639/performance.md b/changes/1639/performance.mdnew file mode 100644index 000000000..d01592f70--- /dev/null+++ b/changes/1639/performance.md@@ -0,0 +1 @@+- AI and MCP agents can edit properties in documents of any size: a one-property edit copies only the layers it changes, so it takes milliseconds instead of seconds on large files and is no longer refused above 10 000 layers.diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex 11417dae7..127d12d5b 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -11,7 +11,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do- `.pen` documents draw as pen.dev draws them. `bun tools/generate/visual-oracles/src/cli.ts compare pen` exports every frame of the document open in pen.dev into `tests/fixtures/pen-oracles/` with the icons and fonts it uses; a new reading rule adds a probe frame there and a threshold to its `manifest.json` (`packages/core/tests/io/formats/pen/oracle.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`).-- An edit that records the document changes it makes, as AI and MCP calls do, runs through `recordEdit`, or `recordEditAsync` when it awaits, which keeps the edit open until its step is recorded so undoing it returns the document to saved; capturing a change by hand fails `open-pencil/no-document-change-capture` (`packages/core/tests/editor/history/edit.test.ts`).+- An edit that records the document changes it makes, as AI and MCP calls do apart from atomic tools (Tools), runs through `recordEdit`, or `recordEditAsync` when it awaits, which keeps the edit open until its step is recorded so undoing it returns the document to saved; capturing a change by hand fails `open-pencil/no-document-change-capture` (`packages/core/tests/editor/history/edit.test.ts`).- The recording copies only what an edit touches: 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@@ -36,7 +36,10 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do- Operations are `ToolDef`s under `packages/core/src/tools/**`; `schema.ts` defines the contract and registries expose them. Each definition owns its native Valibot `input`, execution/mutation metadata, and optional per-interface exposure exclusions (`mcp`, `ai`, `webmcp`). Exposure defaults to inclusion; adapters use `isToolExposed()`, then apply execution support and user permissions independently.- Infer arguments from the schema; derive effects and default capabilities from execution metadata. Do not maintain parameter DSLs or tool-name lists. Add work to the nearest existing domain and the appropriate registry.- `packages/core/src/tools/ai-adapter.ts` converts ToolDefs for Vercel AI; the app binds them to the active editor's `FigmaAPI` in `src/app/ai/tools/index.ts`. MCP v2 registration uses Standard Schema with Valibot JSON Schema conversion; AI and WebMCP adapters share the same input contract.-- `packages/core/src/editor/history/atomic-tool.ts` owns synchronous property/variable transactions; Scene Graph owns checkpoint recovery. AI, MCP, and WebMCP share this execution path. Async and structural tools cannot declare atomic property execution.+- `packages/core/src/editor/history/atomic-tool.ts` owns synchronous property/variable transactions for AI, MCP, and WebMCP and records their undo step itself, not through `recordEdit`; Scene Graph owns checkpoint recovery. Async and structural tools cannot declare atomic property execution (`packages/core/src/tools/schema.ts`).+- An atomic tool writes layers through graph methods, or reports a layer with `willChangeNode` before writing into it, since a transaction copies only the layers the graph reports and their ancestors below the page (`captureTouchedCheckpoint`) (`packages/core/tests/editor/history/atomic/tools.test.ts`).+- An atomic transaction, its undo, and its redo lay out each changed layer once, as the outermost auto-layout frame holding it where there is one, so changed siblings share one layout of their parent; every page is laid out only when a variable changed (`packages/core/tests/editor/history/atomic/layout.test.ts`).+- One atomic call changes at most 10 000 layers, and a larger one is rolled back with an error asking for fewer layers per call (`packages/core/tests/editor/history/atomic/tools.test.ts`).- Shared scene-authoring guidance and tested examples live under `packages/design-jsx/src/reference/`; `reference/index.ts` combines them with renderer metadata. Prompts under `packages/core/src/tools/prompts/` and the app chat/ACP prompt compose that reference rather than copying it. Run `bun run generate:authoring-reference` after changes; `check:authoring-reference` (part of `check:docs`) verifies the committed skill/docs copies. Do not edit generated reference files.- The installable agent skill is maintained in `skills/open-pencil/`. Changes to agent-facing APIs, CLI/MCP behavior, or design authoring must update affected skill examples, prompts, and public documentation in the same change. Keep examples valid in their actual execution environment; do not advertise library exports as scripting globals unless exposed there. Prefer runtime discovery and canonical references over duplicated API/tool inventories.- MCP-only tools and transports: `packages/mcp/AGENTS.md`. WebMCP registration and app completion: `src/AGENTS.md`.diff --git a/packages/core/src/editor/history/atomic-tool.ts b/packages/core/src/editor/history/atomic-tool.tsindex f1ac193c1..6fcc63591 100644--- a/packages/core/src/editor/history/atomic-tool.ts+++ b/packages/core/src/editor/history/atomic-tool.ts@@ -1,5 +1,5 @@-import type { SceneGraph, SceneNode, Variable } from '@open-pencil/scene-graph'-import { captureGraphCheckpoint } from '@open-pencil/scene-graph/checkpoint'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { captureTouchedCheckpoint } from '@open-pencil/scene-graph/checkpoint'import type { Editor } from '#core/editor/create'import { ReadOnlyDocumentError } from '#core/editor/read-only'@@ -7,10 +7,20 @@ import { resolveEditorProfile, type EditorProfileInputs } from '#core/editor/vieimport type { FigmaAPI } from '#core/figma-api'import { isAtomicTool, type ToolDef } from '#core/tools/schema'-import { diffFields, type FieldChanges } from './diff'+import {+ applyDocumentChange,+ countChangedLayers,+ documentChangeFromCheckpoint,+ emptyDocumentChange,+ recordChanges,+ type DocumentChange+} from './document-change'-// Capture property changes across pages. Component synchronization remains editor-owned.-const MAX_TRANSACTION_NODES = 10_000+/**+ * The most layers one atomic edit may change. Layout that follows it is not counted, and neither+ * is a write of the value a layer already had.+ */+const MAX_ATOMIC_CHANGED_LAYERS = 10_000type MutationEditor = Pick<Editor,@@ -19,22 +29,23 @@ type MutationEditor = Pick<state: EditorProfileInputs}-function changes<T extends object>(- before: Map<string, T>,- after: Map<string, T>-): FieldChanges<T>[] {- const result: FieldChanges<T>[] = []- for (const [id, previous] of before) {- const current = after.get(id)- if (!current) throw new Error('Atomic tools must not remove nodes or variables')- const change = diffFields(id, previous, current)- if (change) result.push(change)- }- if (before.size !== after.size) throw new Error('Atomic tools must not create nodes or variables')- return result+export interface AtomicToolOptions {+ signal?: AbortSignal+ isLive?: () => boolean+ label?: string+ /**+ * Called once after preflight: the committed step's change, or an empty change for no-op,+ * source-only or rolled-back calls.+ */+ onRecorded?: (change: DocumentChange) => void}/**+ * Runs a tool that only changes properties of layers and variables, anywhere in the document, as+ * one undo step, and rolls it back whole when it fails. It records the layers the graph reports+ * it changing (`SceneGraph.observeNodeChanges`), so its cost follows what it touches rather than+ * the document's size. Component synchronization remains editor-owned.+ ** No await is permitted between snapshot and commit. Browser events, other agents and* cancellation cannot interleave with this bounded transaction. Async tools use their* existing execution path and are not exposed through WebMCP.@@ -44,7 +55,7 @@ export function executeAtomicTool(figma: FigmaAPI,def: ToolDef,args: Record<string, unknown>,- options: { signal?: AbortSignal; isLive?: () => boolean; label?: string } = {}+ options: AtomicToolOptions = {}): unknown {if (!isAtomicTool(def)) throw new Error(`Not an atomic tool: ${def.name}`)if (!resolveEditorProfile(editor.state).edits) throw new ReadOnlyDocumentError()@@ -53,40 +64,18 @@ export function executeAtomicTool(throw new Error('The target document is no longer open')}const graph = figma.graph- if (graph.nodes.size + graph.variables.size > MAX_TRANSACTION_NODES) {- throw new Error('Document too large for atomic agent editing (maximum 10000 nodes)')- }- const checkpoint = captureGraphCheckpoint(graph)- const { nodes, variables } = checkpointconst pageId = figma.currentPageId+ const checkpoint = captureTouchedCheckpoint(graph)+ let recorded = emptyDocumentChange(pageId)- const replay = (- nodeChanges: FieldChanges<SceneNode>[],- variableChanges: FieldChanges<Variable>[],- direction: 'before' | 'after'- ) => {+ const replay = (change: DocumentChange, side: 'before' | 'after') => {if (editor.graph !== graph) throw new Error('The target document has been replaced')- for (const change of variableChanges) {- const variable = graph.variables.get(change.id)- if (variable) {- Object.assign(variable, structuredClone(change[direction]))- for (const key of change.absent[direction]) Reflect.deleteProperty(variable, key)- }- }- graph.preserveSourceMetadataDuring(() => {- for (const change of nodeChanges)- graph.restoreNodeProperties(- change.id,- structuredClone(change[direction]),- change.absent[direction]- )- })+ applyDocumentChange(graph, change, side)layout(graph,editor,- pageId,- variableChanges.length > 0,- nodeChanges.map((change) => change.id)+ change.variables.length > 0,+ change.updated.map((update) => update.id))editor.requestRender()}@@ -98,25 +87,28 @@ export function executeAtomicTool(throw new Error(String(result.error))}checkpoint.assertPropertiesOnly()- const variableChanges = changes(variables, graph.variables)- layout(- graph,- editor,- pageId,- variableChanges.length > 0,- changes(nodes, graph.nodes).map((change) => change.id)- )- const nodeChanges = changes(nodes, graph.nodes)+ const changed = countChangedLayers(graph, checkpoint)+ if (changed > MAX_ATOMIC_CHANGED_LAYERS) {+ throw new Error(+ `This edit changes ${changed} layers; one atomic agent edit may change at most ${MAX_ATOMIC_CHANGED_LAYERS}. Change fewer layers per call.`+ )+ }+ const records = recordChanges(graph, checkpoint)+ layout(graph, editor, records.variables.length > 0, checkpoint.reported)+ // Layout must not restructure the document either.+ checkpoint.assertPropertiesOnly()+ checkpoint.stop()+ const change = documentChangeFromCheckpoint(graph, pageId, checkpoint, records)const contentChanged =- variableChanges.length > 0 ||- nodeChanges.some((change) => Object.keys(change.after).some((key) => key !== 'source'))- if (!contentChanged && nodeChanges.length) replay(nodeChanges, [], 'before')+ change.variables.length > 0 || change.updated.some((update) => update.fields)+ if (!contentChanged && change.updated.length) replay(change, 'before')if (contentChanged) {editor.pushUndoStep({label: `${options.label ?? 'Agent'}: ${def.name}`,- inverse: () => replay(nodeChanges, variableChanges, 'before'),- forward: () => replay(nodeChanges, variableChanges, 'after')+ inverse: () => replay(change, 'before'),+ forward: () => replay(change, 'after')})+ recorded = changeeditor.requestRender()}return result@@ -124,22 +116,48 @@ export function executeAtomicTool(checkpoint.restore()editor.requestRender()throw error+ } finally {+ options.onRecorded?.(recorded)}}+/**+ * Lays out the layers an edit changed, as the editor lays out a user's edit: each changed layer+ * with its subtree and the auto-layout frames around it. Bound values follow variables anywhere,+ * so a variable change lays out every page.+ */function layout(graph: SceneGraph,editor: MutationEditor,- pageId: string,allPages: boolean,- changedIds: string[]+ changedIds: Iterable<string>): void {- const scopes = new Set(allPages ? graph.getPages().map((page) => page.id) : [pageId])- for (const id of changedIds) {- let node = graph.getNode(id)- while (node && node.type !== 'CANVAS')- node = node.parentId ? graph.getNode(node.parentId) : undefined- if (node) scopes.add(node.id)+ const pages = new Set(allPages ? graph.getPages().map((page) => page.id) : [])+ for (const id of pages) editor.runLayoutForNode(id)+ for (const id of layoutScopes(graph, changedIds)) {+ const page = graph.pageOf(id)+ if (!page || !pages.has(page)) editor.runLayoutForNode(id)+ }+}++/**+ * The layers to lay out for `ids`, each once. A layer in an auto-layout frame is laid out with+ * that frame, and the frame with any auto-layout frame around it, so changed siblings share one+ * layout of their parent rather than each laying it out again. The document node is left out,+ * as laying it out would lay out every page.+ */+function layoutScopes(graph: SceneGraph, ids: Iterable<string>): string[] {+ const inAutoLayout = (node: SceneNode) => {+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined+ return parent !== undefined && parent.layoutMode !== 'NONE'+ }+ const scopes = new Set<string>()+ for (const id of ids) {+ const scope = graph.closest(id, (node) => !inAutoLayout(node))+ if (scope && scope.id !== graph.rootId) scopes.add(scope.id)}- for (const id of scopes) editor.runLayoutForNode(id)+ return [...scopes].filter((id) => {+ const parentId = graph.getNode(id)?.parentId+ return !parentId || !graph.closest(parentId, (node) => scopes.has(node.id))+ })}diff --git a/packages/core/src/editor/history/document-change.ts b/packages/core/src/editor/history/document-change.tsindex 5f8926667..607b3ef98 100644--- a/packages/core/src/editor/history/document-change.ts+++ b/packages/core/src/editor/history/document-change.ts@@ -1,4 +1,4 @@-import { isEqual } from 'es-toolkit'+import { isEqual, omit } from 'es-toolkit'import type {FigmaSourcePayload,@@ -8,6 +8,7 @@ import type {Variable,VariableCollection} from '@open-pencil/scene-graph'+import type { TouchedCheckpoint } from '@open-pencil/scene-graph/checkpoint'import { withLiveComments } from '@open-pencil/scene-graph/comments'import { cloneInstanceOverrideState } from '@open-pencil/scene-graph/instances/overrides'import {@@ -206,7 +207,10 @@ function recordLayer(}}-function diffRecords<T>(previous: Map<string, T>, current: Map<string, T>): RecordChange<T>[] {+function diffRecords<T>(+ previous: ReadonlyMap<string, T>,+ current: ReadonlyMap<string, T>+): RecordChange<T>[] {const ids = new Set([...previous.keys(), ...current.keys()])return [...ids].flatMap((id) => {const before = previous.get(id) ?? null@@ -275,43 +279,116 @@ export function captureDocumentChange(graph: SceneGraph, pageId: string): () =>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([+ const ids = 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+ return buildDocumentChange(graph, pageId, ids, captured, created, {+ variables: diffRecords(variables, graph.variables),+ collections: diffRecords(collections, graph.variableCollections)+ })+ }+}++type RecordChanges = Pick<DocumentChange, 'variables' | 'collections'>++/**+ * The change of the touched layers `ids`, given each one's state before the edit in `previous`,+ * which also gives the ancestors of layers the edit moved or removed. A layer neither in+ * `previous` nor `created` changed without telling observers and has no state to go back to.+ */+function buildDocumentChange(+ graph: SceneGraph,+ pageId: string,+ ids: Iterable<string>,+ previous: Lookup,+ created: ReadonlySet<string>,+ records: RecordChanges+): DocumentChange {+ const change: DocumentChange = {+ ...emptyDocumentChange(pageId),+ variables: records.variables,+ collections: records.collections+ }+ const pageIds = new Set<string>()+ for (const id of ids) {+ const before = previous.get(id)+ if (!before && !created.has(id)) continue+ const current = graph.getNode(id)+ // Comments are never part of an undo step.+ const kept = before && current && id === graph.rootId ? withCommentsOf(before, current) : before+ recordLayer(change, id, kept, current)+ for (const page of [pageOf(previous, 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(previous))+ change.children.before.sort(byDepth(previous))+ return change+}++/** A change that changed nothing, as an edit that failed or did nothing records. */+export function emptyDocumentChange(pageId: string): DocumentChange {+ return {+ pageId,+ pageIds: [],+ created: [],+ deleted: [],+ updated: [],+ children: { before: [], after: [] },+ variables: [],+ collections: []+ }+}++/** The variables and collections an edit changed, against the copies a checkpoint holds. */+export function recordChanges(graph: SceneGraph, checkpoint: TouchedCheckpoint): RecordChanges {+ return {+ variables: diffRecords(checkpoint.variables, graph.variables),+ collections: diffRecords(checkpoint.variableCollections, graph.variableCollections)+ }+}++/**+ * What a property edit observed by `checkpoint` changed, at the cost of the layers it touched:+ * each copied layer is compared with the live one. Layers the checkpoint did not copy are read+ * live, which they still are, so the pages of the copied layers are found.+ */+export function documentChangeFromCheckpoint(+ graph: SceneGraph,+ pageId: string,+ checkpoint: TouchedCheckpoint,+ records: RecordChanges = recordChanges(graph, checkpoint)+): DocumentChange {+ const created = new Set([...checkpoint.reported].filter((id) => !checkpoint.nodes.has(id)))+ // A layer the edit created has no state before it, though the live graph now holds one.+ const previous: Lookup = {+ get: (id) => checkpoint.nodes.get(id) ?? (created.has(id) ? undefined : graph.getNode(id)),+ size: graph.nodes.size+ }+ const ids = [...checkpoint.nodes.keys(), ...created]+ return buildDocumentChange(graph, pageId, ids, previous, created, records)+}++/**+ * How many layers `checkpoint` saw reported whose own fields now differ, children, parent, and+ * source metadata aside: the layers whose content an undo step would hold. A write of the value a+ * layer already had is not counted.+ */+export function countChangedLayers(graph: SceneGraph, checkpoint: TouchedCheckpoint): number {+ const skipped = [...NESTED_FIELDS]+ let count = 0+ for (const id of checkpoint.reported) {+ const previous = checkpoint.nodes.get(id)+ const current = graph.getNode(id)+ const same = previous && current && isEqual(omit(previous, skipped), omit(current, skipped))+ if (!same) count++}+ return count}export function isEmptyDocumentChange(change: DocumentChange): boolean {diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex 9335808d1..7d7f2c1b9 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -27,7 +27,7 @@ export {pickEditorViewState} from './state/view'export { createDefaultEditorState, createEditor } from './create'-export { executeAtomicTool } from './history/atomic-tool'+export { executeAtomicTool, type AtomicToolOptions } from './history/atomic-tool'export { isEmptyDocumentChange, type DocumentChange } from './history/document-change'export type { RecordEditOptions } from './history/edit'export type { PageSnapshot } from './history/snapshot/page'diff --git a/packages/core/tests/editor/history/atomic/contract.test.ts b/packages/core/tests/editor/history/atomic/contract.test.tsnew file mode 100644index 000000000..4d32b748a--- /dev/null+++ b/packages/core/tests/editor/history/atomic/contract.test.ts@@ -0,0 +1,219 @@+import { beforeAll, describe, expect, test } from 'bun:test'++import { registerTestFont } from '#core-tests/helpers/figma-api'++import { createEditor, executeAtomicTool, type DocumentChange } from '@open-pencil/core'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { OpenPencilAPI } from '@open-pencil/core/openpencil-api'+import { ALL_TOOLS, type ToolDef } from '@open-pencil/core/tools'+import type { SceneGraph } from '@open-pencil/scene-graph'+import { captureGraphCheckpoint } from '@open-pencil/scene-graph/checkpoint'++import { diffFields } from '#core/editor/history/diff'+import { isAtomicTool } from '#core/tools/schema'++beforeAll(() => registerTestFont())++/**+ * The contract of `executeAtomicTool`: it records a layer or variable only if the graph reports+ * it, so a tool that writes without reporting would leave an undo step that misses the write. A+ * full-graph diff (`captureGraphCheckpoint`, O(document), tests only) is the oracle.+ */++interface Targets {+ /** Auto-layout row holding `rect` and `text`. */+ frame: string+ rect: string+ text: string+ /**+ * A layer whose position, rotation and constraints the tools may change: inside an instance+ * those cannot be overridden (the tools refuse), so there it is the instance itself.+ */+ placed: string+}++function build() {+ const editor = createEditor()+ const graph = editor.graph+ const figma = new FigmaAPI(graph)+ const current = graph.getPages()[0]+ const other = graph.addPage('Other')+ expect(figma.currentPageId).toBe(current.id)+ graph.createNode('RECTANGLE', current.id, { name: 'Current page rectangle' })++ const collection = figma.variables.createVariableCollection('Tokens')+ const color = figma.variables.createVariable('Brand', collection, 'COLOR')+ color.setValueForMode(collection.defaultModeId, { r: 1, g: 0, b: 0, a: 1 })+ const size = figma.variables.createVariable('Size', collection, 'FLOAT')+ size.setValueForMode(collection.defaultModeId, 8)++ const row = (parentId: string, name: string): Targets => {+ const frame = graph.createNode('FRAME', parentId, {+ name,+ width: 200,+ height: 100,+ layoutMode: 'HORIZONTAL',+ itemSpacing: 4+ })+ const rect = graph.createNode('RECTANGLE', frame.id, {+ name: `${name} rect`,+ width: 40,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 1, a: 1 }, opacity: 1, visible: true }]+ })+ const text = graph.createNode('TEXT', frame.id, {+ name: `${name} text`,+ text: 'Hello world',+ fontSize: 14,+ width: 80,+ height: 20+ })+ return { frame: frame.id, rect: rect.id, text: text.id, placed: rect.id }+ }+ const plain = row(other.id, 'Plain')++ const component = graph.createNode('COMPONENT', other.id, { name: 'Card' })+ const inner = row(component.id, 'Inner')+ const instance = graph.createInstance(component.id, other.id)+ if (!instance) throw new Error('Missing instance')+ const [frame] = graph.getChildren(instance.id)+ const [rect, text] = graph.getChildren(frame.id)+ const inInstance: Targets = { frame: frame.id, rect: rect.id, text: text.id, placed: instance.id }+ expect(graph.pageOf(inInstance.rect)).toBe(other.id)+ expect(inInstance.rect).not.toBe(inner.rect)++ // Bound layers, for the variable tools; the binding on an instance layer is its own.+ const api = new OpenPencilAPI(figma)+ for (const targets of [plain, inInstance]) {+ api.bindVariable(targets.rect, 'fills/0/color', color)+ api.bindVariable(targets.rect, 'opacity', size)+ }+ // Undo lays layers out again, so the document starts laid out, as an open one is.+ for (const page of graph.getPages()) editor.runLayoutForNode(page.id)+ return {+ editor,+ figma,+ graph,+ variables: { color: color.id, size: size.id, mode: collection.defaultModeId },+ targets: { plain, 'in an instance': inInstance }+ }+}++type Fixture = ReturnType<typeof build>++/** Arguments of each atomic tool for a set of targets; the key set must be all atomic tools. */+const ARGS: Record<string, (t: Targets, f: Fixture) => Record<string, unknown>> = {+ bind_variable: (t, f) => ({+ node_id: t.rect,+ field: 'cornerRadius',+ variable_id: f.variables.size+ }),+ set_variable: (_t, f) => ({ id: f.variables.color, mode: f.variables.mode, value: '#00ff00' }),+ unbind_variable: (t) => ({ node_id: t.rect, field: 'opacity' }),+ set_text: (t) => ({ id: t.text, text: 'Changed text' }),+ set_font: (t) => ({ id: t.text, family: 'Inter', style: 'Regular', size: 20 }),+ set_font_range: (t) => ({ id: t.text, start: 0, end: 5, size: 22, color: '#ff0000' }),+ set_text_resize: (t) => ({ id: t.text, mode: 'HEIGHT' }),+ set_text_properties: (t) => ({+ id: t.text,+ align_horizontal: 'CENTER',+ align_vertical: 'BOTTOM',+ auto_resize: 'NONE',+ direction: 'RTL',+ text_decoration: 'UNDERLINE'+ }),+ set_rotation: (t) => ({ id: t.placed, angle: 30 }),+ set_opacity: (t) => ({ id: t.rect, value: 0.5 }),+ set_radius: (t) => ({ id: t.rect, radius: 6, top_left: 2 }),+ set_minmax: (t) => ({ id: t.rect, min_width: 10, max_width: 90, min_height: 5, max_height: 80 }),+ set_visible: (t) => ({ id: t.rect, value: false }),+ set_blend: (t) => ({ id: t.rect, mode: 'MULTIPLY' }),+ set_locked: (t) => ({ id: t.rect, value: true }),+ set_stroke_align: (t) => ({ id: t.rect, align: 'OUTSIDE' }),+ set_fill: (t) => ({ id: t.rect, color: '#00ff00' }),+ set_stroke: (t) => ({ id: t.rect, color: '#112233', weight: 2, align: 'CENTER' }),+ set_layout: (t) => ({+ id: t.frame,+ direction: 'VERTICAL',+ spacing: 12,+ padding: 8,+ align: 'CENTER',+ counter_align: 'MAX'+ }),+ set_constraints: (t) => ({ id: t.placed, horizontal: 'STRETCH', vertical: 'CENTER' }),+ set_layout_child: (t) => ({+ id: t.rect,+ sizing_horizontal: 'FILL',+ sizing_vertical: 'FIXED',+ grow: 1,+ align_self: 'STRETCH'+ }),+ update_node: (t) => ({+ id: t.placed,+ x: 5,+ y: 6,+ width: 60,+ height: 30,+ opacity: 0.4,+ corner_radius: 3,+ visible: false,+ name: 'Renamed'+ }),+ set_effects: (t) => ({ id: t.rect, type: 'DROP_SHADOW', color: '#000000', radius: 6 })+}++const atomicTools: ToolDef[] = ALL_TOOLS.filter(isAtomicTool)++/** Ids whose fields, or variables whose record, differ from the checkpoint. */+function changedSince(graph: SceneGraph, before: ReturnType<typeof captureGraphCheckpoint>) {+ const nodes = [...before.nodes].flatMap(([id, previous]) => {+ const current = graph.getNode(id)+ return !current || diffFields(id, previous, current) ? [id] : []+ })+ const variables = [...before.variables].flatMap(([id, previous]) => {+ const current = graph.variables.get(id)+ return !current || diffFields(id, previous, current) ? [id] : []+ })+ return { nodes, variables }+}++describe('atomic tool contract', () => {+ test('every atomic tool has arguments, and only atomic tools do', () => {+ expect(Object.keys(ARGS).toSorted()).toEqual(atomicTools.map((def) => def.name).toSorted())+ })++ const cases = atomicTools.flatMap((def) =>+ (['plain', 'in an instance'] as const).map((kind) => [def.name, kind] as const)+ )++ test.each(cases)('%s on a layer on another page: %s', (name, kind) => {+ const def = atomicTools.find((candidate) => candidate.name === name)+ const args = ARGS[name]+ if (!def || !args) throw new Error(`No arguments for ${name}`)+ const fixture = build()+ const { editor, figma, graph } = fixture+ const targets = fixture.targets[kind]+ const before = captureGraphCheckpoint(graph)+ let change: DocumentChange | undefined+ const result = executeAtomicTool(editor, figma, def, args(targets, fixture), {+ onRecorded: (recorded) => {+ change = recorded+ }+ })+ expect(result).not.toHaveProperty('error')+ if (!change) throw new Error('Nothing was recorded')++ const changed = changedSince(graph, before)+ // The tool must do something, or the contract proves nothing.+ expect(changed.nodes.length + changed.variables.length).toBeGreaterThan(0)+ const updated = new Set(change.updated.map((update) => update.id))+ const variables = new Set(change.variables.map((record) => record.id))+ expect(changed.nodes.filter((id) => !updated.has(id))).toEqual([])+ expect(changed.variables.filter((id) => !variables.has(id))).toEqual([])++ editor.undo.undo()+ expect(graph.nodes.size).toBe(before.nodes.size)+ expect(graph.variables.size).toBe(before.variables.size)+ expect(changedSince(graph, before)).toEqual({ nodes: [], variables: [] })+ })+})diff --git a/packages/core/tests/editor/history/atomic/layout.test.ts b/packages/core/tests/editor/history/atomic/layout.test.tsnew file mode 100644index 000000000..0901de43d--- /dev/null+++ b/packages/core/tests/editor/history/atomic/layout.test.ts@@ -0,0 +1,152 @@+import { describe, expect, test } from 'bun:test'++import { setup, tool, withOtherPage } from '#core-tests/helpers/atomic-tool'++import { createEditor, executeAtomicTool, type Editor } from '@open-pencil/core'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import type { ToolDef } from '@open-pencil/core/tools'++/** A real editor whose layout runner also records the layers it is asked to lay out. */+function spiedEditor() {+ const editor = createEditor()+ const figma = new FigmaAPI(editor.graph)+ const laidOut: string[] = []+ const spied: Editor = {+ ...editor,+ runLayoutForNode: (id: string) => {+ laidOut.push(id)+ editor.runLayoutForNode(id)+ }+ }+ return { editor, spied, figma, graph: editor.graph, laidOut }+}++/** A tool that runs `execute` as an atomic property edit. */+function edit(execute: () => void): ToolDef {+ return { ...tool('set_opacity'), execute }+}++describe('atomic agent tool layout', () => {+ test('an edit on another page is recorded, laid out, undone and redone in place', () => {+ const { graph, figma, editor, undo, laidOut, recorded, onRecorded } = setup()+ const { page, rect } = withOtherPage(graph)+ executeAtomicTool(+ editor,+ figma,+ tool('set_opacity'),+ { id: rect.id, value: 0.5 },+ { onRecorded }+ )+ expect(rect.opacity).toBe(0.5)+ expect(recorded).toHaveLength(1)+ expect(recorded[0].updated.map((update) => update.id)).toEqual([rect.id])+ expect(recorded[0].pageIds).toContain(page.id)+ // Only the changed layer is laid out, not its page nor the page on screen.+ expect(laidOut).toEqual([rect.id])+ laidOut.length = 0+ undo.undo()+ expect(graph.getNode(rect.id)).toBe(rect)+ expect(rect.opacity).toBe(1)+ expect(laidOut).toEqual([rect.id])+ undo.redo()+ expect(rect.opacity).toBe(0.5)+ })++ test('an edit of a deep layer lays out the auto-layout frames around it, and so do undo and redo', () => {+ const { editor, spied, figma, graph, laidOut } = spiedEditor()+ const pageId = editor.state.currentPageId+ const hug = { layoutMode: 'HORIZONTAL', primaryAxisSizing: 'HUG' } as const+ const outer = graph.createNode('FRAME', pageId, { ...hug, width: 10, height: 40 })+ const inner = graph.createNode('FRAME', outer.id, { ...hug, width: 10, height: 40 })+ const rect = graph.createNode('RECTANGLE', inner.id, { width: 50, height: 20 })+ editor.runLayoutForNode(pageId)+ expect(outer.width).toBe(50)++ executeAtomicTool(+ spied,+ figma,+ edit(() => graph.updateNode(rect.id, { width: 150 })),+ {}+ )+ expect(inner.width).toBe(150)+ expect(outer.width).toBe(150)+ // The outermost auto-layout frame around the rectangle, not its page.+ expect(laidOut).toEqual([outer.id])+ laidOut.length = 0+ editor.undo.undo()+ expect(rect.width).toBe(50)+ expect(outer.width).toBe(50)+ expect(laidOut).toEqual([outer.id])+ editor.undo.redo()+ expect(outer.width).toBe(150)+ })++ test('changed siblings in an auto-layout row share one layout of the row', () => {+ const { editor, spied, figma, graph, laidOut } = spiedEditor()+ const pageId = editor.state.currentPageId+ const row = graph.createNode('FRAME', pageId, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ width: 1000,+ height: 40+ })+ const children = Array.from({ length: 50 }, () =>+ graph.createNode('RECTANGLE', row.id, { width: 10, height: 10 })+ )+ editor.runLayoutForNode(pageId)++ executeAtomicTool(+ spied,+ figma,+ edit(() => {+ for (const child of children) graph.updateNode(child.id, { opacity: 0.5 })+ graph.updateNode(children[0].id, { width: 30 })+ }),+ {}+ )+ expect(children[1].x).toBe(30)+ expect(laidOut).toEqual([row.id])+ laidOut.length = 0+ editor.undo.undo()+ expect(children[1].x).toBe(10)+ expect(laidOut).toEqual([row.id])+ laidOut.length = 0+ editor.undo.redo()+ expect(children[1].x).toBe(30)+ expect(laidOut).toEqual([row.id])+ })++ test('a variable change lays out every page on commit, undo and redo', () => {+ const { graph, figma, editor, undo, laidOut } = setup()+ graph.addPage('Second')+ graph.addPage('Third')+ const pages = graph.getPages().map((page) => page.id)+ const collection = graph.createCollection('Values')+ const variable = graph.createVariable('Gap', 'FLOAT', collection.id, 8)+ const args = { id: variable.id, mode: collection.defaultModeId, value: '16' }++ executeAtomicTool(editor, figma, tool('set_variable'), args)+ expect(laidOut).toEqual(pages)+ laidOut.length = 0+ undo.undo()+ expect(laidOut).toEqual(pages)+ laidOut.length = 0+ undo.redo()+ expect(laidOut).toEqual(pages)+ })++ test('a layout that writes and then throws rolls the whole edit back', () => {+ const { graph, figma, editor, undo, rectangle } = setup()+ const other = graph.createNode('RECTANGLE', figma.currentPage.id, { x: 0 })+ editor.runLayoutForNode = () => {+ graph.updateNode(other.id, { x: 99 })+ throw new Error('Layout failed')+ }+ expect(() =>+ executeAtomicTool(editor, figma, tool('set_opacity'), { id: rectangle.id, value: 0.5 })+ ).toThrow('Layout failed')+ expect(rectangle.opacity).toBe(1)+ expect(other.x).toBe(0)+ expect(undo.canUndo).toBe(false)+ })+})diff --git a/packages/core/tests/editor/history/atomic-tools.test.ts b/packages/core/tests/editor/history/atomic/tools.test.tssimilarity index 51%rename from packages/core/tests/editor/history/atomic-tools.test.tsrename to packages/core/tests/editor/history/atomic/tools.test.tsindex ba153dfbb..cf0dd7da1 100644--- a/packages/core/tests/editor/history/atomic-tools.test.ts+++ b/packages/core/tests/editor/history/atomic/tools.test.ts@@ -1,41 +1,14 @@import { describe, expect, test } from 'bun:test'-import { OpenPencilAPI } from '@open-pencil/core/openpencil-api'-import {- createEditor,- EDIT_VIEW,- executeAtomicTool,- type EditorProfileInputs-} from '@open-pencil/core'+import { node, setup, withOtherPage } from '#core-tests/helpers/atomic-tool'+import { HEAVY_TEST_TIMEOUT_MS } from '#core-tests/helpers/test-utils'++import { createEditor, executeAtomicTool } from '@open-pencil/core'import { FigmaAPI } from '@open-pencil/core/figma-api'+import { OpenPencilAPI } from '@open-pencil/core/openpencil-api'import { ALL_TOOLS, type ToolDef } from '@open-pencil/core/tools'import { SceneGraph } from '@open-pencil/scene-graph'-import { UndoManager } from '@open-pencil/scene-graph/undo'--function setup() {- const graph = new SceneGraph()- const undo = new UndoManager()- const figma = new FigmaAPI(graph)- const state: EditorProfileInputs = {- documentKind: 'design',- canvasView: EDIT_VIEW,- hostRestrictions: { readOnly: false }- }- const editor = {- graph,- state,- runLayoutForNode: () => undefined,- requestRender: () => undefined,- pushUndoStep: undo.pushStep.bind(undo)- }- const rectangle = figma.createRectangle()- const tool = (name: string): ToolDef => {- const def = ALL_TOOLS.find((candidate) => candidate.name === name)- if (!def) throw new Error(`Missing ${name}`)- return def- }- return { graph, figma, editor, undo, rectangle, tool }-}+import { setInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'describe('atomic agent tools', () => {test('component edits and undo propagate through the editor synchronizer', async () => {@@ -127,6 +100,8 @@ describe('atomic agent tools', () => {{...tool('set_opacity'),execute: () => {+ // Code that writes into a node directly reports it first.+ if (kind === 'node') graph.willChangeNode(graph.getNode(rectangle.id))set(after)}},@@ -313,4 +288,235 @@ describe('atomic agent tools', () => {undo.undo()expect(rectangle.opacity).toBe(1)})++ test.each(['throw', 'error result'] as const)(+ 'an edit across two pages rolls back whole on %s',+ (failure) => {+ const { graph, figma, editor, undo, rectangle, tool, recorded, onRecorded } = setup()+ const { rect } = withOtherPage(graph)+ const first = node(graph, rectangle.id)+ const def: ToolDef = {+ ...tool('set_opacity'),+ execute: () => {+ graph.updateNode(rect.id, { opacity: 0.25 })+ graph.updateNode(first.id, { opacity: 0.75 })+ if (failure === 'throw') throw new Error('Failed')+ return { error: 'Failed' }+ }+ }+ expect(() => executeAtomicTool(editor, figma, def, {}, { onRecorded })).toThrow('Failed')+ expect(rect.opacity).toBe(1)+ expect(first.opacity).toBe(1)+ expect(graph.getNode(rect.id)).toBe(rect)+ expect(graph.getNode(first.id)).toBe(first)+ expect(undo.canUndo).toBe(false)+ expect(recorded).toHaveLength(1)+ expect(recorded[0].updated).toEqual([])+ }+ )++ test('a document far above 10000 layers takes a one-property edit', () => {+ const { graph, figma, editor, undo, rectangle, tool, recorded, onRecorded } = setup()+ for (const pageId of [figma.currentPage.id, graph.addPage('Second').id]) {+ for (let f = 0; f < 2_600; f++) {+ const frame = graph.createNode('FRAME', pageId)+ for (let r = 0; r < 9; r++) graph.createNode('RECTANGLE', frame.id)+ }+ }+ expect(graph.nodes.size).toBeGreaterThan(50_000)+ executeAtomicTool(+ editor,+ figma,+ tool('set_opacity'),+ { id: rectangle.id, value: 0.5 },+ { onRecorded }+ )+ expect(rectangle.opacity).toBe(0.5)+ expect(recorded[0].updated).toHaveLength(1)+ undo.undo()+ expect(rectangle.opacity).toBe(1)+ }, HEAVY_TEST_TIMEOUT_MS)++ test('a node event the graph was not told of beforehand fails and rolls back', () => {+ const { graph, figma, editor, undo, rectangle, tool } = setup()+ const other = graph.createNode('RECTANGLE', figma.currentPage.id)+ const def: ToolDef = {+ ...tool('set_opacity'),+ execute: () => {+ rectangle.opacity = 0.25+ graph.emitter.emit('node:updated', other.id, {})+ }+ }+ expect(() => executeAtomicTool(editor, figma, def, {})).toThrow(+ `Atomic tools must report layer changes to the scene graph (SceneGraph.willChangeNode): ${other.id}`+ )+ expect(rectangle.opacity).toBe(1)+ expect(undo.canUndo).toBe(false)+ })++ test("binding a layer inside an instance on another page restores the instance's overrides", () => {+ const { graph, figma, editor, undo, tool } = setup()+ const page = graph.addPage('Components')+ const component = graph.createNode('COMPONENT', page.id)+ graph.createNode('RECTANGLE', component.id)+ const instance = graph.createInstance(component.id, page.id)+ if (!instance) throw new Error('Missing instance')+ const layer = instance.childIds[0]+ const collection = graph.createCollection('Values')+ const variable = graph.createVariable('Opacity', 'FLOAT', collection.id, 0.5)+ const overrides = structuredClone(instance.instanceOverrides)+ const args = { node_id: layer, field: 'opacity', variable_id: variable.id }++ executeAtomicTool(editor, figma, tool('bind_variable'), args)+ expect(instance.instanceOverrides).not.toEqual(overrides)+ const bound = structuredClone(instance.instanceOverrides)+ undo.undo()+ expect(graph.getNode(instance.id)).toBe(instance)+ expect(instance.instanceOverrides).toEqual(overrides)+ undo.redo()+ expect(instance.instanceOverrides).toEqual(bound)+ undo.undo()++ const failing: ToolDef = {+ ...tool('bind_variable'),+ execute: (api, input) => {+ tool('bind_variable').execute(api, input)+ throw new Error('Failed')+ }+ }+ expect(() => executeAtomicTool(editor, figma, failing, args)).toThrow('Failed')+ expect(instance.instanceOverrides).toEqual(overrides)+ expect(node(graph, layer).boundVariables).toEqual({})+ })++ test('a layer added to the graph without telling it is rejected and removed', () => {+ const { graph, figma, editor, undo, rectangle, tool } = setup()+ const keys = [...graph.nodes.keys()]+ const def: ToolDef = {+ ...tool('set_opacity'),+ execute: () => {+ graph.nodes.set('silent:1', {+ ...structuredClone(node(graph, rectangle.id)),+ id: 'silent:1'+ })+ }+ }+ expect(() => executeAtomicTool(editor, figma, def, {})).toThrow('must not create or remove')+ expect([...graph.nodes.keys()]).toEqual(keys)+ expect(undo.canUndo).toBe(false)+ })++ test('an edit may change at most 10000 layers', () => {+ const { graph, figma, editor, undo, tool } = setup()+ const ids = Array.from(+ { length: 10_001 },+ () => graph.createNode('RECTANGLE', figma.currentPage.id).id+ )+ const def: ToolDef = {+ ...tool('set_opacity'),+ execute: () => {+ for (const id of ids) graph.updateNode(id, { opacity: 0.5 })+ }+ }+ expect(() => executeAtomicTool(editor, figma, def, {})).toThrow(+ 'This edit changes 10001 layers; one atomic agent edit may change at most 10000. Change fewer layers per call.'+ )+ expect(ids.every((id) => node(graph, id).opacity === 1)).toBe(true)+ expect(undo.canUndo).toBe(false)+ }, HEAVY_TEST_TIMEOUT_MS)++ test('writing the values layers already have does not count toward the limit', () => {+ const { graph, figma, editor, undo, tool } = setup()+ const ids = Array.from(+ { length: 10_001 },+ () => graph.createNode('RECTANGLE', figma.currentPage.id).id+ )+ const def: ToolDef = {+ ...tool('set_opacity'),+ execute: () => {+ for (const id of ids) graph.updateNode(id, { opacity: 1 })+ }+ }+ expect(() => executeAtomicTool(editor, figma, def, {})).not.toThrow()+ expect(undo.canUndo).toBe(false)+ }, HEAVY_TEST_TIMEOUT_MS)++ test('binding a paint colour on a layer bound to the whole list keeps that binding on undo and rollback', () => {+ const { graph, figma, editor, undo, rectangle, tool } = setup()+ const collection = graph.createCollection('Colors')+ const color = graph.createVariable('Brand', 'COLOR', collection.id, { r: 1, g: 0, b: 0, a: 1 })+ tool('set_fill').execute(figma, { id: rectangle.id, color: '#ff0000' })+ graph.updateNode(rectangle.id, { boundVariables: { fills: color.id } })+ const layer = node(graph, rectangle.id)+ const args = { node_id: rectangle.id, field: 'fills/0/color', variable_id: color.id }++ executeAtomicTool(editor, figma, tool('bind_variable'), args)+ expect(layer.boundVariables).toEqual({ 'fills/0/color': color.id })+ undo.undo()+ expect(layer.boundVariables).toEqual({ fills: color.id })++ const failing: ToolDef = {+ ...tool('bind_variable'),+ execute: (api, input) => {+ tool('bind_variable').execute(api, input)+ throw new Error('Failed')+ }+ }+ expect(() => executeAtomicTool(editor, figma, failing, args)).toThrow('Failed')+ expect(layer.boundVariables).toEqual({ fills: color.id })+ })++ test('moving a nested instance in an unclaimed slot restores both instances on undo and rollback', () => {+ const { graph, figma, editor, undo, tool } = setup()+ const pageId = figma.currentPage.id+ const propertyId = 'panel:content'+ const panel = graph.createNode('COMPONENT', pageId, {+ name: 'Panel',+ componentPropertyDefinitions: [+ { id: propertyId, name: 'Content', type: 'SLOT', defaultValue: '' }+ ]+ })+ const slotFrame = graph.createNode('FRAME', panel.id, {+ name: 'Content',+ componentPropertyReferences: [{ propertyId, field: 'SLOT_CONTENT' }]+ })+ const card = graph.createNode('COMPONENT', pageId, { name: 'Card' })+ graph.createNode('RECTANGLE', card.id, { name: 'Inner' })+ graph.createInstance(card.id, slotFrame.id)+ const instance = graph.createInstance(panel.id, pageId)+ if (!instance) throw new Error('Missing instance')+ const slot = graph.getChildren(instance.id)[0]+ const nested = graph.getChildren(slot.id).find((child) => child.type === 'INSTANCE')+ const inner = nested && graph.getChildren(nested.id)[0]+ if (!nested || !inner) throw new Error('Missing nested instance')+ setInstanceOverride(instance.instanceOverrides, instance.id, inner.id, 'name', 'Renamed')+ // Claiming drops this override from the outer instance before it reports the nested one.+ setInstanceOverride(instance.instanceOverrides, instance.id, nested.id, 'name', 'Nested')+ const before = {+ instance: structuredClone(instance.instanceOverrides),+ nested: structuredClone(nested.instanceOverrides)+ }+ const expectRestored = () => {+ expect(instance.instanceOverrides).toEqual(before.instance)+ expect(nested.instanceOverrides).toEqual(before.nested)+ }+ const args = { id: nested.id, x: 40 }++ executeAtomicTool(editor, figma, tool('update_node'), args)+ expect(nested.x).toBe(40)+ expect(nested.instanceOverrides).not.toEqual(before.nested)+ undo.undo()+ expectRestored()++ const failing: ToolDef = {+ ...tool('update_node'),+ execute: (api, input) => {+ tool('update_node').execute(api, input)+ throw new Error('Failed')+ }+ }+ expect(() => executeAtomicTool(editor, figma, failing, args)).toThrow('Failed')+ expectRestored()+ expect(nested.x).not.toBe(40)+ })})diff --git a/packages/core/tests/editor/history/document-change.test.ts b/packages/core/tests/editor/history/document-change.test.tsindex 66e470112..485259e91 100644--- a/packages/core/tests/editor/history/document-change.test.ts+++ b/packages/core/tests/editor/history/document-change.test.ts@@ -1,12 +1,13 @@import { describe, expect, test } from 'bun:test'-import { captureDocumentChange } from '#core/editor/history/document-change'import { expectDefined } from '#core-tests/helpers/assert'import { createEditor, graphFromDocumentChange, isEmptyDocumentChange } from '@open-pencil/core'import type { CommentThread } from '@open-pencil/scene-graph'import { readComments, writeComments } from '@open-pencil/scene-graph/comments'+import { captureDocumentChange } from '#core/editor/history/document-change'+function setup() {const editor = createEditor()const pageId = editor.state.currentPageId@@ -240,6 +241,20 @@ describe('document changes', () => {expect(change.updated).toEqual([])})+ test('a layer deleted and created again with its id is undone as updated', () => {+ const { editor, pageId, card, title, badge } = setup()+ const finish = captureDocumentChange(editor.graph, pageId)+ editor.graph.deleteNode(badge.id)+ editor.graph.createNodeWithId(badge.id, 'RECTANGLE', pageId, { opacity: 0.5 })+ const change = finish()+ expect(change.created).toEqual([])+ expect(change.updated.map((update) => update.id)).toContain(badge.id)+ editor.restoreDocumentChange(change, 'before')+ expect(editor.graph.getNode(badge.id)?.opacity).toBe(1)+ expect(editor.graph.getNode(badge.id)?.parentId).toBe(card.id)+ expect(editor.graph.getNode(card.id)?.childIds).toEqual([title.id, badge.id])+ })+test('comments are never part of a change, and undo leaves them as they are', () => {const { editor, pageId } = setup()const { graph } = editordiff --git a/packages/core/tests/helpers/atomic-tool.ts b/packages/core/tests/helpers/atomic-tool.tsnew file mode 100644index 000000000..8654c989c--- /dev/null+++ b/packages/core/tests/helpers/atomic-tool.ts@@ -0,0 +1,53 @@+import { EDIT_VIEW, type DocumentChange, type EditorProfileInputs } from '@open-pencil/core'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { ALL_TOOLS, type ToolDef } from '@open-pencil/core/tools'+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { UndoManager } from '@open-pencil/scene-graph/undo'++/** The tool definition named `name`. */+export function tool(name: string): ToolDef {+ const def = ALL_TOOLS.find((candidate) => candidate.name === name)+ if (!def) throw new Error(`Missing ${name}`)+ return def+}++/** An editor stub over a new graph that records the layers it lays out, and a rectangle. */+export function setup() {+ const graph = new SceneGraph()+ const undo = new UndoManager()+ const figma = new FigmaAPI(graph)+ const state: EditorProfileInputs = {+ documentKind: 'design',+ canvasView: EDIT_VIEW,+ hostRestrictions: { readOnly: false }+ }+ const laidOut: string[] = []+ const editor = {+ graph,+ state,+ runLayoutForNode: (id: string) => {+ laidOut.push(id)+ },+ requestRender: () => undefined,+ pushUndoStep: undo.pushStep.bind(undo)+ }+ const rectangle = figma.createRectangle()+ const recorded: DocumentChange[] = []+ const onRecorded = (change: DocumentChange) => {+ recorded.push(change)+ }+ return { graph, figma, editor, undo, rectangle, tool, laidOut, recorded, onRecorded }+}++/** A second page with a rectangle, while the first page stays current. */+export function withOtherPage(graph: SceneGraph) {+ const page = graph.addPage('Other')+ const rect = graph.createNode('RECTANGLE', page.id)+ return { page, rect }+}++export function node(graph: SceneGraph, id: string): SceneNode {+ const found = graph.getNode(id)+ if (!found) throw new Error(`Missing ${id}`)+ return found+}diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.mdindex 3bc16e005..63dd82730 100644--- a/packages/scene-graph/AGENTS.md+++ b/packages/scene-graph/AGENTS.md@@ -26,7 +26,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice- Every plugin-data key OpenPencil writes is a field of `OPEN_PENCIL_PLUGIN_DATA` in `packages/scene-graph/src/plugin-data/fields.ts`, with the Valibot schema that reads it and its role: `content` travels with library assets and counts towards their hash (`contentPluginData`), `format` repeats a node field for files, `bookkeeping` stays behind. Read and replace entries with `readPluginData` and `withPluginData` instead of matching `pluginId` and `key` by hand. The fields test checks that keys stay unique.- A layer's `status` stays stored wherever the layer moves, as Figma keeps it; whether it shows, and whether one may be set, come from `effectiveStatus` and `statusPlacement` in `packages/scene-graph/src/statuses/node.ts`, which the Figma API, `.fig` and the UI share. Copies start without one (`packages/core/tests/figma-api/dev-status.test.ts`).- Vector network types live here; `vectorNetworkBlob` codecs live in `packages/core/src/vector/`.-- `packages/scene-graph/src/checkpoint.ts` owns transaction checkpoint recovery, including hierarchy and indexes; Core's atomic tool execution relies on it.+- `packages/scene-graph/src/checkpoint.ts` owns transaction checkpoint recovery, including hierarchy and indexes. Core's atomic tool execution uses `captureTouchedCheckpoint`, which copies only the nodes `observeNodeChanges` reports and their ancestors below the page, and fails an edit that sends a node event for a node it did not report first (`packages/scene-graph/tests/checkpoint.test.ts`).- Node types (`SceneNode`, `Effect`, `Fill`, `Stroke`) come from the root entry and primitives (`Color`, `Vector`, `Rect`) from `@open-pencil/scene-graph/primitives`; downstream packages reuse them instead of respelling shapes.- A paint's `gradientTransform` follows Figma's convention, mapping the layer's unit square onto gradient space; read, build, and invert it only through `@open-pencil/scene-graph/gradient`, which renderers, handles, exporters, importers, and tools all share (`packages/scene-graph/tests/gradient.test.ts`, `tests/engine/render/canvas/gradient.test.ts`).- `Stroke` extends `Fill`, so a stroke is a paint plus its geometry; add a paint field to `Fill` and both get it, and copy it in `copyFill`, which `copyStroke` reuses (`packages/scene-graph/src/copy.ts`).diff --git a/packages/scene-graph/src/checkpoint.ts b/packages/scene-graph/src/checkpoint.tsindex 4315bb65b..5fe292db4 100644--- a/packages/scene-graph/src/checkpoint.ts+++ b/packages/scene-graph/src/checkpoint.ts@@ -1,6 +1,13 @@import { isEqual } from 'es-toolkit'import type { SceneGraph } from './graph'+import { createSceneMutationImpact, recordSceneMutations } from './mutation-impact'+import type { SceneNode, Variable, VariableCollection } from './types'++const NODE_COUNT_ERROR = 'Atomic tools must not create or remove nodes or variables'+const NODE_IDENTITY_ERROR = 'Atomic tools must not change node hierarchy or identity'+const VARIABLE_IDENTITY_ERROR = 'Atomic tools must not change variable identity'+const DOCUMENT_ERROR = 'Atomic tools must not change collections, assets or document metadata'/** Capture rollback state without changing graph or surviving object identities. */export function captureGraphCheckpoint(graph: SceneGraph) {@@ -27,7 +34,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {snapshot.nodes.size !== graph.nodes.size ||snapshot.variables.size !== graph.variables.size)- throw new Error('Atomic tools must not create or remove nodes or variables')+ throw new Error(NODE_COUNT_ERROR)for (const [id, before] of snapshot.nodes) {const after = graph.nodes.get(id)if (@@ -39,7 +46,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {before.componentId !== after.componentId ||!isEqual(before.childIds, after.childIds)) {- throw new Error('Atomic tools must not change node hierarchy or identity')+ throw new Error(NODE_IDENTITY_ERROR)}}for (const [id, before] of snapshot.variables) {@@ -51,7 +58,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {before.collectionId !== after.collectionId ||before.type !== after.type)- throw new Error('Atomic tools must not change variable identity')+ throw new Error(VARIABLE_IDENTITY_ERROR)}assertDocumentUnchanged()}@@ -69,7 +76,7 @@ export function captureGraphCheckpoint(graph: SceneGraph) {graph.figKiwiVersion !== snapshot.figKiwiVersion ||!isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)) {- throw new Error('Atomic tools must not change collections, assets or document metadata')+ throw new Error(DOCUMENT_ERROR)}}@@ -121,3 +128,243 @@ function restoreMap<K, V>(target: Map<K, V>, saved: Map<K, V>) {target.clear()for (const [key, value] of saved) target.set(key, value)}++/**+ * Rollback state for an edit that may only change properties, which costs what the edit touches+ * rather than a copy of the document: a node is copied the first time the graph reports it about+ * to change (`SceneGraph.observeNodeChanges`), together with its ancestors below the page, which+ * keep instance override maps the graph writes into in place.+ */+export interface TouchedCheckpoint {+ /** Copies of the reported nodes and their ancestors below the page, as they were before. */+ readonly nodes: ReadonlyMap<string, SceneNode>+ /** Nodes the graph reported changing or creating. */+ readonly reported: ReadonlySet<string>+ /** Copies of every variable, as variables have no change report. */+ readonly variables: ReadonlyMap<string, Variable>+ readonly variableCollections: ReadonlyMap<string, VariableCollection>+ /** Throws unless the edit only changed properties of existing nodes and variables. */+ assertPropertiesOnly(): void+ /** Stops observing and puts back everything the edit changed, keeping object identities. */+ restore(): void+ /** Stops observing the graph. */+ stop(): void+}++/**+ * Starts observing `graph` for an edit that may only change properties. Node identities are+ * kept as pointers, so replacing, adding, or removing a node anywhere is found; a node's fields+ * are compared and restored only where the graph reported it, so code that writes into a node+ * directly calls `SceneGraph.willChangeNode` first, and a node event without such a report fails+ * the edit.+ */+export function captureTouchedCheckpoint(graph: SceneGraph): TouchedCheckpoint {+ const nodeRefs = new Map(graph.nodes)+ const variableRefs = new Map(graph.variables)+ const collectionRefs = new Map(graph.variableCollections)+ const saved = structuredClone({+ variables: graph.variables,+ variableCollections: graph.variableCollections,+ activeMode: graph.activeMode,+ instanceIndex: graph.instanceIndex,+ enabledLibraries: graph.enabledLibraries+ })+ // Property edits cannot edit assets. Retain existing buffers, not copies of every bitmap.+ const images = new Map(graph.images)+ const { rootId, figKiwiVersion, figSchemaDeflated, documentColorSpace } = graph+ const nodes = new Map<string, SceneNode>()+ const reported = new Set<string>()+ const created = new Set<string>()+ const impact = createSceneMutationImpact()++ /** Copies a node as the edit found it: the original object, should the edit have replaced it. */+ function copy(node: SceneNode) {+ nodes.set(node.id, structuredClone(nodeRefs.get(node.id) ?? node))+ }++ const skipped = (node: SceneNode) => nodes.has(node.id) || created.has(node.id)++ /**+ * Copies `node` and each ancestor not copied yet, up to but excluding its page. An ancestor+ * copied already had its own ancestors copied with it, so the walk stops there.+ */+ function copyLineage(node: SceneNode) {+ if (skipped(node)) return+ copy(node)+ if (!node.parentId) return+ graph.closest(node.parentId, (ancestor) => {+ if (ancestor.type === 'CANVAS' || ancestor.id === rootId || skipped(ancestor)) return true+ copy(ancestor)+ return false+ })+ }++ const unobserve = graph.observeNodeChanges({+ created: (node) => {+ created.add(node.id)+ reported.add(node.id)+ },+ before: (node) => {+ reported.add(node.id)+ copyLineage(node)+ }+ })+ const unbindEvents = recordSceneMutations(graph, impact)+ let observing = true++ function stop() {+ if (!observing) return+ observing = false+ unobserve()+ unbindEvents()+ }++ function assertNodes() {+ if (+ created.size > 0 ||+ impact.deletedNodeIds.size > 0 ||+ graph.nodes.size !== nodeRefs.size ||+ graph.variables.size !== variableRefs.size+ )+ throw new Error(NODE_COUNT_ERROR)+ for (const [id, node] of graph.nodes) {+ const original = nodeRefs.get(id)+ if (!original) throw new Error(NODE_COUNT_ERROR)+ if (original !== node) throw new Error(NODE_IDENTITY_ERROR)+ }+ for (const [id, before] of nodes) {+ const after = graph.nodes.get(id)+ if (+ !after ||+ before.id !== after.id ||+ before.type !== after.type ||+ before.parentId !== after.parentId ||+ before.componentId !== after.componentId ||+ !isEqual(before.childIds, after.childIds)+ )+ throw new Error(NODE_IDENTITY_ERROR)+ }+ for (const id of [+ ...impact.changedNodeIds,+ ...impact.previousParentIds,+ ...impact.currentParentIds+ ]) {+ if (!nodes.has(id) && !created.has(id)) {+ throw new Error(+ `Atomic tools must report layer changes to the scene graph (SceneGraph.willChangeNode): ${id}`+ )+ }+ }+ }++ function assertPropertiesOnly() {+ assertNodes()+ for (const [id, before] of saved.variables) {+ const after = graph.variables.get(id)+ if (+ !after ||+ after !== variableRefs.get(id) ||+ before.id !== after.id ||+ before.collectionId !== after.collectionId ||+ before.type !== after.type+ )+ throw new Error(VARIABLE_IDENTITY_ERROR)+ }+ if (+ !isEqual(saved.variableCollections, graph.variableCollections) ||+ !isEqual(saved.activeMode, graph.activeMode) ||+ !isEqual(saved.instanceIndex, graph.instanceIndex) ||+ !isEqual(saved.enabledLibraries, graph.enabledLibraries) ||+ images.size !== graph.images.size ||+ [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||+ graph.rootId !== rootId ||+ graph.documentColorSpace !== documentColorSpace ||+ graph.figKiwiVersion !== figKiwiVersion ||+ // Every writer assigns a new schema rather than writing into it.+ graph.figSchemaDeflated !== figSchemaDeflated+ )+ throw new Error(DOCUMENT_ERROR)+ }++ /** Puts the node map back as it was, in its order, if the edit changed its entries. */+ function restoreNodeMap(): { removed: Map<string, SceneNode>; readded: Set<string> } {+ const removed = new Map<string, SceneNode>()+ const readded = new Set<string>()+ let changed = graph.nodes.size !== nodeRefs.size+ if (!changed) {+ // In lockstep, so a node removed and set again, which moves to the end, is put back too.+ const live = graph.nodes.entries()+ for (const [id, node] of nodeRefs) {+ const next = live.next()+ if (next.done || next.value[0] !== id || next.value[1] !== node) {+ changed = true+ break+ }+ }+ }+ if (!changed) return { removed, readded }+ const failed = new Map(graph.nodes)+ graph.nodes.clear()+ for (const [id, node] of nodeRefs) {+ graph.nodes.set(id, node)+ if (!failed.has(id)) readded.add(id)+ }+ for (const [id, node] of failed) if (!nodeRefs.has(id)) removed.set(id, node)+ return { removed, readded }+ }++ function restore() {+ stop()+ const { removed, readded } = restoreNodeMap()+ for (const [id, copy] of nodes) {+ const original = nodeRefs.get(id)+ if (!original) continue+ for (const key of Object.keys(original)) {+ if (!Object.hasOwn(copy, key)) Reflect.deleteProperty(original, key)+ }+ Object.assign(original, structuredClone(copy))+ }+ restoreObjects(graph.variables, saved.variables, variableRefs)+ restoreObjects(graph.variableCollections, saved.variableCollections, collectionRefs)+ restoreMap(graph.activeMode, structuredClone(saved.activeMode))+ restoreMap(graph.instanceIndex, structuredClone(saved.instanceIndex))+ restoreMap(graph.enabledLibraries, structuredClone(saved.enabledLibraries))+ restoreMap(graph.images, images)+ graph.rootId = rootId+ graph.figKiwiVersion = figKiwiVersion+ graph.figSchemaDeflated = figSchemaDeflated+ graph.documentColorSpace = documentColorSpace+ graph.clearAbsPosCache()+ const touched = new Set([+ ...nodes.keys(),+ ...created,+ ...readded,+ ...removed.keys(),+ ...impact.changedNodeIds,+ ...impact.previousParentIds,+ ...impact.currentParentIds+ ])+ for (const id of touched) {+ if (graph.nodes.get(id)?.type === 'CONNECTOR') graph.connectorIds.add(id)+ else graph.connectorIds.delete(id)+ }+ // Notify consumers only after the complete hierarchy and indexes have been restored.+ for (const [id, node] of removed) graph.emitter.emit('node:deleted', id, node.parentId)+ for (const id of touched) {+ const node = graph.nodes.get(id)+ if (!node) continue+ if (readded.has(id)) graph.emitter.emit('node:created', node)+ else graph.emitter.emit('node:updated', id, node)+ }+ }++ return {+ nodes,+ reported,+ variables: saved.variables,+ variableCollections: saved.variableCollections,+ assertPropertiesOnly,+ restore,+ stop+ }+}diff --git a/packages/scene-graph/src/graph.ts b/packages/scene-graph/src/graph.tsindex 7f0f83816..ccef62ebc 100644--- a/packages/scene-graph/src/graph.ts+++ b/packages/scene-graph/src/graph.ts@@ -25,7 +25,7 @@ import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'import { updateNodePreview, type NodePreviewObserver } from './preview'import type { Color, Rect, Vector } from './primitives'import { markSourceFieldsEdited } from './source-metadata'-import { invalidateTextCaches } from './text/picture'+import { textCacheInvalidationChanges } from './text/picture'import { remapCopiedReferences } from './transfer/copied'import type {DocumentColorSpace,@@ -577,8 +577,15 @@ export class SceneGraph {if (node.componentId) this.unindexInstance(node.componentId, id)if (changes.componentId) this.indexInstance(changes.componentId, id)}- if (node.type === 'TEXT') invalidateTextCaches(node, changes)this.markEdited(node, Object.keys(changes))+ // Cache resets that change the node travel with the change, under the caller's own values,+ // so a layout put-back cannot drop their event.+ if (node.type === 'TEXT') {+ const resets = omitBy(textCacheInvalidationChanges(node, changes), (value, key) =>+ Object.is(node[key], value)+ )+ changes = { ...resets, ...changes }+ }if (changes.vectorNetwork) {changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }}diff --git a/packages/scene-graph/src/instances/index.ts b/packages/scene-graph/src/instances/index.tsindex 66e643b52..54b4c6088 100644--- a/packages/scene-graph/src/instances/index.ts+++ b/packages/scene-graph/src/instances/index.ts@@ -267,6 +267,7 @@ export function recordInstanceOverride(if (relevant.length === 0) return+ graph.willChangeNode(instance)for (const field of relevant)setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })diff --git a/packages/scene-graph/src/slots/content.ts b/packages/scene-graph/src/slots/content.tsindex bf062f39f..948e3e0d6 100644--- a/packages/scene-graph/src/slots/content.ts+++ b/packages/scene-graph/src/slots/content.ts@@ -68,6 +68,7 @@ export function claimSlotContent(): void {const { frame, instance, propertyId } = scopeif (ownsSlotContent(graph, frame, propertyId)) return+ graph.willChangeNode(instance)const overrides = instance.instanceOverridesfor (const node of descendants(graph, frame, false)) {overrides.descendants.delete(node.id)@@ -76,6 +77,7 @@ export function claimSlotContent(continue}// A nested instance keeps the overrides its former owner applied inside it.+ graph.willChangeNode(node)for (const inner of descendants(graph, node, true)) {const fields = overrides.descendants.get(inner.id)if (!fields) continuediff --git a/packages/scene-graph/src/text/picture.ts b/packages/scene-graph/src/text/picture.tsindex eb99a9db4..e165ff4e5 100644--- a/packages/scene-graph/src/text/picture.ts+++ b/packages/scene-graph/src/text/picture.ts@@ -51,7 +51,3 @@ export function textCacheInvalidationChanges(}return invalidated}--export function invalidateTextCaches(node: SceneNode, changes: Partial<SceneNode>): void {- Object.assign(node, textCacheInvalidationChanges(node, changes))-}diff --git a/packages/scene-graph/src/variables/index.ts b/packages/scene-graph/src/variables/index.tsindex 3f3b906a6..4cf1a5d78 100644--- a/packages/scene-graph/src/variables/index.ts+++ b/packages/scene-graph/src/variables/index.ts@@ -1,4 +1,4 @@-import { partition } from 'es-toolkit/array'+import { compact, partition, uniq } from 'es-toolkit/array'import { omit, omitBy } from 'es-toolkit/object'import { BLACK } from '../constants'@@ -267,6 +267,7 @@ export function bindVariable(}// Auto-remove top-level dead binding (e.g. 'fills') when setting indexed bindingif (paint.list in node.boundVariables) {+ graph.willChangeNode(node)node.boundVariables = omit(node.boundVariables, [paint.list])}}@@ -333,6 +334,8 @@ function markBoundVariablesOverrideOnInstance(const owner = variableBindingOwner(graph, node)if (owner.type !== 'INSTANCE') returnconst nearest = findInstanceAncestor(graph, nodeId)+ const instances = uniq(compact([nearest, owner])).filter((x) => x.id !== nodeId)+ for (const instance of instances) graph.willChangeNode(instance)if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')if (field)@@ -343,6 +346,8 @@ function markBoundVariablesOverrideOnInstance(bindingOverrideField(field),node.boundVariables[field] ?? null)+ for (const instance of instances)+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })}export * from './bindings'diff --git a/packages/scene-graph/tests/checkpoint.test.ts b/packages/scene-graph/tests/checkpoint.test.tsnew file mode 100644index 000000000..a0b00cc02--- /dev/null+++ b/packages/scene-graph/tests/checkpoint.test.ts@@ -0,0 +1,148 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'+import { captureTouchedCheckpoint } from '@open-pencil/scene-graph/checkpoint'++function pageId(graph: SceneGraph): string {+ return graph.getPages()[0].id+}++/** About `total` layers on the first page: frames of nine rectangles each. */+function largeGraph(total: number) {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const rectangles: string[] = []+ for (let f = 0; f < total / 10; f++) {+ const frame = graph.createNode('FRAME', page)+ for (let r = 0; r < 9; r++) rectangles.push(graph.createNode('RECTANGLE', frame.id).id)+ }+ return { graph, page, rectangles }+}++describe('touched checkpoint', () => {+ test('copies only the reported layer and its ancestors below the page', () => {+ const { graph, rectangles } = largeGraph(12_000)+ expect(graph.nodes.size).toBeGreaterThan(12_000)+ const target = rectangles[5_000]+ const checkpoint = captureTouchedCheckpoint(graph)+ graph.updateNode(target, { opacity: 0.5 })+ checkpoint.assertPropertiesOnly()+ checkpoint.stop()+ // The rectangle and its frame; the page and document are not copied.+ expect(checkpoint.nodes.size).toBe(2)+ expect([...checkpoint.reported]).toEqual([target])+ expect(checkpoint.nodes.get(target)?.opacity).toBe(1)+ expect(graph.getNode(target)?.opacity).toBe(0.5)+ })++ test('a rollback keeps identities, indexes, modes, and node order', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const frame = graph.createNode('FRAME', page)+ const rect = graph.createNode('RECTANGLE', frame.id)+ const component = graph.createNode('COMPONENT', page)+ const instance = graph.createInstance(component.id, page)+ if (!instance) throw new Error('Missing instance')+ const collection = graph.createCollection('Theme')+ const dark = graph.createMode(collection.id, 'Dark')+ if (!dark) throw new Error('Missing mode')+ const order = [...graph.nodes.keys()]+ const nodes = structuredClone(graph.nodes)+ const index = structuredClone(graph.instanceIndex)+ const modes = structuredClone(graph.activeMode)+ const originals = new Map(graph.nodes)++ const checkpoint = captureTouchedCheckpoint(graph)+ graph.updateNode(rect.id, { opacity: 0.25 })+ graph.deleteNode(instance.id)+ graph.reparentNode(rect.id, page)+ graph.setActiveMode(collection.id, dark)+ graph.createNode('ELLIPSE', frame.id)+ expect(() => checkpoint.assertPropertiesOnly()).toThrow('must not create or remove')+ checkpoint.restore()++ expect([...graph.nodes.keys()]).toEqual(order)+ expect(graph.nodes).toEqual(nodes)+ for (const [id, node] of originals) expect(graph.getNode(id)).toBe(node)+ expect(graph.instanceIndex).toEqual(index)+ expect(graph.activeMode).toEqual(modes)+ })++ test('a node event without a report fails the edit', () => {+ const graph = new SceneGraph()+ const rect = graph.createNode('RECTANGLE', pageId(graph))+ const checkpoint = captureTouchedCheckpoint(graph)+ graph.emitter.emit('node:updated', rect.id, {})+ expect(() => checkpoint.assertPropertiesOnly()).toThrow(+ `must report layer changes to the scene graph (SceneGraph.willChangeNode): ${rect.id}`+ )+ checkpoint.stop()+ })++ test('a changed component id fails the edit', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const component = graph.createNode('COMPONENT', page)+ const instance = graph.createInstance(component.id, page)+ if (!instance) throw new Error('Missing instance')+ const checkpoint = captureTouchedCheckpoint(graph)+ graph.updateNode(instance.id, { componentId: null })+ expect(() => checkpoint.assertPropertiesOnly()).toThrow('must not change node hierarchy')+ checkpoint.restore()+ expect(graph.getNode(instance.id)?.componentId).toBe(component.id)+ })++ test('a rollback after an edit replaced a node restores the original as it was', () => {+ const graph = new SceneGraph()+ const rect = graph.createNode('RECTANGLE', pageId(graph), { name: 'Original' })+ const checkpoint = captureTouchedCheckpoint(graph)+ graph.nodes.set(rect.id, { ...structuredClone(rect), name: 'Replacement' })+ graph.updateNode(rect.id, { opacity: 0.5 })+ expect(() => checkpoint.assertPropertiesOnly()).toThrow('must not change node hierarchy')+ checkpoint.restore()+ expect(graph.getNode(rect.id)).toBe(rect)+ expect(rect.name).toBe('Original')+ expect(rect.opacity).toBe(1)+ })++ test('a rollback puts a node removed and set again back in its place', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const first = graph.createNode('RECTANGLE', page)+ graph.createNode('RECTANGLE', page)+ const order = [...graph.nodes.keys()]+ const checkpoint = captureTouchedCheckpoint(graph)+ graph.nodes.delete(first.id)+ graph.nodes.set(first.id, first)+ expect([...graph.nodes.keys()]).not.toEqual(order)+ checkpoint.restore()+ expect([...graph.nodes.keys()]).toEqual(order)+ })++ test('a rollback restores the connector list for created and deleted connectors', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const kept = graph.createNode('CONNECTOR', page)+ const checkpoint = captureTouchedCheckpoint(graph)+ graph.deleteNode(kept.id)+ const added = graph.createNode('CONNECTOR', page)+ expect(graph.connectorIds.has(kept.id)).toBe(false)+ checkpoint.restore()+ expect(graph.getNode(kept.id)).toBe(kept)+ expect(graph.getNode(added.id)).toBeUndefined()+ expect([...graph.connectorIds]).toEqual([kept.id])+ })++ test('a rollback drops absolute positions the edit cached', () => {+ const graph = new SceneGraph()+ const frame = graph.createNode('FRAME', pageId(graph), { x: 10 })+ const rect = graph.createNode('RECTANGLE', frame.id, { x: 5 })+ expect(graph.getAbsolutePosition(rect.id).x).toBe(15)+ const checkpoint = captureTouchedCheckpoint(graph)+ graph.updateNode(frame.id, { x: 100 })+ expect(graph.getAbsolutePosition(rect.id).x).toBe(105)+ checkpoint.restore()+ expect(frame.x).toBe(10)+ expect(graph.getAbsolutePosition(rect.id).x).toBe(15)+ })+})diff --git a/packages/scene-graph/tests/helpers/observe.ts b/packages/scene-graph/tests/helpers/observe.tsnew file mode 100644index 000000000..2e6920d59--- /dev/null+++ b/packages/scene-graph/tests/helpers/observe.ts@@ -0,0 +1,36 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { cloneInstanceOverrideState } from '@open-pencil/scene-graph/instances/overrides'+import {+ createSceneMutationImpact,+ recordSceneMutations+} from '@open-pencil/scene-graph/mutation-impact'++/** What a recorder keeps in `before()`: the first copy of each reported node, plus the touched set. */+export function observeWrites(graph: SceneGraph) {+ const before = new Map<+ string,+ { overrides: SceneNode['instanceOverrides']; boundVariables: SceneNode['boundVariables'] }+ >()+ const created = new Set<string>()+ const impact = createSceneMutationImpact()+ const stopChanges = graph.observeNodeChanges({+ created: (node) => created.add(node.id),+ before: (node) => {+ if (before.has(node.id)) return+ before.set(node.id, {+ overrides: cloneInstanceOverrideState(node.instanceOverrides),+ boundVariables: { ...node.boundVariables }+ })+ }+ })+ const stopEvents = recordSceneMutations(graph, impact)+ return {+ before,+ created,+ touched: impact.changedNodeIds,+ stop: () => {+ stopChanges()+ stopEvents()+ }+ }+}diff --git a/packages/scene-graph/tests/instances/report-writes.test.ts b/packages/scene-graph/tests/instances/report-writes.test.tsnew file mode 100644index 000000000..903643e60--- /dev/null+++ b/packages/scene-graph/tests/instances/report-writes.test.ts@@ -0,0 +1,28 @@+import { expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'+import { recordInstanceOverride } from '@open-pencil/scene-graph/instances'+import { hasInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'++import { observeWrites } from '../helpers/observe'++test('recordInstanceOverride reports the instance before its overrides change', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const component = graph.createNode('COMPONENT', page.id)+ graph.createNode('RECTANGLE', component.id)+ const instance = graph.createInstance(component.id, page.id)+ if (!instance) throw new Error('No instance')+ const copy = graph.getChildren(instance.id)[0]++ const seen = observeWrites(graph)+ recordInstanceOverride(graph, copy.id, ['opacity'])+ seen.stop()++ const kept = seen.before.get(instance.id)+ expect(kept && hasInstanceOverride(kept.overrides, instance.id, copy.id, 'opacity')).toBe(false)+ expect(hasInstanceOverride(instance.instanceOverrides, instance.id, copy.id, 'opacity')).toBe(+ true+ )+ expect(seen.touched.has(instance.id)).toBe(true)+})diff --git a/packages/scene-graph/tests/slots/content.test.ts b/packages/scene-graph/tests/slots/content.test.tsindex 619669403..db96e7d01 100644--- a/packages/scene-graph/tests/slots/content.test.ts+++ b/packages/scene-graph/tests/slots/content.test.ts@@ -1,6 +1,10 @@import { describe, expect, test } from 'bun:test'import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import {+ hasInstanceOverride,+ setInstanceOverride+} from '@open-pencil/scene-graph/instances/overrides'import {claimSlotContent,clearSlotContent,@@ -10,6 +14,8 @@ import {slotScope} from '@open-pencil/scene-graph/slots'+import { observeWrites } from '../helpers/observe'+/** A component set with a Small and a Large variant, each with a `Content` slot. */function panel(graph: SceneGraph, page: SceneNode) {const set = graph.createNode('COMPONENT_SET', page.id, { name: 'Panel' })@@ -151,3 +157,57 @@ describe('slot scope', () => {expect(graph.getChildren(slot.id)[0].componentId).not.toBeNull()})})++describe('claiming slot content reports the instance', () => {+ test('before its overrides change, and with an event', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const { small } = panel(graph, page)+ const instance = graph.createInstance(small.id, page.id)+ if (!instance) throw new Error('No instance')+ const slot = graph.getChildren(instance.id)[0]+ const [content] = graph.getChildren(slot.id)+ setInstanceOverride(instance.instanceOverrides, instance.id, content.id, 'name')+ const scope = slotScope(graph, slot.id)+ if (scope.kind !== 'slot') throw new Error(`Expected a slot, got ${scope.kind}`)++ const seen = observeWrites(graph)+ claimSlotContent(graph, scope)+ seen.stop()++ const kept = seen.before.get(instance.id)+ expect(kept && hasInstanceOverride(kept.overrides, instance.id, content.id, 'name')).toBe(true)+ expect(hasInstanceOverride(instance.instanceOverrides, instance.id, content.id, 'name')).toBe(+ false+ )+ expect(seen.touched.has(instance.id)).toBe(true)+ })++ test('a nested instance is reported before it takes over the overrides', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const { small } = panel(graph, page)+ const card = graph.createNode('COMPONENT', page.id, { name: 'Card' })+ graph.createNode('RECTANGLE', card.id, { name: 'Inner' })+ const slotFrame = graph.getChildren(small.id)[0]+ graph.createInstance(card.id, slotFrame.id)+ const instance = graph.createInstance(small.id, page.id)+ if (!instance) throw new Error('No instance')+ const slot = graph.getChildren(instance.id)[0]+ const nested = graph.getChildren(slot.id).find((child) => child.type === 'INSTANCE')+ const inner = nested && graph.getChildren(nested.id)[0]+ if (!nested || !inner) throw new Error('No nested instance')+ setInstanceOverride(instance.instanceOverrides, instance.id, inner.id, 'opacity', 0.5)+ const scope = slotScope(graph, slot.id)+ if (scope.kind !== 'slot') throw new Error(`Expected a slot, got ${scope.kind}`)++ const seen = observeWrites(graph)+ claimSlotContent(graph, scope)+ seen.stop()++ const kept = seen.before.get(nested.id)+ expect(kept && hasInstanceOverride(kept.overrides, nested.id, inner.id, 'opacity')).toBe(false)+ expect(hasInstanceOverride(nested.instanceOverrides, nested.id, inner.id, 'opacity')).toBe(true)+ expect(seen.touched.has(nested.id)).toBe(true)+ })+})diff --git a/packages/scene-graph/tests/text/layout-invalidation.test.ts b/packages/scene-graph/tests/text/layout-invalidation.test.tsindex 324df2921..157045dd7 100644--- a/packages/scene-graph/tests/text/layout-invalidation.test.ts+++ b/packages/scene-graph/tests/text/layout-invalidation.test.ts@@ -1,4 +1,4 @@-import { expect, test } from 'bun:test'+import { describe, expect, test } from 'bun:test'import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import { copyStyleRuns } from '@open-pencil/scene-graph/copy'@@ -96,3 +96,77 @@ test('resizing flat text drops its glyphs so it reflows, while path text scalesexpect(flat.derivedTextGlyphs).toBeNull()expect(path.derivedTextGlyphs?.[0].scaleX).toBe(2)})++describe('text cache resets', () => {+ const glyphs = [{ commandsBlob: new Uint8Array([0]), x: 0, y: 10, fontSize: 12 }]+ const cached = (graph: SceneGraph) =>+ graph.createNode('TEXT', graph.getPages()[0].id, {+ text: 'Text',+ width: 100,+ height: 20,+ derivedLayout: { width: 100, height: 20 },+ derivedTextGlyphs: glyphs+ })+ const publish = (graph: SceneGraph) => {+ const updates: Partial<SceneNode>[] = []+ graph.onNodeEvents({ updated: (_id, changes) => updates.push({ ...changes }) })+ return updates+ }++ test('a size put back during layout still publishes the caches it reset', () => {+ const graph = new SceneGraph()+ const node = cached(graph)+ const updates = publish(graph)++ graph.withLayoutMutations(() => {+ graph.updateNode(node.id, { width: 50 })+ graph.updateNode(node.id, { width: 100 })+ })++ expect(node.derivedLayout).toBeNull()+ expect(node.derivedTextGlyphs).toBeNull()+ expect(updates).toEqual([{ derivedLayout: null, derivedTextGlyphs: null }])+ })++ test('a size put back during layout publishes nothing when nothing was cached', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, { text: 'Text', width: 100 })+ const updates = publish(graph)++ graph.withLayoutMutations(() => {+ graph.updateNode(node.id, { width: 50 })+ graph.updateNode(node.id, { width: 100 })+ })++ expect(updates).toEqual([])+ })++ test('a direct edit carries only the caches that were set', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, { text: 'Text', width: 100 })+ const updates = publish(graph)++ graph.updateNode(node.id, { width: 50 })++ expect(updates).toEqual([{ width: 50 }])+ })++ test('values the caller supplies win over the resets', () => {+ const graph = new SceneGraph()+ const node = cached(graph)+ Object.assign(node, { textPicture: new Uint8Array([1]) })+ const picture = new Uint8Array([2])+ graph.updateNode(node.id, { width: 50, textPicture: picture })+ expect(node.textPicture).toBe(picture)++ const pathData = {+ network: { vertices: [], segments: [], regions: [] },+ normalizedSize: { x: 1, y: 1 },+ tValue: 0,+ forward: true+ }+ Object.assign(node, { derivedTextGlyphs: glyphs })+ graph.updateNode(node.id, { text: 'Old', derivedTextGlyphs: null, textPathData: pathData })+ expect(node.textPathData).toBe(pathData)+ })+})diff --git a/packages/scene-graph/tests/variables/report-writes.test.ts b/packages/scene-graph/tests/variables/report-writes.test.tsnew file mode 100644index 000000000..6eab1cd59--- /dev/null+++ b/packages/scene-graph/tests/variables/report-writes.test.ts@@ -0,0 +1,125 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import {+ bindingOverrideField,+ hasInstanceOverride+} from '@open-pencil/scene-graph/instances/overrides'+import { bindVariable, unbindVariable } from '@open-pencil/scene-graph/variables'++import { observeWrites } from '../helpers/observe'++function setup() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const component = graph.createNode('COMPONENT', page.id, { name: 'C' })+ const layer = graph.createNode('RECTANGLE', component.id, {+ name: 'Layer',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]+ })+ const instance = graph.createInstance(component.id, page.id)+ if (!instance) throw new Error('No instance')+ const copy = graph.getChildren(instance.id)[0]+ const collection = graph.createCollection('Tokens')+ const number = graph.createVariable('n', 'FLOAT', collection.id, 0.5)+ const color = graph.createVariable('c', 'COLOR', collection.id, { r: 0, g: 0, b: 0, a: 1 })+ return { graph, layer, instance, copy, number, color }+}++describe('bindings inside an instance report the instance override writes', () => {+ test('bindVariable reports the instance before its overrides change', () => {+ const { graph, instance, copy, number } = setup()+ const claims = (state: SceneNode['instanceOverrides']) =>+ hasInstanceOverride(state, instance.id, copy.id, bindingOverrideField('opacity'))+ const seen = observeWrites(graph)+ bindVariable(graph, copy.id, 'opacity', number.id)+ seen.stop()++ const kept = seen.before.get(instance.id)+ expect(kept).toBeDefined()+ expect(kept && claims(kept.overrides)).toBe(false)+ expect(claims(instance.instanceOverrides)).toBe(true)+ expect(seen.touched.has(instance.id)).toBe(true)+ })++ test('unbindVariable reports the instance before its overrides change', () => {+ const { graph, instance, copy, number } = setup()+ bindVariable(graph, copy.id, 'opacity', number.id)+ const claims = (state: SceneNode['instanceOverrides']) =>+ hasInstanceOverride(state, instance.id, copy.id, bindingOverrideField('opacity'))+ const seen = observeWrites(graph)+ unbindVariable(graph, copy.id, 'opacity')+ seen.stop()++ const kept = seen.before.get(instance.id)+ expect(kept).toBeDefined()+ expect(kept && claims(kept.overrides)).toBe(true)+ expect(seen.touched.has(instance.id)).toBe(true)+ })+})++test('binding one paint colour reports the node before dropping its whole-list binding', () => {+ const { graph, layer, color } = setup()+ graph.updateNode(layer.id, { boundVariables: { fills: color.id } })+ const seen = observeWrites(graph)+ bindVariable(graph, layer.id, 'fills/0/color', color.id)+ seen.stop()++ expect(seen.before.get(layer.id)?.boundVariables).toEqual({ fills: color.id })+ expect(layer.boundVariables).toEqual({ 'fills/0/color': color.id })+ expect(seen.touched.has(layer.id)).toBe(true)+})++describe('bindings where the nearest and owning instances differ or coincide with the node', () => {+ const opacityClaim = bindingOverrideField('opacity')++ test('a layer in a nested instance reports both instances before their overrides change', () => {+ const { graph, layer, number } = setup()+ const page = graph.getPages()[0]+ const inner = graph.getNode(layer.parentId ?? '')+ if (!inner) throw new Error('No component')+ const outer = graph.createNode('COMPONENT', page.id, { name: 'Outer' })+ const nested = graph.createInstance(inner.id, outer.id)+ const instance = graph.createInstance(outer.id, page.id)+ if (!nested || !instance) throw new Error('No instance')+ const nestedCopy = graph.getChildren(instance.id)[0]+ const copy = graph.getChildren(nestedCopy.id)[0]++ const seen = observeWrites(graph)+ bindVariable(graph, copy.id, 'opacity', number.id)+ seen.stop()++ expect(nestedCopy.type).toBe('INSTANCE')+ for (const target of [nestedCopy, instance]) {+ const kept = seen.before.get(target.id)+ expect(+ kept && hasInstanceOverride(kept.overrides, target.id, copy.id, 'boundVariables')+ ).toBe(false)+ expect(+ hasInstanceOverride(target.instanceOverrides, target.id, copy.id, 'boundVariables')+ ).toBe(true)+ expect(seen.touched.has(target.id)).toBe(true)+ }+ expect(+ hasInstanceOverride(instance.instanceOverrides, instance.id, copy.id, opacityClaim)+ ).toBe(true)+ })++ test('an instance bound itself is reported once, before its own overrides change', () => {+ const { graph, instance, number } = setup()++ const seen = observeWrites(graph)+ bindVariable(graph, instance.id, 'opacity', number.id)+ seen.stop()++ const kept = seen.before.get(instance.id)+ expect(kept?.boundVariables).toEqual({})+ expect(+ kept && hasInstanceOverride(kept.overrides, instance.id, instance.id, opacityClaim)+ ).toBe(false)+ expect(+ hasInstanceOverride(instance.instanceOverrides, instance.id, instance.id, opacityClaim)+ ).toBe(true)+ expect(seen.touched.has(instance.id)).toBe(true)+ })+})diff --git a/src/app/ai/tools/runner.ts b/src/app/ai/tools/runner.tsindex 1bc9b123f..7131d4568 100644--- a/src/app/ai/tools/runner.ts+++ b/src/app/ai/tools/runner.ts@@ -132,14 +132,14 @@ async function editAndRecord(call: EditorToolCall, reply: ReplyCall | null): Pro}try {if (isAtomicTool(def)) {- // An atomic tool commits its own step at once; loading its fonts after is not part of it.- const result = store.recordEdit({ ...options, push: false }, () =>- executeAtomicTool(store, figma, def, args, {- label: prefix,- signal: call.signal,- isLive: call.isLive- })- )+ // An atomic tool records and commits its own step at once, from the layers it touched;+ // loading its fonts after is not part of it.+ const result = executeAtomicTool(store, figma, def, args, {+ label: prefix,+ signal: call.signal,+ isLive: call.isLive,+ onRecorded: options.onRecorded+ })await loadAtomicToolFonts(store, figma, args, { isLive: call.isLive })return result}diff --git a/tests/app/ai/tools/runner.test.ts b/tests/app/ai/tools/runner.test.tsindex aa19f23ea..4c6acbca9 100644--- a/tests/app/ai/tools/runner.test.ts+++ b/tests/app/ai/tools/runner.test.ts@@ -1,9 +1,12 @@import 'fake-indexeddb/auto'-import { afterEach, beforeEach, expect, test } from 'bun:test'+import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test'import { ALL_TOOLS } from '@open-pencil/core/tools'import { SceneGraph } from '@open-pencil/scene-graph'+import { Run } from '@/app/ai/reply/run'+import { DEFAULT_AGENT_STEPS } from '@/app/ai/reply/step-limit'+import { readToolChange } from '@/app/ai/tools/changes/store'import { runEditorTool } from '@/app/ai/tools/runner'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'import { createEditorStore, type EditorStore } from '@/app/editor/session/create'@@ -79,3 +82,36 @@ test('undoing an asynchronous tool call returns the document to saved', async ()await Promise.resolve()expect(store.hasUnsavedChanges()).toBe(false)})++test("a reply's property edit is recorded once, as one undo entry", async () => {+ const setOpacity = expectDefined(+ ALL_TOOLS.find((tool) => tool.name === 'set_opacity'),+ 'set_opacity'+ )+ const pageId = store.state.currentPageId+ const figma = makeFigmaFromStore(store, pageId)+ const rect = store.graph.createNode('RECTANGLE', pageId, { width: 100, height: 70 })+ const run = new Run(DEFAULT_AGENT_STEPS, pageId, false)+ // The atomic tool records its own step; nothing captures the document around it again.+ const recordEdit = spyOn(store, 'recordEdit')+ const recordEditAsync = spyOn(store, 'recordEditAsync')++ await runEditorTool({+ store,+ figma,+ def: setOpacity,+ args: { id: rect.id, value: 0.5 },+ reply: { run, toolCallId: 'call-1' }+ })++ expect(store.graph.getNode(rect.id)?.opacity).toBe(0.5)+ expect(recordEdit).not.toHaveBeenCalled()+ expect(recordEditAsync).not.toHaveBeenCalled()+ expect(store.undo.peekUndo()?.label).toBe('AI: set_opacity')+ expect(run.undoCalls.map(({ toolCallId }) => toolCallId)).toEqual(['call-1'])+ expect(run.changedCalls.has('call-1')).toBe(true)+ expect(readToolChange('call-1')).not.toBeNull()+ store.undo.undo()+ expect(store.graph.getNode(rect.id)?.opacity).toBe(1)+ expect(store.undo.canUndo).toBe(false)+})diff --git a/tests/app/collab/shared-tree/sync.test.ts b/tests/app/collab/shared-tree/sync.test.tsindex 20d8cef91..3dce71a9b 100644--- a/tests/app/collab/shared-tree/sync.test.ts+++ b/tests/app/collab/shared-tree/sync.test.ts@@ -2,7 +2,10 @@ import { describe, expect, test } from 'bun:test'import type * as Y from 'yjs'-import { captureGraphCheckpoint } from '@open-pencil/scene-graph/checkpoint'+import {+ captureGraphCheckpoint,+ captureTouchedCheckpoint+} from '@open-pencil/scene-graph/checkpoint'import { readPage } from '@/app/collab/shared-tree/fields'@@ -157,6 +160,69 @@ describe('collab layer tree', () => {)})+ test('a touched checkpoint rollback moves restored layers back on the other peer', async () => {+ await withSyncedStores(+ async (stores) => {+ const { hostStore, peerStore } = stores+ const pageId = expectDefined(hostStore.graph.getPages()[0], 'first page').id+ hostStore.graph.createNode('FRAME', pageId, { id: 'frame:1' })+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:2' })+ stores.hostSync.syncAllNodesToYjs()+ await settleGraphSync()++ const checkpoint = captureTouchedCheckpoint(hostStore.graph)+ hostStore.graph.updateNode('rect:2', { opacity: 0.5 })+ hostStore.graph.reparentNode('rect:1', 'frame:1')+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').parentId).toBe('frame:1')+ expect(getNodeOrThrow(peerStore.graph, 'rect:2').opacity).toBe(0.5)++ checkpoint.restore()+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').parentId).toBe(pageId)+ expect(getNodeOrThrow(peerStore.graph, 'rect:2').opacity).toBe(1)+ expect(getNodeOrThrow(peerStore.graph, pageId).childIds).toEqual([+ 'frame:1',+ 'rect:1',+ 'rect:2'+ ])+ expectSameLayerTree(stores, [pageId])+ },+ { bindGraphEvents: true }+ )+ })++ test('a touched checkpoint rollback brings back deleted layers and removes created ones on the other peer', async () => {+ await withSyncedStores(+ async (stores) => {+ const { hostStore, peerStore } = stores+ const pageId = expectDefined(hostStore.graph.getPages()[0], 'first page').id+ hostStore.graph.createNode('FRAME', pageId, { id: 'frame:1' })+ hostStore.graph.createNode('RECTANGLE', 'frame:1', { id: 'rect:1' })+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:2' })+ stores.hostSync.syncAllNodesToYjs()+ await settleGraphSync()++ const checkpoint = captureTouchedCheckpoint(hostStore.graph)+ hostStore.graph.deleteNode('frame:1')+ hostStore.graph.createNode('ELLIPSE', pageId, { id: 'ellipse:1' })+ await settleGraphSync()+ expect(peerStore.graph.getNode('frame:1')).toBeUndefined()+ expect(peerStore.graph.getNode('ellipse:1')).toBeDefined()++ checkpoint.restore()+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'frame:1').childIds).toEqual(['rect:1'])+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').parentId).toBe('frame:1')+ expect(peerStore.graph.getNode('ellipse:1')).toBeUndefined()+ expect(getNodeOrThrow(peerStore.graph, pageId).childIds).toEqual(['frame:1', 'rect:2'])+ expectSameLayerTree(stores, [pageId])+ },+ { bindGraphEvents: true }+ )+ })+test('an edit that moves several layers sends one update', async () => {await withSyncedStores(async (stores) => {