AI-native design editor. Open-source Figma alternative.
feat(ai): show what each AI edit changed in its tool call (#812)
Danila Poyarkovd2fd6db1412f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fc213e949..76138284f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,7 @@- Jump between pages from the command palette: it lists the pages you visited recently in the tab, **Go to page…** lists every page, and typing a page name finds it.- Choose how much an AI model thinks for each message from the chat composer, from Off to Extra high or the provider default. Anthropic, Google, DeepSeek, OpenAI, OpenRouter, and compatible models apply it, where reasoning effort previously reached only OpenAI and OpenRouter models. A model profile's thinking level, which replaces its free-text reasoning effort, sets the starting choice, and finished reasoning shows how long the model thought.- Read AI tool calls at a glance: each call shows a one-line summary and buttons that bring the layers it touched into view, even on another page. Expanded, it shows highlighted JSX, scripts, and JSON input and output, and exported images inline. A render call's JSX streams in as the model writes it, and a long run folds its earlier steps into one row.+- Review what each AI edit changed from its tool call in the chat: a before and after image with a comparison slider or highlighted changed pixels, and a diff of the layers' JSX. Both are saved with the conversation. Settings → Chat → Change previews sets the image size (240, 480, or 960 px) or turns images off to keep only the JSX diff. The chat AI can check its own work the same way with `diff_changes`, which compares the page or a layer with its state before the run edited it as a patch that `diff_apply` can replay.- Preview designs progressively on the canvas as direct AI providers stream JSX, without saving partial designs or adding intermediate undo steps. A preview stays with its page: it hides while you view another page and returns when you come back.- Write design trees as TSX with `@open-pencil/design-jsx` as the JSX import source, and render them with `renderTree`.- Swap the component behind an instance with `instance.swapComponent(component)` in the plugin API, as in Figma.diff --git a/bun.lock b/bun.lockindex 67ada07d2..b9118b492 100644--- a/bun.lock+++ b/bun.lock@@ -21,6 +21,7 @@"@codemirror/lang-json": "^6.0.2","@codemirror/language": "^6.12.4","@codemirror/lint": "^6.9.7",+ "@codemirror/merge": "^6.12.2","@codemirror/search": "^6.7.1","@codemirror/state": "^6.7.1","@codemirror/view": "^6.43.9",@@ -60,6 +61,7 @@"copy-to-clipboard": "^4.0.2","culori": "^4.0.2","dedent": "^1.7.2",+ "diff": "^8.0.4","es-toolkit": "^1.51.0","fflate": "^0.8.3","fuse.js": "^7.5.0",@@ -904,6 +906,8 @@"@codemirror/lint": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.42.0", "crelt": "^1.0.5" } }, "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg=="],+ "@codemirror/merge": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/highlight": "^1.0.0", "style-mod": "^4.1.0" } }, "sha512-V8JvyAPjHbPupqP7BeMcsdsYCbyPij74jxIbaIJDORI+VZzW44zFmon8bF+oxGWvOKhcRmkiUMXd8MxHr3YA2w=="],+"@codemirror/search": ["@codemirror/[email protected]", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.37.0", "crelt": "^1.0.5" } }, "sha512-uMe5UO6PamJtSHrXhhHOzSX3ReWtiJrva6GnPMwSOrZtiExb5X5eExhr2OUZQVvdxPsKpY3Ro2mFbQadpPWmHA=="],"@codemirror/state": ["@codemirror/[email protected]", "", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-9QzNDgE4EYDnAHfrTlR2lwiPciiOymLtwKK+8yHQzCc7GXhAP9xdEbEJFy2IWB1j9UGUl9BsgMmTo/ImA02T7A=="],diff --git a/package.json b/package.jsonindex 07f33dd71..211b4724a 100644--- a/package.json+++ b/package.json@@ -115,6 +115,7 @@"@codemirror/lang-json": "^6.0.2","@codemirror/language": "^6.12.4","@codemirror/lint": "^6.9.7",+ "@codemirror/merge": "^6.12.2","@codemirror/search": "^6.7.1","@codemirror/state": "^6.7.1","@codemirror/view": "^6.43.9",@@ -154,6 +155,7 @@"copy-to-clipboard": "^4.0.2","culori": "^4.0.2","dedent": "^1.7.2",+ "diff": "^8.0.4","es-toolkit": "^1.51.0","fflate": "^0.8.3","fuse.js": "^7.5.0",diff --git a/packages/core/src/editor/history/snapshot-graph.ts b/packages/core/src/editor/history/snapshot-graph.tsnew file mode 100644index 000000000..2adc4d525--- /dev/null+++ b/packages/core/src/editor/history/snapshot-graph.ts@@ -0,0 +1,25 @@+import type { SceneGraph } from '@open-pencil/scene-graph'++import { extractPageContext } from '#core/io/subgraph'++import type { PageSnapshot } from './snapshot'++/**+ * 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.+ */+export function graphFromPageSnapshot(+ source: SceneGraph,+ snapshot: PageSnapshot+): SceneGraph | null {+ // `snapshotPage` records the page first.+ const page = snapshot.values().next().value+ if (!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)+ for (const node of snapshot.values()) graph.nodes.set(node.id, structuredClone(node))+ graph.clearAbsPosCache()+ return graph+}diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex 2f8d272c6..da0f3a806 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -14,6 +14,8 @@ export {} from './state/view'export { createDefaultEditorState, createEditor } from './create'export { executeAtomicTool } from './history/atomic-tool'+export type { PageSnapshot } from './history/snapshot'+export { graphFromPageSnapshot } from './history/snapshot-graph'export type { ClipboardPayload, ClipboardSnapshot } from './clipboard/copy'export type { Editor } from './create'export { reapplyInstanceComponentProperties } from './components/properties'diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex 713f35fef..94010a1a7 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -600,4 +600,6 @@ export class FigmaAPI implements NodeProxyHost {exportImage?: (nodeIds: string[], options: ExportImageOptions) => Promise<Uint8Array | null>rasterCodec?: RasterCodec+ /** The document as it was before the current AI run first edited `pageId`, or null if unedited. */+ changeBaseline?: (pageId: string) => SceneGraph | null}diff --git a/packages/core/src/io/formats/raster/compare.ts b/packages/core/src/io/formats/raster/compare.tsnew file mode 100644index 000000000..282fead5e--- /dev/null+++ b/packages/core/src/io/formats/raster/compare.ts@@ -0,0 +1,44 @@+import pixelmatch from 'pixelmatch'++import type { RasterCodec } from './pixels'++export interface PixelComparison {+ width: number+ height: number+ changedPixels: number+ totalPixels: number+ /** Changed pixels in the highlight color over transparency, as a PNG; null when none. */+ mask: Uint8Array | null+}++export interface PixelComparisonOptions {+ /** Per-pixel color tolerance from 0 to 1 (pixelmatch's threshold). */+ threshold?: number+ highlight?: [number, number, number]+}++/** Compares two equally sized PNGs pixel by pixel, ignoring anti-aliasing noise. */+export function comparePNGs(+ codec: RasterCodec,+ before: Uint8Array,+ after: Uint8Array,+ options: PixelComparisonOptions = {}+): PixelComparison | null {+ const left = codec.decode(before)+ const right = codec.decode(after)+ if (!left || !right || left.width !== right.width || left.height !== right.height) return null+ const { width, height } = left+ const data = new Uint8Array(width * height * 4)+ const changedPixels = pixelmatch(left.data, right.data, data, width, height, {+ threshold: options.threshold ?? 0.1,+ diffColor: options.highlight ?? [255, 51, 102],+ diffMask: true+ })+ return {+ width,+ height,+ changedPixels,+ totalPixels: width * height,+ mask: changedPixels > 0 ? codec.encodePNG({ width, height, data }) : null+ }+}diff --git a/packages/core/src/io/formats/raster/index.ts b/packages/core/src/io/formats/raster/index.tsindex eb1f32b99..8d9085fe2 100644--- a/packages/core/src/io/formats/raster/index.ts+++ b/packages/core/src/io/formats/raster/index.ts@@ -7,3 +7,5 @@ export {} from './render'export { initCanvasKit, headlessRenderNodes, headlessRenderThumbnail } from './headless'export { createCanvasKitRasterCodec, type RasterCodec, type RGBAImage } from './pixels'+export { comparePNGs, type PixelComparison, type PixelComparisonOptions } from './compare'+export { renderRegionToImage, type RegionRenderOptions } from './region'diff --git a/packages/core/src/io/formats/raster/region.ts b/packages/core/src/io/formats/raster/region.tsnew file mode 100644index 000000000..34de9c80c--- /dev/null+++ b/packages/core/src/io/formats/raster/region.ts@@ -0,0 +1,41 @@+import type { CanvasKit } from 'canvaskit-wasm'++import type { Color, SceneGraph } from '@open-pencil/scene-graph'+import type { VisualBounds } from '@open-pencil/scene-graph/geometry'++import { SkiaRenderer } from '#core/canvas'++import { drawRegionToImage } from './render'++export interface RegionRenderOptions {+ /** Background behind the page content; the live canvas's page colour by default. */+ pageColor?: Color+}++/**+ * Renders everything on a page inside `bounds`, over the page colour, as a PNG. Two states of+ * one region rendered with the same bounds and scale align pixel for pixel.+ *+ * Each call uses a renderer of its own. Renderer caches are keyed by node ID, so drawing a past+ * state of live nodes with the editor's renderer would leave that geometry on the live canvas.+ */+export async function renderRegionToImage(+ ck: CanvasKit,+ graph: SceneGraph,+ pageId: string,+ bounds: VisualBounds,+ scale: number,+ options: RegionRenderOptions = {}+): Promise<Uint8Array | null> {+ const surface = ck.MakeSurface(1, 1)+ if (!surface) return null+ const renderer = new SkiaRenderer(ck, surface)+ try {+ if (options.pageColor) renderer.pageColor = options.pageColor+ await renderer.loadFonts()+ await renderer.prepareForExport(graph, pageId, graph.getNode(pageId)?.childIds ?? [])+ return drawRegionToImage(ck, renderer, graph, pageId, bounds, scale)+ } finally {+ renderer.destroy()+ }+}diff --git a/packages/core/src/io/formats/raster/render.ts b/packages/core/src/io/formats/raster/render.tsindex 197a0cf34..dae220d26 100644--- a/packages/core/src/io/formats/raster/render.ts+++ b/packages/core/src/io/formats/raster/render.ts@@ -7,7 +7,7 @@ import {type SceneNode} from '@open-pencil/scene-graph'import type { RenderColorSpace } from '@open-pencil/scene-graph/color'-import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry'+import { computeDescendantVisualBounds, type VisualBounds } from '@open-pencil/scene-graph/geometry'import type { SkiaRenderer } from '#core/canvas'import { extractExportGraph, findPageId } from '#core/io/subgraph'@@ -351,3 +351,22 @@ export function renderThumbnail(canvas.scale(scale, scale)})}++/** Draws a page region with `renderer`; `region.ts` gives it a renderer of its own. */+export function drawRegionToImage(+ ck: CanvasKit,+ renderer: SkiaRenderer,+ graph: SceneGraph,+ pageId: string,+ bounds: VisualBounds,+ scale: number+): Uint8Array | null {+ const pixelW = Math.max(1, Math.round((bounds.maxX - bounds.minX) * scale))+ const pixelH = Math.max(1, Math.round((bounds.maxY - bounds.minY) * scale))+ if (!graph.getNode(pageId) || !Number.isFinite(pixelW * pixelH)) return null+ return renderToSurface(ck, renderer, graph, pageId, pixelW, pixelH, 'PNG', 100, (canvas) => {+ canvas.clear(ck.Color4f(renderer.pageColor.r, renderer.pageColor.g, renderer.pageColor.b, 1))+ canvas.scale(scale, scale)+ canvas.translate(-bounds.minX, -bounds.minY)+ })+}diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.tsindex a1e7f59b5..1b5170531 100644--- a/packages/core/src/tools/ai-adapter.ts+++ b/packages/core/src/tools/ai-adapter.ts@@ -50,7 +50,12 @@ export interface StepBudget {export interface AIAdapterOptions {getFigma: () => FigmaAPIonBeforeExecute?: (def: ToolDef) => void- executeTool?: (def: ToolDef, figma: FigmaAPI, args: Record<string, unknown>) => Promise<unknown>+ executeTool?: (+ def: ToolDef,+ figma: FigmaAPI,+ args: Record<string, unknown>,+ call: { toolCallId: string }+ ) => Promise<unknown>onAfterExecute?: (def: ToolDef) => Promise<void> | voidonFlashNodes?: (nodeIds: string[]) => voidonToolLog?: (entry: ToolLogEntry) => void@@ -167,7 +172,7 @@ export function toolsToAI(const toolOpts: Record<string, unknown> = {description: def.description,inputSchema: toStandardJSONSchema(def.input),- execute: async (args: Record<string, unknown>) => {+ execute: async (args: Record<string, unknown>, { toolCallId }: { toolCallId: string }) => {const startTime = Date.now()const figma = options.getFigma()const nodeBefore =@@ -176,7 +181,7 @@ export function toolsToAI(options.onBeforeExecute?.(def)try {let execResult = options.executeTool- ? await options.executeTool(def, figma, args)+ ? await options.executeTool(def, figma, args, { toolCallId }): await def.execute(figma, args)if (def.mutates && options.onFlashNodes) {const ids = extractNodeIds(execResult)diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.tsindex 717c87452..fdfe3ccf9 100644--- a/packages/core/src/tools/analyze.ts+++ b/packages/core/src/tools/analyze.ts@@ -1,7 +1,15 @@export { analyzeClusters, calcClusterConfidence } from './analyze/clusters'export { analyzeColors } from './analyze/colors'-export { diffApply, diffCreate, diffDocuments, diffShow, diffVisual } from './analyze/diff'-export type { DocumentDiff, DocumentDiffOptions } from './analyze/diff'+export {+ diffApply,+ diffChanges,+ diffCreate,+ diffDocuments,+ diffPageLayersJSX,+ diffShow,+ diffVisual+} from './analyze/diff'+export type { DocumentDiff, DocumentDiffOptions, LayerJSXChange } from './analyze/diff'export { evalCode } from './analyze/eval'export { wrapEvalCode } from './analyze/eval/wrap'export { analyzeOverlaps, computeOverlaps } from './analyze/overlaps'diff --git a/packages/core/src/tools/analyze/diff/changes.ts b/packages/core/src/tools/analyze/diff/changes.tsnew file mode 100644index 000000000..355e9ecb0--- /dev/null+++ b/packages/core/src/tools/analyze/diff/changes.ts@@ -0,0 +1,73 @@+import * as v from 'valibot'++import { sceneNodeToJSX } from '@open-pencil/design-jsx'+import type { SceneGraph } from '@open-pencil/scene-graph'++import { findPageId } from '#core/io/subgraph'+import { defineTool } from '#core/tools/schema'++import { formatOperations } from './format'+import { deltaOperations, type DiffOperation } from './operations'+import { diffProjections, projectTree } from './projection'++/** Edits between two states of one tree, matching nodes by ID. */+function treeChanges(baseline: SceneGraph, graph: SceneGraph, rootId: string): DiffOperation[] {+ const before = projectTree(baseline, rootId, { match: 'id' })+ const after = projectTree(graph, rootId, { match: 'id' })+ if (!before || !after) return []+ return deltaOperations(diffProjections(before, after), before, after, (id) =>+ sceneNodeToJSX(id, graph)+ )+}++/**+ * Edits to one node. A node the run added or removed exists on one side only, so its+ * parent is compared instead, keeping the edits that add or remove it.+ */+function nodeChanges(+ baseline: SceneGraph,+ graph: SceneGraph,+ id: string,+ pageId: string+): DiffOperation[] {+ if (baseline.getNode(id) && graph.getNode(id)) return treeChanges(baseline, graph, id)+ const parentId = (graph.getNode(id) ?? baseline.getNode(id))?.parentId+ const rootId =+ parentId && baseline.getNode(parentId) && graph.getNode(parentId) ? parentId : pageId+ const added = graph.getNode(id) ? sceneNodeToJSX(id, graph) : null+ return treeChanges(baseline, graph, rootId).filter((operation) =>+ operation.kind === 'add' ? added !== null && operation.jsx.includes(added) : operation.id === id+ )+}++export const diffChanges = defineTool({+ name: 'diff_changes',+ description:+ 'Patch of what this run changed: a node, or the whole current page, compared with its page before the run first edited it. Same format as diff_create, matching nodes by ID, so diff_apply can replay it on the starting state. Use it before reporting to confirm that only the intended layers changed.',+ execution: { kind: 'sync', mutation: 'none' },+ // Only an AI chat run records the state it started from.+ exposure: { mcp: false, webmcp: false },+ input: v.object({+ id: v.optional(v.pipe(v.string(), v.description('Node to compare (default: the current page)')))+ }),+ execute: (figma, args) => {+ if (!figma.changeBaseline) return { error: 'diff_changes is available only in an AI chat run' }+ const targetId = args.id ?? figma.currentPage.id+ // A node is compared with its own page's baseline; a removed one is looked up on this page.+ const pageId = args.id+ ? (findPageId(figma.graph, args.id) ?? figma.currentPage.id)+ : figma.currentPage.id+ const baseline = figma.changeBaseline(pageId)+ if (!baseline) return { diff: null, message: 'This run has not changed that page' }+ if (!baseline.getNode(targetId) && !figma.graph.getNode(targetId)) {+ return { error: `Node "${targetId}" not found` }+ }+ const operations =+ targetId === pageId+ ? treeChanges(baseline, figma.graph, pageId)+ : nodeChanges(baseline, figma.graph, targetId, pageId)+ return operations.length === 0+ ? { diff: null, message: 'No differences found' }+ : { diff: formatOperations(operations) }+ }+})diff --git a/packages/core/src/tools/analyze/diff/index.ts b/packages/core/src/tools/analyze/diff/index.tsindex 56225b301..1dab61511 100644--- a/packages/core/src/tools/analyze/diff/index.ts+++ b/packages/core/src/tools/analyze/diff/index.ts@@ -1,3 +1,5 @@+export { diffChanges } from './changes'export { diffDocuments, type DocumentDiff, type DocumentDiffOptions } from './documents'export { diffApply, diffCreate, diffShow } from './tools'export { diffVisual } from './visual'+export { diffPageLayersJSX, jsxPatch, type LayerJSXChange } from './jsx'diff --git a/packages/core/src/tools/analyze/diff/jsx.ts b/packages/core/src/tools/analyze/diff/jsx.tsnew file mode 100644index 000000000..b3c2d732c--- /dev/null+++ b/packages/core/src/tools/analyze/diff/jsx.ts@@ -0,0 +1,55 @@+import { createTwoFilesPatch, FILE_HEADERS_ONLY } from 'diff'++import { sceneNodeToJSX } from '@open-pencil/design-jsx'+import type { SceneGraph } from '@open-pencil/scene-graph'++/** Unified diff of two JSX sources, as `diff_jsx` returns it; `null` when they match. */+export function jsxPatch(+ fromName: string,+ toName: string,+ fromJSX: string,+ toJSX: string+): string | null {+ if (fromJSX === toJSX) return null+ // Line-terminated sources keep "No newline at end of file" out of the patch.+ const lines = (jsx: string) => (jsx ? `${jsx}\n` : '')+ return createTwoFilesPatch(fromName, toName, lines(fromJSX), lines(toJSX), undefined, undefined, {+ context: 3,+ headerOptions: FILE_HEADERS_ONLY+ })+}++export interface LayerJSXChange {+ id: string+ /** Empty when the layer was added. */+ before: string+ /** Empty when the layer was removed. */+ after: string+ patch: string+}++function layerJSX(graph: SceneGraph, id: string): string {+ return graph.getNode(id) ? sceneNodeToJSX(id, graph) : ''+}++/**+ * Top-level layers of a page whose JSX differs between two states of a document, in their+ * order afterwards, then removed ones. Both graphs must share node IDs, as a snapshot does.+ */+export function diffPageLayersJSX(+ before: SceneGraph,+ after: SceneGraph,+ pageId: string+): LayerJSXChange[] {+ const ids = new Set([+ ...(after.getNode(pageId)?.childIds ?? []),+ ...(before.getNode(pageId)?.childIds ?? [])+ ])+ return [...ids].flatMap((id) => {+ const from = layerJSX(before, id)+ const to = layerJSX(after, id)+ const name = after.getNode(id)?.name ?? before.getNode(id)?.name ?? id+ const patch = jsxPatch(`${name} #${id}`, `${name} #${id}`, from, to)+ return patch === null ? [] : [{ id, before: from, after: to, patch }]+ })+}diff --git a/packages/core/src/tools/analyze/diff/tools.ts b/packages/core/src/tools/analyze/diff/tools.tsindex 66f6aa66b..b701aed4f 100644--- a/packages/core/src/tools/analyze/diff/tools.ts+++ b/packages/core/src/tools/analyze/diff/tools.ts@@ -114,10 +114,13 @@ export const diffShow = defineTool({export const diffApply = defineTool({name: 'diff_apply',description:- "Apply a patch from diff_create or diff_show. Each node must still have the patch's old values unless force is set, and nothing changes unless every hunk applies. Use dryRun to check first.",+ "Apply a patch from diff_create, diff_show, or diff_changes. Each node must still have the patch's old values unless force is set, and nothing changes unless every hunk applies. Use dryRun to check first.",execution: { kind: 'async', mutation: 'document' },input: v.object({- patch: v.pipe(v.string(), v.description('Patch text from diff_create or diff_show')),+ patch: v.pipe(+ v.string(),+ v.description('Patch text from diff_create, diff_show, or diff_changes')+ ),dryRun: v.optional(v.pipe(v.boolean(), v.description('Check and report changes without applying')),falsediff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex f99deda6c..e373b87b1 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -21,8 +21,8 @@ export { isAtomicTool, isToolExposed, type ToolInterface, type ToolExposure } frexport { toolNumber } from './input'export { toolsToAI, buildDebugLog } from './ai-adapter'export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'-export { calcClusterConfidence, diffDocuments, wrapEvalCode } from './analyze'-export type { DocumentDiff, DocumentDiffOptions } from './analyze'+export { calcClusterConfidence, diffDocuments, diffPageLayersJSX, wrapEvalCode } from './analyze'+export type { DocumentDiff, DocumentDiffOptions, LayerJSXChange } from './analyze'export {VALID_OVERLAP_CATEGORIES,VALID_OVERLAP_SCOPES,diff --git a/packages/core/src/tools/read/jsx.ts b/packages/core/src/tools/read/jsx.tsindex 347b8a51a..4c758052e 100644--- a/packages/core/src/tools/read/jsx.ts+++ b/packages/core/src/tools/read/jsx.ts@@ -1,8 +1,8 @@-import { createTwoFilesPatch } from 'diff'import * as v from 'valibot'import { sceneNodeToJSX } from '@open-pencil/design-jsx'+import { jsxPatch } from '#core/tools/analyze/diff/jsx'import { nodeIdInput, nodeComparisonInput } from '#core/tools/input'import { defineTool } from '#core/tools/schema'@@ -53,20 +53,12 @@ export const diffJSX = defineTool({const toNode = figma.getNodeById(to)if (!toNode) return { error: `Node "${to}" not found` }- const fromJSX = sceneNodeToJSX(from, figma.graph)- const toJSX = sceneNodeToJSX(to, figma.graph)-- if (fromJSX === toJSX) return { diff: null, message: 'No differences' }-- const patch = createTwoFilesPatch(+ const patch = jsxPatch(fromNode.name,toNode.name,- fromJSX,- toJSX,- 'source',- 'target',- { context: 3 }+ sceneNodeToJSX(from, figma.graph),+ sceneNodeToJSX(to, figma.graph))- return { diff: patch }+ return patch === null ? { diff: null, message: 'No differences' } : { diff: patch }}})diff --git a/packages/core/src/tools/registry-core.ts b/packages/core/src/tools/registry-core.tsindex 1ee289104..a18cea2e1 100644--- a/packages/core/src/tools/registry-core.ts+++ b/packages/core/src/tools/registry-core.ts@@ -1,4 +1,4 @@-import { diffCreate, diffVisual, evalCode } from './analyze'+import { diffChanges, diffCreate, diffVisual, evalCode } from './analyze'import { calc } from './calc'import { render } from './create'import { describe } from './describe'@@ -19,7 +19,7 @@ import { batchUpdate, deleteNode, nodeResize, reparentNode } from './structure'import { viewportZoomToFit } from './vector'/**- * Core tools registered by default in AI chat (25 tools, ~5K schema tokens).+ * Core tools registered by default in AI chat (26 tools, ~5K schema tokens).* Covers 90%+ of design sessions: render, describe, modify, structure, and diff checks.*/export const CORE_TOOLS: ToolDef[] = [@@ -48,6 +48,7 @@ export const CORE_TOOLS: ToolDef[] = [stockPhoto,// Inspect & utilitydescribe,+ diffChanges,diffCreate,diffJSX,diffVisual,diff --git a/packages/core/tests/editor/history/snapshot-graph.test.ts b/packages/core/tests/editor/history/snapshot-graph.test.tsnew file mode 100644index 000000000..19b0f02a6--- /dev/null+++ b/packages/core/tests/editor/history/snapshot-graph.test.ts@@ -0,0 +1,72 @@+import { describe, expect, test } from 'bun:test'++import { createEditor, graphFromPageSnapshot } from '@open-pencil/core/editor'+import {+ comparePNGs,+ createCanvasKitRasterCodec,+ initCanvasKit,+ renderRegionToImage+} from '@open-pencil/core/io/formats/raster'++import { expectDefined } from '#core-tests/helpers/assert'++function setup() {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const card = editor.graph.createNode('FRAME', pageId, { name: 'Card', width: 120, height: 80 })+ const label = editor.graph.createNode('TEXT', card.id, { name: 'Label', text: 'Hello' })+ return { editor, pageId, card, label }+}++describe('page snapshot graphs', () => {+ test('rebuilds the past page apart from the live document', () => {+ const { editor, pageId, label } = setup()+ const before = editor.snapshotPage(pageId)+ editor.graph.updateNode(label.id, { text: 'Changed' })++ const past = expectDefined(graphFromPageSnapshot(editor.graph, before), 'past graph')+ expect(past.getNode(label.id)?.text).toBe('Hello')+ past.updateNode(label.id, { text: 'Edited copy' })+ expect(editor.graph.getNode(label.id)?.text).toBe('Changed')+ })++ test('renders both states of a region at one size and finds the changed pixels', async () => {+ const { editor, pageId, card } = setup()+ editor.graph.updateNode(card.id, {+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }]+ })+ const before = editor.snapshotPage(pageId)+ editor.graph.updateNode(card.id, {+ fills: [{ type: 'SOLID', color: { r: 0.2, g: 0.4, b: 1, a: 1 }, opacity: 1, visible: true }]+ })+ const after = editor.snapshotPage(pageId)++ const ck = await initCanvasKit()+ const codec = createCanvasKitRasterCodec(ck)+ const bounds = { minX: -10, minY: -10, maxX: 130, maxY: 90 }+ const render = async (snapshot: typeof before) =>+ expectDefined(+ await renderRegionToImage(+ ck,+ expectDefined(graphFromPageSnapshot(editor.graph, snapshot), 'graph'),+ pageId,+ bounds,+ 0.5+ ),+ 'region PNG'+ )++ const unchanged = expectDefined(+ comparePNGs(codec, await render(before), await render(before)),+ 'same'+ )+ expect(unchanged).toMatchObject({ width: 70, height: 50, changedPixels: 0, mask: null })++ const changed = expectDefined(+ comparePNGs(codec, await render(before), await render(after)),+ 'changed'+ )+ expect(changed.changedPixels / changed.totalPixels).toBeGreaterThan(0.5)+ expect(changed.mask).toBeInstanceOf(Uint8Array)+ })+})diff --git a/packages/core/tests/tools/analyze/diff/changes.test.ts b/packages/core/tests/tools/analyze/diff/changes.test.tsnew file mode 100644index 000000000..f00eee976--- /dev/null+++ b/packages/core/tests/tools/analyze/diff/changes.test.ts@@ -0,0 +1,128 @@+import { expect, test } from 'bun:test'++import { createEditor, graphFromPageSnapshot } from '@open-pencil/core/editor'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import { sceneNodeToJSX } from '@open-pencil/design-jsx'++import { expectDefined } from '#core-tests/helpers/assert'++type ChangesResult = { diff?: string | null; message?: string; error?: string }++const diffChanges = expectDefined(+ ALL_TOOLS.find((tool) => tool.name === 'diff_changes'),+ 'diff_changes'+)+const diffApply = expectDefined(+ ALL_TOOLS.find((tool) => tool.name === 'diff_apply'),+ 'diff_apply'+)++function setup() {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const card = editor.graph.createNode('FRAME', pageId, { name: 'Card', width: 100, height: 60 })+ editor.graph.createNode('RECTANGLE', pageId, { name: 'Untouched', x: 300 })+ const figma = new FigmaAPI(editor.graph)+ figma.currentPage = figma.wrapNode(pageId)+ const baselines = new Map<string, ReturnType<typeof editor.snapshotPage>>()+ figma.changeBaseline = (id) => {+ const snapshot = baselines.get(id)+ return snapshot ? graphFromPageSnapshot(editor.graph, snapshot) : null+ }+ /** Records a page's state before the run edits it, as the app does. */+ const startEditing = (id = pageId) => baselines.set(id, editor.snapshotPage(id))+ return { editor, pageId, card, figma, startEditing }+}++async function run(figma: FigmaAPI, args: Record<string, unknown> = {}) {+ return (await diffChanges.execute(figma, args)) as ChangesResult+}++test('patches the page or one node against the page before the run edited it', async () => {+ const { editor, pageId, card, figma, startEditing } = setup()+ startEditing()+ editor.graph.updateNode(card.id, { width: 240 })+ editor.graph.createNode('ELLIPSE', pageId, { name: 'Badge' })++ const page = await run(figma)+ expect(page.diff).toContain(`@@ /Page 1/Card #${card.id}\n-w={100}\n+w={240}`)+ expect(page.diff).toContain(`@@ /Page 1/Badge added to #${pageId} at 2\n+<Ellipse name="Badge"`)+ expect(page.diff).not.toContain('Untouched')++ const node = await run(figma, { id: card.id })+ expect(node.diff).toBe(`@@ /Card #${card.id}\n-w={100}\n+w={240}`)+})++test('shows only the edit that adds or removes a node asked about', async () => {+ const { editor, pageId, card, figma, startEditing } = setup()+ startEditing()+ const badge = editor.graph.createNode('ELLIPSE', pageId, { name: 'Badge' })+ editor.graph.updateNode(card.id, { width: 240 })++ const added = await run(figma, { id: badge.id })+ expect(added.diff).toMatch(/^@@ \/Page 1\/Badge added to/)+ expect(added.diff).not.toContain('Card')++ editor.graph.deleteNode(card.id)+ expect((await run(figma, { id: card.id })).diff).toBe(`@@ /Page 1/Card #${card.id} removed`)+})++test('replays on the starting state with diff_apply', async () => {+ const { editor, pageId, card, figma, startEditing } = setup()+ startEditing()+ editor.graph.updateNode(card.id, { width: 240, opacity: 0.5 })+ editor.graph.createNode('ELLIPSE', pageId, { name: 'Badge' })+ const patch = expectDefined((await run(figma)).diff, 'patch')++ const start = expectDefined(figma.changeBaseline?.(pageId), 'baseline')+ const replay = new FigmaAPI(start)+ const applied = await diffApply.execute(replay, { patch })+ expect(applied).toMatchObject({ failed: 0 })+ expect(sceneNodeToJSX(pageId, start)).toBe(sceneNodeToJSX(pageId, editor.graph))+ expect(start.getNode(card.id)).toMatchObject({ width: 240, opacity: 0.5 })+})++test('covers every attribute the JSX export writes, such as an auto-layout gap', async () => {+ const { editor, card, figma, startEditing } = setup()+ editor.graph.updateNode(card.id, { layoutMode: 'VERTICAL', itemSpacing: 8 })+ startEditing()+ editor.graph.updateNode(card.id, { itemSpacing: 24 })++ const result = await run(figma, { id: card.id })+ expect(result.diff).toContain('gap={8}')+ expect(result.diff).toContain('gap={24}')+})++test('shows a rename as a changed name, not a removed and re-added layer', async () => {+ const { editor, card, figma, startEditing } = setup()+ startEditing()+ editor.graph.updateNode(card.id, { name: 'Hero' })++ const result = await run(figma)+ expect(result.diff).toBe(`@@ /Page 1/Card #${card.id}\n-name="Card"\n+name="Hero"`)+})++test("compares a node on another page with that page's own baseline", async () => {+ const { editor, figma, startEditing } = setup()+ const other = editor.graph.addPage('Other')+ const elsewhere = editor.graph.createNode('FRAME', other.id, { name: 'Elsewhere' })+ startEditing()++ // The run edited only the current page, so the other page has no baseline.+ expect(await run(figma, { id: elsewhere.id })).toEqual({+ diff: null,+ message: 'This run has not changed that page'+ })+ startEditing(other.id)+ editor.graph.updateNode(elsewhere.id, { width: 50 })+ expect((await run(figma, { id: elsewhere.id })).diff).toContain('w={50}')+})++test('explains when there is no run or no edit to compare with', async () => {+ const { figma } = setup()+ const noRun = new FigmaAPI(figma.graph)+ noRun.currentPage = figma.currentPage+ expect((await run(noRun)).error).toContain('AI chat run')+ expect(await run(figma)).toEqual({ diff: null, message: 'This run has not changed that page' })+})diff --git a/packages/core/tests/tools/analyze/diff/jsx.test.ts b/packages/core/tests/tools/analyze/diff/jsx.test.tsnew file mode 100644index 000000000..0a32226f1--- /dev/null+++ b/packages/core/tests/tools/analyze/diff/jsx.test.ts@@ -0,0 +1,32 @@+import { expect, test } from 'bun:test'++import { createEditor, graphFromPageSnapshot } from '@open-pencil/core/editor'+import { diffPageLayersJSX } from '@open-pencil/core/tools'++import { expectDefined } from '#core-tests/helpers/assert'++test('reports top-level layers changed deep in their subtree, added, or removed', () => {+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const card = editor.graph.createNode('FRAME', pageId, { name: 'Card', width: 120, height: 80 })+ const label = editor.graph.createNode('TEXT', card.id, { name: 'Label', text: 'Hello' })+ const other = editor.graph.createNode('RECTANGLE', pageId, { name: 'Other', x: 300 })+ editor.graph.createNode('RECTANGLE', pageId, { name: 'Untouched', x: 600 })+ const before = expectDefined(+ graphFromPageSnapshot(editor.graph, editor.snapshotPage(pageId)),+ 'before'+ )++ editor.graph.updateNode(label.id, { text: 'Hi' })+ const added = editor.graph.createNode('ELLIPSE', pageId, { name: 'Badge' })+ editor.graph.deleteNode(other.id)++ const changes = diffPageLayersJSX(before, editor.graph, pageId)+ expect(changes.map((change) => change.id)).toEqual([card.id, added.id, other.id])+ const [edited, created, removed] = changes+ expect(edited?.patch).toMatch(/^-.*Hello/m)+ expect(edited?.patch).toMatch(/^\+.*Hi/m)+ expect(created?.before).toBe('')+ expect(removed?.after).toBe('')+ expect(diffPageLayersJSX(editor.graph, editor.graph, pageId)).toEqual([])+})diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex 44223fdc6..3abb92dd4 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -40,6 +40,22 @@"toolSteps": "Frühere Schritte: {count}","toolStepsFailed": "fehlgeschlagen: {count}","showNodeOnCanvas": "{name} auf der Arbeitsfläche zeigen",+ "toolChanges": "Änderungen",+ "changeView": "Änderungsansicht",+ "changeCompare": "Vergleichen",+ "changeHighlight": "Hervorheben",+ "changeBefore": "Vorher",+ "changeAfter": "Nachher",+ "changeSplit": "Trennlinie zwischen vorher und nachher",+ "changeStructure": "Strukturänderungen",+ "changedPixels": "{percent} % der Pixel geändert",+ "noVisibleChange": "Keine sichtbare Änderung",+ "changePreview": "Änderungsvorschauen",+ "changePreviewHint": "Vorher-nachher-Bilder, die mit jeder KI-Bearbeitung im Chatverlauf gespeichert werden. Größere Vorschauen belegen mehr Speicher.",+ "changePreviewOff": "Aus, nur Struktur",+ "changePreviewSmall": "Klein (240 px)",+ "changePreviewMedium": "Mittel (480 px)",+ "changePreviewLarge": "Groß (960 px)","unknownTool": "Unbekanntes Werkzeug","permissionRequestTitle": "Berechtigungsanfrage","permissionRequest": "{tool} fordert eine Berechtigung an.",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 2d184f0b6..fd2c905cf 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -40,6 +40,22 @@"toolSteps": "Pasos anteriores: {count}","toolStepsFailed": "con errores: {count}","showNodeOnCanvas": "Mostrar {name} en el lienzo",+ "toolChanges": "Cambios",+ "changeView": "Vista de cambios",+ "changeCompare": "Comparar",+ "changeHighlight": "Resaltar",+ "changeBefore": "Antes",+ "changeAfter": "Después",+ "changeSplit": "División entre antes y después",+ "changeStructure": "Cambios de estructura",+ "changedPixels": "{percent} % de píxeles cambiados",+ "noVisibleChange": "Sin cambios visibles",+ "changePreview": "Vistas previas de cambios",+ "changePreviewHint": "Imágenes de antes y después que se guardan con cada edición de la IA en el historial del chat. Las vistas previas más grandes ocupan más espacio.",+ "changePreviewOff": "Desactivadas, solo estructura",+ "changePreviewSmall": "Pequeñas (240 px)",+ "changePreviewMedium": "Medianas (480 px)",+ "changePreviewLarge": "Grandes (960 px)","unknownTool": "Herramienta desconocida","permissionRequestTitle": "Solicitud de permiso","permissionRequest": "{tool} solicita permiso.",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex c192673d7..5578e9e03 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -40,6 +40,22 @@"toolSteps": "Étapes précédentes : {count}","toolStepsFailed": "en échec : {count}","showNodeOnCanvas": "Afficher {name} sur le canevas",+ "toolChanges": "Modifications",+ "changeView": "Vue des modifications",+ "changeCompare": "Comparer",+ "changeHighlight": "Surligner",+ "changeBefore": "Avant",+ "changeAfter": "Après",+ "changeSplit": "Séparation avant et après",+ "changeStructure": "Modifications de structure",+ "changedPixels": "{percent} % des pixels modifiés",+ "noVisibleChange": "Aucune modification visible",+ "changePreview": "Aperçus des modifications",+ "changePreviewHint": "Images avant et après conservées avec chaque modification de l’IA dans l’historique du chat. Les aperçus plus grands occupent plus d’espace.",+ "changePreviewOff": "Désactivés, structure seulement",+ "changePreviewSmall": "Petits (240 px)",+ "changePreviewMedium": "Moyens (480 px)",+ "changePreviewLarge": "Grands (960 px)","unknownTool": "Outil inconnu","permissionRequestTitle": "Demande d’autorisation","permissionRequest": "{tool} demande une autorisation.",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex 2c7bd33f7..efacb6fe8 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -40,6 +40,22 @@"toolSteps": "Passaggi precedenti: {count}","toolStepsFailed": "non riusciti: {count}","showNodeOnCanvas": "Mostra {name} nella tela",+ "toolChanges": "Modifiche",+ "changeView": "Vista delle modifiche",+ "changeCompare": "Confronta",+ "changeHighlight": "Evidenzia",+ "changeBefore": "Prima",+ "changeAfter": "Dopo",+ "changeSplit": "Divisione tra prima e dopo",+ "changeStructure": "Modifiche alla struttura",+ "changedPixels": "{percent}% dei pixel modificati",+ "noVisibleChange": "Nessuna modifica visibile",+ "changePreview": "Anteprime delle modifiche",+ "changePreviewHint": "Immagini prima e dopo conservate con ogni modifica dell’IA nella cronologia della chat. Le anteprime più grandi occupano più spazio.",+ "changePreviewOff": "Disattivate, solo struttura",+ "changePreviewSmall": "Piccole (240 px)",+ "changePreviewMedium": "Medie (480 px)",+ "changePreviewLarge": "Grandi (960 px)","unknownTool": "Strumento sconosciuto","permissionRequestTitle": "Richiesta di autorizzazione","permissionRequest": "{tool} richiede l’autorizzazione.",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex 36093ca17..1d7e38155 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -40,6 +40,22 @@"toolSteps": "以前のステップ: {count}","toolStepsFailed": "失敗: {count}","showNodeOnCanvas": "{name} をキャンバスに表示",+ "toolChanges": "変更",+ "changeView": "変更の表示",+ "changeCompare": "比較",+ "changeHighlight": "ハイライト",+ "changeBefore": "変更前",+ "changeAfter": "変更後",+ "changeSplit": "変更前と変更後の境界",+ "changeStructure": "構造の変更",+ "changedPixels": "{percent}% のピクセルが変更",+ "noVisibleChange": "見た目の変更なし",+ "changePreview": "変更のプレビュー",+ "changePreviewHint": "AI による各編集の変更前と変更後の画像をチャット履歴に保存します。大きいプレビューほど容量を使います。",+ "changePreviewOff": "オフ(構造のみ)",+ "changePreviewSmall": "小(240ピクセル)",+ "changePreviewMedium": "中(480ピクセル)",+ "changePreviewLarge": "大(960ピクセル)","unknownTool": "不明なツール","permissionRequestTitle": "権限リクエスト","permissionRequest": "{tool}が権限を要求しています。",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 92eb60098..1d951e9e4 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -40,6 +40,22 @@"toolSteps": "Wcześniejsze kroki: {count}","toolStepsFailed": "nieudane: {count}","showNodeOnCanvas": "Pokaż {name} na kanwie",+ "toolChanges": "Zmiany",+ "changeView": "Widok zmian",+ "changeCompare": "Porównaj",+ "changeHighlight": "Wyróżnij",+ "changeBefore": "Przed",+ "changeAfter": "Po",+ "changeSplit": "Podział między stanem przed i po",+ "changeStructure": "Zmiany struktury",+ "changedPixels": "Zmienione piksele: {percent}%",+ "noVisibleChange": "Brak widocznych zmian",+ "changePreview": "Podglądy zmian",+ "changePreviewHint": "Obrazy przed i po zapisywane z każdą edycją AI w historii czatu. Większe podglądy zajmują więcej miejsca.",+ "changePreviewOff": "Wyłączone, tylko struktura",+ "changePreviewSmall": "Małe (240 px)",+ "changePreviewMedium": "Średnie (480 px)",+ "changePreviewLarge": "Duże (960 px)","unknownTool": "Nieznane narzędzie","permissionRequestTitle": "Prośba o uprawnienie","permissionRequest": "{tool} prosi o uprawnienie.",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex 5f62e66ba..2fd804946 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -40,6 +40,22 @@"toolSteps": "Предыдущие шаги: {count}","toolStepsFailed": "с ошибкой: {count}","showNodeOnCanvas": "Показать {name} на холсте",+ "toolChanges": "Изменения",+ "changeView": "Вид изменений",+ "changeCompare": "Сравнить",+ "changeHighlight": "Подсветить",+ "changeBefore": "До",+ "changeAfter": "После",+ "changeSplit": "Граница между «до» и «после»",+ "changeStructure": "Изменения структуры",+ "changedPixels": "Изменено пикселей: {percent}%",+ "noVisibleChange": "Видимых изменений нет",+ "changePreview": "Превью изменений",+ "changePreviewHint": "Изображения «до» и «после», которые сохраняются в истории чата для каждой правки ИИ. Крупные превью занимают больше места.",+ "changePreviewOff": "Выключены, только структура",+ "changePreviewSmall": "Маленькие (240 px)",+ "changePreviewMedium": "Средние (480 px)",+ "changePreviewLarge": "Большие (960 px)","unknownTool": "Неизвестный инструмент","permissionRequestTitle": "Запрос разрешения","permissionRequest": "Инструмент «{tool}» запрашивает разрешение.",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex 9e82af4e3..a570942f8 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -40,6 +40,22 @@"toolSteps": "之前的步骤:{count}","toolStepsFailed": "失败:{count}","showNodeOnCanvas": "在画布上显示 {name}",+ "toolChanges": "更改",+ "changeView": "更改视图",+ "changeCompare": "对比",+ "changeHighlight": "高亮",+ "changeBefore": "之前",+ "changeAfter": "之后",+ "changeSplit": "前后分割线",+ "changeStructure": "结构更改",+ "changedPixels": "{percent}% 的像素已更改",+ "noVisibleChange": "无可见更改",+ "changePreview": "更改预览",+ "changePreviewHint": "AI 每次编辑前后的图像会保存在聊天记录中。预览越大,占用的存储空间越多。",+ "changePreviewOff": "关闭,仅结构",+ "changePreviewSmall": "小(240 像素)",+ "changePreviewMedium": "中(480 像素)",+ "changePreviewLarge": "大(960 像素)","unknownTool": "未知工具","permissionRequestTitle": "权限请求","permissionRequest": "{tool} 正在请求权限。",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex 60e7073a9..85dea38b5 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -82,6 +82,23 @@ export const aiMessageDefaults = {toolSteps: params('Earlier steps: {count}'),toolStepsFailed: params('failed: {count}'),showNodeOnCanvas: params('Show {name} on canvas'),+ toolChanges: 'Changes',+ changeView: 'Change view',+ changeCompare: 'Compare',+ changeHighlight: 'Highlight',+ changeBefore: 'Before',+ changeAfter: 'After',+ changeSplit: 'Before and after split',+ changeStructure: 'Structure changes',+ changedPixels: params('{percent}% of pixels changed'),+ noVisibleChange: 'No visible change',+ changePreview: 'Change previews',+ changePreviewHint:+ 'Before and after images kept with each AI edit in the chat history. Larger previews take more storage.',+ changePreviewOff: 'Off, structure only',+ changePreviewSmall: 'Small (240 px)',+ changePreviewMedium: 'Medium (480 px)',+ changePreviewLarge: 'Large (960 px)',unknownTool: 'Unknown tool',permissionRequestTitle: 'Permission request',permissionRequest: params('{tool} is requesting permission.'),diff --git a/src/app/ai/chat/history/messages.ts b/src/app/ai/chat/history/messages.tsindex aadcbed5e..aac4ae2a4 100644--- a/src/app/ai/chat/history/messages.ts+++ b/src/app/ai/chat/history/messages.ts@@ -1,4 +1,4 @@-import type { UIMessage } from 'ai'+import { isToolUIPart, type UIMessage } from 'ai'import { toRaw } from 'vue'import {@@ -6,6 +6,7 @@ import {setMessageAttachments} from '@/app/ai/attachment/presentation/store'import { visibleMessageText, setVisibleMessageText } from '@/app/ai/chat/presentation'+import { readToolChange, setToolChange } from '@/app/ai/tools/changes/store'import type { ConversationMessage } from './types'@@ -20,7 +21,11 @@ export function snapshotMessages(messages: UIMessage[]): ConversationMessage[] {displayText: visibleMessageText(message.id, text),attachments: attachmentsForMessage(message.id).value.map((attachment) =>structuredClone(toRaw(attachment))- )+ ),+ toolChanges: message.parts.flatMap((part) => {+ const change = isToolUIPart(part) ? readToolChange(part.toolCallId) : null+ return change ? [structuredClone(toRaw(change))] : []+ })}})}@@ -29,6 +34,7 @@ export function restoreMessages(messages: ConversationMessage[]): UIMessage[] {for (const row of messages) {if (row.displayText !== undefined) setVisibleMessageText(row.message.id, row.displayText)setMessageAttachments(row.message.id, row.attachments)+ for (const change of row.toolChanges ?? []) setToolChange(change)}return messages.map((row) => structuredClone(row.message))}diff --git a/src/app/ai/chat/history/session.ts b/src/app/ai/chat/history/session.tsindex 566d10b83..54bd86cfa 100644--- a/src/app/ai/chat/history/session.ts+++ b/src/app/ai/chat/history/session.ts@@ -1,6 +1,8 @@import { watchThrottled } from '@vueuse/core'import { watch } from 'vue'+import { toolChangesVersion } from '@/app/ai/tools/changes/store'+import type { HistoryChat } from './types'/** Owns live subscriptions; a failed final save deliberately leaves the session attached. */@@ -30,9 +32,12 @@ export function createHistorySession(reset: () => Promise<void>) {save()})+ // Change previews render after their message settles; save them when they arrive.+ const stopChanges = watchThrottled(toolChangesVersion, save, { throttle: 500, trailing: true })stopWatch = () => {stopMessages()stopStatus()+ stopChanges()}}diff --git a/src/app/ai/chat/history/types.ts b/src/app/ai/chat/history/types.tsindex 43eb2b26d..4dc891854 100644--- a/src/app/ai/chat/history/types.ts+++ b/src/app/ai/chat/history/types.ts@@ -2,6 +2,7 @@ import type { Chat } from '@ai-sdk/vue'import type { UIMessage } from 'ai'import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'+import type { ToolChange } from '@/app/ai/tools/changes/types'import type { ChatDocumentEditor } from './document'@@ -32,6 +33,8 @@ export interface ConversationMessage {message: UIMessagedisplayText?: stringattachments: AttachmentPresentation[]+ /** Absent in conversations saved before changes were recorded. */+ toolChanges?: ToolChange[]}export interface Conversation extends ConversationMeta {diff --git a/src/app/ai/chat/preferences.ts b/src/app/ai/chat/preferences.tsindex e8055794b..2f0e2bf74 100644--- a/src/app/ai/chat/preferences.ts+++ b/src/app/ai/chat/preferences.ts@@ -1,6 +1,10 @@import { computed } from 'vue'-import { appPreferences, type ReasoningDisplay } from '@/app/settings/preferences/store'+import {+ appPreferences,+ type ChangePreviewSize,+ type ReasoningDisplay+} from '@/app/settings/preferences/store'import { resolveAgentStepLimit } from './step-limit'@@ -23,3 +27,13 @@ export const reasoningDisplay = computed({}}})++export const changePreviewSize = computed({+ get: () => appPreferences.value.chat.changePreviewSize,+ set: (changePreviewSize: ChangePreviewSize) => {+ appPreferences.value = {+ ...appPreferences.value,+ chat: { ...appPreferences.value.chat, changePreviewSize }+ }+ }+})diff --git a/src/app/ai/chat/system-prompt.md b/src/app/ai/chat/system-prompt.mdindex da443110f..eae529198 100644--- a/src/app/ai/chat/system-prompt.md+++ b/src/app/ai/chat/system-prompt.md@@ -11,7 +11,7 @@ You are a design assistant inside OpenPencil. Create and modify designs using th- Ordinary JavaScript through `eval` is appropriate for supported scripting operations. Respect that environment's exposed API. Prefer auto-layout to arithmetic for content sizing; use `calc` only when it is useful.- Check actual rendered output when completing or reviewing visual work. Export the affected nodes rather than a huge page, inspect the image, and summarize what you observed. Structural diagnostics alone are not visual acceptance.- Edit existing designs in place with targeted property and structure tools; re-render a whole tree only when its structure must change.-- Use diffs to verify edits. Before a risky change to an existing design, `clone_node` it as a reference when that tool is available. Afterwards, `diff_jsx` or `diff_create` against the reference confirms the structural change, and `diff_visual` confirms that only the intended region changed: check `changedBounds` against your target and inspect the returned image. Delete the reference afterwards.+- Use diffs to verify edits. Before reporting, `diff_changes` lists what this run changed on the page, or under one node, against its state before the run; nothing needs to be cloned for it. Before a risky change to an existing design, `clone_node` it as a reference when that tool is available. Afterwards, `diff_jsx` or `diff_create` against the reference confirms the structural change, and `diff_visual` confirms that only the intended region changed: check `changedBounds` against your target and inspect the returned image. Delete the reference afterwards.- Select and focus the resulting design with the available selection and viewport tools so the user can see it. Do not repeatedly refocus while the user is working elsewhere.- Respect the remaining tool budget. If a budget warning appears, finish the current bounded step and report what remains.diff --git a/src/app/ai/tools/changes/capture.ts b/src/app/ai/tools/changes/capture.tsnew file mode 100644index 000000000..fe1fe3a71--- /dev/null+++ b/src/app/ai/tools/changes/capture.ts@@ -0,0 +1,91 @@+import { diffLines, type ChangeObject } from 'diff'++import { graphFromPageSnapshot, type PageSnapshot } from '@open-pencil/core/editor'+import { diffPageLayersJSX } from '@open-pencil/core/tools'++import { changePreviewSize } from '@/app/ai/chat/preferences'+import type { EditorStore } from '@/app/editor/active-store'++import { renderToolChangeImages } from './images'+import { setToolChange } from './store'+import type { ToolChange } from './types'++/** Longer sources keep only the changed region, so the history stays small. */+const MAX_JSX_LENGTH = 40_000+/** Unchanged source kept on each side of the changed region. */+const CLIP_CONTEXT = 2_000++function joinJSX(sources: string[]): string {+ return sources.filter(Boolean).join('\n\n')+}++function lineStart(text: string, index: number): number {+ return index <= 0 ? 0 : text.lastIndexOf('\n', index - 1) + 1+}++/**+ * Clips both sources to the region where they differ, plus context, so a change deep in a+ * long layer stays visible. Clipping each source from the start would cut it off.+ */+export function clipChangedJSX(before: string, after: string): [string, string] {+ if (before.length <= MAX_JSX_LENGTH && after.length <= MAX_JSX_LENGTH) return [before, after]+ // The unchanged lines before the first change and after the last one.+ const changes = diffLines(before, after)+ const unchanged = (change: ChangeObject<string> | undefined) =>+ change && !change.added && !change.removed ? change.value.length : 0+ const prefix = unchanged(changes[0])+ const suffix = changes.length > 1 ? unchanged(changes.at(-1)) : 0+ const clip = (text: string): string => {+ const from = lineStart(text, prefix - CLIP_CONTEXT)+ const to = Math.min(text.length, text.length - suffix + CLIP_CONTEXT)+ let region = text.slice(from, to)+ if (region.length > MAX_JSX_LENGTH) region = `${region.slice(0, MAX_JSX_LENGTH)}\n…`+ return `${from > 0 ? '…\n' : ''}${region}${to < text.length ? '\n…' : ''}`+ }+ return [clip(before), clip(after)]+}++/**+ * 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.+ */+export function recordToolChange(+ store: EditorStore,+ toolCallId: string,+ before: PageSnapshot,+ after: PageSnapshot+): 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+ // The same JSX diff `diff_jsx` returns decides which layers changed.+ const layers = diffPageLayersJSX(beforeGraph, afterGraph, pageId)+ if (layers.length === 0) return null+ const nodeIds = layers.map((layer) => layer.id)+ const [jsxBefore, jsxAfter] = clipChangedJSX(+ joinJSX(layers.map((layer) => layer.before)),+ joinJSX(layers.map((layer) => layer.after))+ )+ const change: ToolChange = {+ toolCallId,+ pageId,+ nodeIds,+ jsx: { before: jsxBefore, after: jsxAfter }+ }+ setToolChange(change)+ const size = changePreviewSize.value+ if (size !== 'off') {+ void (async () => {+ const images = await renderToolChangeImages(store, {+ beforeGraph,+ afterGraph,+ pageId,+ nodeIds,+ size+ })+ if (images) setToolChange({ ...change, images })+ })().catch((error: unknown) => console.warn('Could not render AI change previews', error))+ }+ return change+}diff --git a/src/app/ai/tools/changes/images.ts b/src/app/ai/tools/changes/images.tsnew file mode 100644index 000000000..3e4035735--- /dev/null+++ b/src/app/ai/tools/changes/images.ts@@ -0,0 +1,91 @@+import { promiseTimeout } from '@vueuse/core'++import {+ comparePNGs,+ computeContentBounds,+ createCanvasKitRasterCodec,+ renderRegionToImage+} from '@open-pencil/core/io/formats/raster'+import type { SceneGraph } from '@open-pencil/scene-graph'+import type { VisualBounds } from '@open-pencil/scene-graph/geometry'++import { boundedImageScale } from '@/app/ai/tools/vision'+import type { EditorStore } from '@/app/editor/active-store'+import type { ChangePreviewSize } from '@/app/settings/preferences/store'++import type { ToolChangeImages } from './types'++/** Longest stored image edge, in pixels, for each preview size. */+export const CHANGE_PREVIEW_MAX_EDGE: Record<Exclude<ChangePreviewSize, 'off'>, number> = {+ small: 240,+ medium: 480,+ large: 960+}++/** Context kept around the changed layers, in document units. */+const REGION_MARGIN = 16++interface ChangeRegion {+ beforeGraph: SceneGraph+ afterGraph: SceneGraph+ pageId: string+ nodeIds: string[]+ size: Exclude<ChangePreviewSize, 'off'>+}++function regionOf(graph: SceneGraph, nodeIds: string[]): VisualBounds | null {+ const present = nodeIds.filter((id) => graph.getNode(id) !== undefined)+ return present.length > 0 ? computeContentBounds(graph, present) : null+}++function unionRegion(regions: (VisualBounds | null)[]): VisualBounds | null {+ const known = regions.filter((region) => region !== null)+ if (known.length === 0) return null+ return {+ minX: Math.min(...known.map((region) => region.minX)) - REGION_MARGIN,+ minY: Math.min(...known.map((region) => region.minY)) - REGION_MARGIN,+ maxX: Math.max(...known.map((region) => region.maxX)) + REGION_MARGIN,+ maxY: Math.max(...known.map((region) => region.maxY)) + REGION_MARGIN+ }+}++function pngBlob(bytes: Uint8Array | null): Blob | null {+ return bytes ? new Blob([new Uint8Array(bytes)], { type: 'image/png' }) : null+}++/**+ * Renders the changed region in both states at the same bounds and scale, and highlights the+ * pixels that differ. Runs after the tool returns so the model never waits for it.+ */+export async function renderToolChangeImages(+ store: EditorStore,+ { beforeGraph, afterGraph, pageId, nodeIds, size }: ChangeRegion+): Promise<ToolChangeImages | null> {+ // Let the tool result reach the model before rendering.+ await promiseTimeout(0)+ const renderer = store.renderer+ if (!renderer) return null+ const bounds = unionRegion([regionOf(beforeGraph, nodeIds), regionOf(afterGraph, nodeIds)])+ if (!bounds) return null+ const scale = boundedImageScale(+ bounds.maxX - bounds.minX,+ bounds.maxY - bounds.minY,+ CHANGE_PREVIEW_MAX_EDGE[size]+ )+ if (scale <= 0) return null+ const { ck, pageColor } = renderer+ const [before, after] = await Promise.all([+ renderRegionToImage(ck, beforeGraph, pageId, bounds, scale, { pageColor }),+ renderRegionToImage(ck, afterGraph, pageId, bounds, scale, { pageColor })+ ])+ const comparison =+ before && after ? comparePNGs(createCanvasKitRasterCodec(ck), before, after) : null+ return {+ before: pngBlob(before),+ after: pngBlob(after),+ highlight: pngBlob(comparison?.mask ?? null),+ width: comparison?.width ?? 0,+ height: comparison?.height ?? 0,+ changedRatio: comparison ? comparison.changedPixels / comparison.totalPixels : 0+ }+}diff --git a/src/app/ai/tools/changes/store.ts b/src/app/ai/tools/changes/store.tsnew file mode 100644index 000000000..550365831--- /dev/null+++ b/src/app/ai/tools/changes/store.ts@@ -0,0 +1,21 @@+import { shallowReactive, shallowRef } from 'vue'++import type { ToolChange } from './types'++const changes = shallowReactive(new Map<string, ToolChange>())+/** Bumped whenever a change is recorded or its images arrive, so the history saves it. */+export const toolChangesVersion = shallowRef(0)++/** Reactive in a computed or template: the map tracks reads by key. */+export function readToolChange(toolCallId: string): ToolChange | null {+ return changes.get(toolCallId) ?? null+}++export function setToolChange(change: ToolChange): void {+ changes.set(change.toolCallId, change)+ toolChangesVersion.value+++}++export function clearToolChanges(): void {+ changes.clear()+}diff --git a/src/app/ai/tools/changes/types.ts b/src/app/ai/tools/changes/types.tsnew file mode 100644index 000000000..1b578322c--- /dev/null+++ b/src/app/ai/tools/changes/types.ts@@ -0,0 +1,22 @@+/** Images of the changed region before and after one AI edit, kept with the chat history. */+export interface ToolChangeImages {+ before: Blob | null+ after: Blob | null+ /** The after image with changed pixels highlighted; null when nothing visible changed. */+ highlight: Blob | null+ width: number+ height: number+ /** Share of the region's pixels that differ, from 0 to 1. */+ changedRatio: number+}++/** What one document-changing tool call did to its page, for review in the transcript. */+export interface ToolChange {+ toolCallId: string+ pageId: string+ /** Top-level layers added, removed, or changed. */+ nodeIds: string[]+ jsx: { before: string; after: string }+ /** Absent while rendering, or when previews are off. */+ images?: ToolChangeImages+}diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex 98102f148..9c358c751 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -1,6 +1,14 @@import { tool } from 'ai'-import { registerComponentCatalog, isAtomicTool, toolsToAI } from '@open-pencil/core/tools'+import { graphFromPageSnapshot } from '@open-pencil/core/editor'+import type { FigmaAPI } from '@open-pencil/core/figma-api'+import {+ registerComponentCatalog,+ isAtomicTool,+ toolChangesDocument,+ toolsToAI,+ type ToolDef+} from '@open-pencil/core/tools'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'import { executeAtomicEditorTool } from '@/app/automation/execution/editor'@@ -10,57 +18,94 @@ import { ensureGraphFonts } from '@/app/editor/fonts'import { useLibraryService } from '@/app/libraries'import { aiToolDefinitions } from './catalog'-import { markRunWork, moveRunToPage, runPageId, stepBudget } from './run'+import { recordToolChange } from './changes/capture'+import { createMutex } from './mutex'+import {+ markRunWork,+ moveRunToPage,+ recordRunBaseline,+ runBaseline,+ runPageId,+ stepBudget+} from './run'export { didHitStepLimit, endRun, recordStep, runPageId, startRun } from './run'export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnosticContext) {- let before: { pageId: string; snapshot: ReturnType<EditorStore['snapshotPage']> } | null = null+ const acquireMutation = createMutex()const libraryService = useLibraryService()libraryService.bindEditor(store)registerComponentCatalog(store.graph, libraryService)+ async function runTool(+ def: ToolDef,+ figma: FigmaAPI,+ args: Record<string, unknown>,+ pageId: string+ ): Promise<unknown> {+ if (isAtomicTool(def)) {+ return executeAtomicEditorTool(store, figma, def, args, { label: 'AI' })+ }+ return store.runMutationWithLayout(+ () => def.execute(figma, args),+ pageId,+ async () => {+ const pageNode = store.graph.getNode(pageId)+ if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)+ }+ )+ }+return toolsToAI(aiToolDefinitions,{- getFigma: () => makeFigmaFromStore(store, runPageId(store)),- executeTool: async (def, figma, args) => {+ getFigma: () => {+ const figma = makeFigmaFromStore(store, runPageId(store))+ figma.changeBaseline = (pageId) => {+ const baseline = runBaseline(store, pageId)+ return baseline ? graphFromPageSnapshot(store.graph, baseline) : null+ }+ return figma+ },+ executeTool: async (def, figma, args, { toolCallId }) => {const pageId = figma.currentPageId+ if (!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)try {- if (isAtomicTool(def)) {- return await executeAtomicEditorTool(store, figma, def, args, { label: 'AI' })- }- if (!def.mutates) return await def.execute(figma, args)- before = { pageId, snapshot: store.snapshotPage(pageId) }- return await store.runMutationWithLayout(- () => def.execute(figma, args),- pageId,- async () => {- const pageNode = store.graph.getNode(pageId)- if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)- }- )+ return await runTool(def, figma, args, pageId)} finally {- // `switch_page` moves the run, and the user's view with it.- if (figma.currentPageId !== pageId) await moveRunToPage(store, figma.currentPageId)- }- },- onAfterExecute: async (def) => {- if (isAtomicTool(def)) return- if (def.mutates) {- store.requestRender()- if (before) {- const { pageId, snapshot } = before- const after = store.snapshotPage(pageId)+ const after = store.snapshotPage(pageId)+ // Atomic tools record their own undo entry.+ if (!isAtomicTool(def)) {store.pushUndoEntry({label: `AI: ${def.name}`,forward: () => store.restorePageFromSnapshot(after),- inverse: () => store.restorePageFromSnapshot(snapshot)+ inverse: () => store.restorePageFromSnapshot(before)})- before = null+ }+ // View tools (selection, viewport, pages) cannot change the document.+ if (toolChangesDocument(def)) {+ try {+ recordToolChange(store, toolCallId, before, after)+ } 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)+ }+ }+ try {+ // `switch_page` moves the run, and the user's view with it.+ if (figma.currentPageId !== pageId) await moveRunToPage(store, figma.currentPageId)+ } finally {+ release()}}},+ onAfterExecute: (def) => {+ if (def.mutates && !isAtomicTool(def)) store.requestRender()+ },onFlashNodes: (nodeIds) => {markRunWork(store, nodeIds)store.renderer?.aiClearActive()diff --git a/src/app/ai/tools/mutex.ts b/src/app/ai/tools/mutex.tsnew file mode 100644index 000000000..9b7d22c72--- /dev/null+++ b/src/app/ai/tools/mutex.ts@@ -0,0 +1,13 @@+import { createDeferred } from '@/app/runtime/deferred'++/** Runs holders one at a time, in arrival order. `acquire` resolves with the release function. */+export function createMutex() {+ let tail: Promise<unknown> = Promise.resolve()+ return async function acquire(): Promise<() => void> {+ const { promise, resolve } = createDeferred<undefined>()+ const previous = tail+ tail = previous.then(() => promise)+ await previous+ return () => resolve(undefined)+ }+}diff --git a/src/app/ai/tools/run.ts b/src/app/ai/tools/run.tsindex 34309a001..885c2d5cb 100644--- a/src/app/ai/tools/run.ts+++ b/src/app/ai/tools/run.ts@@ -1,3 +1,4 @@+import type { PageSnapshot } from '@open-pencil/core/editor'import { computeContentBounds } from '@open-pencil/core/io'import type { StepBudget } from '@open-pencil/core/tools'@@ -14,11 +15,14 @@ class RunState {pageId: string | null = null/** The built-in chat as other people see it; one per document, kept between replies. */agent: AgentHandle | null = null+ /** Each page as it was before the run first edited it, for `diff_changes`. */+ baselines = new Map<string, PageSnapshot>()start(maxSteps: number, pageId: string): void {this.currentSteps = 0this.maxSteps = resolveAgentStepLimit(maxSteps)this.pageId = pageId+ this.baselines = new Map()}hitLimit(): boolean {@@ -88,3 +92,14 @@ export async function moveRunToPage(store: EditorStore, pageId: string): PromisegetRunState(store).pageId = pageIdif (store.state.currentPageId !== pageId) await store.switchPage(pageId)}++/** Keep `snapshot` as the run's starting state of its page unless the run already edited it. */+export function recordRunBaseline(store: EditorStore, snapshot: PageSnapshot): void {+ const pageId = snapshot.values().next().value?.id+ const { baselines } = getRunState(store)+ if (pageId && !baselines.has(pageId)) baselines.set(pageId, snapshot)+}++export function runBaseline(store: EditorStore, pageId: string): PageSnapshot | null {+ return getRunState(store).baselines.get(pageId) ?? null+}diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.tsindex 9006e71a3..c79ca04a6 100644--- a/src/app/settings/preferences/store.ts+++ b/src/app/settings/preferences/store.ts@@ -8,11 +8,19 @@ export type AnimationPreference = 'system' | 'off'export type ReasoningDisplay = 'collapsed' | 'while-thinking' | 'expanded'+export const CHANGE_PREVIEW_SIZES = ['off', 'small', 'medium', 'large'] as const+/** How large the before/after images kept for each AI edit are; `off` keeps only the JSX diff. */+export type ChangePreviewSize = (typeof CHANGE_PREVIEW_SIZES)[number]+export type CanvasRenderingMode = 'retained' | 'tiled'export interface AppPreferences {appearance: { animations: AnimationPreference }- chat: { reasoningDisplay: ReasoningDisplay; maxAgentSteps: number }+ chat: {+ reasoningDisplay: ReasoningDisplay+ maxAgentSteps: number+ changePreviewSize: ChangePreviewSize+ }version: 1recovery: {enabled: boolean@@ -27,7 +35,11 @@ export interface AppPreferences {export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {appearance: { animations: 'system' },- chat: { reasoningDisplay: 'collapsed', maxAgentSteps: DEFAULT_AGENT_STEPS },+ chat: {+ reasoningDisplay: 'collapsed',+ maxAgentSteps: DEFAULT_AGENT_STEPS,+ changePreviewSize: 'medium'+ },version: 1,recovery: { enabled: true },editing: {@@ -50,7 +62,7 @@ interface StoredSnappingPreferences {interface StoredAppPreferences {appearance?: { animations?: unknown }- chat?: { reasoningDisplay?: unknown; maxAgentSteps?: unknown }+ chat?: { reasoningDisplay?: unknown; maxAgentSteps?: unknown; changePreviewSize?: unknown }recovery?: { enabled?: unknown }editing?: { snapping?: StoredSnappingPreferences }rendering?: { canvasMode?: unknown }@@ -70,7 +82,10 @@ function normalizeChatPreferences(chat: StoredAppPreferences['chat']): AppPreferreasoningDisplay:chat?.reasoningDisplay === 'expanded' || chat?.reasoningDisplay === 'while-thinking'? chat.reasoningDisplay- : 'collapsed'+ : 'collapsed',+ changePreviewSize: CHANGE_PREVIEW_SIZES.includes(chat?.changePreviewSize as ChangePreviewSize)+ ? (chat?.changePreviewSize as ChangePreviewSize)+ : DEFAULT_APP_PREFERENCES.chat.changePreviewSize}}diff --git a/src/components/chat/tool/ToolCallCard.vue b/src/components/chat/tool/ToolCallCard.vueindex 0bd3c6fe9..8e541941d 100644--- a/src/components/chat/tool/ToolCallCard.vue+++ b/src/components/chat/tool/ToolCallCard.vue@@ -15,7 +15,9 @@ import {toolSummary,type ToolCallPart} from '@/app/ai/chat/tool-calls/display'+import { readToolChange } from '@/app/ai/tools/changes/store'import { toolCallState } from '@/components/chat/tool/state'+import ToolChangeView from '@/components/chat/tool/ToolChangeView.vue'import ToolNodeChips from '@/components/chat/tool/ToolNodeChips.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'@@ -43,16 +45,30 @@ const hasOutput = computed(() => output.value !== undefined)// Streaming source is worth watching; other pending calls have nothing to show yet.const expandable = computed(() => state.value !== 'pending' || source.value !== null)-const view = ref<'input' | 'output'>('output')-const shownView = computed(() => {- if (!hasOutput.value) return 'input'- if (!hasInput.value) return 'output'- return view.value+const change = computed(() => readToolChange(part.toolCallId))++type DetailView = 'changes' | 'input' | 'output'+const views = computed(() => {+ const available: { value: DetailView; label: string }[] = []+ if (change.value) available.push({ value: 'changes', label: ai.value.toolChanges })+ if (hasInput.value) available.push({ value: 'input', label: ai.value.toolInput })+ if (hasOutput.value) available.push({ value: 'output', label: ai.value.toolOutput })+ return available+})+const chosenView = ref<DetailView | null>(null)+// What a call changed is the most useful view; until it exists, its output, then its input.+const shownView = computed<DetailView | null>(() => {+ const available = views.value.map((option) => option.value)+ if (chosenView.value && available.includes(chosenView.value)) return chosenView.value+ if (available.includes('changes')) return 'changes'+ return available.includes('output') ? 'output' : (available[0] ?? null)+})+const viewModel = computed({+ get: () => shownView.value ?? '',+ set: (value: string) => {+ chosenView.value = views.value.find((option) => option.value === value)?.value ?? null+ }})-const viewOptions = computed(() => [- { value: 'input', label: ai.value.toolInput },- { value: 'output', label: ai.value.toolOutput }-])const stateLabel = computed(() => {if (state.value === 'pending') return ai.value.toolRunningreturn state.value === 'done' ? ai.value.toolFinished : ai.value.toolError@@ -83,13 +99,14 @@ function json(value: unknown): string {<AppAlert v-if="error" tone="error" :heading="ai.toolError" :description="error" /><ToolNodeChips :ids="nodeIds" /><SegmentedControl- v-if="hasInput && hasOutput"- v-model="view"- :options="viewOptions"+ v-if="views.length > 1"+ v-model="viewModel"+ :options="views":label="ai.toolDetails"size="sm"/>- <template v-if="shownView === 'input'">+ <ToolChangeView v-if="shownView === 'changes' && change" :change="change" />+ <template v-else-if="shownView === 'input'"><CodeViewerv-if="source":code="source.code"@@ -103,9 +120,14 @@ function json(value: unknown): string {:label="ai.toolInput"/></template>- <img v-else-if="image" :src="image" :alt="summary || name" :class="ui.image()" />+ <img+ v-else-if="shownView === 'output' && image"+ :src="image"+ :alt="summary || name"+ :class="ui.image()"+ /><CodeViewer- v-else-if="hasOutput"+ v-else-if="shownView === 'output'":code="json(output)"language="json":label="ai.toolOutput"diff --git a/src/components/chat/tool/ToolChangeView.stories.ts b/src/components/chat/tool/ToolChangeView.stories.tsnew file mode 100644index 000000000..713630fd9--- /dev/null+++ b/src/components/chat/tool/ToolChangeView.stories.ts@@ -0,0 +1,56 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { toUint8Array } from 'js-base64'++import type { ToolChange } from '@/app/ai/tools/changes/types'++import ToolChangeView from './ToolChangeView.vue'++const BEFORE_PNG =+ 'iVBORw0KGgoAAAANSUhEUgAAAGAAAAA4CAYAAAACRf2iAAAAgklEQVR42u3bsQkAIAxE0ewquH8KCysdQUgThFf8Be7VF7n2UV9hBAAABACAAAAQAAACAODVmPltAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8BFz0hMAAAIAQAAACAAAVburId+HNheO5AAAAABJRU5ErkJggg=='+const AFTER_PNG =+ 'iVBORw0KGgoAAAANSUhEUgAAAGAAAAA4CAYAAAACRf2iAAAAgUlEQVR42u3bMREAIAwEwUjAMrIii4KCCmRkwmxxBn7rj7XPVV1hBAAABACAAAAQAAACAKC6kbNtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkJMeAAEAIAAABACAAPzbA4wnD7kKs8uLAAAAAElFTkSuQmCC'+const HIGHLIGHT_PNG =+ 'iVBORw0KGgoAAAANSUhEUgAAAGAAAAA4CAYAAAACRf2iAAAAaElEQVR42u3RAQkAAAjAMDvZyf4NtIABRHZ4gkVIkiRJkiTdrrPa+wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAkSZIk6W8DhJ0lO3L6NnEAAAAASUVORK5CYII='++function png(base64: string): Blob {+ return new Blob([new Uint8Array(toUint8Array(base64))], { type: 'image/png' })+}++const change: ToolChange = {+ toolCallId: 'move-card',+ pageId: '0:1',+ nodeIds: ['12:4'],+ jsx: {+ before:+ '<Frame name="Card" x={12} w={48} h={36} bg="#6366F1">\n <Text>Starter</Text>\n</Frame>',+ after: '<Frame name="Card" x={36} w={48} h={36} bg="#10B981">\n <Text>Starter</Text>\n</Frame>'+ },+ images: {+ before: png(BEFORE_PNG),+ after: png(AFTER_PNG),+ highlight: png(HIGHLIGHT_PNG),+ width: 96,+ height: 56,+ changedRatio: 0.42+ }+}++interface Args {+ change: ToolChange+}++const meta = {+ title: 'Chat/Tool change',+ component: ToolChangeView,+ args: { change },+ render: (args) => ({+ components: { ToolChangeView },+ setup: () => ({ args }),+ template: '<div class="w-80"><ToolChangeView v-bind="args" /></div>'+ })+} satisfies Meta<Args>+export default meta+type Story = StoryObj<Omit<typeof meta, 'component'>>++export const Visual: Story = {}+export const StructureOnly: Story = { args: { change: { ...change, images: undefined } } }diff --git a/src/components/chat/tool/ToolChangeView.vue b/src/components/chat/tool/ToolChangeView.vuenew file mode 100644index 000000000..445b861fe--- /dev/null+++ b/src/components/chat/tool/ToolChangeView.vue@@ -0,0 +1,100 @@+<script setup lang="ts">+import { useObjectUrl } from '@vueuse/core'+import { computed, defineAsyncComponent, ref } from 'vue'++import { useI18n } from '@open-pencil/vue'++import type { ToolChange } from '@/app/ai/tools/changes/types'+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'+import { chatToolTheme } from '@/theme/chat/tool'++const CodeViewer = defineAsyncComponent(() => import('@/components/code-editor/CodeViewer.vue'))++const { change } = defineProps<{ change: ToolChange }>()+const { ai } = useI18n()+const ui = chatToolTheme()++const beforeURL = useObjectUrl(() => change.images?.before ?? undefined)+const afterURL = useObjectUrl(() => change.images?.after ?? undefined)+const highlightURL = useObjectUrl(() => change.images?.highlight ?? undefined)++const mode = ref<'compare' | 'highlight'>('compare')+const modeOptions = computed(() => [+ { value: 'compare', label: ai.value.changeCompare },+ { value: 'highlight', label: ai.value.changeHighlight }+])+/** Share of the comparison that shows the before state, from the left edge. */+const split = ref(50)+const changedPercent = computed(() => {+ const ratio = change.images?.changedRatio ?? 0+ return ratio > 0 && ratio < 0.001 ? '<0.1' : (ratio * 100).toFixed(ratio < 0.1 ? 1 : 0)+})+const hasImages = computed(() => Boolean(beforeURL.value || afterURL.value))+const visible = computed(() => (change.images?.changedRatio ?? 0) > 0)+const aspectRatio = computed(() =>+ change.images && change.images.height > 0+ ? `${change.images.width} / ${change.images.height}`+ : undefined+)+</script>++<template>+ <div class="space-y-2" data-slot="chat-tool-change">+ <template v-if="hasImages">+ <div class="flex items-center justify-between gap-2">+ <SegmentedControl v-model="mode" :options="modeOptions" :label="ai.changeView" size="sm" />+ <span class="text-[10px] text-muted">+ {{ visible ? ai.changedPixels({ percent: changedPercent }) : ai.noVisibleChange }}+ </span>+ </div>+ <div+ :class="ui.compare()"+ :style="{ aspectRatio }"+ :data-mode="mode"+ data-slot="chat-tool-change-images"+ >+ <img v-if="afterURL" :src="afterURL" :alt="ai.changeAfter" :class="ui.compareImage()" />+ <img+ v-if="mode === 'compare' && beforeURL"+ :src="beforeURL"+ :alt="ai.changeBefore"+ :class="ui.compareImage()"+ :style="{ clipPath: `inset(0 ${100 - split}% 0 0)` }"+ />+ <div+ v-if="mode === 'compare'"+ :class="ui.compareDivider()"+ :style="{ left: `${split}%` }"+ aria-hidden="true"+ />+ <img+ v-if="mode === 'highlight' && highlightURL"+ :src="highlightURL"+ alt=""+ :class="ui.compareImage()"+ />+ <span v-if="mode === 'compare'" :class="ui.compareLabel({ class: 'left-1' })">+ {{ ai.changeBefore }}+ </span>+ <span v-if="mode === 'compare'" :class="ui.compareLabel({ class: 'right-1' })">+ {{ ai.changeAfter }}+ </span>+ </div>+ <input+ v-if="mode === 'compare'"+ v-model.number="split"+ type="range"+ min="0"+ max="100"+ :aria-label="ai.changeSplit"+ :class="ui.compareSlider()"+ />+ </template>+ <CodeViewer+ :code="change.jsx.after"+ :original="change.jsx.before"+ language="design-jsx"+ :label="ai.changeStructure"+ />+ </div>+</template>diff --git a/src/components/code-editor/CodeViewer.vue b/src/components/code-editor/CodeViewer.vueindex 16c812a16..9a7d46921 100644--- a/src/components/code-editor/CodeViewer.vue+++ b/src/components/code-editor/CodeViewer.vue@@ -2,6 +2,7 @@import { javascript } from '@codemirror/lang-javascript'import { json } from '@codemirror/lang-json'import { foldGutter } from '@codemirror/language'+import { unifiedMergeView } from '@codemirror/merge'import { search, searchKeymap } from '@codemirror/search'import { EditorState, type Extension } from '@codemirror/state'import { EditorView, highlightSpecialChars, keymap } from '@codemirror/view'@@ -12,10 +13,12 @@ import { codeEditorTheme, codeViewerTheme } from '@/theme/code/editor'export type CodeViewerLanguage = 'json' | 'design-jsx' | 'javascript'-const { code, language, label } = defineProps<{+const { code, language, label, original } = defineProps<{code: stringlanguage: CodeViewerLanguagelabel: string+ /** Shows `code` as a unified diff against this text. Read at mount. */+ original?: string}>()function languageExtension(language: CodeViewerLanguage): Extension {@@ -32,7 +35,10 @@ const view = useCodeMirror(useTemplateRef('host'), {foldGutter(),search({ top: true }),keymap.of(searchKeymap),- EditorView.lineWrapping+ EditorView.lineWrapping,+ original === undefined+ ? []+ : unifiedMergeView({ original, mergeControls: false, collapseUnchanged: {} })],reactive: [() => languageExtension(language)]})diff --git a/src/components/settings/chat/ChatSettingsSection.vue b/src/components/settings/chat/ChatSettingsSection.vueindex 67b686788..04ddb018e 100644--- a/src/components/settings/chat/ChatSettingsSection.vue+++ b/src/components/settings/chat/ChatSettingsSection.vue@@ -3,7 +3,7 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue'-import { maxAgentSteps, reasoningDisplay } from '@/app/ai/chat/preferences'+import { changePreviewSize, maxAgentSteps, reasoningDisplay } from '@/app/ai/chat/preferences'import { AGENT_STEP_LIMIT_MIN, AGENT_STEP_LIMIT_MAX } from '@/app/ai/chat/step-limit'import { openToolAccessSettings } from '@/app/automation/tool-access/settings/use'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'@@ -23,6 +23,12 @@ const options = computed(() => [{ value: 'while-thinking' as const, label: ai.value.reasoningWhileThinking },{ value: 'expanded' as const, label: ai.value.reasoningExpanded }])+const previewOptions = computed(() => [+ { value: 'off' as const, label: ai.value.changePreviewOff },+ { value: 'small' as const, label: ai.value.changePreviewSmall },+ { value: 'medium' as const, label: ai.value.changePreviewMedium },+ { value: 'large' as const, label: ai.value.changePreviewLarge }+])</script><template>@@ -37,6 +43,18 @@ const options = computed(() => [:ui="{ trigger: 'w-full sm:w-52' }"/></SettingsRow>+ <SettingsRow+ :label="ai.changePreview"+ :description="ai.changePreviewHint"+ class="max-sm:flex-col max-sm:items-stretch"+ >+ <AppSelect+ v-model="changePreviewSize"+ :label="ai.changePreview"+ :options="previewOptions"+ :ui="{ trigger: 'w-full sm:w-52' }"+ />+ </SettingsRow><SettingsRow:label="ai.maxAgentSteps":description="ai.maxAgentStepsHint"diff --git a/src/theme/chat/tool.ts b/src/theme/chat/tool.tsindex 56da9b7f3..fe315f464 100644--- a/src/theme/chat/tool.ts+++ b/src/theme/chat/tool.ts@@ -19,6 +19,14 @@ export const chatToolTheme = tv({nodeLabel: 'truncate',image:'max-h-56 w-auto max-w-full rounded border border-border bg-[repeating-conic-gradient(var(--color-hover)_0_25%,transparent_0_50%)] bg-size-[12px_12px] object-contain',+ compare:+ 'relative w-full max-w-full overflow-hidden rounded border border-border bg-input select-none data-[mode=highlight]:[&>img:first-child]:opacity-40',+ compareImage: 'absolute inset-0 size-full object-contain',+ compareDivider:+ 'pointer-events-none absolute inset-y-0 w-px -translate-x-1/2 bg-accent shadow-[0_0_0_1px_rgb(0_0_0/0.25)]',+ compareLabel:+ 'pointer-events-none absolute top-1 rounded bg-black/55 px-1 py-px text-[9px] font-medium text-white',+ compareSlider: 'block w-full accent-(--color-accent)',group: 'rounded-lg border border-dashed border-border',groupTrigger:'flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[11px] text-muted hover:bg-hover hover:text-surface',diff --git a/tests/app/ai/tools/changes/capture.test.ts b/tests/app/ai/tools/changes/capture.test.tsnew file mode 100644index 000000000..effc44455--- /dev/null+++ b/tests/app/ai/tools/changes/capture.test.ts@@ -0,0 +1,165 @@+import 'fake-indexeddb/auto'+import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test'++import type { ToolExecutionOptions } from 'ai'+import { toRaw } from 'vue'++import { FigmaAPI } from '@open-pencil/core/figma-api'++import { snapshotMessages, restoreMessages } from '@/app/ai/chat/history/messages'+import { changePreviewSize } from '@/app/ai/chat/preferences'+import { createAITools, startRun } from '@/app/ai/tools'+import { clipChangedJSX } from '@/app/ai/tools/changes/capture'+import { clearToolChanges, readToolChange } from '@/app/ai/tools/changes/store'+import * as figmaFactory from '@/app/automation/bridge/figma-factory'+import { createEditorStore } from '@/app/editor/session/create'+import { appPreferences } from '@/app/settings/preferences/store'++type EditorStore = ReturnType<typeof createEditorStore>++let store: EditorStore+let previousPreferences: typeof appPreferences.value+let factory: ReturnType<typeof spyOn>++beforeEach(() => {+ previousPreferences = structuredClone(toRaw(appPreferences.value))+ // No canvas renders here; the structural record is the contract under test.+ changePreviewSize.value = 'off'+ store = createEditorStore()+ factory = spyOn(figmaFactory, 'makeFigmaFromStore').mockImplementation((editor, pageId) => {+ const api = new FigmaAPI(editor.graph)+ api.currentPage = api.wrapNode(pageId ?? editor.state.currentPageId)+ return api+ })+})++afterEach(() => {+ appPreferences.value = previousPreferences+ factory.mockRestore()+ clearToolChanges()+ store.dispose()+})++function call(toolCallId: string): ToolExecutionOptions<unknown> {+ return { toolCallId, messages: [], context: undefined }+}++async function execute(name: string, input: Record<string, unknown>, toolCallId: string) {+ const tool = createAITools(store)[name]+ if (!tool?.execute) throw new Error(`Missing ${name}`)+ return tool.execute(input, call(toolCallId))+}++test('records the layers a call changed with their JSX before and after', async () => {+ const pageId = store.state.currentPageId+ const card = store.graph.createNode('FRAME', pageId, { name: 'Card', width: 100, height: 60 })+ store.graph.createNode('RECTANGLE', pageId, { name: 'Untouched', x: 300 })++ await execute('set_fill', { id: card.id, color: '#ff0000' }, 'fill-call')++ const change = readToolChange('fill-call')+ expect(change?.nodeIds).toEqual([card.id])+ expect(change?.jsx.before).toContain('name="Card"')+ expect(change?.jsx.after).toContain('#FF0000')+ expect(change?.jsx.before).not.toContain('#FF0000')+ expect(change?.images).toBeUndefined()+})++test('records nothing for calls that leave the page as it was', async () => {+ const card = store.graph.createNode('FRAME', store.state.currentPageId, { name: 'Card' })+ await execute('get_node', { id: card.id }, 'read-call')+ await execute('set_fill', { id: card.id, color: '#123456' }, 'first-fill')+ await execute('set_fill', { id: card.id, color: '#123456' }, 'same-fill')++ expect(readToolChange('read-call')).toBeNull()+ expect(readToolChange('first-fill')).not.toBeNull()+ expect(readToolChange('same-fill')).toBeNull()+})++test('keeps an undo step per structural call and records removed layers', async () => {+ const card = store.graph.createNode('FRAME', store.state.currentPageId, { name: 'Card' })++ await execute('delete_node', { id: card.id }, 'delete-call')++ const change = readToolChange('delete-call')+ expect(change?.nodeIds).toEqual([card.id])+ expect(change?.jsx.after).toBe('')+ store.undo.undo()+ expect(store.graph.getNode(card.id)?.name).toBe('Card')+})++test('diff_changes compares the run page with its state before the run first edited it', async () => {+ const pageId = store.state.currentPageId+ const card = store.graph.createNode('FRAME', pageId, { name: 'Card', width: 100, height: 60 })+ startRun(store, 10)++ await execute('set_fill', { id: card.id, color: '#ff0000' }, 'first')+ await execute('node_resize', { id: card.id, width: 240, height: 60 }, 'second')+ const result = (await execute('diff_changes', {}, 'check')) as { diff: string | null }++ // Both calls show up against the state before the first one.+ expect(result.diff).toBe(`@@ /Page 1/Card #${card.id}\n-w={100}\n+w={240}\n+bg="#FF0000"`)+})++test('saves recorded changes with the conversation and restores them', async () => {+ const card = store.graph.createNode('FRAME', store.state.currentPageId, { name: 'Card' })+ await execute('set_fill', { id: card.id, color: '#00ff00' }, 'saved-call')+ const recorded = readToolChange('saved-call')++ const rows = snapshotMessages([+ {+ id: 'assistant',+ role: 'assistant',+ parts: [+ {+ type: 'tool-set_fill',+ toolCallId: 'saved-call',+ state: 'output-available',+ input: { id: card.id, color: '#00ff00' },+ output: { id: card.id }+ }+ ]+ }+ ])+ clearToolChanges()+ expect(readToolChange('saved-call')).toBeNull()++ restoreMessages(rows)+ expect(readToolChange('saved-call')).toEqual(recorded)+})++test('concurrent calls in one step each undo only their own edit', async () => {+ const pageId = store.state.currentPageId+ const left = store.graph.createNode('FRAME', pageId, { name: 'Left', width: 100, height: 60 })+ const right = store.graph.createNode('FRAME', pageId, { name: 'Right', width: 100, height: 60 })+ const tools = createAITools(store)+ const resize = (id: string, width: number, toolCallId: string) =>+ tools.node_resize?.execute?.({ id, width, height: 60 }, call(toolCallId))++ await Promise.all([resize(left.id, 200, 'left'), resize(right.id, 300, 'right')])+ expect(store.graph.getNode(left.id)?.width).toBe(200)+ expect(store.graph.getNode(right.id)?.width).toBe(300)++ store.undo.undo()+ expect(store.graph.getNode(right.id)?.width).toBe(100)+ expect(store.graph.getNode(left.id)?.width).toBe(200)+ store.undo.undo()+ expect(store.graph.getNode(left.id)?.width).toBe(100)++ // Overlapping page snapshots would make redoing the first call bring back the second too.+ store.undo.redo()+ expect(store.graph.getNode(left.id)?.width).toBe(200)+ expect(store.graph.getNode(right.id)?.width).toBe(100)+})++test('long sources keep the changed region instead of their beginning', () => {+ const head = Array.from({ length: 3000 }, (_, index) => `<Rectangle name="R${index}" />`).join(+ '\n'+ )+ const [before, after] = clipChangedJSX(`${head}\n<Text>Old</Text>`, `${head}\n<Text>New</Text>`)+ expect(before).toContain('<Text>Old</Text>')+ expect(after).toContain('<Text>New</Text>')+ expect(before.startsWith('…\n')).toBe(true)+ expect(before.length).toBeLessThan(head.length)+ expect(clipChangedJSX('<A />', '<B />')).toEqual(['<A />', '<B />'])+})diff --git a/tests/engine/tools/ai-adapter.test.ts b/tests/engine/tools/ai-adapter.test.tsindex 32c4d4ac6..bc8710c47 100644--- a/tests/engine/tools/ai-adapter.test.ts+++ b/tests/engine/tools/ai-adapter.test.ts@@ -7,14 +7,23 @@ import { ALL_TOOLS, FigmaAPI, SceneGraph, toolsToAI } from '@open-pencil/core'import { expectDefined } from '#tests/helpers/assert'type AdapterTool = { execute(args: Record<string, unknown>): Promise<unknown>; description: string }+type SDKTool = {+ execute(args: Record<string, unknown>, call: { toolCallId: string }): Promise<unknown>+ description: string+}interface PageTreeToolResult {page: unknownchildren: unknown[]}+/** Calls a tool as the AI SDK does, with the call's options. */function adapterTool(tools: Record<string, unknown>, name: string): AdapterTool {- return tools[name] as AdapterTool+ const sdkTool = tools[name] as SDKTool+ return {+ description: sdkTool.description,+ execute: (args) => sdkTool.execute(args, { toolCallId: `${name}-call` })+ }}function setup() {diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 96d1e6c0d..41dea47c2 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -22,6 +22,7 @@ ja:ai.modelIDja:ai.modelIDPlaceholderja:ai.modelRoleDesignDescriptionja:ai.provider+ja:ai.changePreviewHintja:automation.addServerConnectionja:automation.aiToolAccessDescriptionja:automation.authenticationDescription@@ -157,6 +158,7 @@ zh-cn:ai.modelIDzh-cn:ai.modelIDPlaceholderzh-cn:ai.modelRoleDesignDescriptionzh-cn:ai.provider+zh-cn:ai.changePreviewHintzh-cn:automation.addServerConnectionzh-cn:automation.aiToolAccessDescriptionzh-cn:automation.authenticationDescription