AI-native design editor. Open-source Figma alternative.
fix: return undone AI and MCP edits to saved (#1564)
Danila Poyarkov6e8e0e9b3c6b
diff --git a/changes/1564/fixed.md b/changes/1564/fixed.mdnew file mode 100644index 000000000..758017dc5--- /dev/null+++ b/changes/1564/fixed.md@@ -0,0 +1 @@+- Undoing every edit an AI agent or MCP client made returns the document to saved instead of leaving it marked as edited.diff --git a/oxlint.json b/oxlint.jsonindex 1b9a992ec..3276441dd 100644--- a/oxlint.json+++ b/oxlint.json@@ -202,6 +202,7 @@}],"open-pencil/no-core-parent-relative-imports": "error",+ "open-pencil/no-document-change-capture": "error","open-pencil/no-mcp-parent-relative-imports": "error","open-pencil/no-vue-parent-relative-imports": "error","open-pencil/no-cli-parent-relative-imports": "error",diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex 68b777ead..633e57dbe 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -11,7 +11,8 @@ 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`).-- Undo for structural AI and MCP edits records only what an edit touches with `captureDocumentChange`: the edit's page is copied up front, and another page or the document node the first time `SceneGraph.observeNodeChanges` reports it about to change, so code that writes into a node directly calls `willChangeNode` first. Copies share values rather than deep-copying, so values must be replaced rather than written into, apart from the child lists, source metadata, and override maps it copies; comments on the document node stay out of undo (`packages/core/tests/editor/history/document-change.test.ts`).+- 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`).+- 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`).## Layoutdiff --git a/packages/core/src/editor/alignment/arrange.ts b/packages/core/src/editor/alignment/arrange.tsindex 768145721..10676ca1d 100644--- a/packages/core/src/editor/alignment/arrange.ts+++ b/packages/core/src/editor/alignment/arrange.ts@@ -1,8 +1,4 @@-import {- captureDocumentChange,- isEmptyDocumentChange,- restoreDocumentChange-} from '#core/editor/history/document-change'+import { recordEdit } from '#core/editor/history/edit'import type { EditorContext } from '#core/editor/types'import {arrangeLayers,@@ -30,15 +26,8 @@ export function createArrangeActions(ctx: EditorContext) {if (ctx.graph !== graph) {throw new Error('The document changed while the layers were being arranged')}- const finish = captureDocumentChange(ctx.graph, ctx.state.currentPageId)- apply()- const change = finish()- if (isEmptyDocumentChange(change)) return- ctx.undo.push({- label: 'Arrange',- forward: () => restoreDocumentChange(ctx, change, 'after'),- inverse: () => restoreDocumentChange(ctx, change, 'before')- })+ // The moves land after the layout's await, so any batch open now is another edit's.+ recordEdit(ctx, { label: 'Arrange', ownStep: true }, apply)})} finally {ctx.requestRender()diff --git a/packages/core/src/editor/bridges/undo.ts b/packages/core/src/editor/bridges/undo.tsindex 9d4c87ee5..423598638 100644--- a/packages/core/src/editor/bridges/undo.ts+++ b/packages/core/src/editor/bridges/undo.ts@@ -31,7 +31,8 @@ export function createUndoBridge(},snapshotPage: undoActions.snapshotPage,restorePageFromSnapshot: undoActions.restorePageFromSnapshot,- captureDocumentChange: undoActions.captureDocumentChange,+ recordEdit: undoActions.recordEdit,+ recordEditAsync: undoActions.recordEditAsync,restoreDocumentChange: undoActions.restoreDocumentChange,pushUndoEntry: undoActions.pushUndoEntry,pushUndoStep: undoActions.pushUndoStepdiff --git a/packages/core/src/editor/history/edit.ts b/packages/core/src/editor/history/edit.tsnew file mode 100644index 000000000..845c87728--- /dev/null+++ b/packages/core/src/editor/history/edit.ts@@ -0,0 +1,83 @@+import {+ captureDocumentChange,+ isEmptyDocumentChange,+ restoreDocumentChange,+ type DocumentChange+} from '#core/editor/history/document-change'+import type { EditorContext } from '#core/editor/types'++export interface RecordEditOptions {+ /** The undo step's label. */+ label: string+ /** The page the edit is made from; it is recorded wherever in the document it lands. */+ pageId?: string+ /** False for an edit that records its own steps, such as an atomic tool's. */+ push?: boolean+ /**+ * Records the step on its own, settling any batch first, rather than as part of an open batch.+ * An edit that finishes after an await needs this: a batch open by then belongs to another+ * edit, such as a picker drag. `recordEditAsync` always does.+ */+ ownStep?: boolean+ /** Receives what the edit changed, also when it fails, before its step closes. */+ onRecorded?: (change: DocumentChange) => void+}++function begin(ctx: EditorContext, options: RecordEditOptions) {+ const finish = captureDocumentChange(ctx.graph, options.pageId ?? ctx.state.currentPageId)+ return () => {+ const change = finish()+ // An edit that changed nothing, such as a read-only script, leaves no empty step behind.+ if (options.push !== false && !isEmptyDocumentChange(change)) {+ const entry = {+ label: options.label,+ forward: () => restoreDocumentChange(ctx, change, 'after'),+ inverse: () => restoreDocumentChange(ctx, change, 'before')+ }+ if (options.ownStep) ctx.undo.pushStep(entry)+ else ctx.undo.push(entry)+ }+ options.onRecorded?.(change)+ }+}++/**+ * Runs a synchronous edit as one undo step of everything it changed in the document, also when+ * it throws part way, so what it did stays undoable. Its step is recorded in the same task as its+ * changes, as the document's unsaved state expects of an edit, and joins a batch open around it.+ */+export function recordEdit<T>(ctx: EditorContext, options: RecordEditOptions, run: () => T): T {+ const finish = begin(ctx, options)+ try {+ return run()+ } finally {+ finish()+ }+}++/**+ * Runs an edit that awaits before it finishes, such as an agent's tool call that loads fonts or+ * runs a layout, as one undo step. The edit stays open until its step is recorded, so the changes+ * it makes meanwhile count as its own rather than as edits outside the history. An edit made+ * elsewhere while it runs, such as the user's, lands in the same step: nothing tells whose write+ * is whose across an await. An edit that can compute first and apply in one go records only the+ * apply with `recordEdit` instead.+ */+export async function recordEditAsync<T>(+ ctx: EditorContext,+ options: RecordEditOptions,+ run: () => Promise<T>+): Promise<T> {+ // Capturing can throw; the edit opens only once it has, so a failure never leaves it open.+ const finish = begin(ctx, { ...options, ownStep: true })+ const close = ctx.undo.openEdit()+ try {+ return await run()+ } finally {+ try {+ finish()+ } finally {+ close()+ }+ }+}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex fdb89c33e..553f99cfe 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -26,6 +26,7 @@ export {export { createDefaultEditorState, createEditor } from './create'export { executeAtomicTool } 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'export { graphFromDocumentChange, graphFromPageSnapshot } from './history/snapshot/graph'export type { ClipboardPayload, ClipboardSnapshot, CopyOptions } from './clipboard/copy'diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.tsindex b82dfa1ab..2bb6c15bc 100644--- a/packages/core/src/editor/read-only/actions.ts+++ b/packages/core/src/editor/read-only/actions.ts@@ -9,7 +9,6 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set(['acceptingParent','acceptsChildren','canDistributeNodes',- 'captureDocumentChange','collectVariantOptions','findVariantByValues','getChildren',@@ -43,6 +42,9 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set(['isTopLevel','pageSwitchCount','previewRenameSelected',+ // Recording only: what the edit runs is refused or allowed on its own.+ 'recordEdit',+ 'recordEditAsync','resolveColorVariable','resolveNumberVariable','screenToCanvas',diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.tsindex 0afebaa5a..7386e61b4 100644--- a/packages/core/src/editor/undo.ts+++ b/packages/core/src/editor/undo.ts@@ -10,10 +10,14 @@ import { textAutoResizeChanges } from '#core/layout/text-auto-resize'import { assertNodeEditable } from './capabilities'import {- captureDocumentChange as startDocumentChange,restoreDocumentChange as applyDocumentChangeToEditor,type DocumentChange} from './history/document-change'+import {+ recordEdit as recordEditIn,+ recordEditAsync as recordEditAsyncIn,+ type RecordEditOptions+} from './history/edit'import { collectNodePositions, pushPositionUndo } from './history/position'import {restorePageFromSnapshot as restorePageSnapshot,@@ -252,18 +256,20 @@ export function createUndoActions(ctx: EditorContext) {restorePageSnapshot(ctx, snapshot)}- /**- * Starts recording an edit made from a page, wherever in the document it lands; the returned- * function ends it with what changed.- */- function captureDocumentChange(pageId = ctx.state.currentPageId): () => DocumentChange {- return startDocumentChange(ctx.graph, pageId)- }-function restoreDocumentChange(change: DocumentChange, side: 'before' | 'after') {applyDocumentChangeToEditor(ctx, change, side)}+ /** Runs a synchronous edit as one undo step of what it changed in the document. */+ function recordEdit<T>(options: RecordEditOptions, run: () => T): T {+ return recordEditIn(ctx, options, run)+ }++ /** Runs an edit that awaits before it finishes as one undo step, open until it ends. */+ function recordEditAsync<T>(options: RecordEditOptions, run: () => Promise<T>): Promise<T> {+ return recordEditAsyncIn(ctx, options, run)+ }+function pushUndoEntry(entry: UndoEntry) {ctx.undo.push(entry)}@@ -285,7 +291,8 @@ export function createUndoActions(ctx: EditorContext) {redoAction,snapshotPage,restorePageFromSnapshot,- captureDocumentChange,+ recordEdit,+ recordEditAsync,restoreDocumentChange,pushUndoEntry,pushUndoStepdiff --git a/packages/core/tests/editor/history/document-change.test.ts b/packages/core/tests/editor/history/document-change.test.tsindex ecc913a3e..66e470112 100644--- a/packages/core/tests/editor/history/document-change.test.ts+++ b/packages/core/tests/editor/history/document-change.test.ts@@ -1,5 +1,6 @@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'@@ -32,7 +33,7 @@ function documentState(editor: Editor) {/** Records an edit, then checks that undo and redo bring back each side exactly. */function roundTrip(editor: Editor, edit: () => void) {const before = documentState(editor)- const finish = editor.captureDocumentChange(editor.state.currentPageId)+ const finish = captureDocumentChange(editor.graph, editor.state.currentPageId)edit()const change = finish()const after = documentState(editor)@@ -97,7 +98,7 @@ describe('document changes', () => {test('keeps copies of only the layers the edit touched', () => {const { editor, pageId, card, title, badge, other } = setup()- const finish = editor.captureDocumentChange(pageId)+ const finish = captureDocumentChange(editor.graph, pageId)editor.graph.updateNode(title.id, { text: 'Changed' })editor.graph.createNode('RECTANGLE', other.id, { name: 'New' })const change = finish()@@ -121,13 +122,13 @@ describe('document changes', () => {test('an edit that changes nothing is empty', () => {const { editor, pageId } = setup()- const finish = editor.captureDocumentChange(pageId)+ const finish = captureDocumentChange(editor.graph, pageId)expect(isEmptyDocumentChange(finish())).toBe(true)})test('builds standalone graphs of both sides of an edit', () => {const { editor, pageId, title, badge } = setup()- const finish = editor.captureDocumentChange(pageId)+ const finish = captureDocumentChange(editor.graph, pageId)editor.graph.updateNode(title.id, { text: 'Changed' })editor.graph.deleteNode(badge.id)const change = finish()@@ -146,7 +147,7 @@ describe('document changes', () => {test('the past side of a move to another page keeps the layer on its first page', () => {const { editor, pageId, card } = setup()const second = editor.graph.addPage('Second')- const finish = editor.captureDocumentChange(pageId)+ const finish = captureDocumentChange(editor.graph, pageId)editor.graph.reparentNode(card.id, second.id)const change = finish()@@ -160,7 +161,7 @@ describe('document changes', () => {test('the past side of removing the page the edit ran on brings that page back', () => {const { editor, pageId, card } = setup()editor.graph.addPage('Second')- const finish = editor.captureDocumentChange(pageId)+ const finish = captureDocumentChange(editor.graph, pageId)editor.graph.deleteNode(pageId)const change = finish()@@ -174,7 +175,7 @@ describe('document changes', () => {const { editor, pageId, card, title } = setup()// Nothing in the graph's API makes a cycle; a damaged file can.expectDefined(editor.graph.getNode(card.id), 'card').parentId = title.id- const finish = editor.captureDocumentChange(pageId)+ const finish = captureDocumentChange(editor.graph, pageId)editor.graph.updateNode(title.id, { text: 'Changed' })expect(isEmptyDocumentChange(finish())).toBe(false)})@@ -242,12 +243,12 @@ describe('document changes', () => {test('comments are never part of a change, and undo leaves them as they are', () => {const { editor, pageId } = setup()const { graph } = editor- const finishComment = editor.captureDocumentChange(pageId)+ const finishComment = captureDocumentChange(editor.graph, pageId)writeComments(graph, [thread('first', pageId)])expect(isEmptyDocumentChange(finishComment())).toBe(true)// A step that renames the document and comments as it goes.- const finish = editor.captureDocumentChange(pageId)+ const finish = captureDocumentChange(editor.graph, pageId)graph.updateNode(graph.rootId, { name: 'Renamed' })writeComments(graph, [thread('first', pageId), thread('second', pageId)])const change = finish()diff --git a/packages/core/tests/editor/history/edit.test.ts b/packages/core/tests/editor/history/edit.test.tsnew file mode 100644index 000000000..26ff7f360--- /dev/null+++ b/packages/core/tests/editor/history/edit.test.ts@@ -0,0 +1,113 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core'++function setup() {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const card = editor.graph.createNode('RECTANGLE', pageId, { x: 0, width: 100, height: 50 })+ return { editor, pageId, card }+}++describe('recordEdit', () => {+ test('records a synchronous edit as one step', () => {+ const { editor, card } = setup()++ editor.recordEdit({ label: 'Move' }, () => {+ editor.graph.updateNode(card.id, { x: 40 })+ editor.graph.updateNode(card.id, { y: 10 })+ })++ expect(editor.undo.undo()).toBe('Move')+ expect(editor.graph.getNode(card.id)).toMatchObject({ x: 0, y: 0 })+ expect(editor.undo.canUndo).toBe(false)+ })++ test('joins a batch open around it, unless it records its own step', () => {+ const { editor, card } = setup()++ editor.undo.beginBatch('Drag')+ editor.recordEdit({ label: 'Move' }, () => editor.graph.updateNode(card.id, { x: 40 }))+ editor.undo.rollbackBatch()+ expect(editor.graph.getNode(card.id)?.x).toBe(0)+ expect(editor.undo.canUndo).toBe(false)++ editor.undo.beginBatch('Drag')+ editor.recordEdit({ label: 'Arrange', ownStep: true }, () =>+ editor.graph.updateNode(card.id, { x: 60 })+ )+ editor.undo.rollbackBatch()+ expect(editor.graph.getNode(card.id)?.x).toBe(60)+ expect(editor.undo.undo()).toBe('Arrange')+ })++ test('records what an edit did before it threw', () => {+ const { editor, card } = setup()++ expect(() =>+ editor.recordEdit({ label: 'Script' }, () => {+ editor.graph.updateNode(card.id, { x: 40 })+ throw new Error('failed part way')+ })+ ).toThrow('failed part way')++ expect(editor.undo.undo()).toBe('Script')+ expect(editor.graph.getNode(card.id)?.x).toBe(0)+ })++ test('leaves no step for an edit that changed nothing, and still reports it', () => {+ const { editor } = setup()+ let reported = false++ editor.recordEdit({ label: 'Read', onRecorded: () => (reported = true) }, () => undefined)++ expect(reported).toBe(true)+ expect(editor.undo.canUndo).toBe(false)+ })+})++describe('recordEditAsync', () => {+ test('keeps the edit open across awaits and records one step when it ends', async () => {+ const { editor, card } = setup()+ const open: boolean[] = []++ await editor.recordEditAsync({ label: 'Agent: arrange' }, async () => {+ open.push(editor.undo.isRecording)+ await Promise.resolve()+ editor.graph.updateNode(card.id, { x: 40 })+ await Promise.resolve()+ open.push(editor.undo.isRecording)+ })++ expect(open).toEqual([true, true])+ expect(editor.undo.isRecording).toBe(false)+ expect(editor.undo.undo()).toBe('Agent: arrange')+ expect(editor.graph.getNode(card.id)?.x).toBe(0)+ })++ test('closes the edit and keeps its changes undoable when it rejects', async () => {+ const { editor, card } = setup()++ const edit = editor.recordEditAsync({ label: 'Agent: eval' }, async () => {+ await Promise.resolve()+ editor.graph.updateNode(card.id, { x: 40 })+ throw new Error('script failed')+ })++ await expect(edit).rejects.toThrow('script failed')+ expect(editor.undo.isRecording).toBe(false)+ expect(editor.undo.undo()).toBe('Agent: eval')+ expect(editor.graph.getNode(card.id)?.x).toBe(0)+ })++ test('does not record a step for an edit that records its own', async () => {+ const { editor, card } = setup()++ await editor.recordEditAsync({ label: 'Agent', push: false }, async () => {+ await Promise.resolve()+ editor.graph.updateNode(card.id, { x: 40 })+ })++ expect(editor.undo.canUndo).toBe(false)+ })+})diff --git a/packages/scene-graph/src/undo.ts b/packages/scene-graph/src/undo.tsindex 1fb918c18..3860f6488 100644--- a/packages/scene-graph/src/undo.ts+++ b/packages/scene-graph/src/undo.ts@@ -25,6 +25,7 @@ export class UndoManager {private redoStack: UndoEntry[] = []private batches: UndoBatch[] = []private replaying = 0+ private openEdits = 0private readonly settlers = new Set<() => void>()private readonly limit: numberprivate readonly onChange: (() => void) | undefined@@ -185,6 +186,28 @@ export class UndoManager {return this.batches.length > 0}+ /**+ * Marks an edit whose step is recorded when it ends, such as an agent's call that awaits fonts+ * or a layout before it finishes. Returns the function that ends it; ending it twice is a no-op.+ */+ openEdit(): () => void {+ this.openEdits+++ let open = true+ return () => {+ if (!open) return+ open = false+ this.openEdits--+ }+ }++ /**+ * Whether a batch or an edit opened with `openEdit` will record a step for the changes made now,+ * so they are not edits outside the history.+ */+ get isRecording(): boolean {+ return this.isBatching || this.openEdits > 0+ }+/** Committed history, or changes in an open batch that a settling hook commits first. */get canUndo(): boolean {if (this.undoStack.length > 0) return truediff --git a/packages/scene-graph/tests/undo/open-edit.test.ts b/packages/scene-graph/tests/undo/open-edit.test.tsnew file mode 100644index 000000000..c4e322a46--- /dev/null+++ b/packages/scene-graph/tests/undo/open-edit.test.ts@@ -0,0 +1,26 @@+import { expect, test } from 'bun:test'++import { UndoManager } from '@open-pencil/scene-graph/undo'++test('an open edit records until it is ended, once', () => {+ const undo = new UndoManager()+ expect(undo.isRecording).toBe(false)++ const end = undo.openEdit()+ const other = undo.openEdit()+ expect(undo.isRecording).toBe(true)++ end()+ end()+ expect(undo.isRecording).toBe(true)+ other()+ expect(undo.isRecording).toBe(false)+})++test('a batch records as an open edit does', () => {+ const undo = new UndoManager()+ undo.beginBatch('Drag')+ expect(undo.isRecording).toBe(true)+ undo.commitBatch()+ expect(undo.isRecording).toBe(false)+})diff --git a/src/app/ai/tools/runner.ts b/src/app/ai/tools/runner.tsindex 7f61352af..4d56d1a9d 100644--- a/src/app/ai/tools/runner.ts+++ b/src/app/ai/tools/runner.ts@@ -1,4 +1,4 @@-import { isEmptyDocumentChange } from '@open-pencil/core'+import { executeAtomicTool, isEmptyDocumentChange, type DocumentChange } from '@open-pencil/core'import type { FigmaAPI } from '@open-pencil/core/figma-api'import { isAtomicTool, toolChangesDocument, type ToolDef } from '@open-pencil/core/tools'@@ -10,7 +10,7 @@ import {recordRunUndoEntry,type Run} from '@/app/ai/reply/run'-import { AUTOMATION_UNDO_LABEL, executeAtomicEditorTool } from '@/app/automation/execution/editor'+import { AUTOMATION_UNDO_LABEL, loadAtomicToolFonts } from '@/app/automation/execution/editor'import type { EditorStore } from '@/app/editor/active-store'import { ensureGraphFonts } from '@/app/editor/fonts'@@ -66,15 +66,8 @@ function writtenPageId(figma: FigmaAPI, args: Record<string, unknown>): string {return page?.id ?? figma.currentPageId}-async function execute(call: EditorToolCall, pageId: string, prefix: string): Promise<unknown> {+async function execute(call: EditorToolCall, pageId: string): Promise<unknown> {const { store, figma, def, args } = call- if (isAtomicTool(def)) {- return executeAtomicEditorTool(store, figma, def, args, {- label: prefix,- signal: call.signal,- isLive: call.isLive- })- }return store.runMutationWithLayout(() => def.execute(figma, args),pageId,@@ -89,7 +82,7 @@ async function execute(call: EditorToolCall, pageId: string, prefix: string): Prasync function recordReplyCall(call: EditorToolCall,reply: ReplyCall,- change: ReturnType<ReturnType<EditorStore['captureDocumentChange']>>,+ change: DocumentChange,undoBefore: ReturnType<EditorStore['undo']['peekUndo']>,viewPageId: string): Promise<void> {@@ -124,20 +117,32 @@ async function editAndRecord(call: EditorToolCall, reply: ReplyCall | null): Pro}const prefix = reply ? AI_UNDO_PREFIX : (call.source ?? AUTOMATION_UNDO_LABEL)const undoBefore = store.undo.peekUndo()- const finishChange = store.captureDocumentChange(pageId)+ const recorded: { change?: DocumentChange } = {}+ const options = {+ label: `${prefix}: ${def.name}`,+ pageId,+ onRecorded: (change: DocumentChange) => {+ recorded.change = change+ }+ }try {- return await execute(call, pageId, prefix)+ 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+ })+ )+ await loadAtomicToolFonts(store, figma, args, { isLive: call.isLive })+ return result+ }+ return await store.recordEditAsync(options, () => execute(call, pageId))} finally {- const change = finishChange()- // Atomic tools record their own entry; an edit that changed nothing records none.- if (!isAtomicTool(def) && !isEmptyDocumentChange(change)) {- store.pushUndoStep({- label: `${prefix}: ${def.name}`,- forward: () => store.restoreDocumentChange(change, 'after'),- inverse: () => store.restoreDocumentChange(change, 'before')- })+ if (reply && recorded.change) {+ await recordReplyCall(call, reply, recorded.change, undoBefore, viewPageId)}- if (reply) await recordReplyCall(call, reply, change, undoBefore, viewPageId)}}diff --git a/src/app/automation/execution/editor.ts b/src/app/automation/execution/editor.tsindex 812cb4859..342f4d89a 100644--- a/src/app/automation/execution/editor.ts+++ b/src/app/automation/execution/editor.ts@@ -1,6 +1,4 @@-import { executeAtomicTool, isEmptyDocumentChange } from '@open-pencil/core'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'@@ -16,15 +14,16 @@ export function isAutomationUndoLabel(label: string | null): boolean {return label?.startsWith(`${AUTOMATION_UNDO_LABEL}: `) === true}-/** Commit first; asynchronous font availability is presentation work, not a transaction. */-export async function executeAtomicEditorTool(+/**+ * Loads the fonts a committed atomic edit drew its text in. This is presentation work after the+ * edit's step, not part of it, so it runs outside the edit.+ */+export async function loadAtomicToolFonts(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)+ options: { isLive?: () => boolean } = {}+): Promise<void> {const targetId = typeof args.id === 'string' ? args.id : figma.currentPageIdif (figma.graph.getNode(targetId)?.type === 'TEXT') {try {@@ -38,7 +37,6 @@ export async function executeAtomicEditorTool(console.warn('[Agent fonts]', error)}}- return result}/**@@ -52,18 +50,5 @@ export async function executeWithDocumentUndo<T>(label: string,run: () => Promise<T>): Promise<T> {- const finishChange = store.captureDocumentChange(pageId)- try {- return await run()- } finally {- const change = finishChange()- // Read-only scripts and no-op edits must not leave empty steps in the user's history.- if (!isEmptyDocumentChange(change)) {- store.pushUndoStep({- label,- forward: () => store.restoreDocumentChange(change, 'after'),- inverse: () => store.restoreDocumentChange(change, 'before')- })- }- }+ return store.recordEditAsync({ label, pageId }, run)}diff --git a/src/app/document/io/changes.ts b/src/app/document/io/changes.tsindex 487a59c29..1148848c4 100644--- a/src/app/document/io/changes.ts+++ b/src/app/document/io/changes.ts@@ -48,8 +48,8 @@ export function createDocumentChanges(editor: Editor) {revision.value++contentRevision = revision.valueconst at = contentRevision- // Text editing and coalesced edits record their step when they end, not with each change.- if (editor.state.editingTextId !== null || editor.undo.isBatching) return+ // Text editing, coalesced edits, and edits that await record their step when they end.+ if (editor.state.editingTextId !== null || editor.undo.isRecording) returnqueueMicrotask(() => {if (historyRevision < at) outsideRevision = Math.max(outsideRevision, at)})diff --git a/tests/app/ai/tools/runner.test.ts b/tests/app/ai/tools/runner.test.tsindex 975c25569..aa19f23ea 100644--- a/tests/app/ai/tools/runner.test.ts+++ b/tests/app/ai/tools/runner.test.ts@@ -57,3 +57,25 @@ test('a call cancelled while it waits for its turn edits nothing', async () => {expect(store.graph.getChildren(pageId)).toEqual([])expect(store.undo.peekUndo()).toBeUndefined()})++test('undoing an asynchronous tool call returns the document to saved', async () => {+ const tool = (name: string) =>+ expectDefined(+ ALL_TOOLS.find((candidate) => candidate.name === name),+ name+ )+ const pageId = store.state.currentPageId+ const figma = makeFigmaFromStore(store, pageId)+ const ids = [0, 20, 40].map(+ (x) => store.graph.createNode('RECTANGLE', pageId, { x, y: x / 2, width: 100, height: 70 }).id+ )+ store.markDocumentSaved()++ await runEditorTool({ store, figma, def: tool('arrange'), args: { ids }, source: 'MCP' })+ await Promise.resolve()+ expect(store.hasUnsavedChanges()).toBe(true)++ store.undo.undo()+ await Promise.resolve()+ expect(store.hasUnsavedChanges()).toBe(false)+})diff --git a/tests/app/automation/execution/editor.test.ts b/tests/app/automation/execution/editor.test.tsnew file mode 100644index 000000000..c21b2fe71--- /dev/null+++ b/tests/app/automation/execution/editor.test.ts@@ -0,0 +1,37 @@+import 'fake-indexeddb/auto'+import { afterEach, beforeEach, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { executeWithDocumentUndo } from '@/app/automation/execution/editor'+import { createEditorStore, type EditorStore } from '@/app/editor/session/create'++let store: EditorStore++beforeEach(() => {+ Object.assign(globalThis, { window: { innerWidth: 1024, innerHeight: 768 } })+ store = createEditorStore(new SceneGraph())+})++afterEach(() => {+ store.dispose()+ Reflect.deleteProperty(globalThis, 'window')+})++test('undoing an automation edit that awaits returns the document to saved', async () => {+ const pageId = store.state.currentPageId+ store.markDocumentSaved()++ await executeWithDocumentUndo(store, pageId, 'Agent: eval', async () => {+ await Promise.resolve()+ store.graph.createNode('RECTANGLE', pageId, { width: 40, height: 20 })+ await Promise.resolve()+ })+ await Promise.resolve()+ expect(store.hasUnsavedChanges()).toBe(true)++ expect(store.undo.undo()).toBe('Agent: eval')+ await Promise.resolve()+ expect(store.graph.getChildren(pageId)).toEqual([])+ expect(store.hasUnsavedChanges()).toBe(false)+})diff --git a/tools/checks/lint/src/plugin.ts b/tools/checks/lint/src/plugin.tsindex cd1bb6db5..37ef28af3 100644--- a/tools/checks/lint/src/plugin.ts+++ b/tools/checks/lint/src/plugin.ts@@ -385,6 +385,7 @@ import {noDeepParentRelativeImports,noDeepParentRelativePaths,noCoreParentRelativeImports,+ noDocumentChangeCapture,noMcpParentRelativeImports,noVueParentRelativeImports,noCliParentRelativeImports,@@ -463,6 +464,7 @@ const plugin = {'no-deep-parent-relative-imports': noDeepParentRelativeImports,'no-deep-parent-relative-paths': noDeepParentRelativePaths,'no-core-parent-relative-imports': noCoreParentRelativeImports,+ 'no-document-change-capture': noDocumentChangeCapture,'no-mcp-parent-relative-imports': noMcpParentRelativeImports,'no-vue-parent-relative-imports': noVueParentRelativeImports,'no-cli-parent-relative-imports': noCliParentRelativeImports,diff --git a/tools/checks/lint/src/rules/imports.ts b/tools/checks/lint/src/rules/imports.tsindex b4c995549..fee7fa7e7 100644--- a/tools/checks/lint/src/rules/imports.ts+++ b/tools/checks/lint/src/rules/imports.ts@@ -227,7 +227,41 @@ const noCoreFrameworkImports = createImportSourceRule({`@open-pencil/core must stay framework-agnostic; do not import '${source}'.`})+/**+ * An edit records what it changed through `recordEdit` or `recordEditAsync`, which push its undo+ * step when the document's unsaved state expects it; capturing a change by hand elsewhere is how+ * an edit's step came to land after an await and left undone documents unsaved.+ */+const noDocumentChangeCapture: RuleDefinition = {+ meta: {+ type: 'problem',+ docs: {+ description:+ 'Disallow captureDocumentChange outside core editor history — record edits with recordEdit or recordEditAsync'+ },+ schema: []+ },+ create(context: RuleContext) {+ const file = normalizedFilename(context)+ // The history module owns the capture, and its tests exercise it directly.+ if (!file.includes('/src/') || file.includes('/packages/core/src/editor/history/')) return {}+ return {+ ImportSpecifier(node) {+ const imported =+ node.imported.type === 'Identifier' ? node.imported.name : node.imported.value+ if (imported !== 'captureDocumentChange') return+ context.report({+ node,+ message:+ 'Record the edit with recordEdit or recordEditAsync instead of capturing a document change by hand.'+ })+ }+ }+ }+}+export {+ noDocumentChangeCapture,noVueSelfPackageImports,noCrossPackageSourceImports,noDeepParentRelativeImports,diff --git a/tools/checks/lint/tests/document-change-capture.test.ts b/tools/checks/lint/tests/document-change-capture.test.tsnew file mode 100644index 000000000..2d04ca8ac--- /dev/null+++ b/tools/checks/lint/tests/document-change-capture.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from 'bun:test'++import { lint, ruleDiagnostics } from './helpers/lint.ts'++const rule = 'no-document-change-capture'+const rules = { [`open-pencil/${rule}`]: 'error' }+const capture = "import { captureDocumentChange } from '#core/editor/history/document-change'"++describe('no-document-change-capture', () => {+ test.each([+ 'packages/core/src/editor/alignment/arrange.ts',+ 'packages/core/src/tools/structure/arrange.ts',+ 'src/app/ai/tools/runner.ts'+ ])('rejects a capture in %s', async (path) => {+ expect(ruleDiagnostics(await lint(capture, rules, path), rule)).toHaveLength(1)+ })++ test.each([+ 'packages/core/src/editor/history/edit.ts',+ 'packages/core/tests/editor/history/document-change.test.ts'+ ])('accepts a capture in %s', async (path) => {+ expect(ruleDiagnostics(await lint(capture, rules, path), rule)).toHaveLength(0)+ })++ test('accepts the other document change helpers anywhere', async () => {+ const source =+ "import { isEmptyDocumentChange, restoreDocumentChange } from '#core/editor/history/document-change'"+ const path = 'packages/core/src/editor/undo.ts'+ expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(0)+ })+})