AI-native design editor. Open-source Figma alternative.
fix(undo): keep only the layers an AI or MCP edit touched (#1000)
Danila Poyarkovbfe7a622d6d0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 94cafedc4..dd13bbe9f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -134,6 +134,7 @@### Fixed+- Keep memory flat while the AI chat or an MCP client edits a document (#587). Each edit kept two copies of its whole page in the undo history, about 10 MB a call on a 400-layer page, until the 200-step history limit, so long sessions grew until the app ran out of memory; an edit now keeps only the layers it changed, and undoing it leaves the other layers as they are.- Keep the new-tab button and the active tab in view when many documents are open. Tabs shrink before the tab bar scrolls, the clipped side fades with a chevron that scrolls to hidden tabs, and the new-tab button is a compact button beside the last tab instead of scrolling away with the tabs.- Show when the browser menubar has more menus than fit in the left panel. The clipped side fades out and a chevron scrolls to the hidden menus; before, Arrange and Text could be cut off with no sign the bar scrolls.- List storage documents as soon as storage settings are saved. The home tab kept asking to configure storage until it next refreshed, which happened on window focus or up to a minute later.diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex 199cb09ed..687fbd3ac 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -6,6 +6,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do- CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`. Headless raster export may dynamically load `canvaskit-wasm/full`; elsewhere `import type` and pass CanvasKit in.- Drawing and input share preview-aware geometry through `@open-pencil/core/geometry`, built on Scene Graph matrices. Use it for world/screen transforms, inverses, bounds, and handle placement.- Copies of part of a document, such as previews, history snapshots, and exports, come from `extractPageContext` or `extractExportGraph` in `packages/core/src/io/subgraph.ts`, not another copier. Pass `componentSets` when instances must switch variant and `shareTables` for a read-only view rebuilt often (`packages/core/tests/io/subgraph.test.ts`).+- Undo for structural AI and MCP edits records only the layers an edit touches with `capturePageChange`, whose capture shares unchanged values instead of deep-copying the page, since a page copy per tool call grows memory with every call. It relies on every change emitting a graph event and on values being replaced rather than written into, apart from the child lists, source metadata, and override maps it copies (`packages/core/tests/editor/history/page-change.test.ts`).## Layoutdiff --git a/packages/core/src/editor/bridges/undo.ts b/packages/core/src/editor/bridges/undo.tsindex 8915f9688..a495fad7f 100644--- a/packages/core/src/editor/bridges/undo.ts+++ b/packages/core/src/editor/bridges/undo.ts@@ -17,6 +17,8 @@ export function createUndoBridge(undoActions: UndoActions, selection: SelectionAredoAction: () => undoActions.redoAction(selection.validateEnteredContainer),snapshotPage: undoActions.snapshotPage,restorePageFromSnapshot: undoActions.restorePageFromSnapshot,+ capturePageChange: undoActions.capturePageChange,+ restorePageChange: undoActions.restorePageChange,pushUndoEntry: undoActions.pushUndoEntry}}diff --git a/packages/core/src/editor/history/atomic-tool.ts b/packages/core/src/editor/history/atomic-tool.tsindex 7637e99f4..e67e0a1d5 100644--- a/packages/core/src/editor/history/atomic-tool.ts+++ b/packages/core/src/editor/history/atomic-tool.ts@@ -1,5 +1,3 @@-import { isEqual } from 'es-toolkit'-import {captureGraphCheckpoint,type SceneGraph,@@ -11,36 +9,23 @@ import type { Editor } from '#core/editor/create'import type { FigmaAPI } from '#core/figma-api'import { isAtomicTool, type ToolDef } from '#core/tools/schema'+import { diffFields, type FieldChanges } from './diff'+// Capture property changes across pages. Component synchronization remains editor-owned.const MAX_TRANSACTION_NODES = 10_000type MutationEditor = Pick<Editor, 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoEntry'>-type Changes<T> = {- id: string- before: Partial<T>- after: Partial<T>- absent: Record<'before' | 'after', (keyof T)[]>-}-function changes<T extends object>(before: Map<string, T>, after: Map<string, T>): Changes<T>[] {- const result: Changes<T>[] = []+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 inverse: Partial<T> = {}- const forward: Partial<T> = {}- const absent: Changes<T>['absent'] = { before: [], after: [] }- const keys = new Set([...Object.keys(previous), ...Object.keys(current)] as (keyof T)[])- for (const key of keys) {- const existed = Object.hasOwn(previous, key)- const exists = Object.hasOwn(current, key)- if (existed === exists && isEqual(previous[key], current[key])) continue- inverse[key] = structuredClone(previous[key])- forward[key] = structuredClone(current[key])- if (!existed) absent.before.push(key)- if (!exists) absent.after.push(key)- }- if (Object.keys(forward).length) result.push({ id, before: inverse, after: forward, absent })+ 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@@ -72,8 +57,8 @@ export function executeAtomicTool(const pageId = figma.currentPageIdconst replay = (- nodeChanges: Changes<SceneNode>[],- variableChanges: Changes<Variable>[],+ nodeChanges: FieldChanges<SceneNode>[],+ variableChanges: FieldChanges<Variable>[],direction: 'before' | 'after') => {if (editor.graph !== graph) throw new Error('The target document has been replaced')diff --git a/packages/core/src/editor/history/diff.ts b/packages/core/src/editor/history/diff.tsnew file mode 100644index 000000000..557eebb02--- /dev/null+++ b/packages/core/src/editor/history/diff.ts@@ -0,0 +1,34 @@+import { isEqual } from 'es-toolkit'++/** The fields one record changed, each side holding its own copy of the values. */+export interface FieldChanges<T> {+ id: string+ before: Partial<T>+ after: Partial<T>+ /** Fields a side does not have, so restoring that side removes them. */+ absent: Record<'before' | 'after', (keyof T)[]>+}++/** Compares two states of one record field by field; `null` when nothing differs. */+export function diffFields<T extends object>(+ id: string,+ previous: T,+ current: T,+ skip: ReadonlySet<keyof T> = new Set()+): FieldChanges<T> | null {+ const before: Partial<T> = {}+ const after: Partial<T> = {}+ const absent: FieldChanges<T>['absent'] = { before: [], after: [] }+ const keys = new Set([...Object.keys(previous), ...Object.keys(current)] as (keyof T)[])+ for (const key of keys) {+ if (skip.has(key)) continue+ const existed = Object.hasOwn(previous, key)+ const exists = Object.hasOwn(current, key)+ if (existed === exists && isEqual(previous[key], current[key])) continue+ before[key] = structuredClone(previous[key])+ after[key] = structuredClone(current[key])+ if (!existed) absent.before.push(key)+ if (!exists) absent.after.push(key)+ }+ return Object.keys(after).length ? { id, before, after, absent } : null+}diff --git a/packages/core/src/editor/history/page-change.ts b/packages/core/src/editor/history/page-change.tsnew file mode 100644index 000000000..664144365--- /dev/null+++ b/packages/core/src/editor/history/page-change.ts@@ -0,0 +1,236 @@+import { isEqual } from 'es-toolkit'++import {+ cloneInstanceOverrideState,+ createSceneMutationImpact,+ recordSceneMutations,+ type FigmaSourcePayload,+ type SceneGraph,+ type SceneNode,+ type SourceMetadata+} from '@open-pencil/scene-graph'++import type { EditorContext } from '#core/editor/types'+import { computeAllLayouts } from '#core/layout'++import { diffFields, type FieldChanges } from './diff'++type Side = 'before' | 'after'++/**+ * The fields an edit changed on a layer that exists on both sides. Source metadata is compared+ * a level down and its `.fig` payload a level below that, so marking a field edited keeps that+ * change rather than the layer's whole `.fig` record.+ */+interface LayerUpdate {+ id: string+ fields: FieldChanges<SceneNode> | null+ source: FieldChanges<SourceMetadata> | null+ fig: FieldChanges<FigmaSourcePayload> | null+}++/** A parent's children in one state, listed parents first. */+interface ChildList {+ id: string+ childIds: string[]+}++/**+ * What one edit did to a page: copies of only the layers it created, deleted, or changed, so an+ * undo step costs what the edit touched rather than a copy of the whole page.+ */+export interface PageChange {+ pageId: string+ /** Layers as the edit left them, parents first. */+ created: SceneNode[]+ /** Layers as they were before the edit removed them, parents first. */+ deleted: SceneNode[]+ /** Fields the edit changed on layers that exist in both states, children aside. */+ updated: LayerUpdate[]+ /** Child lists that differ between the states, each side's parents first. */+ children: Record<Side, ChildList[]>+}++const NESTED_FIELDS: ReadonlySet<keyof SceneNode> = new Set(['childIds', 'parentId', 'source'])+const SOURCE_PAYLOAD: ReadonlySet<keyof SourceMetadata> = new Set(['fig'])++function diffLayer(id: string, previous: SceneNode, current: SceneNode): LayerUpdate | null {+ const update: LayerUpdate = {+ id,+ fields: diffFields(id, previous, current, NESTED_FIELDS),+ source: diffFields(id, previous.source, current.source, SOURCE_PAYLOAD),+ fig: diffFields(id, previous.source.fig, current.source.fig)+ }+ return update.fields || update.source || update.fig ? update : null+}++function withChanges<T extends object>(value: T, changes: FieldChanges<T> | null, side: Side): T {+ if (!changes) return value+ const result = { ...value, ...structuredClone(changes[side]) }+ for (const key of changes.absent[side]) Reflect.deleteProperty(result, key)+ return result+}++function restoreLayer(graph: SceneGraph, update: LayerUpdate, side: Side): void {+ const node = graph.getNode(update.id)+ if (!node) return+ const changes: Partial<SceneNode> = update.fields ? structuredClone(update.fields[side]) : {}+ if (update.source || update.fig) {+ changes.source = {+ ...withChanges(node.source, update.source, side),+ fig: withChanges(node.source.fig, update.fig, side)+ }+ }+ graph.restoreNodeProperties(update.id, changes, update.fields?.absent[side] ?? [])+}++/**+ * A copy that keeps the layer's values as they are now. Values are replaced, never written into+ * (`materialize-instance.ts` in `@open-pencil/fig`), so sharing them is safe; the graph edits+ * child lists, source metadata, and override maps in place, so those are copied.+ */+function captureNode(node: SceneNode): SceneNode {+ const { source, instanceOverrides } = node+ return {+ ...node,+ childIds: [...node.childIds],+ source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },+ instanceOverrides: cloneInstanceOverrideState(instanceOverrides)+ }+}++function capturePage(graph: SceneGraph, pageId: string): Map<string, SceneNode> {+ const captured = new Map<string, SceneNode>()+ const stack = [pageId]+ for (let id = stack.pop(); id !== undefined; id = stack.pop()) {+ const node = graph.getNode(id)+ if (!node) continue+ captured.set(id, captureNode(node))+ stack.push(...node.childIds)+ }+ return captured+}++function depthIn(nodes: (id: string) => SceneNode | undefined, id: string, pageId: string) {+ let depth = 0+ for (let node = nodes(id); node && node.id !== pageId; node = nodes(node.parentId ?? '')) depth+++ return depth+}++function isOnPage(graph: SceneGraph, node: SceneNode, pageId: string): boolean {+ for (let current: SceneNode | undefined = node; current;) {+ if (current.id === pageId) return true+ current = current.parentId ? graph.getNode(current.parentId) : undefined+ }+ return false+}++/** Adds one touched layer to the change, given its state on each side, if it has one. */+function recordLayer(+ change: PageChange,+ id: string,+ previous: SceneNode | undefined,+ current: SceneNode | undefined+): void {+ if (previous && !isEqual(previous.childIds, current?.childIds ?? [])) {+ change.children.before.push({ id, childIds: previous.childIds })+ }+ if (current && !isEqual(current.childIds, previous?.childIds ?? [])) {+ change.children.after.push({ id, childIds: [...current.childIds] })+ }+ if (!previous) {+ if (current) change.created.push(structuredClone(current))+ } else if (!current) {+ change.deleted.push(structuredClone(previous))+ } else {+ const update = diffLayer(id, previous, current)+ if (update) change.updated.push(update)+ }+}++/**+ * Starts recording an edit to a page. Call the returned function once the edit is done, also+ * when it failed, to stop recording and get what the edit changed.+ */+export function capturePageChange(graph: SceneGraph, pageId: string): () => PageChange {+ const captured = capturePage(graph, pageId)+ const impact = createSceneMutationImpact()+ const unbind = recordSceneMutations(graph, impact)++ return () => {+ unbind()+ const change: PageChange = {+ pageId,+ created: [],+ deleted: [],+ updated: [],+ children: { before: [], after: [] }+ }+ const touched = new Set([+ ...impact.changedNodeIds,+ ...impact.previousParentIds,+ ...impact.currentParentIds+ ])+ const beforeDepth = (id: string) => depthIn((key) => captured.get(key), id, pageId)+ const afterDepth = (id: string) => depthIn((key) => graph.getNode(key), id, pageId)+ for (const id of touched) {+ const live = graph.getNode(id)+ const current = live && isOnPage(graph, live, pageId) ? live : undefined+ recordLayer(change, id, captured.get(id), current)+ }+ const byDepth = (depth: (id: string) => number) => (a: { id: string }, b: { id: string }) =>+ depth(a.id) - depth(b.id)+ change.created.sort(byDepth(afterDepth))+ change.children.after.sort(byDepth(afterDepth))+ change.deleted.sort(byDepth(beforeDepth))+ change.children.before.sort(byDepth(beforeDepth))+ return change+ }+}++export function isEmptyPageChange(change: PageChange): boolean {+ return (+ change.created.length === 0 &&+ change.deleted.length === 0 &&+ change.updated.length === 0 &&+ change.children.before.length === 0 &&+ change.children.after.length === 0+ )+}++/**+ * Puts the layers an edit touched back as they were on one side of it. The graph must be as the+ * other side left it; layers the edit did not touch are left alone.+ */+export function applyPageChange(graph: SceneGraph, change: PageChange, side: Side): void {+ const restored = side === 'before' ? change.deleted : change.created+ const removed = side === 'before' ? change.created : change.deleted+ graph.preserveSourceMetadataDuring(() => {+ for (const node of restored) {+ const { parentId, childIds: _childIds, ...fields } = structuredClone(node)+ graph.createNode(node.type, parentId ?? change.pageId, { ...fields, childIds: [] })+ }+ // Parents come first, so a layer never moves under one of its own descendants.+ for (const { id, childIds } of change.children[side]) {+ for (const [index, childId] of childIds.entries()) {+ if (graph.getNode(id)?.childIds[index] !== childId) graph.insertChildAt(childId, id, index)+ }+ }+ // Layers that survive have moved out of the removed ones by now.+ for (const node of removed) graph.deleteNode(node.id)+ for (const update of change.updated) restoreLayer(graph, update, side)+ })+ graph.clearAbsPosCache()+}++/** Undoes or redoes an edit in the editor, whichever page is on screen. */+export function restorePageChange(ctx: EditorContext, change: PageChange, side: Side): void {+ if (!ctx.graph.getNode(change.pageId)) return+ applyPageChange(ctx.graph, change, side)+ computeAllLayouts(ctx.graph, change.pageId)+ if (change.pageId === ctx.state.currentPageId) {+ ctx.setSelectedIds(new Set())+ ctx.state.hoveredNodeId = null+ }+ ctx.requestRender()+}diff --git a/packages/core/src/editor/history/snapshot-graph.ts b/packages/core/src/editor/history/snapshot-graph.tsindex 2adc4d525..8f72e31d8 100644--- a/packages/core/src/editor/history/snapshot-graph.ts+++ b/packages/core/src/editor/history/snapshot-graph.ts@@ -2,8 +2,17 @@ import type { SceneGraph } from '@open-pencil/scene-graph'import { extractPageContext } from '#core/io/subgraph'+import { applyPageChange, type PageChange } from './page-change'import type { PageSnapshot } from './snapshot'+function pageContext(source: SceneGraph, pageId: string, nodeIds: string[]): SceneGraph {+ const graph = extractPageContext(source, pageId, nodeIds)+ graph.images = new Map(source.images)+ graph.variables = structuredClone(source.variables)+ graph.variableCollections = structuredClone(source.variableCollections)+ return graph+}+/*** A standalone copy of the document whose snapshot page is as it was when taken, so a past* state can be rendered or diffed next to the live one. Other pages are left empty.@@ -15,11 +24,26 @@ export function graphFromPageSnapshot(// `snapshotPage` records the page first.const page = snapshot.values().next().valueif (!page || !source.getNode(page.id)) return null- const graph = extractPageContext(source, page.id, [])- graph.images = new Map(source.images)- graph.variables = structuredClone(source.variables)- graph.variableCollections = structuredClone(source.variableCollections)+ const graph = pageContext(source, page.id, [])for (const node of snapshot.values()) graph.nodes.set(node.id, structuredClone(node))graph.clearAbsPosCache()return graph}++/**+ * A standalone copy of the document with the change's page on one side of the change. The+ * source must be as the change left it, as it is right after the edit. Other pages are left+ * empty.+ */+export function graphFromPageChange(+ source: SceneGraph,+ change: PageChange,+ side: 'before' | 'after'+): SceneGraph | null {+ const page = source.getNode(change.pageId)+ if (!page) return null+ const graph = pageContext(source, page.id, page.childIds)+ if (side === 'before') applyPageChange(graph, change, 'before')+ graph.clearAbsPosCache()+ return graph+}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex c705af8f9..3747a1280 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -14,8 +14,10 @@ export {} from './state/view'export { createDefaultEditorState, createEditor } from './create'export { executeAtomicTool } from './history/atomic-tool'+export type { PageChange } from './history/page-change'+export { isEmptyPageChange } from './history/page-change'export type { PageSnapshot } from './history/snapshot'-export { graphFromPageSnapshot } from './history/snapshot-graph'+export { graphFromPageChange, graphFromPageSnapshot } from './history/snapshot-graph'export type { ClipboardPayload, ClipboardSnapshot } from './clipboard/copy'export { resolvePasteTarget } from './clipboard/paste-target'export { playIslandRoots } from './play/islands'diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.tsindex e83b8b6f2..fa28c0f8a 100644--- a/packages/core/src/editor/undo.ts+++ b/packages/core/src/editor/undo.ts@@ -8,6 +8,11 @@ import type { UndoEntry } from '@open-pencil/scene-graph/undo'import { assertNodeEditable } from './capabilities'import { restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'+import {+ capturePageChange as startPageChange,+ restorePageChange as applyPageChangeToEditor,+ type PageChange+} from './history/page-change'import { collectNodePositions, pushPositionUndo } from './history/position'import {restorePageFromSnapshot as restorePageSnapshot,@@ -236,6 +241,15 @@ export function createUndoActions(ctx: EditorContext) {restorePageSnapshot(ctx, snapshot)}+ /** Starts recording an edit to a page; the returned function ends it with what changed. */+ function capturePageChange(pageId = ctx.state.currentPageId): () => PageChange {+ return startPageChange(ctx.graph, pageId)+ }++ function restorePageChange(change: PageChange, side: 'before' | 'after') {+ applyPageChangeToEditor(ctx, change, side)+ }+function pushUndoEntry(entry: UndoEntry) {ctx.undo.push(entry)}@@ -252,6 +266,8 @@ export function createUndoActions(ctx: EditorContext) {redoAction,snapshotPage,restorePageFromSnapshot,+ capturePageChange,+ restorePageChange,pushUndoEntry}}diff --git a/packages/core/tests/editor/history/page-change.test.ts b/packages/core/tests/editor/history/page-change.test.tsnew file mode 100644index 000000000..c88ddaa46--- /dev/null+++ b/packages/core/tests/editor/history/page-change.test.ts@@ -0,0 +1,116 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { createEditor, graphFromPageChange, isEmptyPageChange } from '@open-pencil/core/editor'++function setup() {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const card = editor.graph.createNode('FRAME', pageId, { name: 'Card', width: 200, height: 120 })+ const title = editor.graph.createNode('TEXT', card.id, { name: 'Title', text: 'Hello' })+ const badge = editor.graph.createNode('RECTANGLE', card.id, { name: 'Badge', width: 24 })+ const other = editor.graph.createNode('FRAME', pageId, { name: 'Other', x: 400 })+ return { editor, pageId, card, title, badge, other }+}++/** Records an edit, then checks that undo and redo bring back each side exactly. */+function roundTrip(editor: ReturnType<typeof setup>['editor'], edit: () => void) {+ const pageId = editor.state.currentPageId+ const before = editor.snapshotPage(pageId)+ const finish = editor.capturePageChange(pageId)+ edit()+ const change = finish()+ const after = editor.snapshotPage(pageId)++ editor.restorePageChange(change, 'before')+ expect(editor.snapshotPage(pageId)).toEqual(before)+ editor.restorePageChange(change, 'after')+ expect(editor.snapshotPage(pageId)).toEqual(after)+ return change+}++describe('page changes', () => {+ test('undo and redo restore created, edited, and deleted layers', () => {+ const { editor, card, title, badge } = setup()+ roundTrip(editor, () => {+ editor.graph.updateNode(title.id, { text: 'Changed', x: 12 })+ editor.graph.deleteNode(badge.id)+ const added = editor.graph.createNode('FRAME', card.id, { name: 'Added' })+ editor.graph.createNode('TEXT', added.id, { name: 'Inner', text: 'New' })+ })+ })++ test('undo and redo restore moves, including nesting two layers the other way round', () => {+ const { editor, pageId, card, title, other } = setup()+ roundTrip(editor, () => {+ editor.graph.insertChildAt(title.id, other.id, 0)+ editor.graph.reorderChild(other.id, pageId, 0)+ })+ roundTrip(editor, () => {+ editor.graph.reparentNode(other.id, card.id)+ })+ roundTrip(editor, () => {+ editor.graph.reparentNode(card.id, pageId)+ editor.graph.reparentNode(other.id, pageId)+ editor.graph.reparentNode(card.id, other.id)+ })+ })++ test('layers that survive a removed parent are moved back out first', () => {+ const { editor, pageId, card, other } = setup()+ roundTrip(editor, () => {+ const wrapper = editor.graph.createNode('FRAME', pageId, { name: 'Wrapper' })+ editor.graph.reparentNode(card.id, wrapper.id)+ editor.graph.reparentNode(other.id, wrapper.id)+ })+ })++ test('keeps copies of only the layers the edit touched', () => {+ const { editor, pageId, card, title, badge, other } = setup()+ const finish = editor.capturePageChange(pageId)+ editor.graph.updateNode(title.id, { text: 'Changed' })+ editor.graph.createNode('RECTANGLE', other.id, { name: 'New' })+ const change = finish()++ expect(change.updated.map((update) => update.id)).toEqual([title.id])+ expect(change.updated[0]?.fields?.after).toEqual({ text: 'Changed' })+ // Marking the field edited keeps that list, not the layer's whole source metadata.+ expect(change.updated[0]?.source?.after).toEqual({ editedFields: ['text'] })+ expect(change.updated[0]?.fig).toBeNull()+ expect(change.created.map((node) => node.name)).toEqual(['New'])+ expect(change.children.after.map((list) => list.id)).toEqual([other.id])++ // Undo edits the layers in place, leaving untouched ones as they are.+ const untouched = editor.graph.getNode(badge.id)+ const edited = editor.graph.getNode(title.id)+ editor.restorePageChange(change, 'before')+ expect(editor.graph.getNode(badge.id)).toBe(expectDefined(untouched, 'badge'))+ expect(editor.graph.getNode(title.id)).toBe(expectDefined(edited, 'title'))+ expect(editor.graph.getNode(card.id)?.childIds).toEqual([title.id, badge.id])+ })++ test('an edit that changes nothing is empty', () => {+ const { editor, pageId } = setup()+ const finish = editor.capturePageChange(pageId)+ expect(isEmptyPageChange(finish())).toBe(true)+ })++ test('builds standalone graphs of both sides of an edit', () => {+ const { editor, pageId, title, badge } = setup()+ const finish = editor.capturePageChange(pageId)+ editor.graph.updateNode(title.id, { text: 'Changed' })+ editor.graph.deleteNode(badge.id)+ const change = finish()++ const before = expectDefined(graphFromPageChange(editor.graph, change, 'before'), 'before')+ const after = expectDefined(graphFromPageChange(editor.graph, change, 'after'), 'after')+ expect(before.getNode(title.id)?.text).toBe('Hello')+ expect(before.getNode(badge.id)?.name).toBe('Badge')+ expect(after.getNode(title.id)?.text).toBe('Changed')+ expect(after.getNode(badge.id)).toBeUndefined()+ // Building the past side leaves the document alone.+ expect(editor.graph.getNode(title.id)?.text).toBe('Changed')+ expect(editor.graph.getNode(badge.id)).toBeUndefined()+ })+})diff --git a/src/app/ai/tools/changes/capture.ts b/src/app/ai/tools/changes/capture.tsindex ff0d94326..856929ddd 100644--- a/src/app/ai/tools/changes/capture.ts+++ b/src/app/ai/tools/changes/capture.ts@@ -1,7 +1,7 @@import { diffLines, type ChangeObject } from 'diff'import { compact } from 'es-toolkit/array'-import { graphFromPageSnapshot, type PageSnapshot } from '@open-pencil/core/editor'+import { graphFromPageChange, isEmptyPageChange, type PageChange } from '@open-pencil/core/editor'import { diffPageLayersJSX } from '@open-pencil/core/tools'import { changePreviewSize } from '@/app/ai/chat/preferences'@@ -47,19 +47,20 @@ export function clipChangedJSX(before: string, after: string): [string, string]}/**- * Records what a finished call changed on its page. The structural diff is immediate; images- * render afterwards from frozen copies of both states, so later edits cannot leak into them.+ * Records what a finished call changed on its page, called right after it while the page is as+ * the call left it. The structural diff is immediate; images render afterwards from frozen+ * copies of both states, so later edits cannot leak into them.*/export function recordToolChange(store: EditorStore,toolCallId: string,- before: PageSnapshot,- after: PageSnapshot+ pageChange: PageChange): ToolChange | null {- const beforeGraph = graphFromPageSnapshot(store.graph, before)- const afterGraph = graphFromPageSnapshot(store.graph, after)- const pageId = after.values().next().value?.id- if (!beforeGraph || !afterGraph || !pageId) return null+ if (isEmptyPageChange(pageChange)) return null+ const beforeGraph = graphFromPageChange(store.graph, pageChange, 'before')+ const afterGraph = graphFromPageChange(store.graph, pageChange, 'after')+ const { pageId } = pageChange+ if (!beforeGraph || !afterGraph) return null// The same JSX diff `diff_jsx` returns decides which layers changed.const layers = diffPageLayersJSX(beforeGraph, afterGraph, pageId)if (layers.length === 0) return nulldiff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex 71cdfb3c6..e3cb0885b 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -1,6 +1,6 @@import { tool } from 'ai'-import { graphFromPageSnapshot } from '@open-pencil/core/editor'+import { graphFromPageSnapshot, isEmptyPageChange } from '@open-pencil/core/editor'import type { FigmaAPI } from '@open-pencil/core/figma-api'import {registerComponentCatalog,@@ -82,28 +82,31 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnostif (!def.mutates) return def.execute(figma, args)// A step's calls may run concurrently; whole-page snapshots must not interleave.const release = await acquireMutation()- const before = store.snapshotPage(pageId)- if (toolChangesDocument(def)) recordRunBaseline(store, before)+ // The run's first edit to a page keeps the whole page, which `changeBaseline` diffs.+ if (toolChangesDocument(def) && !runBaseline(store, pageId)) {+ recordRunBaseline(store, store.snapshotPage(pageId))+ }+ const undoBefore = store.undo.peekUndo()+ const finishChange = store.capturePageChange(pageId)try {return await runTool(def, figma, args, pageId)} finally {- const after = store.snapshotPage(pageId)- // Atomic tools record their own undo entry.- if (!isAtomicTool(def)) {+ const change = finishChange()+ // Atomic tools record their own undo entry; an edit that changed nothing records none.+ if (!isAtomicTool(def) && !isEmptyPageChange(change)) {store.pushUndoEntry({label: `AI: ${def.name}`,- forward: () => store.restorePageFromSnapshot(after),- inverse: () => store.restorePageFromSnapshot(before)+ forward: () => store.restorePageChange(change, 'after'),+ inverse: () => store.restorePageChange(change, 'before')})}- // Every entry the run pushes belongs to its turn, view changes included: one left on- // top, such as a closing zoom to fit, would otherwise keep the turn from reverting.- // Atomic and snapshot edits both label their entries this way.- recordRunUndoEntry(store, `AI: ${def.name}`)+ // Every entry the run pushes belongs to its turn; atomic and page edits both label+ // their entries this way. View tools change nothing on the page and push none.+ recordRunUndoEntry(store, `AI: ${def.name}`, undoBefore)// View tools (selection, viewport, pages) cannot change the document.if (toolChangesDocument(def)) {try {- recordToolChange(store, toolCallId, before, after)+ recordToolChange(store, toolCallId, change)} catch (error) {// The change record is a review aid; the edit and its undo entry already stand.console.warn('Could not record AI tool change', error)diff --git a/src/app/ai/tools/run.ts b/src/app/ai/tools/run.tsindex 4456961ad..f25d6a430 100644--- a/src/app/ai/tools/run.ts+++ b/src/app/ai/tools/run.ts@@ -129,11 +129,20 @@ export function runBaseline(store: EditorStore, pageId: string): PageSnapshot |return getRunState(store).baselines.get(pageId) ?? null}-/** Note the entry an edit just pushed, if it carries the run's label (`AI: <tool>`). */-export function recordRunUndoEntry(store: EditorStore, label: string): void {+/**+ * Note the entry an edit just pushed, if it carries the run's label (`AI: <tool>`). An edit that+ * changed nothing pushes none, so the entry on top before it, `previous`, is not the edit's.+ */+export function recordRunUndoEntry(+ store: EditorStore,+ label: string,+ previous: UndoEntry | undefined+): void {const entry = store.undo.peekUndo()const { undoEntries } = getRunState(store)- if (entry?.label === label && !undoEntries.includes(entry)) undoEntries.push(entry)+ if (entry !== previous && entry?.label === label && !undoEntries.includes(entry)) {+ undoEntries.push(entry)+ }}export function runUndoEntries(store: EditorStore): readonly UndoEntry[] {diff --git a/src/app/automation/execution/editor.ts b/src/app/automation/execution/editor.tsindex 71b1e84af..07dd9e676 100644--- a/src/app/automation/execution/editor.ts+++ b/src/app/automation/execution/editor.ts@@ -1,6 +1,4 @@-import { isEqual } from 'es-toolkit'--import { executeAtomicTool } from '@open-pencil/core/editor'+import { executeAtomicTool, isEmptyPageChange } from '@open-pencil/core/editor'import type { FigmaAPI } from '@open-pencil/core/figma-api'import type { ToolDef } from '@open-pencil/core/tools'@@ -44,8 +42,8 @@ export async function executeAtomicEditorTool(}/**- * Run a structural edit as one undo step by snapshotting its page around it, as the AI chat- * does, so `undo` reverts what an automation client created, moved, or deleted.+ * Run a structural edit as one undo step by recording what it changes on its page, as the AI+ * chat does, so `undo` reverts what an automation client created, moved, or deleted.*/export async function executeWithPageUndo<T>(store: EditorStore,@@ -53,17 +51,17 @@ export async function executeWithPageUndo<T>(label: string,run: () => Promise<T>): Promise<T> {- const before = store.snapshotPage(pageId)+ const finishChange = store.capturePageChange(pageId)try {return await run()} finally {- const after = store.snapshotPage(pageId)+ const change = finishChange()// Read-only scripts and no-op edits must not leave empty steps in the user's history.- if (!isEqual(before, after)) {+ if (!isEmptyPageChange(change)) {store.pushUndoEntry({label,- forward: () => store.restorePageFromSnapshot(after),- inverse: () => store.restorePageFromSnapshot(before)+ forward: () => store.restorePageChange(change, 'after'),+ inverse: () => store.restorePageChange(change, 'before')})}}diff --git a/tests/app/ai/tools/run.test.ts b/tests/app/ai/tools/run.test.tsindex 42468328d..2ac5f2ef2 100644--- a/tests/app/ai/tools/run.test.ts+++ b/tests/app/ai/tools/run.test.ts@@ -10,7 +10,7 @@ import { FigmaAPI } from '@open-pencil/core/figma-api'import { createToolLoopTransport } from '@/app/ai/chat/transports'import { endRun, markRunPreview, runPageId, startRun } from '@/app/ai/tools'import { aiToolOverrides } from '@/app/ai/tools/preferences'-import { markRunWork } from '@/app/ai/tools/run'+import { markRunWork, runUndoEntries } from '@/app/ai/tools/run'import * as figmaFactory from '@/app/automation/bridge/figma-factory'import { createEditorStore } from '@/app/editor/session/create'import { presenceOf } from '@/app/presence/registry'@@ -121,6 +121,20 @@ const rectangle = {input: { type: 'RECTANGLE', x: 0, y: 0, width: 10, height: 10 }}+test("an edit that changes nothing adds no undo step and does not claim an earlier reply's", async () => {+ await withStore(async (store, { a }) => {+ aiToolOverrides.value = { ...aiToolOverrides.value, delete_node: true }+ const node = store.graph.createNode('RECTANGLE', a, { name: 'Card' })+ await runMessage(store, [{ toolName: 'delete_node', input: { id: node.id } }])+ const deleted = expectDefined(store.undo.peekUndo(), 'delete entry')+ expect(runUndoEntries(store)).toEqual([deleted])++ await runMessage(store, [{ toolName: 'delete_node', input: { id: 'missing' } }])+ expect(store.undo.peekUndo()).toBe(deleted)+ expect(runUndoEntries(store)).toEqual([])+ })+})+test('a run keeps working on its page while the user views another', async () => {await withStore(async (store, { a, b }) => {await runMessage(store, [(editor) => editor.switchPage(b), rectangle])diff --git a/tests/app/automation/bridge/handlers.test.ts b/tests/app/automation/bridge/handlers.test.tsindex e4d3f8d80..d23f48ee4 100644--- a/tests/app/automation/bridge/handlers.test.ts+++ b/tests/app/automation/bridge/handlers.test.ts@@ -153,6 +153,26 @@ describe('undo and redo', () => {expect(tab.store.graph.getNode(id)).toBeUndefined()})+ test('undo and redo of a deletion leave the layers it did not touch alone', async () => {+ const tab = createTab()+ const graph = tab.store.graph+ const kept = tab.store.createShape('RECTANGLE', 0, 0, 40, 40)+ const deleted = tab.store.createShape('RECTANGLE', 60, 0, 40, 40)+ const keptNode = graph.getNode(kept)+ const pageId = tab.store.state.currentPageId+ const order = [...(graph.getNode(pageId)?.childIds ?? [])]+ await request('tool', { document_id: tab.id, name: 'delete_node', args: { id: deleted } })++ await request('undo', { document_id: tab.id })+ expect(graph.getNode(deleted)?.x).toBe(60)+ expect(graph.getNode(pageId)?.childIds).toEqual(order)+ expect(graph.getNode(kept)).toBe(keptNode)++ await request('redo', { document_id: tab.id })+ expect(graph.getNode(deleted)).toBeUndefined()+ expect(graph.getNode(kept)).toBe(keptNode)+ })+test('undo reverts a render into a frame on another page', async () => {const tab = createTab()const graph = tab.store.graph