AI-native design editor. Open-source Figma alternative.
feat(automation): share atomic property-edit transactions
Danila Poyarkov892550a28789
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex 4cbf24022..021fa01e4 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -12,6 +12,8 @@ import type { StepBudget, ToolLogEntry } from '@open-pencil/core/tools'import type { SceneNode } from '@open-pencil/scene-graph'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import { ATOMIC_TOOL_NAMES } from '@/app/automation/execution/atomic'+import { executeAtomicEditorTool } from '@/app/automation/execution/editor'import { getActiveEditorStore } from '@/app/editor/active-store'import type { EditorStore } from '@/app/editor/active-store'import { ensureGraphFonts } from '@/app/editor/fonts'@@ -85,6 +87,9 @@ export function createAITools(store: EditorStore) {{getFigma: () => makeFigmaFromStore(store),executeTool: async (def, figma, args) => {+ if (ATOMIC_TOOL_NAMES.has(def.name)) {+ return executeAtomicEditorTool(store, figma, def, args, { label: 'AI' })+ }if (def.mutates) beforeSnapshot = store.snapshotPage()return def.mutates? store.runMutationWithLayout(@@ -98,6 +103,7 @@ export function createAITools(store: EditorStore) {: def.execute(figma, args)},onAfterExecute: async (def) => {+ if (ATOMIC_TOOL_NAMES.has(def.name)) returnif (def.mutates) {store.requestRender()if (beforeSnapshot) {diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.tsindex 70859b146..65f0c4cff 100644--- a/src/app/automation/bridge/tool-handlers.ts+++ b/src/app/automation/bridge/tool-handlers.ts@@ -4,6 +4,8 @@ import { ALL_TOOLS, registerComponentCatalog } from '@open-pencil/core/tools'import type { JSONObject } from '@open-pencil/scene-graph/primitives'import type { AutomationTarget } from '@/app/automation/bridge/target'+import { ATOMIC_TOOL_NAMES } from '@/app/automation/execution/atomic'+import { executeAtomicEditorTool } from '@/app/automation/execution/editor'import { ensureGraphFonts } from '@/app/editor/fonts'import { useLibraryService } from '@/app/libraries'@@ -52,16 +54,21 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {libraryService.bindEditor(store)registerComponentCatalog(store.graph, libraryService)const figma = makeFigma(store, target.pageId)- const result = def.mutates- ? await store.runMutationWithLayout(- () => def.execute(figma, toolArgs),- figma.currentPageId,- async () => {- const pageNode = store.graph.getNode(figma.currentPageId)- if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)- }- )- : await def.execute(figma, toolArgs)+ let result: unknown+ if (ATOMIC_TOOL_NAMES.has(def.name)) {+ result = await executeAtomicEditorTool(store, figma, def, toolArgs)+ } else if (def.mutates) {+ result = await store.runMutationWithLayout(+ () => def.execute(figma, toolArgs),+ figma.currentPageId,+ async () => {+ const pageNode = store.graph.getNode(figma.currentPageId)+ if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)+ }+ )+ } else {+ result = await def.execute(figma, toolArgs)+ }if (def.mutates) {store.requestRender()diff --git a/src/app/automation/execution/atomic.ts b/src/app/automation/execution/atomic.tsnew file mode 100644index 000000000..7888b052a--- /dev/null+++ b/src/app/automation/execution/atomic.ts@@ -0,0 +1,162 @@+import { isEqual } from 'es-toolkit'++import type { FigmaAPI } from '@open-pencil/core/figma-api'+import type { ToolDef } from '@open-pencil/core/tools'+import type { SceneGraph, SceneNode, Variable } from '@open-pencil/scene-graph'++import type { EditorStore } from '@/app/editor/active-store'++/** Audited synchronous operations: update existing nodes/values, never hierarchy or assets. */+export const ATOMIC_TOOL_NAMES: ReadonlySet<string> = new Set([+ 'update_node',+ 'set_rotation',+ 'set_opacity',+ 'set_radius',+ 'set_minmax',+ 'set_fill',+ 'set_stroke',+ 'set_effects',+ 'set_visible',+ 'set_blend',+ 'set_locked',+ 'set_stroke_align',+ 'set_layout',+ 'set_constraints',+ 'set_layout_child',+ 'set_text',+ 'set_font',+ 'set_font_range',+ 'set_text_resize',+ 'set_text_properties',+ 'set_variable',+ 'bind_variable',+ 'unbind_variable'+])++// Capture property changes across pages. Component synchronization remains editor-owned.+const MAX_TRANSACTION_NODES = 10_000++type MutationEditor = Pick<+ EditorStore,+ 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoEntry'+>+type Changes<T> = { id: string; before: Partial<T>; after: Partial<T> }++function changes<T extends object>(before: Map<string, T>, after: Map<string, T>): Changes<T>[] {+ const result: Changes<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 inverse: Partial<T> = {}+ const forward: Partial<T> = {}+ const keys = new Set([...Object.keys(previous), ...Object.keys(current)] as (keyof T)[])+ for (const key of keys) {+ if (isEqual(previous[key], current[key])) continue+ inverse[key] = structuredClone(previous[key])+ forward[key] = structuredClone(current[key])+ }+ if (Object.keys(forward).length) result.push({ id, before: inverse, after: forward })+ }+ if (before.size !== after.size) throw new Error('Atomic tools must not create nodes or variables')+ return result+}++/**+ * 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.+ */+export function executeAtomicTool(+ editor: MutationEditor,+ figma: FigmaAPI,+ def: ToolDef,+ args: Record<string, unknown>,+ options: { signal?: AbortSignal; isLive?: () => boolean; label?: string } = {}+): unknown {+ if (!ATOMIC_TOOL_NAMES.has(def.name)) throw new Error(`Not an atomic tool: ${def.name}`)+ options.signal?.throwIfAborted()+ if (editor.graph !== figma.graph || options.isLive?.() === false) {+ 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 nodes = structuredClone(graph.nodes)+ const variables = structuredClone(graph.variables)+ const pageId = figma.currentPageId++ const replay = (+ nodeChanges: Changes<SceneNode>[],+ variableChanges: Changes<Variable>[],+ direction: '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]))+ }+ graph.preserveSourceMetadataDuring(() => {+ for (const change of nodeChanges)+ graph.updateNode(change.id, structuredClone(change[direction]))+ })+ layout(+ graph,+ editor,+ pageId,+ variableChanges.length > 0,+ nodeChanges.map((change) => change.id)+ )+ editor.requestRender()+ }++ try {+ const result = def.execute(figma, args)+ if (result instanceof Promise) throw new Error('Atomic tools must execute synchronously')+ if (result && typeof result === 'object' && 'error' in result) {+ throw new Error(String(result.error))+ }+ 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 contentChanged =+ variableChanges.length > 0 ||+ nodeChanges.some((change) => Object.keys(change.after).some((key) => key !== 'source'))+ if (!contentChanged && nodeChanges.length) replay(nodeChanges, [], 'before')+ if (contentChanged) {+ editor.pushUndoEntry({+ label: `${options.label ?? 'Agent'}: ${def.name}`,+ inverse: () => replay(nodeChanges, variableChanges, 'before'),+ forward: () => replay(nodeChanges, variableChanges, 'after')+ })+ editor.requestRender()+ }+ return result+ } catch (error) {+ replay(changes(nodes, graph.nodes), changes(variables, graph.variables), 'before')+ throw error+ }+}++function layout(+ graph: SceneGraph,+ editor: MutationEditor,+ pageId: string,+ allPages: boolean,+ changedIds: 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)+ }+ for (const id of scopes) editor.runLayoutForNode(id)+}diff --git a/src/app/automation/execution/editor.ts b/src/app/automation/execution/editor.tsnew file mode 100644index 000000000..25832a4ea--- /dev/null+++ b/src/app/automation/execution/editor.ts@@ -0,0 +1,32 @@+import type { FigmaAPI } from '@open-pencil/core/figma-api'+import type { ToolDef } from '@open-pencil/core/tools'++import type { EditorStore } from '@/app/editor/active-store'+import { ensureGraphFonts } from '@/app/editor/fonts'++import { executeAtomicTool } from './atomic'++/** Commit first; asynchronous font availability is presentation work, not a transaction. */+export async function executeAtomicEditorTool(+ store: EditorStore,+ figma: FigmaAPI,+ def: ToolDef,+ args: Record<string, unknown>,+ options: Parameters<typeof executeAtomicTool>[4] = {}+): Promise<unknown> {+ const result = executeAtomicTool(store, figma, def, args, options)+ const targetId = typeof args.id === 'string' ? args.id : figma.currentPageId+ if (figma.graph.getNode(targetId)?.type === 'TEXT') {+ try {+ await ensureGraphFonts(figma.graph, [targetId], store.renderer)+ if (store.graph === figma.graph && options.isLive?.() !== false) {+ store.runLayoutForNode(targetId)+ store.requestRender()+ }+ } catch (error) {+ // The edit is already committed and undoable. Font failure must not report it as failed.+ console.warn('[Agent fonts]', error)+ }+ }+ return result+}diff --git a/tests/engine/app/automation/atomic-tools.test.ts b/tests/engine/app/automation/atomic-tools.test.tsnew file mode 100644index 000000000..b341b009a--- /dev/null+++ b/tests/engine/app/automation/atomic-tools.test.ts@@ -0,0 +1,153 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { FigmaAPI } from '@open-pencil/core/figma-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'++import { executeAtomicTool } from '@/app/automation/execution/atomic'++function setup() {+ const graph = new SceneGraph()+ const undo = new UndoManager()+ const figma = new FigmaAPI(graph)+ const editor = {+ graph,+ runLayoutForNode: () => undefined,+ requestRender: () => undefined,+ pushUndoEntry: undo.push.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 }+}++describe('atomic agent tools', () => {+ test('component edits and undo propagate through the editor synchronizer', async () => {+ const editor = createEditor()+ const figma = new FigmaAPI(editor.graph)+ const component = figma.createComponent()+ const instance = component.createInstance()+ await Promise.resolve()+ const def = ALL_TOOLS.find((tool) => tool.name === 'set_opacity')+ if (!def) throw new Error('Missing set_opacity')+ executeAtomicTool(editor, figma, def, { id: component.id, value: 0.5 })+ await Promise.resolve()+ expect(instance.opacity).toBe(0.5)+ editor.undo.undo()+ await Promise.resolve()+ expect(component.opacity).toBe(1)+ expect(instance.opacity).toBe(1)+ editor.undo.redo()+ await Promise.resolve()+ expect(instance.opacity).toBe(0.5)+ })++ test('undo targets the original page and keeps unrelated later changes', () => {+ const { figma, editor, undo, rectangle, tool } = setup()+ const pageId = figma.currentPage.id+ executeAtomicTool(editor, figma, tool('set_opacity'), { id: rectangle.id, value: 0.5 })+ const another = figma.createPage()+ figma.currentPage = another+ rectangle.name = 'Later name'+ undo.undo()+ expect(rectangle.opacity).toBe(1)+ expect(rectangle.name).toBe('Later name')+ expect(rectangle.parent?.id).toBe(pageId)+ expect(figma.currentPage.id).toBe(another.id)+ undo.redo()+ expect(rectangle.opacity).toBe(0.5)+ })++ test('variable values and bound nodes are undoable across pages', () => {+ const { figma, editor, undo, rectangle, tool } = setup()+ const collection = figma.createVariableCollection('Colors')+ const variable = figma.createVariable('Brand', 'COLOR', collection.id, {+ r: 1,+ g: 0,+ b: 0,+ a: 1+ })+ tool('set_fill').execute(figma, { id: rectangle.id, color: '#ff0000' })+ figma.bindVariable(rectangle.id, 'fills/0/color', variable.id)+ const page = figma.createPage()+ figma.currentPage = page+ executeAtomicTool(editor, figma, tool('set_variable'), {+ id: variable.id,+ mode: collection.defaultModeId,+ value: '#00ff00'+ })+ expect(+ figma.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]+ ).toMatchObject({ g: 1 })+ undo.undo()+ expect(+ figma.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]+ ).toMatchObject({ r: 1, g: 0 })+ undo.redo()+ expect(+ figma.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]+ ).toMatchObject({ r: 0, g: 1 })+ })++ test('partial failures roll back without adding history', () => {+ const { figma, editor, undo, rectangle } = setup()+ const def: ToolDef = {+ name: 'set_opacity',+ params: {},+ description: 'failure seam',+ mutates: true,+ execute: () => {+ rectangle.opacity = 0.25+ throw new Error('Failed')+ }+ }+ expect(() => executeAtomicTool(editor, figma, def, {})).toThrow('Failed')+ expect(rectangle.opacity).toBe(1)+ expect(undo.canUndo).toBe(false)+ })++ test('error results roll back; no-op operations do not create history', () => {+ const { figma, editor, undo, rectangle, tool } = setup()+ executeAtomicTool(editor, figma, tool('set_opacity'), { id: rectangle.id, value: 1 })+ expect(undo.canUndo).toBe(false)+ expect(() =>+ executeAtomicTool(editor, figma, tool('set_opacity'), { id: 'missing', value: 0 })+ ).toThrow()+ expect(undo.canUndo).toBe(false)+ })++ test('aborted and closed/replaced targets are rejected before mutation', () => {+ const { figma, editor, rectangle, tool } = setup()+ const signal = AbortSignal.abort()+ const args = { id: rectangle.id, value: 0.5 }+ expect(() => executeAtomicTool(editor, figma, tool('set_opacity'), args, { signal })).toThrow()+ expect(() =>+ executeAtomicTool(editor, figma, tool('set_opacity'), args, { isLive: () => false })+ ).toThrow('no longer open')+ editor.graph = new SceneGraph()+ expect(() => executeAtomicTool(editor, figma, tool('set_opacity'), args)).toThrow(+ 'no longer open'+ )+ expect(rectangle.opacity).toBe(1)+ })++ test('back-to-back calls produce separate undo entries', async () => {+ const { figma, editor, undo, rectangle, tool } = setup()+ await Promise.all(+ [0.5, 0.25].map(async (value) =>+ executeAtomicTool(editor, figma, tool('set_opacity'), { id: rectangle.id, value })+ )+ )+ expect(rectangle.opacity).toBe(0.25)+ undo.undo()+ expect(rectangle.opacity).toBe(0.5)+ undo.undo()+ expect(rectangle.opacity).toBe(1)+ })+})