AI-native design editor. Open-source Figma alternative.
feat: add visual diff and patch apply tools and openpencil diff (#810)
Danila Poyarkov3f594fdc3a2f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5f7fb6bf4..80198db54 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,7 @@- `sceneNodeToJSX` and `selectionToJSX` in `@open-pencil/core` produce only OpenPencil JSX, and `JSXFormat` and `JSXExportOptions` are removed. For Tailwind JSX, use `sceneNodesToTailwindJSX(graph, nodeIds)` from `@open-pencil/dom-css` or the browser-safe `@open-pencil/dom-css/export`.- Color conversion and management and text/layout direction helpers moved from `@open-pencil/core/color` and `@open-pencil/core/text` to `@open-pencil/scene-graph/color` and `@open-pencil/scene-graph/text-direction`, and `@open-pencil/core/bytes` is removed in favor of `js-base64`; the `@open-pencil/core` root exports are unchanged. `@open-pencil/dom-css` no longer requires `@open-pencil/core`, and `exportHTMLBundle` takes a font resolver in `fonts` instead of `'assets'`; pass one built on `exportWebFontFaceAssets` from `@open-pencil/core/text/web-font/assets` to keep font files in standalone exports.- Design JSX moved from `@open-pencil/core` to the new `@open-pencil/design-jsx` package, which depends only on `@open-pencil/scene-graph`. Import elements, paint and effect helpers, variables, `JSX_REFERENCE`, `buildComponent`, `sceneNodeToJSX`, and `selectionToJSX` from `@open-pencil/design-jsx`; `@open-pencil/core/design-jsx` now exports only `renderJSX` and `renderTree`, which render with OpenPencil's icons and layout. The `@open-pencil/core` root keeps `renderJSX` and `renderTree` and drops the other design JSX exports, `renderTreeNode` is removed in favor of `renderTree`, and the `@open-pencil/core/io/formats/jsx` subpath is removed.+- `diff_create` and `diff_show` patches list changed JSX attributes per node, such as `-rounded={8}` and `+rounded={12}`, instead of `key: value` property lines, so they cover every property the JSX export writes and report reordered children as moves. `diff_show` takes JSX attributes in `attributes`, such as `w={200} bg="#FF0000"`, instead of a JSON `props` object, and patches in the old format no longer apply.### Added@@ -27,6 +28,8 @@- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, with a story and `select` controls per variant, a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).- Export HTML and Tailwind JSX from the app's export options and through the IO registry, and export Tailwind JSX from the CLI with `-f tailwind-jsx` (`-f jsx --style tailwind` still works). HTML export of a single layer now includes the layer itself, as other formats do.- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.+- Let AI and MCP agents verify and replay their edits with diff tools: `diff_visual` returns a pixel diff of two rendered nodes with the changed region, and `diff_apply` applies a `diff_create` or `diff_show` patch, including moved, added, and removed children, only when every node still matches it. The built-in AI chat enables `diff_create`, `diff_jsx`, and `diff_visual` by default.+- Compare designs from the terminal with `openpencil diff`: `create`, `jsx`, `show`, `apply`, and `visual` work on a file or the running app, and `diff files` compares two documents page by page and exits with status 1 when they differ.### Changeddiff --git a/bun.lock b/bun.lockindex 67ed695a1..ecf557302 100644--- a/bun.lock+++ b/bun.lock@@ -224,10 +224,12 @@"fzstd": "^0.1.1","js-base64": "^3.9.3","jsep": "^1.4.0",+ "jsondiffpatch": "0.7.6","jspdf": "^4.2.1","nanoevents": "^9.1.0","ofetch": "^1.5.1","opentype.js": "^2.0.0",+ "pixelmatch": "^7.2.0","pptxgenjs": "^4.0.1","rbush": "^4.0.1","sucrase": "^3.35.1",@@ -946,6 +948,8 @@"@dependents/detective-less": ["@dependents/[email protected]", "", { "dependencies": { "gonzales-pe": "^4.3.0", "node-source-walk": "^7.0.1" } }, "sha512-v6oD9Ukp+N7V4n6p5I/+mM5fIohSfkrDSGlFm5w/pYmchvbk+sMIHsLxrFJ5Lnujewj1BzWL0K84d88lwZAMQA=="],+ "@dmsnell/diff-match-patch": ["@dmsnell/[email protected]", "", {}, "sha512-yejLPmM5pjsGvxS9gXablUSbInW7H976c/FJ4iQxWIm7/38xBySRemTPDe34lhg1gVLbJntX0+sH0jYfU+PN9A=="],+"@dnsquery/dns-packet": ["@dnsquery/[email protected]", "", { "dependencies": { "@leichtgewicht/ip-codec": "^2.0.4", "utf8-codec": "^1.0.0" } }, "sha512-WXTuFvL3G+74SchFAtz3FgIYVOe196ycvGsMgvSH/8Goptb1qpIQtIuM4SOK9G9lhMWYpHxnXyy544ZhluFOew=="],"@docsearch/css": ["@docsearch/[email protected]", "", {}, "sha512-Sk5xkdRFeE7PeWjG9l4AfTwdvMfr9wHiwNNCpHXT4v4SNyNMKdHGvEILc31BgaVFGDDNbv5u/a73tofRiwbEZw=="],@@ -3344,6 +3348,8 @@"jsonc-parser": ["[email protected]", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="],+ "jsondiffpatch": ["[email protected]", "", { "dependencies": { "@dmsnell/diff-match-patch": "^1.1.0" }, "bin": { "jsondiffpatch": "bin/jsondiffpatch.js" } }, "sha512-zE9+AXFq+MkTolDor2Cw1nJzLC0aleqPkYf52Kb4Kn4mJcka/gFHpGI2JBVEJCfWOvBl0OoxZS+wuLdislQcqg=="],+"jsonfile": ["[email protected]", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="],"jsonpointer": ["[email protected]", "", {}, "sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ=="],@@ -3790,6 +3796,8 @@"pirates": ["[email protected]", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="],+ "pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^7.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-xhcb4yHu9sM/G7foGzoLtXYcC0zHEaOXXjRKhGup0fw78Nf2Tkiapv4EQyMzrbcmQPsllAI7DbFY2UT7PlI9Pg=="],+"pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],"pkg-types": ["[email protected]", "", { "dependencies": { "confbox": "^0.2.4", "exsolve": "^1.0.8", "pathe": "^2.0.3" } }, "sha512-y+ichcgc2LrADuhLNAx8DFjVfgz91pRxfZdI3UDhxHvcVEZsenLO+7XaU5vOp0u/7V/wZ+plyuQxtrDlZJ+yeg=="],@@ -3800,6 +3808,8 @@"pluralize": ["[email protected]", "", {}, "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA=="],+ "pngjs": ["[email protected]", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],+"portless": ["[email protected]", "", { "os": [ "linux", "win32", "darwin", ], "bin": { "portless": "dist/cli.js" } }, "sha512-zmJu4Q8/fY54oVUT/5NnmF4Ih8wTdCvCf6JCN783dRYl9mXkJBzXSckX2lztGCLIbM70varDjCudAbGKT73XPg=="],"possible-typed-array-names": ["[email protected]", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="],diff --git a/package.json b/package.jsonindex 95f7ad669..e105d9a2e 100644--- a/package.json+++ b/package.json@@ -52,7 +52,7 @@"benchmark:navigation": "bun tools/dev/navigation-benchmark/src/cli.ts run","test:native": "bun run build:native-test && wdio run wdio.conf.ts","lint": "bun run lint:structure && oxlint -c oxlint.json --type-aware --type-check src/ packages/scene-graph/src/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/dom-css/src/ packages/pen/src/ packages/design-jsx/src/ packages/codegen/src/ packages/kiwi/src/ packages/fig/src/",- "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/codegen/src/ packages/codegen/tests/ packages/codegen/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/",+ "lint:structure": "oxlint -c oxlint.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/vue/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/codegen/src/ packages/codegen/tests/ packages/codegen/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ packages/core/tests/ packages/cli/tests/ packages/scene-graph/tests/ packages/vue/tests/ tests/ scripts/ tools/","format": "oxfmt --write .oxfmtrc.json commitlint.config.ts vite.config.ts vite/ .storybook/ src/ packages/scene-graph/src/ packages/scene-graph/scripts/ packages/core/src/ packages/cli/src/ packages/mcp/src/ packages/harness/src/ packages/harness/tests/ packages/vue/src/ packages/dom-css/src/ packages/dom-css/tests/ packages/dom-css/scripts/ packages/pen/src/ packages/pen/scripts/ packages/design-jsx/src/ packages/design-jsx/tests/ packages/design-jsx/scripts/ packages/codegen/src/ packages/codegen/tests/ packages/codegen/scripts/ packages/kiwi/src/ packages/kiwi/tests/ packages/kiwi/scripts/ packages/fig/src/ packages/fig/tests/ packages/fig/scripts/ tests scripts/ tools/","format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)","check": "bun run check:icons && bun run build:packages && bun run lint && tsgo --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes",diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 022292635..03be591db 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -4,7 +4,8 @@"license": "MIT","type": "module","imports": {- "#cli/*": "./src/*"+ "#cli/*": "./src/*",+ "#cli-tests/*": "./tests/*"},"bin": {"openpencil": "./bin/openpencil.js"diff --git a/packages/cli/src/commands/diff/apply.ts b/packages/cli/src/commands/diff/apply.tsnew file mode 100644index 000000000..6ab76bf61--- /dev/null+++ b/packages/cli/src/commands/diff/apply.ts@@ -0,0 +1,97 @@+import { readFile } from 'node:fs/promises'++import { defineCommand } from 'citty'++import { appTargetOptions } from '#cli/app-target'+import { dim, entity, fail, fmtList, ok, printError, warn } from '#cli/format'+import { documentWriteOptions, writeFigDocument } from '#cli/headless'+import { runToolData } from '#cli/tool-data'++interface PatchResult {+ path: string+ id: string | null+ status: string+ changes?: string[]+ error?: string+}++interface ApplyResult {+ error?: string+ dryRun?: boolean+ applied?: number+ failed?: number+ results?: PatchResult[]+}++async function readPatch(source: string): Promise<string> {+ if (source !== '-') return readFile(source, 'utf-8')+ const chunks: Buffer[] = []+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer)+ return Buffer.concat(chunks).toString('utf-8')+}++function patchDetails(row: PatchResult) {+ if (row.error) return [fail(row.error)]+ if (row.changes) return { changes: row.changes.join(', ') }+ return undefined+}++function printApplyResult(result: ApplyResult, dryRun: boolean): void {+ if (result.error) printError(result.error)+ const rows = result.results ?? []+ if (rows.length > 0) {+ console.log(+ fmtList(+ rows.map((row) => ({+ header: entity(row.status, row.path, row.id ?? undefined),+ details: patchDetails(row)+ }))+ )+ )+ }+ if (result.error) return+ const failed = result.failed ?? 0+ const line = `${result.applied ?? 0} ${dryRun ? 'would apply' : 'applied'}, ${failed} failed`+ console.log(failed > 0 ? fail(line) : ok(line))+}++export default defineCommand({+ meta: { description: 'Apply a patch from diff create or diff show' },+ args: {+ patch: { type: 'positional', description: 'Patch file path, or - for stdin', required: true },+ file: {+ type: 'positional',+ description: 'Document file path (omit to connect to running app)',+ required: false+ },+ 'dry-run': { type: 'boolean', description: 'Validate and list changes without applying' },+ force: { type: 'boolean', description: 'Apply even when current values differ from the patch' },+ ...documentWriteOptions,+ ...appTargetOptions,+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ const dryRun = !!args['dry-run']+ const { result, graph } = await runToolData(+ args.file,+ 'diff_apply',+ { patch: await readPatch(args.patch), dryRun, force: !!args.force },+ args+ )+ const report = result as ApplyResult+ if (args.json) console.log(JSON.stringify(report, null, 2))+ else printApplyResult(report, dryRun)++ const failed = Boolean(report.error) || (report.failed ?? 0) > 0+ if (graph && !dryRun && !failed) {+ const outPath = args.output || (args.write ? args.file : undefined)+ if (outPath) {+ await writeFigDocument(graph, outPath)+ if (!args.json) console.error(dim(`Written to ${outPath}`))+ } else if (!args.json) {+ console.error(warn('Not saved; pass --write or --output to save the document'))+ }+ }+ if (failed) process.exit(1)+ }+})diff --git a/packages/cli/src/commands/diff/args.ts b/packages/cli/src/commands/diff/args.tsnew file mode 100644index 000000000..26aa771b0--- /dev/null+++ b/packages/cli/src/commands/diff/args.ts@@ -0,0 +1,14 @@+import { appTargetOptions } from '#cli/app-target'++/** The document and node pair every two-node diff command takes. */+export const nodePairArgs = {+ file: {+ type: 'positional',+ description: 'Document file path (omit to connect to running app)',+ required: false+ },+ from: { type: 'string', description: 'Source node ID', required: true },+ to: { type: 'string', description: 'Target node ID', required: true },+ ...appTargetOptions,+ json: { type: 'boolean', description: 'Output as JSON' }+} as constdiff --git a/packages/cli/src/commands/diff/create.ts b/packages/cli/src/commands/diff/create.tsnew file mode 100644index 000000000..4527778c2--- /dev/null+++ b/packages/cli/src/commands/diff/create.ts@@ -0,0 +1,23 @@+import { defineCommand } from 'citty'++import { runToolData } from '#cli/tool-data'++import { nodePairArgs } from './args'+import { printDiffResult, type DiffResult } from './output'++export default defineCommand({+ meta: { description: 'Property diff between two node trees as a unified patch' },+ args: {+ ...nodePairArgs,+ depth: { type: 'string', description: 'Max tree depth (default: 10)' }+ },+ async run({ args }) {+ const { result } = await runToolData(+ args.file,+ 'diff_create',+ { from: args.from, to: args.to, ...(args.depth ? { depth: Number(args.depth) } : {}) },+ args+ )+ printDiffResult(result as DiffResult, !!args.json)+ }+})diff --git a/packages/cli/src/commands/diff/files.ts b/packages/cli/src/commands/diff/files.tsnew file mode 100644index 000000000..046a785d0--- /dev/null+++ b/packages/cli/src/commands/diff/files.ts@@ -0,0 +1,56 @@+import { defineCommand } from 'citty'++import { diffDocuments } from '@open-pencil/core/tools'++import { bold, dim, ok, printError } from '#cli/format'+import { loadDocument, populateWholeDocument } from '#cli/headless'++import { printUnifiedDiff } from './output'++export default defineCommand({+ meta: { description: 'Structural diff of two documents, page by page' },+ args: {+ before: { type: 'positional', description: 'Original document path', required: true },+ after: { type: 'positional', description: 'Changed document path', required: true },+ page: { type: 'string', description: 'Compare only the page with this name' },+ depth: { type: 'string', description: 'Max tree depth below each page (default: unlimited)' },+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ const depth = args.depth ? Number(args.depth) : undefined+ if (depth !== undefined && !(Number.isInteger(depth) && depth >= 0)) {+ // Like diff(1): exit 2 on trouble, since 1 means the documents differ.+ printError(`--depth must be a non-negative integer, got "${args.depth}"`)+ process.exit(2)+ }+ // Load in order: node IDs count up per process, so the first document gets the IDs a+ // single load gives it, and the patch applies to it with `diff apply`.+ const before = await loadDocument(args.before)+ const after = await loadDocument(args.after)+ populateWholeDocument(before)+ populateWholeDocument(after)+ const result = diffDocuments(before, after, { page: args.page, depth })+ if (args.page && result.pages.length === 0) {+ printError(`Neither document has a page named "${args.page}"`)+ process.exit(2)+ }++ if (args.json) {+ console.log(JSON.stringify(result, null, 2))+ } else if (!result.changed) {+ console.log(ok('Documents match'))+ } else {+ for (const page of result.pages) {+ if (page.diff) {+ if (process.stdout.isTTY) console.log(bold(`\n ${page.name} (${page.status})\n`))+ printUnifiedDiff(page.diff)+ } else if (page.status !== 'unchanged') {+ // On stderr, so piped output stays a patch; patches do not add or remove pages.+ console.error(dim(`Page "${page.name}" ${page.status}`))+ }+ }+ }+ // Like diff(1): exit 1 when the documents differ, so scripts can branch on it.+ if (result.changed) process.exitCode = 1+ }+})diff --git a/packages/cli/src/commands/diff/index.ts b/packages/cli/src/commands/diff/index.tsnew file mode 100644index 000000000..13f5ea7f5--- /dev/null+++ b/packages/cli/src/commands/diff/index.ts@@ -0,0 +1,20 @@+import { defineCommand } from 'citty'++import apply from './apply'+import create from './create'+import files from './files'+import jsx from './jsx'+import show from './show'+import visual from './visual'++export default defineCommand({+ meta: { description: 'Compare nodes and documents, and apply property patches' },+ subCommands: {+ create,+ jsx,+ show,+ apply,+ visual,+ files+ }+})diff --git a/packages/cli/src/commands/diff/jsx.ts b/packages/cli/src/commands/diff/jsx.tsnew file mode 100644index 000000000..6ba0d298e--- /dev/null+++ b/packages/cli/src/commands/diff/jsx.ts@@ -0,0 +1,22 @@+import { defineCommand } from 'citty'++import { runToolData } from '#cli/tool-data'++import { nodePairArgs } from './args'+import { printDiffResult, type DiffResult } from './output'++export default defineCommand({+ meta: { description: 'Structural diff between two nodes as design JSX' },+ args: {+ ...nodePairArgs+ },+ async run({ args }) {+ const { result } = await runToolData(+ args.file,+ 'diff_jsx',+ { from: args.from, to: args.to },+ args+ )+ printDiffResult(result as DiffResult, !!args.json)+ }+})diff --git a/packages/cli/src/commands/diff/output.ts b/packages/cli/src/commands/diff/output.tsnew file mode 100644index 000000000..b287f62aa--- /dev/null+++ b/packages/cli/src/commands/diff/output.ts@@ -0,0 +1,37 @@+import { bold, cyan, dim, green, ok, printError, red } from '#cli/format'++export interface DiffResult {+ diff?: string | null+ message?: string+ error?: string+}++function colorLine(line: string): string {+ if (line.startsWith('+++') || line.startsWith('---')) return bold(line)+ if (line.startsWith('@@')) return cyan(line)+ if (line.startsWith('+')) return green(line)+ if (line.startsWith('-')) return red(line)+ return dim(line)+}++/** Print a unified diff, colored on a terminal and raw when piped so it stays a valid patch. */+export function printUnifiedDiff(diff: string): void {+ if (!process.stdout.isTTY) {+ console.log(diff)+ return+ }+ console.log(diff.split('\n').map(colorLine).join('\n'))+}++export function printDiffResult(result: DiffResult, json: boolean): void {+ if (result.error) {+ printError(result.error)+ process.exit(1)+ }+ if (json) {+ console.log(JSON.stringify(result, null, 2))+ return+ }+ if (result.diff) printUnifiedDiff(result.diff)+ else console.log(ok(result.message ?? 'No differences found'))+}diff --git a/packages/cli/src/commands/diff/show.ts b/packages/cli/src/commands/diff/show.tsnew file mode 100644index 000000000..ef9c232e6--- /dev/null+++ b/packages/cli/src/commands/diff/show.ts@@ -0,0 +1,34 @@+import { defineCommand } from 'citty'++import { appTargetOptions } from '#cli/app-target'+import { runToolData } from '#cli/tool-data'++import { printDiffResult, type DiffResult } from './output'++export default defineCommand({+ meta: { description: 'Preview the patch that setting JSX attributes on a node would produce' },+ args: {+ id: { type: 'positional', description: 'Node ID', required: true },+ file: {+ type: 'positional',+ description: 'Document file path (omit to connect to running app)',+ required: false+ },+ attributes: {+ type: 'string',+ description: 'JSX attributes to set, e.g. \'w={200} bg="#FF0000"\'',+ required: true+ },+ ...appTargetOptions,+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ async run({ args }) {+ const { result } = await runToolData(+ args.file,+ 'diff_show',+ { id: args.id, attributes: args.attributes },+ args+ )+ printDiffResult(result as DiffResult, !!args.json)+ }+})diff --git a/packages/cli/src/commands/diff/visual.ts b/packages/cli/src/commands/diff/visual.tsnew file mode 100644index 000000000..a4cdc8b42--- /dev/null+++ b/packages/cli/src/commands/diff/visual.ts@@ -0,0 +1,81 @@+import { writeFile } from 'node:fs/promises'++import { defineCommand } from 'citty'+import { toUint8Array } from 'js-base64'++import type { Rect } from '@open-pencil/scene-graph/primitives'++import { dim, fmtSummary, kv, ok, printError } from '#cli/format'+import { runToolData } from '#cli/tool-data'++import { nodePairArgs } from './args'++interface VisualDiffResult {+ error?: string+ base64?: string+ width?: number+ height?: number+ scale?: number+ changedPixels?: number+ totalPixels?: number+ changedRatio?: number+ changedBounds?: Rect | null+ sizeChanged?: boolean+}++function optionalNumber(value: string | undefined): number | undefined {+ return value === undefined ? undefined : Number(value)+}++export default defineCommand({+ meta: { description: 'Pixel diff between two rendered nodes, written as a PNG' },+ args: {+ ...nodePairArgs,+ output: { type: 'string', alias: 'o', description: 'Diff PNG path', required: true },+ scale: { type: 'string', description: 'Render scale before the max-edge limit (default: 1)' },+ 'max-edge': { type: 'string', description: 'Maximum image width or height (default: 1280)' },+ threshold: {+ type: 'string',+ description: 'Color tolerance 0–1; smaller is stricter (default: 0.1)'+ }+ },+ async run({ args }) {+ const toolArgs = Object.fromEntries(+ Object.entries({+ from: args.from,+ to: args.to,+ scale: optionalNumber(args.scale),+ maxEdge: optionalNumber(args['max-edge']),+ threshold: optionalNumber(args.threshold)+ }).filter(([, value]) => value !== undefined)+ )+ const data = await runToolData(args.file, 'diff_visual', toolArgs, args)+ const result = data.result as VisualDiffResult+ if (result.error || !result.base64) {+ printError(result.error ?? 'Visual diff produced no image')+ process.exit(1)+ }+ await writeFile(args.output, toUint8Array(result.base64))++ // The image went to the file; keep the base64 payload out of the report.+ const summary = { ...result, base64: undefined }+ if (args.json) {+ console.log(JSON.stringify({ ...summary, output: args.output }, null, 2))+ return+ }+ console.log(ok(`Wrote ${args.output}`))+ console.log(+ fmtSummary({+ 'changed pixels': summary.changedPixels ?? 0,+ 'total pixels': summary.totalPixels ?? 0+ })+ )+ console.log(kv('changed', `${((summary.changedRatio ?? 0) * 100).toFixed(2)}%`))+ if (summary.changedBounds) {+ const { x, y, width, height } = summary.changedBounds+ console.log(kv('region', `${width}×${height} at ${x}, ${y}`))+ }+ if (summary.sizeChanged)+ console.log(dim(' Rendered sizes differ; the smaller side is padded.'))+ }+})diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.tsindex 832081b52..e06a23b96 100644--- a/packages/cli/src/commands/eval.ts+++ b/packages/cli/src/commands/eval.ts@@ -1,5 +1,3 @@-import { writeFile } from 'node:fs/promises'-import { defineCommand } from 'citty'import { FigmaAPI } from '@open-pencil/core/figma-api'@@ -7,7 +5,12 @@ import { FigmaAPI } from '@open-pencil/core/figma-api'import { isAppMode, requireFile, rpc } from '#cli/app-client'import { appTargetOptions, appTargetRPCArgs } from '#cli/app-target'import { printError } from '#cli/format'-import { loadDocument, populateWholeDocument } from '#cli/headless'+import {+ documentWriteOptions,+ loadDocument,+ populateWholeDocument,+ writeFigDocument+} from '#cli/headless'function printResult(value: unknown, json: boolean) {if (json || !process.stdout.isTTY) {@@ -36,13 +39,7 @@ export default defineCommand({},code: { type: 'string', alias: 'c', description: 'JavaScript code to execute' },stdin: { type: 'boolean', description: 'Read code from stdin' },- write: { type: 'boolean', alias: 'w', description: 'Write changes back to the input file' },- output: {- type: 'string',- alias: 'o',- description: 'Write to a different file',- required: false- },+ ...documentWriteOptions,...appTargetOptions,json: { type: 'boolean', description: 'Output as JSON' },quiet: { type: 'boolean', alias: 'q', description: 'Suppress output' }@@ -97,11 +94,8 @@ export default defineCommand({}if (args.write || args.output) {- const { BUILTIN_IO_FORMATS, IORegistry } = await import('@open-pencil/core/io')- const io = new IORegistry(BUILTIN_IO_FORMATS)const outPath = args.output ? args.output : file- const result = await io.writeDocument('fig', graph)- await writeFile(outPath, result.data as Uint8Array)+ await writeFigDocument(graph, outPath)if (!args.quiet) {console.error(`Written to ${outPath}`)}diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.tsindex f6cff82f7..fbab2732a 100644--- a/packages/cli/src/format.ts+++ b/packages/cli/src/format.ts@@ -1,9 +1,12 @@import {ok,fail,+ warn,dim,bold,cyan,+ green,+ red,box as fmtBox,entity,kv,@@ -20,9 +23,12 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'export {ok,fail,+ warn,dim,bold,cyan,+ green,+ red,entity,kv,fmtTree,diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.tsindex 9cc51ca6f..6fda698a4 100644--- a/packages/cli/src/headless.ts+++ b/packages/cli/src/headless.ts@@ -1,4 +1,4 @@-import { readFile } from 'node:fs/promises'+import { readFile, writeFile } from 'node:fs/promises'import { BUILTIN_IO_FORMATS, IORegistry, initCanvasKit } from '@open-pencil/core/io'import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'@@ -18,6 +18,18 @@ export async function loadDocument(filePath: string): Promise<SceneGraph> {return graph}+/** `--write` and `--output` for commands that change a headless document. */+export const documentWriteOptions = {+ write: { type: 'boolean', alias: 'w', description: 'Write changes back to the input file' },+ output: { type: 'string', alias: 'o', description: 'Write to a different file', required: false }+} as const++/** Save a headless document as `.fig`, as `eval --write` and `diff apply --write` do. */+export async function writeFigDocument(graph: SceneGraph, filePath: string): Promise<void> {+ const result = await io.writeDocument('fig', graph)+ await writeFile(filePath, result.data as Uint8Array)+}+export function populateDocumentPage(graph: SceneGraph, pageId: string): boolean {const changed = populateFigPage(graph, pageId)if (changed) computeAllLayouts(graph, pageId)diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 9a54bb860..0bf6f3dbc 100755--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -3,6 +3,7 @@ import { defineCommand, runMain } from 'citty'import analyze from './commands/analyze'import convert from './commands/convert'+import diff from './commands/diff'import documents from './commands/documents'import evalCmd from './commands/eval'import exportCmd from './commands/export'@@ -31,6 +32,7 @@ const main = defineCommand({subCommands: {analyze,convert,+ diff,documents,eval: evalCmd,export: exportCmd,diff --git a/packages/cli/src/tool-data.ts b/packages/cli/src/tool-data.tsnew file mode 100644index 000000000..562d16cbf--- /dev/null+++ b/packages/cli/src/tool-data.ts@@ -0,0 +1,43 @@+import { FigmaAPI } from '@open-pencil/core/figma-api'+import {+ createCanvasKitRasterCodec,+ headlessRenderNodes,+ initCanvasKit+} from '@open-pencil/core/io/formats/raster'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import type { SceneGraph } from '@open-pencil/scene-graph'++import { isAppMode, requireFile, rpc } from '#cli/app-client'+import { appTargetRPCArgs, type AppTargetCLIArgs } from '#cli/app-target'+import { loadDocument, populateWholeDocument } from '#cli/headless'++/** A Figma API over a headless document, with CanvasKit raster export and pixel decoding. */+export async function createHeadlessFigma(graph: SceneGraph): Promise<FigmaAPI> {+ const figma = new FigmaAPI(graph)+ figma.exportImage = (nodeIds, options) =>+ headlessRenderNodes(graph, options.pageId ?? figma.currentPageId, nodeIds, options)+ figma.rasterCodec = createCanvasKitRasterCodec(await initCanvasKit())+ return figma+}++/**+ * Run a Core tool against the running app, or headlessly against a document file.+ * Headless runs return the loaded graph so mutating commands can write it back.+ */+export async function runToolData(+ file: string | undefined,+ name: string,+ args: Record<string, unknown>,+ targetArgs?: AppTargetCLIArgs+): Promise<{ result: unknown; graph: SceneGraph | null }> {+ if (isAppMode(file)) {+ const target = targetArgs ? appTargetRPCArgs(targetArgs) : {}+ return { result: await rpc('tool', { ...target, name, args }), graph: null }+ }+ const tool = ALL_TOOLS.find((candidate) => candidate.name === name)+ if (!tool) throw new Error(`Unknown tool: ${name}`)+ const graph = await loadDocument(requireFile(file))+ populateWholeDocument(graph)+ const figma = await createHeadlessFigma(graph)+ return { result: await tool.execute(figma, args), graph }+}diff --git a/packages/cli/tests/commands/diff.test.ts b/packages/cli/tests/commands/diff.test.tsnew file mode 100644index 000000000..711b184d5--- /dev/null+++ b/packages/cli/tests/commands/diff.test.ts@@ -0,0 +1,93 @@+import { describe, expect, setDefaultTimeout, test } from 'bun:test'+import { mkdtemp, readFile, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { CLI_ENTRY, FIXTURES } from '#cli-tests/helpers/paths'++setDefaultTimeout(60_000)++const FIXTURE = join(FIXTURES, 'gold-preview.fig')+const LOGO = '0:10'+const TITLE = '0:9'+const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47]++async function cli(args: string[]) {+ const proc = Bun.spawn([process.execPath, CLI_ENTRY, ...args], { stdout: 'pipe', stderr: 'pipe' })+ const [stdout, stderr] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text()+ ])+ return { stdout: stdout.trim(), stderr: stderr.trim(), exitCode: await proc.exited }+}++describe('diff CLI', () => {+ test('show, apply, and files round-trip an attribute patch headlessly', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-diff-'))+ const patchPath = join(dir, 'logo.diff')+ const outPath = join(dir, 'out.fig')++ const shown = await cli([+ 'diff',+ 'show',+ LOGO,+ FIXTURE,+ '--attributes',+ 'name="Brand" opacity={0.5}'+ ])+ expect(shown.exitCode).toBe(0)+ expect(shown.stdout).toBe(`@@ /Logo #${LOGO}\n-name="Logo"\n+name="Brand"\n+opacity={0.5}`)+ await writeFile(patchPath, shown.stdout)++ const applied = await cli(['diff', 'apply', patchPath, FIXTURE, '--output', outPath, '--json'])+ expect(applied.exitCode).toBe(0)+ expect(JSON.parse(applied.stdout)).toMatchObject({ applied: 1, failed: 0 })++ // Matched by path, the renamed logo reads as removed and added.+ const files = await cli(['diff', 'files', FIXTURE, outPath, '--json'])+ // Like diff(1), a difference exits 1.+ expect(files.exitCode).toBe(1)+ const result = JSON.parse(files.stdout) as { diff: string }+ expect(result.diff).toContain(`/Logo #${LOGO} removed`)+ expect(result.diff).toContain('opacity={0.5}')++ const stalePath = join(dir, 'stale.diff')+ await writeFile(stalePath, shown.stdout.replace('-name="Logo"', '-name="Other"'))+ const stale = await cli(['diff', 'apply', stalePath, FIXTURE, '--dry-run', '--json'])+ expect(stale.exitCode).toBe(1)+ expect(stale.stdout).toContain('name: expected name=\\"Other\\", found name=\\"Logo\\"')+ })++ test.each([+ [['--page', 'Nope'], 'Neither document has a page named "Nope"'],+ [['--depth', 'abc'], '--depth must be a non-negative integer, got "abc"'],+ [['--depth=-1'], '--depth must be a non-negative integer, got "-1"']+ ])('files rejects %p instead of reporting a match', async (options, error) => {+ const result = await cli(['diff', 'files', FIXTURE, FIXTURE, ...options])+ expect(result.exitCode).toBe(2)+ expect(result.stderr).toContain(error)+ })++ test('visual writes a PNG and reports the changed area', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-diff-'))+ const output = join(dir, 'diff.png')++ const result = await cli([+ 'diff',+ 'visual',+ FIXTURE,+ '--from',+ TITLE,+ '--to',+ TITLE,+ '--output',+ output,+ '--max-edge',+ '256',+ '--json'+ ])+ expect(result.exitCode).toBe(0)+ expect(JSON.parse(result.stdout)).toMatchObject({ changedPixels: 0, changedBounds: null })+ expect([...(await readFile(output)).subarray(0, 4)]).toEqual(PNG_SIGNATURE)+ })+})diff --git a/packages/cli/tests/helpers/paths.ts b/packages/cli/tests/helpers/paths.tsnew file mode 100644index 000000000..b01f3bb6f--- /dev/null+++ b/packages/cli/tests/helpers/paths.ts@@ -0,0 +1,7 @@+import { resolve } from 'node:path'++/** The CLI entry point, for tests that run it as a subprocess. */+export const CLI_ENTRY = Bun.resolveSync('#cli/index.ts', import.meta.dir)++/** Fixtures shared across the repository; a module import would escape the package root. */+export const FIXTURES = resolve(import.meta.dir, '../../../../tests/fixtures')diff --git a/packages/core/package.json b/packages/core/package.jsonindex cfaa6916b..923bee48f 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -188,10 +188,12 @@"fzstd": "^0.1.1","js-base64": "^3.9.3","jsep": "^1.4.0",+ "jsondiffpatch": "^0.7.6","jspdf": "^4.2.1","nanoevents": "^9.1.0","ofetch": "^1.5.1","opentype.js": "^2.0.0",+ "pixelmatch": "^7.2.0","pptxgenjs": "^4.0.1","rbush": "^4.0.1","sucrase": "^3.35.1",diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex dc62b835d..713f35fef 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -19,7 +19,7 @@ import type { SkiaRenderer } from '#core/canvas'import { canMakeBooleanSourceNode } from '#core/canvas/boolean'import { flattenNodesToVectorProps } from '#core/canvas/flatten'import { IS_BROWSER } from '#core/constants'-import type { RasterExportFormat } from '#core/io/formats/raster'+import type { RasterCodec } from '#core/io/formats/raster'import { reconcileVariableLayouts } from '#core/layout/variables'import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'@@ -47,11 +47,13 @@ import {type FigmaFontName,type NodeProxyHost} from './proxy'+import type { ExportImageOptions } from './types'const noop = () => undefinedexport { FigmaNodeProxy } from './proxy'export type { FigmaEffect } from './effects'+export type { ExportImageOptions } from './types'export type {FigmaBooleanOperationNode,FigmaComponentNode,@@ -596,8 +598,6 @@ export class FigmaAPI implements NodeProxyHost {return undefined}- exportImage?: (- nodeIds: string[],- options: { scale?: number; format?: RasterExportFormat; quality?: number }- ) => Promise<Uint8Array | null>+ exportImage?: (nodeIds: string[], options: ExportImageOptions) => Promise<Uint8Array | null>+ rasterCodec?: RasterCodec}diff --git a/packages/core/src/figma-api/types.ts b/packages/core/src/figma-api/types.tsindex 981dc6ad9..3e39f9c60 100644--- a/packages/core/src/figma-api/types.ts+++ b/packages/core/src/figma-api/types.ts@@ -1 +1,11 @@+import type { RasterExportFormat } from '#core/io/formats/raster'+export type FigmaTransform = [[number, number, number], [number, number, number]]++/** Raster export request; `pageId` names the page holding the nodes (default: the current page). */+export interface ExportImageOptions {+ scale?: number+ format?: RasterExportFormat+ quality?: number+ pageId?: string+}diff --git a/packages/core/src/io/formats/raster/index.ts b/packages/core/src/io/formats/raster/index.tsindex 674841fcd..eb1f32b99 100644--- a/packages/core/src/io/formats/raster/index.ts+++ b/packages/core/src/io/formats/raster/index.ts@@ -6,3 +6,4 @@ export {type ExportFormat} from './render'export { initCanvasKit, headlessRenderNodes, headlessRenderThumbnail } from './headless'+export { createCanvasKitRasterCodec, type RasterCodec, type RGBAImage } from './pixels'diff --git a/packages/core/src/io/formats/raster/pixels.ts b/packages/core/src/io/formats/raster/pixels.tsnew file mode 100644index 000000000..859ea6563--- /dev/null+++ b/packages/core/src/io/formats/raster/pixels.ts@@ -0,0 +1,51 @@+import type { CanvasKit } from 'canvaskit-wasm'++/** Unpremultiplied sRGB RGBA pixels, row-major with no padding. */+export interface RGBAImage {+ width: number+ height: number+ data: Uint8Array+}++/** Decode and encode raster images for pixel-level tools; backed by CanvasKit in app and CLI. */+export interface RasterCodec {+ decode(bytes: Uint8Array): RGBAImage | null+ encodePNG(image: RGBAImage): Uint8Array | null+}++export function createCanvasKitRasterCodec(ck: CanvasKit): RasterCodec {+ const info = (width: number, height: number) => ({+ alphaType: ck.AlphaType.Unpremul,+ colorType: ck.ColorType.RGBA_8888,+ colorSpace: ck.ColorSpace.SRGB,+ width,+ height+ })++ return {+ decode(bytes) {+ const image = ck.MakeImageFromEncoded(bytes)+ if (!image) return null+ try {+ const width = image.width()+ const height = image.height()+ const pixels = image.readPixels(0, 0, info(width, height))+ // RGBA_8888 always reads back as bytes.+ if (!(pixels instanceof Uint8Array)) return null+ return { width, height, data: pixels }+ } finally {+ image.delete()+ }+ },+ encodePNG({ width, height, data }) {+ const image = ck.MakeImage(info(width, height), data, width * 4)+ if (!image) return null+ try {+ const encoded = image.encodeToBytes(ck.ImageFormat.PNG, 100)+ return encoded ? new Uint8Array(encoded) : null+ } finally {+ image.delete()+ }+ }+ }+}diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.tsindex 3b27b71fd..a1e7f59b5 100644--- a/packages/core/src/tools/ai-adapter.ts+++ b/packages/core/src/tools/ai-adapter.ts@@ -138,6 +138,20 @@ function emitToolLog(})}+function isImageOutput(+ output: unknown+): output is { base64: string; mimeType: string; [key: string]: unknown } {+ return (+ typeof output === 'object' &&+ output !== null &&+ 'base64' in output &&+ typeof output.base64 === 'string' &&+ 'mimeType' in output &&+ typeof output.mimeType === 'string' &&+ output.mimeType.startsWith('image/')+ )+}+export function toolsToAI(tools: ToolDef[],options: AIAdapterOptions,@@ -183,17 +197,19 @@ export function toolsToAI(}}- if (def.name === 'export_image') {- toolOpts.toModelOutput = ({ output }: { output: unknown }) => {- if (output && typeof output === 'object' && 'base64' in output && 'mimeType' in output) {- const r = output as { base64: string; mimeType: string }- return {- type: 'content' as const,- value: [{ type: 'media' as const, mediaType: r.mimeType, data: r.base64 }]- }- }- return { type: 'json' as const, value: output as JSONObject }+ // Image results reach the model as media, with their metadata as text.+ toolOpts.toModelOutput = ({ output }: { output: unknown }) => {+ if (isImageOutput(output)) {+ const { base64, mimeType, ...metadata } = output+ const media = { type: 'media' as const, mediaType: mimeType, data: base64 }+ return Object.keys(metadata).length > 0+ ? {+ type: 'content' as const,+ value: [{ type: 'text' as const, text: JSON.stringify(metadata) }, media]+ }+ : { type: 'content' as const, value: [media] }}+ return { type: 'json' as const, value: output as JSONObject }}result[def.name] = tool(toolOpts as never)diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.tsindex f1d414f8d..717c87452 100644--- a/packages/core/src/tools/analyze.ts+++ b/packages/core/src/tools/analyze.ts@@ -1,6 +1,7 @@export { analyzeClusters, calcClusterConfidence } from './analyze/clusters'export { analyzeColors } from './analyze/colors'-export { diffCreate, diffShow } from './analyze/diff'+export { diffApply, diffCreate, diffDocuments, diffShow, diffVisual } from './analyze/diff'+export type { DocumentDiff, DocumentDiffOptions } 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.ts b/packages/core/src/tools/analyze/diff.tsdeleted file mode 100644index 45a5d76f9..000000000--- a/packages/core/src/tools/analyze/diff.ts+++ /dev/null@@ -1,249 +0,0 @@-import { safeDestr } from 'destr'-import { createTwoFilesPatch } from 'diff'-import * as v from 'valibot'--import type { SceneNode } from '@open-pencil/scene-graph'-import { colorToHex, parseColor } from '@open-pencil/scene-graph/color'--import type { FigmaAPI } from '#core/figma-api'-import { toolNumber, nodeIdInput, nodeComparisonInput } from '#core/tools/input'-import { defineTool } from '#core/tools/schema'--function serializePaintProps(raw: SceneNode, lines: string[]): void {- const solidFill = raw.fills.find((f) => f.type === 'SOLID' && f.visible)- if (solidFill) lines.push(`fill: ${colorToHex(solidFill.color)}`)-- const solidStroke = raw.strokes.find((s) => s.visible)- if (solidStroke) {- lines.push(`stroke: ${colorToHex(solidStroke.color)}`)- if (solidStroke.weight) lines.push(`strokeWeight: ${solidStroke.weight}`)- }-}--function serializeCornerRadii(raw: SceneNode, lines: string[]): void {- const tl = raw.topLeftRadius- const tr = raw.topRightRadius- const br = raw.bottomRightRadius- const bl = raw.bottomLeftRadius- if (tl || tr || br || bl) {- if (tl === tr && tr === br && br === bl) {- lines.push(`radius: ${tl}`)- } else {- lines.push(`radii: ${tl} ${tr} ${br} ${bl}`)- }- }-}--function serializeEffects(raw: SceneNode, lines: string[]): void {- for (const effect of raw.effects) {- const parts: string[] = [effect.type]- parts.push(`r=${effect.radius}`)- parts.push(`c=${colorToHex(effect.color)}`)- parts.push(`x=${effect.offset.x} y=${effect.offset.y}`)- parts.push(`s=${effect.spread}`)- lines.push(`effect: ${parts.join(' ')}`)- }-}--function serializeTextProps(raw: SceneNode, lines: string[]): void {- if (raw.type !== 'TEXT') return- if (raw.text) lines.push(`text: ${JSON.stringify(raw.text)}`)- if (raw.fontSize) lines.push(`fontSize: ${raw.fontSize}`)- if (raw.fontFamily) lines.push(`fontFamily: ${raw.fontFamily}`)- if (raw.fontWeight) lines.push(`fontWeight: ${raw.fontWeight}`)-}--function serializeNodeProps(raw: SceneNode): string {- const lines: string[] = []- lines.push(`type: ${raw.type}`)- lines.push(`size: ${raw.width} ${raw.height}`)- lines.push(`pos: ${raw.x} ${raw.y}`)-- serializePaintProps(raw, lines)-- if (raw.opacity !== 1) lines.push(`opacity: ${Math.round(raw.opacity * 100) / 100}`)-- serializeCornerRadii(raw, lines)-- if (raw.blendMode !== 'NORMAL') lines.push(`blendMode: ${raw.blendMode}`)- if (raw.rotation !== 0) lines.push(`rotation: ${Math.round(raw.rotation * 100) / 100}`)- if (raw.clipsContent) lines.push(`clipsContent: true`)-- serializeEffects(raw, lines)- serializeTextProps(raw, lines)-- if (!raw.visible) lines.push(`visible: false`)- if (raw.locked) lines.push(`locked: true`)-- return lines.join('\n')-}--function collectNodeTree(- figma: FigmaAPI,- nodeId: string,- parentPath: string,- depth: number,- maxDepth: number-): Map<string, { path: string; id: string; serialized: string }> {- const result = new Map<string, { path: string; id: string; serialized: string }>()- const raw = figma.graph.getNode(nodeId)- if (!raw) return result-- const path = parentPath ? `${parentPath}/${raw.name}` : `/${raw.name}`- result.set(path, { path, id: raw.id, serialized: serializeNodeProps(raw) })-- if (depth < maxDepth) {- for (const childId of raw.childIds) {- const childNodes = collectNodeTree(figma, childId, path, depth + 1, maxDepth)- for (const [k, v] of childNodes) result.set(k, v)- }- }- return result-}--function createUnifiedDiff(- oldFilename: string,- newFilename: string,- oldContent: string,- newContent: string-): string {- const patch = createTwoFilesPatch(oldFilename, newFilename, oldContent, newContent, '', '')- return patch- .split('\n')- .filter(- (l) =>- !l.startsWith('Index:') &&- l !== '==================================================================='- )- .join('\n')- .trim()-}--// ─── Diff tools ───────────────────────────────────────────────--export const diffCreate = defineTool({- name: 'diff_create',- description:- 'Create a structural diff between two node trees. Compares properties (fills, strokes, effects, text, size, position) in unified diff format.',- execution: { kind: 'sync', mutation: 'none' },- exposure: { webmcp: false },- input: v.object({- ...nodeComparisonInput.entries,- depth: v.optional(toolNumber(v.pipe(v.number(), v.description('Max tree depth (default: 10)'))))- }),- execute: (figma, args) => {- const maxDepth = args.depth ?? 10- const fromNode = figma.graph.getNode(args.from)- const toNode = figma.graph.getNode(args.to)- if (!fromNode) return { error: `Node "${args.from}" not found` }- if (!toNode) return { error: `Node "${args.to}" not found` }-- const fromNodes = collectNodeTree(figma, args.from, '', 0, maxDepth)- const toNodes = collectNodeTree(figma, args.to, '', 0, maxDepth)- const allPaths = new Set([...fromNodes.keys(), ...toNodes.keys()])-- const patches: string[] = []- for (const path of allPaths) {- const fromEntry = fromNodes.get(path)- const toEntry = toNodes.get(path)-- if (!fromEntry && toEntry) {- const filename = `${path} #${toEntry.id}`- const newLines = toEntry.serialized.split('\n')- patches.push(- `--- /dev/null\n+++ ${filename}\n@@ -0,0 +1,${newLines.length} @@\n${newLines.map((l) => `+${l}`).join('\n')}`- )- } else if (fromEntry && !toEntry) {- const filename = `${path} #${fromEntry.id}`- const oldLines = fromEntry.serialized.split('\n')- patches.push(- `--- ${filename}\n+++ /dev/null\n@@ -1,${oldLines.length} +0,0 @@\n${oldLines.map((l) => `-${l}`).join('\n')}`- )- } else if (fromEntry && toEntry && fromEntry.serialized !== toEntry.serialized) {- patches.push(- createUnifiedDiff(- `${path} #${fromEntry.id}`,- `${path} #${toEntry.id}`,- fromEntry.serialized,- toEntry.serialized- )- )- }- }-- if (patches.length === 0) return { diff: null, message: 'No differences found' }- return { diff: patches.join('\n') }- }-})--export const diffShow = defineTool({- name: 'diff_show',- description:- 'Preview what would change if properties were applied to a node. Shows a unified diff of current vs proposed state.',- execution: { kind: 'sync', mutation: 'none' },- exposure: { webmcp: false },- input: v.object({- id: nodeIdInput,- props: v.pipe(- v.string(),- v.description(- 'JSON object of new properties, e.g. \'{"opacity": 1, "fill": "#FF0000", "width": 200}\''- )- )- }),- execute: (figma, args) => {- const raw = figma.graph.getNode(args.id)- if (!raw) return { error: `Node "${args.id}" not found` }-- const oldContent = serializeNodeProps(raw)-- let newProps: Record<string, unknown>- try {- newProps = safeDestr<Record<string, unknown>>(args.props)- } catch {- return { error: 'Invalid JSON in props' }- }-- const modified: SceneNode = structuredClone(raw)- if (newProps.fill) {- modified.fills = [- { type: 'SOLID', color: parseColor(newProps.fill as string), opacity: 1, visible: true }- ]- }- if (newProps.stroke) {- modified.strokes = [- {- color: parseColor(newProps.stroke as string),- weight: modified.strokes[0]?.weight ?? 1,- opacity: 1,- visible: true,- align: modified.strokes[0]?.align ?? 'INSIDE'- }- ]- }- if (newProps.opacity !== undefined) modified.opacity = Number(newProps.opacity)- if (newProps.radius !== undefined) {- const r = Number(newProps.radius)- modified.cornerRadius = r- modified.topLeftRadius = r- modified.topRightRadius = r- modified.bottomRightRadius = r- modified.bottomLeftRadius = r- }- if (newProps.width !== undefined) modified.width = Number(newProps.width)- if (newProps.height !== undefined) modified.height = Number(newProps.height)- if (newProps.x !== undefined) modified.x = Number(newProps.x)- if (newProps.y !== undefined) modified.y = Number(newProps.y)- if (newProps.visible !== undefined) modified.visible = Boolean(newProps.visible)- if (newProps.locked !== undefined) modified.locked = Boolean(newProps.locked)- if (newProps.rotation !== undefined) modified.rotation = Number(newProps.rotation)- if (newProps.text !== undefined) modified.text = newProps.text as string-- const newContent = serializeNodeProps(modified)-- if (oldContent === newContent) return { diff: null, message: 'No changes' }-- const filename = `/${raw.name} #${args.id}`- return { diff: createUnifiedDiff(filename, filename, oldContent, newContent) }- }-})diff --git a/packages/core/src/tools/analyze/diff/apply.ts b/packages/core/src/tools/analyze/diff/apply.tsnew file mode 100644index 000000000..7152fd1f6--- /dev/null+++ b/packages/core/src/tools/analyze/diff/apply.ts@@ -0,0 +1,294 @@+import { groupBy, isEqual } from 'es-toolkit'++import {+ buildComponent,+ createElement,+ DESIGN_JSX_SUPPORTED_PROPERTIES,+ jsxNodeFields,+ parseJSXAttributes,+ resolveToTree,+ sceneNodeAttributes,+ type JSXAttributeSource+} from '@open-pencil/design-jsx'+import { recordInstanceOverride, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'++import { assertNodeEditable } from '#core/editor/capabilities'+import type { FigmaAPI } from '#core/figma-api'++import type { DiffOperation } from './operations'++export type ApplyStatus = 'applied' | 'removed' | 'moved' | 'added' | 'unchanged' | 'failed'++export interface ApplyResult {+ path: string+ id: string | null+ status: ApplyStatus+ /** Attributes an update sets or clears. */+ changes?: string[]+ error?: string+}++export interface ApplyOptions {+ dryRun: boolean+ /** Skip comparing the patch's old values with the document. */+ force: boolean+}++interface NodeUpdate {+ id: string+ fields: Partial<SceneNode>+ bind: Record<string, string>+ unbind: string[]+}++/** Where a moved node (`ids`) or an added one (`jsx`, rendered into `ids`) ends up. */+interface Placement {+ parentId: string+ index: number+ ids?: string[]+ jsx?: string+}++/** A checked operation, with what committing it needs. */+interface Plan {+ result: ApplyResult+ update?: NodeUpdate+ place?: Placement+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++function failed(operation: DiffOperation, error: string): Plan {+ const id = operation.kind === 'add' ? operation.parentId : operation.id+ return { result: { path: operation.path, id, status: 'failed', error } }+}++function editableNode(graph: SceneGraph, id: string): SceneNode | string {+ const node = graph.getNode(id)+ if (!node) return `Node "${id}" not found`+ try {+ assertNodeEditable(graph, id)+ } catch (error) {+ return errorMessage(error)+ }+ return node+}++/** Attributes as written; one the renderer would ignore fails, rather than applying as nothing. */+function parseSources(sources: string[]): JSXAttributeSource[] {+ const attributes = sources.flatMap((source) => parseJSXAttributes(source))+ const unsupported = attributes.find(({ name }) => !DESIGN_JSX_SUPPORTED_PROPERTIES.has(name))+ if (unsupported) throw new Error(`Unsupported attribute "${unsupported.name}"`)+ return attributes+}++/** Old values that differ from the node's, and new attributes it already has. */+function staleValues(+ current: Map<string, string>,+ removed: JSXAttributeSource[],+ added: JSXAttributeSource[]+): string[] {+ const removedNames = new Set(removed.map((attribute) => attribute.name))+ const describe = (name: string) => current.get(name) ?? '(none)'+ return [+ ...removed+ .filter((attribute) => current.get(attribute.name) !== attribute.source)+ .map(({ name, source }) => `${name}: expected ${source}, found ${describe(name)}`),+ ...added+ .filter((attribute) => !removedNames.has(attribute.name) && current.has(attribute.name))+ .map(({ name }) => `${name}: expected none, found ${describe(name)}`)+ ]+}++/** The fields and bindings that change between two attribute sets of one node. */+function nodeUpdate(+ graph: SceneGraph,+ node: SceneNode,+ before: JSXAttributeSource[],+ after: JSXAttributeSource[]+): NodeUpdate {+ const parentId = node.parentId ?? ''+ const from = jsxNodeFields(graph, node.type, before, parentId)+ const to = jsxNodeFields(graph, node.type, after, parentId)+ const fields = Object.fromEntries(+ Object.entries(to.fields).filter(+ ([key, value]) => !isEqual(from.fields[key as keyof SceneNode], value)+ )+ )+ return {+ id: node.id,+ fields,+ bind: Object.fromEntries(+ Object.entries(to.bindings).filter(([field, id]) => from.bindings[field] !== id)+ ),+ unbind: Object.keys(from.bindings).filter((field) => !(field in to.bindings))+ }+}++function planUpdate(+ graph: SceneGraph,+ operation: Extract<DiffOperation, { kind: 'update' }>,+ force: boolean+): Plan {+ const node = editableNode(graph, operation.id)+ if (typeof node === 'string') return failed(operation, node)+ const attributes = sceneNodeAttributes(node.id, graph)+ if (!attributes) return failed(operation, `${node.type} nodes have no JSX attributes`)+ try {+ const removed = parseSources(operation.removed)+ const added = parseSources(operation.added)+ const current = new Map(attributes.map(({ name, source }) => [name, source]))+ const stale = force ? [] : staleValues(current, removed, added)+ if (stale.length > 0) {+ return failed(operation, `Current state does not match: ${stale.join('; ')}`)+ }+ const target = new Map(current)+ for (const { name } of removed) target.delete(name)+ for (const { name, source } of added) target.set(name, source)+ const toSources = (map: Map<string, string>) =>+ [...map].map(([name, source]) => ({ name, source }))+ const update = nodeUpdate(graph, node, attributes, toSources(target))+ const changes = [...new Set([...removed, ...added].map((attribute) => attribute.name))]+ const empty =+ Object.keys(update.fields).length === 0 &&+ Object.keys(update.bind).length === 0 &&+ update.unbind.length === 0+ const status = empty ? 'unchanged' : 'applied'+ return { result: { path: operation.path, id: node.id, status, changes }, update }+ } catch (error) {+ return failed(operation, errorMessage(error))+ }+}++function planAdd(graph: SceneGraph, operation: Extract<DiffOperation, { kind: 'add' }>): Plan {+ const parent = editableNode(graph, operation.parentId)+ if (typeof parent === 'string') return failed(operation, parent)+ if (!operation.jsx.trim()) return failed(operation, 'Added node has no JSX')+ try {+ // Evaluate now so invalid JSX fails before anything changes.+ if (!resolveToTree(createElement(buildComponent(operation.jsx), null))) {+ return failed(operation, 'Added JSX renders nothing')+ }+ } catch (error) {+ return failed(operation, errorMessage(error))+ }+ const place = { parentId: parent.id, index: operation.index, jsx: operation.jsx }+ return { result: { path: operation.path, id: null, status: 'added' }, place }+}++function planOperation(graph: SceneGraph, operation: DiffOperation, force: boolean): Plan {+ switch (operation.kind) {+ case 'update':+ return planUpdate(graph, operation, force)+ case 'remove': {+ const node = editableNode(graph, operation.id)+ if (typeof node === 'string') return failed(operation, node)+ return { result: { path: operation.path, id: node.id, status: 'removed' } }+ }+ case 'move': {+ const node = editableNode(graph, operation.id)+ if (typeof node === 'string') return failed(operation, node)+ if (!node.parentId) return failed(operation, `Node "${node.id}" has no parent`)+ const place = { parentId: node.parentId, index: operation.index, ids: [node.id] }+ return { result: { path: operation.path, id: node.id, status: 'moved' }, place }+ }+ }+ return planAdd(graph, operation)+}++/** Check every operation against the document without changing it. */+export function planOperations(+ graph: SceneGraph,+ operations: DiffOperation[],+ force: boolean+): Plan[] {+ return operations.map((operation) => planOperation(graph, operation, force))+}++function commitUpdate(graph: SceneGraph, update: NodeUpdate): void {+ graph.updateNode(update.id, update.fields)+ recordInstanceOverride(graph, update.id, Object.keys(update.fields))+ for (const field of update.unbind) graph.unbindVariable(update.id, field)+ for (const [field, variableId] of Object.entries(update.bind)) {+ graph.bindVariable(update.id, field, variableId)+ }+}++type Placed = Plan & { place: Placement }++/**+ * Render added nodes before changing anything else. Rendering can still fail, for example on+ * an icon that cannot be fetched; then the nodes rendered so far are deleted and nothing else+ * is committed, so a patch never half-applies.+ */+async function renderAdditions(figma: FigmaAPI, plans: Placed[]): Promise<boolean> {+ const { renderJSX } = await import('#core/design-jsx')+ const rendered: string[] = []+ for (const plan of plans) {+ const { jsx, parentId } = plan.place+ if (jsx === undefined) continue+ try {+ const results = await renderJSX(figma.graph, jsx, { parentId })+ plan.place.ids = results.map((result) => result.id)+ plan.result.id = results[0].id+ rendered.push(...plan.place.ids)+ } catch (error) {+ plan.result.status = 'failed'+ plan.result.error = errorMessage(error)+ for (const id of rendered.toReversed()) figma.graph.deleteNode(id)+ for (const other of plans) if (other.place.jsx !== undefined) other.result.id = null+ return false+ }+ }+ return true+}++/**+ * Moves and additions under one parent, as jsondiffpatch patches arrays: take the placed+ * children out, then insert each at its final index, in index order.+ */+function commitPlacements(graph: SceneGraph, parentId: string, plans: Placed[]): void {+ const placed = new Set(plans.flatMap((plan) => plan.place.ids ?? []))+ const order = (graph.getNode(parentId)?.childIds ?? []).filter((id) => !placed.has(id))+ for (const plan of plans.toSorted((a, b) => a.place.index - b.place.index)) {+ order.splice(plan.place.index, 0, ...(plan.place.ids ?? []))+ }+ for (const [index, id] of order.entries()) {+ if (graph.getNode(parentId)?.childIds[index] !== id) graph.insertChildAt(id, parentId, index)+ }+}++/**+ * Apply a patch's operations. Every operation is checked first and nothing changes unless all+ * pass; a dry run stops there. Added nodes render first, so one that fails to render leaves the+ * document as it was. Updates go through the JSX renderer's prop handling and change only the+ * fields their attributes move, so IDs, instance links, and other state survive.+ */+export async function applyOperations(+ figma: FigmaAPI,+ operations: DiffOperation[],+ options: ApplyOptions+): Promise<ApplyResult[]> {+ const plans = planOperations(figma.graph, operations, options.force)+ const results = () => plans.map((plan) => plan.result)+ if (options.dryRun || plans.some((plan) => plan.result.status === 'failed')) return results()+ const placed = plans.filter((plan): plan is Placed => !!plan.place)+ if (!(await renderAdditions(figma, placed))) return results()+ for (const plan of plans) {+ if (plan.update && plan.result.status === 'applied') {+ commitUpdate(figma.graph, plan.update)+ }+ }+ for (const plan of plans) {+ if (plan.result.status === 'removed' && plan.result.id) {+ // A removed ancestor already took its descendants with it.+ figma.getNodeById(plan.result.id)?.remove()+ }+ }+ for (const [parentId, group] of Object.entries(groupBy(placed, (plan) => plan.place.parentId))) {+ commitPlacements(figma.graph, parentId, group)+ }+ return results()+}diff --git a/packages/core/src/tools/analyze/diff/documents.ts b/packages/core/src/tools/analyze/diff/documents.tsnew file mode 100644index 000000000..7fcc3e384--- /dev/null+++ b/packages/core/src/tools/analyze/diff/documents.ts@@ -0,0 +1,77 @@+import { sceneNodeToJSX } from '@open-pencil/design-jsx'+import type { SceneGraph } from '@open-pencil/scene-graph'++import type { TreeArgs } from '#core/rpc'++import { formatOperations } from './format'+import { deltaOperations } from './operations'+import { diffProjections, projectTree, type ProjectedNode } from './projection'++/** `page` limits the diff to one page by name; `depth` bounds each page tree (default: unlimited). */+export type DocumentDiffOptions = TreeArgs++export interface DocumentDiff {+ pages: {+ name: string+ status: 'added' | 'removed' | 'changed' | 'unchanged'+ diff: string | null+ }[]+ /** All page patches joined, or `null` when no page that both documents have differs. */+ diff: string | null+ /** Whether the documents differ, including pages only one of them has. */+ changed: boolean+}++type PageStatus = DocumentDiff['pages'][number]['status']++function pageStatus(before: boolean, after: boolean, diff: string | null): PageStatus {+ if (!before) return 'added'+ if (!after) return 'removed'+ return diff ? 'changed' : 'unchanged'+}++function pageDiff(+ before: ProjectedNode,+ after: ProjectedNode,+ afterGraph: SceneGraph+): string | null {+ const operations = deltaOperations(diffProjections(before, after), before, after, (id) =>+ sceneNodeToJSX(id, afterGraph)+ )+ return operations.length > 0 ? formatOperations(operations) : null+}++/**+ * Structural diff of two documents, page by page. Pages match by name and nodes by name path,+ * so two versions of a file compare even though their node IDs differ. Each page's patch+ * applies to the first document. Patches do not add or remove pages, so a page only one+ * document has is reported by its status alone.+ */+export function diffDocuments(+ before: SceneGraph,+ after: SceneGraph,+ options: DocumentDiffOptions = {}+): DocumentDiff {+ const project = { match: 'path' as const, depth: options.depth }+ const beforePages = new Map(before.getPages().map((page) => [page.name, page]))+ const afterPages = new Map(after.getPages().map((page) => [page.name, page]))+ const names = [...new Set([...beforePages.keys(), ...afterPages.keys()])].filter(+ (name) => options.page === undefined || name === options.page+ )++ const pages = names.map((name) => {+ const beforePage = beforePages.get(name)+ const afterPage = afterPages.get(name)+ const from = beforePage ? projectTree(before, beforePage.id, project) : null+ const to = afterPage ? projectTree(after, afterPage.id, project) : null+ const diff = from && to ? pageDiff(from, to, after) : null+ return { name, status: pageStatus(Boolean(beforePage), Boolean(afterPage), diff), diff }+ })++ const patches = pages.flatMap((page) => (page.diff ? [page.diff] : []))+ return {+ pages,+ diff: patches.length > 0 ? patches.join('\n') : null,+ changed: pages.some((page) => page.status !== 'unchanged')+ }+}diff --git a/packages/core/src/tools/analyze/diff/format.ts b/packages/core/src/tools/analyze/diff/format.tsnew file mode 100644index 000000000..70d04ca53--- /dev/null+++ b/packages/core/src/tools/analyze/diff/format.ts@@ -0,0 +1,92 @@+import type { DiffOperation } from './operations'++/**+ * A patch is a list of hunks. Each header names a node by path, for reading, and by ID, which+ * locates it; JSX attribute lines follow, `-` for the old value and `+` for the new one:+ *+ * @@ /Card #1:2+ * -rounded={12}+ * +rounded={16}+ * @@ /Card/Badge #1:5 moved to 0+ * @@ /Card/Note #1:8 removed+ * @@ /Card/Price added to #1:2 at 3+ * +<Text name="Price" size={24}>$9</Text>+ */+function formatOperation(operation: DiffOperation): string[] {+ switch (operation.kind) {+ case 'update':+ return [+ `@@ ${operation.path} #${operation.id}`,+ ...operation.removed.map((source) => `-${source}`),+ ...operation.added.map((source) => `+${source}`)+ ]+ case 'remove':+ return [`@@ ${operation.path} #${operation.id} removed`]+ case 'move':+ return [`@@ ${operation.path} #${operation.id} moved to ${operation.index}`]+ }+ return [+ `@@ ${operation.path} added to #${operation.parentId} at ${operation.index}`,+ ...operation.jsx.split('\n').map((line) => `+${line}`)+ ]+}++export function formatOperations(operations: DiffOperation[]): string {+ return operations.flatMap(formatOperation).join('\n')+}++/** Headers anchor on their endings, so a name containing ` #` or `removed` still parses. */+const HEADERS: [RegExp, (match: RegExpExecArray) => DiffOperation][] = [+ [+ /^@@ (.*) added to #(\S+) at (\d+)$/,+ ([, path, parentId, index]) => ({ kind: 'add', path, parentId, index: Number(index), jsx: '' })+ ],+ [/^@@ (.*) #(\S+) removed$/, ([, path, id]) => ({ kind: 'remove', path, id })],+ [+ /^@@ (.*) #(\S+) moved to (\d+)$/,+ ([, path, id, index]) => ({ kind: 'move', path, id, index: Number(index) })+ ],+ [/^@@ (.*) #(\S+)$/, ([, path, id]) => ({ kind: 'update', path, id, removed: [], added: [] })]+]++function parseHeader(line: string): DiffOperation | null {+ for (const [pattern, build] of HEADERS) {+ const match = pattern.exec(line)+ if (match) return build(match)+ }+ return null+}++function addBodyLine(operation: DiffOperation, line: string): boolean {+ const marker = line[0]+ const body = line.slice(1)+ if (operation.kind === 'update' && (marker === '-' || marker === '+')) {+ ;(marker === '-' ? operation.removed : operation.added).push(body)+ return true+ }+ if (operation.kind === 'add' && marker === '+') {+ operation.jsx = operation.jsx ? `${operation.jsx}\n${body}` : body+ return true+ }+ return false+}++/** Parse a patch from `formatOperations`; throws naming the first line it cannot read. */+export function parseOperations(text: string): DiffOperation[] {+ const operations: DiffOperation[] = []+ for (const [index, raw] of text.split('\n').entries()) {+ const line = raw.replace(/\r$/, '')+ if (line.trim() === '') continue+ if (line.startsWith('@@ ')) {+ const operation = parseHeader(line)+ if (!operation) throw new Error(`Line ${index + 1}: unrecognized hunk header: ${line}`)+ operations.push(operation)+ continue+ }+ const current = operations.at(-1)+ if (!current || !addBodyLine(current, line)) {+ throw new Error(`Line ${index + 1}: unexpected line: ${line}`)+ }+ }+ return operations+}diff --git a/packages/core/src/tools/analyze/diff/index.ts b/packages/core/src/tools/analyze/diff/index.tsnew file mode 100644index 000000000..56225b301--- /dev/null+++ b/packages/core/src/tools/analyze/diff/index.ts@@ -0,0 +1,3 @@+export { diffDocuments, type DocumentDiff, type DocumentDiffOptions } from './documents'+export { diffApply, diffCreate, diffShow } from './tools'+export { diffVisual } from './visual'diff --git a/packages/core/src/tools/analyze/diff/operations.ts b/packages/core/src/tools/analyze/diff/operations.tsnew file mode 100644index 000000000..cda65c7b9--- /dev/null+++ b/packages/core/src/tools/analyze/diff/operations.ts@@ -0,0 +1,119 @@+import type { Delta } from 'jsondiffpatch'++import type { ProjectedNode } from './projection'++/** One edit to a node tree; together they turn the old tree into the new one. */+export type DiffOperation =+ | {+ kind: 'update'+ path: string+ id: string+ /** Attribute sources the node has now and loses. */+ removed: string[]+ /** Attribute sources the node gains. */+ added: string[]+ }+ | { kind: 'remove'; path: string; id: string }+ | { kind: 'move'; path: string; id: string; index: number }+ | { kind: 'add'; path: string; parentId: string; index: number; jsx: string }++// jsondiffpatch documents its delta shapes; its type guards are not exported at runtime.+type ObjectDelta = Record<string, Delta>+const isObjectDelta = (delta: unknown): delta is ObjectDelta =>+ typeof delta === 'object' && delta !== null && !Array.isArray(delta)+const isAdded = (delta: unknown): delta is [unknown] => Array.isArray(delta) && delta.length === 1+const isDeleted = (delta: unknown): delta is [unknown, 0, 0] =>+ Array.isArray(delta) && delta.length === 3 && delta[2] === 0+const isMoved = (delta: unknown): delta is [unknown, number, 3] =>+ Array.isArray(delta) && delta.length === 3 && delta[2] === 3++/** Paths are for reading; IDs locate nodes, so a name's line breaks can become spaces. */+function childPath(parentPath: string, node: ProjectedNode): string {+ return `${parentPath}/${node.name.replace(/[\r\n]+/g, ' ')}`+}++function attributeChanges(before: ProjectedNode, after: ProjectedNode) {+ const names = new Set([...Object.keys(before.attributes), ...Object.keys(after.attributes)])+ const removed: string[] = []+ const added: string[] = []+ for (const name of names) {+ const from = before.attributes[name] as string | undefined+ const to = after.attributes[name] as string | undefined+ if (from === to) continue+ if (from !== undefined) removed.push(from)+ if (to !== undefined) added.push(to)+ }+ return { removed, added }+}++interface Walk {+ /** JSX for an added node, by its ID in the new tree. */+ jsxFor: (id: string) => string+ out: DiffOperation[]+}++function childOperations(+ delta: ObjectDelta,+ before: ProjectedNode,+ after: ProjectedNode,+ path: string,+ walk: Walk+): void {+ const oldChildren = before.children ?? []+ const newChildren = after.children ?? []+ const removals: DiffOperation[] = []+ // Array deltas key removals and moves by old index, additions and edits by new index.+ for (const [key, change] of Object.entries(delta)) {+ if (key === '_t') continue+ if (key.startsWith('_')) {+ const child = oldChildren[Number(key.slice(1))]+ if (isDeleted(change))+ removals.push({ kind: 'remove', path: childPath(path, child), id: child.id })+ else if (isMoved(change)) {+ walk.out.push({+ kind: 'move',+ path: childPath(path, child),+ id: child.id,+ index: change[1]+ })+ }+ continue+ }+ const index = Number(key)+ const child = newChildren[index]+ if (isAdded(change)) {+ const jsx = walk.jsxFor(child.id)+ walk.out.push({ kind: 'add', path: childPath(path, child), parentId: before.id, index, jsx })+ continue+ }+ const counterpart = oldChildren.find((item) => item.key === child.key)+ if (counterpart) nodeOperations(change, counterpart, child, childPath(path, counterpart), walk)+ }+ walk.out.push(...removals)+}++function nodeOperations(+ delta: Delta,+ before: ProjectedNode,+ after: ProjectedNode,+ path: string,+ walk: Walk+): void {+ if (!isObjectDelta(delta)) return+ if (delta.attributes) {+ walk.out.push({ kind: 'update', path, id: before.id, ...attributeChanges(before, after) })+ }+ if (isObjectDelta(delta.children)) childOperations(delta.children, before, after, path, walk)+}++/** The edits a delta between two projected trees describes, applying to the old tree. */+export function deltaOperations(+ delta: Delta,+ before: ProjectedNode,+ after: ProjectedNode,+ jsxFor: (id: string) => string+): DiffOperation[] {+ const walk: Walk = { jsxFor, out: [] }+ nodeOperations(delta, before, after, childPath('', before), walk)+ return walk.out+}diff --git a/packages/core/src/tools/analyze/diff/projection.ts b/packages/core/src/tools/analyze/diff/projection.tsnew file mode 100644index 000000000..815bce6d7--- /dev/null+++ b/packages/core/src/tools/analyze/diff/projection.ts@@ -0,0 +1,92 @@+import { create, type Delta } from 'jsondiffpatch'++import { sceneNodeAttributes } from '@open-pencil/design-jsx'+import type { NodeType, SceneGraph } from '@open-pencil/scene-graph'++export const DEFAULT_DIFF_DEPTH = 10++/**+ * How nodes find their counterparts: by ID between two states of one document, or by name+ * path between copies and files, whose IDs differ.+ */+export type DiffMatch = 'id' | 'path'++/** A node as the diff sees it: its JSX attributes and its children. */+export interface ProjectedNode {+ id: string+ /** Matches the node to its counterpart: its ID, or its type and name, counting repeats. */+ key: string+ type: NodeType+ name: string+ /** Attribute sources by name, as the JSX export prints them; empty for nodes it skips. */+ attributes: Record<string, string>+ /** `null` past the depth limit, so children that were not visited never read as removed. */+ children: ProjectedNode[] | null+}++export interface ProjectOptions {+ match: DiffMatch+ /** Levels of children to include (default: unlimited). */+ depth?: number+}++function projectNode(+ graph: SceneGraph,+ id: string,+ key: string,+ match: DiffMatch,+ depth: number+): ProjectedNode | null {+ const node = graph.getNode(id)+ if (!node) return null+ const attributes = Object.fromEntries(+ (sceneNodeAttributes(id, graph) ?? []).map(({ name, source }) => [name, source])+ )+ let children: ProjectedNode[] | null = null+ if (depth > 0) {+ // Number repeated names so each sibling matches its counterpart, not its namesake.+ const seen = new Map<string, number>()+ children = node.childIds.flatMap((childId) => {+ const child = graph.getNode(childId)+ if (!child) return []+ const base = `${child.type}:${child.name}`+ const count = (seen.get(base) ?? 0) + 1+ seen.set(base, count)+ const pathKey = count > 1 ? `${base}[${count}]` : base+ return projectNode(graph, childId, match === 'id' ? childId : pathKey, match, depth - 1) ?? []+ })+ }+ return { id, key, type: node.type, name: node.name, attributes, children }+}++export function projectTree(+ graph: SceneGraph,+ rootId: string,+ options: ProjectOptions+): ProjectedNode | null {+ return projectNode(+ graph,+ rootId,+ rootId,+ options.match,+ options.depth ?? Number.POSITIVE_INFINITY+ )+}++function isProjectedNode(value: unknown): value is ProjectedNode {+ return typeof value === 'object' && value !== null && 'attributes' in value && 'key' in value+}++/** Labels, not state: a renamed node's `name` attribute carries the change. */+const NODE_LABELS = new Set(['id', 'name'])++const differ = create({+ objectHash: (item) => (isProjectedNode(item) ? item.key : undefined),+ arrays: { detectMove: true, includeValueOnMove: false },+ propertyFilter: (name, context) => !(NODE_LABELS.has(name) && isProjectedNode(context.left))+})++/** The jsondiffpatch delta between two projected trees; `undefined` when they match. */+export function diffProjections(before: ProjectedNode, after: ProjectedNode): Delta {+ return differ.diff(before, after)+}diff --git a/packages/core/src/tools/analyze/diff/tools.ts b/packages/core/src/tools/analyze/diff/tools.tsnew file mode 100644index 000000000..66f6aa66b--- /dev/null+++ b/packages/core/src/tools/analyze/diff/tools.ts@@ -0,0 +1,155 @@+import * as v from 'valibot'++import { parseJSXAttributes, sceneNodeAttributes, sceneNodeToJSX } from '@open-pencil/design-jsx'+import type { SceneGraph } from '@open-pencil/scene-graph'++import { toolNumber, nodeIdInput, nodeComparisonInput } from '#core/tools/input'+import { defineTool } from '#core/tools/schema'++import { applyOperations, planOperations, type ApplyStatus } from './apply'+import { formatOperations, parseOperations } from './format'+import { deltaOperations, type DiffOperation } from './operations'+import { DEFAULT_DIFF_DEPTH, diffProjections, projectTree, type ProjectOptions } from './projection'++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++/** Operations that turn the `from` tree into the `to` tree, matching children by name path. */+function treeOperations(+ graph: SceneGraph,+ from: string,+ to: string,+ options: ProjectOptions+): DiffOperation[] {+ const before = projectTree(graph, from, options)+ const after = projectTree(graph, to, options)+ if (!before || !after) return []+ // Compare the trees, not their roots' names: a copy is usually renamed.+ const { name: _name, ...attributes } = after.attributes+ const name = before.attributes.name as string | undefined+ const target = {+ ...after,+ name: before.name,+ attributes: name ? { ...attributes, name } : attributes+ }+ return deltaOperations(diffProjections(before, target), before, target, (id) =>+ sceneNodeToJSX(id, graph)+ )+}++export const diffCreate = defineTool({+ name: 'diff_create',+ description:+ 'Patch that turns one node tree into another, as JSX attribute changes per node plus moved, added, and removed children. Children are matched by name. Apply it to the first tree with diff_apply.',+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ ...nodeComparisonInput.entries,+ depth: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.integer(),+ v.minValue(0),+ v.description(`Max tree depth (default: ${DEFAULT_DIFF_DEPTH})`)+ )+ )+ )+ }),+ execute: (figma, args) => {+ if (!figma.graph.getNode(args.from)) return { error: `Node "${args.from}" not found` }+ if (!figma.graph.getNode(args.to)) return { error: `Node "${args.to}" not found` }+ const operations = treeOperations(figma.graph, args.from, args.to, {+ match: 'path',+ depth: args.depth ?? DEFAULT_DIFF_DEPTH+ })+ return operations.length === 0+ ? { diff: null, message: 'No differences found' }+ : { diff: formatOperations(operations) }+ }+})++export const diffShow = defineTool({+ name: 'diff_show',+ description:+ 'Preview setting JSX attributes on a node, without changing it. Returns the patch, which diff_apply applies.',+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ id: nodeIdInput,+ attributes: v.pipe(+ v.string(),+ v.description(+ 'JSX attributes to set, named as the JSX export writes them. Example: w={200} bg="#FF0000" opacity={0.5}'+ )+ )+ }),+ execute: (figma, args) => {+ const node = figma.graph.getNode(args.id)+ if (!node) return { error: `Node "${args.id}" not found` }+ const current = sceneNodeAttributes(node.id, figma.graph)+ if (!current) return { error: `${node.type} nodes have no JSX attributes` }+ let proposed+ try {+ proposed = parseJSXAttributes(args.attributes)+ } catch (error) {+ return { error: errorMessage(error) }+ }+ const sources = new Map(current.map(({ name, source }) => [name, source]))+ const changed = proposed.filter(({ name, source }) => sources.get(name) !== source)+ if (changed.length === 0) return { diff: null, message: 'No changes' }+ const operation: DiffOperation = {+ kind: 'update',+ path: `/${node.name}`,+ id: node.id,+ removed: changed.flatMap(({ name }) => sources.get(name) ?? []),+ added: changed.map(({ source }) => source)+ }+ // Check the change the way diff_apply would, so invalid values surface here.+ const [plan] = planOperations(figma.graph, [operation], false)+ if (plan.result.error) return { error: plan.result.error }+ return { diff: formatOperations([operation]) }+ }+})++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.",+ execution: { kind: 'async', mutation: 'document' },+ input: v.object({+ patch: v.pipe(v.string(), v.description('Patch text from diff_create or diff_show')),+ dryRun: v.optional(+ v.pipe(v.boolean(), v.description('Check and report changes without applying')),+ false+ ),+ force: v.optional(+ v.pipe(v.boolean(), v.description('Apply even when current values differ from the patch')),+ false+ )+ }),+ execute: async (figma, args) => {+ let operations: DiffOperation[]+ try {+ operations = parseOperations(args.patch)+ } catch (error) {+ return { error: errorMessage(error) }+ }+ if (operations.length === 0) return { error: 'No hunks found' }+ const results = await applyOperations(figma, operations, {+ dryRun: args.dryRun,+ force: args.force+ })+ const count = (...statuses: ApplyStatus[]) =>+ results.filter((result) => statuses.includes(result.status)).length+ const failed = count('failed')+ if (failed > 0 && !args.dryRun) {+ return { error: 'Patch does not apply', results: results.filter((r) => r.error) }+ }+ return {+ dryRun: args.dryRun,+ applied: count('applied', 'removed', 'moved', 'added'),+ failed,+ results+ }+ }+})diff --git a/packages/core/src/tools/analyze/diff/visual.ts b/packages/core/src/tools/analyze/diff/visual.tsnew file mode 100644index 000000000..e8c9ccd30--- /dev/null+++ b/packages/core/src/tools/analyze/diff/visual.ts@@ -0,0 +1,160 @@+import { fromUint8Array } from 'js-base64'+import pixelmatch from 'pixelmatch'+import * as v from 'valibot'++import type { FigmaAPI } from '#core/figma-api'+import { computeContentBounds, type RGBAImage } from '#core/io/formats/raster'+import { findPageId } from '#core/io/subgraph'+import { nodeComparisonInput, toolNumber } from '#core/tools/input'+import { defineTool } from '#core/tools/schema'+import { boundedRasterScale, rasterScaleInputs } from '#core/tools/vector/export'++/** pixelmatch paints mismatches in this color over a faded grayscale copy of the source. */+const DIFF_COLOR: [number, number, number] = [255, 0, 0]++interface Rendered {+ image: RGBAImage+ /** World coordinates of pixel (0, 0). */+ originX: number+ originY: number+}++async function renderNode(+ figma: FigmaAPI,+ id: string,+ scale: number+): Promise<Rendered | { error: string }> {+ const pageId = findPageId(figma.graph, id)+ const bounds = computeContentBounds(figma.graph, [id])+ if (!pageId || !bounds) return { error: `Node "${id}" has no visible content` }+ const bytes = await figma.exportImage?.([id], { scale, format: 'PNG', pageId })+ const image = bytes ? figma.rasterCodec?.decode(bytes) : null+ if (!image) return { error: `Node "${id}" could not be rendered` }+ return { image, originX: bounds.minX, originY: bounds.minY }+}++/** Copy into a transparent canvas of the given size, so differently sized renders compare. */+function padImage(image: RGBAImage, width: number, height: number): Uint8Array {+ if (image.width === width && image.height === height) return image.data+ const data = new Uint8Array(width * height * 4)+ for (let y = 0; y < image.height; y++) {+ const row = image.data.subarray(y * image.width * 4, (y + 1) * image.width * 4)+ data.set(row, y * width * 4)+ }+ return data+}++function changedPixelBounds(output: Uint8Array, width: number, height: number) {+ let minX = width+ let minY = height+ let maxX = -1+ let maxY = -1+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const offset = (y * width + x) * 4+ if (+ output[offset] !== DIFF_COLOR[0] ||+ output[offset + 1] !== DIFF_COLOR[1] ||+ output[offset + 2] !== DIFF_COLOR[2]+ ) {+ continue+ }+ minX = Math.min(minX, x)+ minY = Math.min(minY, y)+ maxX = Math.max(maxX, x + 1)+ maxY = Math.max(maxY, y + 1)+ }+ }+ return maxX < 0 ? null : { minX, minY, maxX, maxY }+}++function round(value: number): number {+ return Math.round(value * 100) / 100+}++export const diffVisual = defineTool({+ name: 'diff_visual',+ description:+ 'Pixel diff between two rendered nodes. Returns a PNG with changed pixels in red over a faded copy of the source, the changed pixel ratio, and the changed region in source-node coordinates. Use it to confirm an edit only touched the intended area.',+ execution: { kind: 'async', mutation: 'none' },+ input: v.object({+ ...nodeComparisonInput.entries,+ ...rasterScaleInputs,+ threshold: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.minValue(0),+ v.maxValue(1),+ v.description('Per-pixel color tolerance from 0 to 1; smaller is stricter (default: 0.1)')+ )+ ),+ 0.1+ )+ }),+ execute: async (figma, args) => {+ if (!figma.exportImage || !figma.rasterCodec) {+ return { error: 'Visual diff is not available in this environment' }+ }+ const fromNode = figma.graph.getNode(args.from)+ if (!fromNode) return { error: `Node "${args.from}" not found` }+ if (!figma.graph.getNode(args.to)) return { error: `Node "${args.to}" not found` }++ const fromBounds = computeContentBounds(figma.graph, [args.from])+ const toBounds = computeContentBounds(figma.graph, [args.to])+ if (!fromBounds || !toBounds) return { error: 'Both nodes need visible content to compare' }+ // One scale for both sides, so equal designs produce equal pixels.+ const scale = boundedRasterScale(+ Math.max(fromBounds.maxX - fromBounds.minX, toBounds.maxX - toBounds.minX),+ Math.max(fromBounds.maxY - fromBounds.minY, toBounds.maxY - toBounds.minY),+ args.scale,+ args.maxEdge+ )+ if (scale <= 0) return { error: 'Both nodes need visible content to compare' }++ const before = await renderNode(figma, args.from, scale)+ if ('error' in before) return before+ const after = await renderNode(figma, args.to, scale)+ if ('error' in after) return after++ const width = Math.max(before.image.width, after.image.width)+ const height = Math.max(before.image.height, after.image.height)+ const output = new Uint8Array(width * height * 4)+ const changedPixels = pixelmatch(+ padImage(before.image, width, height),+ padImage(after.image, width, height),+ output,+ width,+ height,+ { threshold: args.threshold, diffColor: DIFF_COLOR }+ )+ const png = figma.rasterCodec.encodePNG({ width, height, data: output })+ if (!png) return { error: 'Visual diff image could not be encoded' }++ const pixels = changedPixelBounds(output, width, height)+ const origin = figma.graph.getAbsolutePosition(args.from)+ const totalPixels = width * height+ return {+ mimeType: 'image/png',+ base64: fromUint8Array(png),+ byteLength: png.length,+ width,+ height,+ scale,+ changedPixels,+ totalPixels,+ changedRatio:+ totalPixels > 0 ? Math.round((changedPixels / totalPixels) * 10_000) / 10_000 : 0,+ changedBounds: pixels+ ? {+ x: round(before.originX - origin.x + pixels.minX / scale),+ y: round(before.originY - origin.y + pixels.minY / scale),+ width: round((pixels.maxX - pixels.minX) / scale),+ height: round((pixels.maxY - pixels.minY) / scale)+ }+ : null,+ sizeChanged:+ before.image.width !== after.image.width || before.image.height !== after.image.height+ }+ }+})diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex ee0970fbb..f99deda6c 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -21,7 +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, wrapEvalCode } from './analyze'+export { calcClusterConfidence, diffDocuments, wrapEvalCode } from './analyze'+export type { DocumentDiff, DocumentDiffOptions } 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 e5be4b5bb..347b8a51a 100644--- a/packages/core/src/tools/read/jsx.ts+++ b/packages/core/src/tools/read/jsx.ts@@ -46,7 +46,6 @@ export const diffJSX = defineTool({description:'Structural diff between two nodes in JSX format. Shows added/removed children, changed props.',execution: { kind: 'sync', mutation: 'none' },- exposure: { webmcp: false },input: nodeComparisonInput,execute: (figma, { from, to }) => {const fromNode = figma.getNodeById(from)diff --git a/packages/core/src/tools/registry-core.ts b/packages/core/src/tools/registry-core.tsindex 18764a442..1ee289104 100644--- a/packages/core/src/tools/registry-core.ts+++ b/packages/core/src/tools/registry-core.ts@@ -1,4 +1,4 @@-import { evalCode } from './analyze'+import { diffCreate, diffVisual, evalCode } from './analyze'import { calc } from './calc'import { render } from './create'import { describe } from './describe'@@ -12,15 +12,15 @@ import {setTextProperties,updateNode} from './modify'-import { findNodes, getJSX, getNode, getSelection } from './read'+import { diffJSX, findNodes, getJSX, getNode, getSelection } from './read'import type { ToolDef } from './schema'import { stockPhoto } from './stock-photo'import { batchUpdate, deleteNode, nodeResize, reparentNode } from './structure'import { viewportZoomToFit } from './vector'/**- * Core tools registered by default in AI chat (~30 tools, ~3K schema tokens).- * Covers 90%+ of design sessions: render, describe, modify, structure, icons.+ * Core tools registered by default in AI chat (25 tools, ~5K schema tokens).+ * Covers 90%+ of design sessions: render, describe, modify, structure, and diff checks.*/export const CORE_TOOLS: ToolDef[] = [// Read@@ -48,6 +48,9 @@ export const CORE_TOOLS: ToolDef[] = [stockPhoto,// Inspect & utilitydescribe,+ diffCreate,+ diffJSX,+ diffVisual,calc,evalCode,viewportZoomToFitdiff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.tsindex 4c67d8155..94c7f8dc2 100644--- a/packages/core/src/tools/registry-extended.ts+++ b/packages/core/src/tools/registry-extended.ts@@ -4,7 +4,7 @@ import {analyzeOverlaps,analyzeSpacing,analyzeTypography,- diffCreate,+ diffApply,diffShow} from './analyze'import { designToComponentMap, designToTokens } from './codegen'@@ -38,7 +38,6 @@ import {setVisible} from './modify'import {- diffJSX,getComponents,getCurrentPage,getFontStatus,@@ -120,7 +119,6 @@ export const EXTENDED_TOOLS: ToolDef[] = [getFontStatus,listFonts,listAvailableFonts,- diffJSX,// Create (advanced)createShape,searchIconsTool,@@ -197,8 +195,8 @@ export const EXTENDED_TOOLS: ToolDef[] = [analyzeSpacing,analyzeClusters,analyzeOverlaps,- diffCreate,diffShow,+ diffApply,// CodegendesignToTokens,designToComponentMapdiff --git a/packages/core/src/tools/vector/export.ts b/packages/core/src/tools/vector/export.tsindex fc38e06ea..1b8f7423b 100644--- a/packages/core/src/tools/vector/export.ts+++ b/packages/core/src/tools/vector/export.ts@@ -23,6 +23,47 @@ const exportInputs = {)}+/** Scale inputs shared by every tool that returns a raster image to a model. */+export const rasterScaleInputs = {+ scale: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.minValue(0.1),+ v.maxValue(4),+ v.description(+ 'Export scale multiplier before the maximum-edge limit is applied (default: 1)'+ )+ )+ ),+ 1+ ),+ maxEdge: v.optional(+ toolNumber(+ v.pipe(+ v.number(),+ v.minValue(64),+ v.maxValue(4096),+ v.description(+ 'Maximum output width or height in pixels. Preserves aspect ratio and never upscales. Defaults to 1280 for bounded model input.'+ )+ )+ ),+ 1280+ )+}++/** The requested scale, reduced so the longest edge fits `maxEdge`; 0 for empty content. */+export function boundedRasterScale(+ width: number,+ height: number,+ scale: number,+ maxEdge: number+): number {+ const longestEdge = Math.max(width, height)+ return longestEdge > 0 ? Math.min(scale, maxEdge / longestEdge) : 0+}+export const exportSVG = defineTool({name: 'export_svg',description: 'Export nodes as SVG markup. Returns the SVG string.',@@ -71,32 +112,7 @@ export const exportImage = defineTool({v.pipe(v.picklist(['PNG', 'JPG', 'WEBP']), v.description('Image format')),'PNG'),- scale: v.optional(- toolNumber(- v.pipe(- v.number(),- v.minValue(0.1),- v.maxValue(4),- v.description(- 'Export scale multiplier before the maximum-edge limit is applied (default: 1)'- )- )- ),- 1- ),- maxEdge: v.optional(- toolNumber(- v.pipe(- v.number(),- v.minValue(64),- v.maxValue(4096),- v.description(- 'Maximum output width or height in pixels. Preserves aspect ratio and never upscales. Defaults to 1280 for bounded model input.'- )- )- ),- 1280- )+ ...rasterScaleInputs}),execute: async (figma, args) => {if (!figma.exportImage) {@@ -127,8 +143,7 @@ export const exportImage = defineTool({)const width = bounds.maxX - bounds.minXconst height = bounds.maxY - bounds.minY- const longestEdge = Math.max(width, height)- const boundedScale = longestEdge > 0 ? Math.min(requestedScale, maxEdge / longestEdge) : 0+ const boundedScale = boundedRasterScale(width, height, requestedScale, maxEdge)if (boundedScale <= 0) return { error: 'No visible nodes to export' }const data = await figma.exportImage(ids, {scale: boundedScale,diff --git a/packages/core/tests/design-jsx/export-round-trip.test.ts b/packages/core/tests/design-jsx/export-round-trip.test.tsindex 2f7f41f63..05c5a2dee 100644--- a/packages/core/tests/design-jsx/export-round-trip.test.ts+++ b/packages/core/tests/design-jsx/export-round-trip.test.ts@@ -3,9 +3,10 @@ import { pick } from 'es-toolkit'import { renderJSX } from '@open-pencil/core/design-jsx'import { sceneNodeToJSX } from '@open-pencil/design-jsx'-import { SceneGraph, type Fill, type SceneNode, type Stroke } from '@open-pencil/scene-graph'+import { SceneGraph } from '@open-pencil/scene-graph'-import { expectDefined, getNodeOrThrow } from '../helpers/assert'+import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'+import { findByName, PROPERTY_CASES } from '#core-tests/helpers/property-cases'describe('attribute string round-trip', () => {it.each([@@ -42,329 +43,6 @@ describe('text content round-trip', () => {})})-const RED = { r: 1, g: 0, b: 0, a: 1 }-const BLUE = { r: 0, g: 0, b: 1, a: 1 }-/** Alphas that survive the two-digit hex of exported colors exactly. */-const SHADE = { r: 0, g: 0, b: 0, a: 0.2 }--function solidFill(color = RED, fields: Partial<Fill> = {}): Fill {- return { type: 'SOLID', color, opacity: color.a, visible: true, ...fields }-}--function stroke(fields: Partial<Stroke> = {}): Stroke {- return { color: BLUE, weight: 1, opacity: 1, visible: true, align: 'INSIDE', ...fields }-}--interface RoundTripCase {- name: string- /** Builds the exported root under `pageId` and returns the name of the node to compare. */- build(graph: SceneGraph, pageId: string): { rootId: string; target: string }- fields: (keyof SceneNode)[]-}--function frame(graph: SceneGraph, parentId: string, fields: Partial<SceneNode> = {}) {- return graph.createNode('FRAME', parentId, { name: 'Root', width: 300, height: 200, ...fields })-}--function child(- graph: SceneGraph,- parentId: string,- type: SceneNode['type'],- fields: Partial<SceneNode>-) {- return graph.createNode(type, parentId, { name: 'Target', width: 40, height: 30, ...fields })-}--/** A leaf under a plain frame, compared on `fields`. */-function leafCase(- name: string,- type: SceneNode['type'],- fields: Partial<SceneNode>,- compared = Object.keys(fields) as (keyof SceneNode)[]-): RoundTripCase {- return {- name,- build(graph, pageId) {- const root = frame(graph, pageId)- child(graph, root.id, type, fields)- return { rootId: root.id, target: 'Target' }- },- fields: compared- }-}--const CASES: RoundTripCase[] = [- leafCase('hidden layer', 'RECTANGLE', { visible: false }),- leafCase('locked layer', 'RECTANGLE', { locked: true }),- leafCase('constraints', 'RECTANGLE', {- horizontalConstraint: 'MAX',- verticalConstraint: 'STRETCH'- }),- leafCase('scale and center constraints', 'RECTANGLE', {- horizontalConstraint: 'SCALE',- verticalConstraint: 'CENTER'- }),- leafCase('size limits', 'FRAME', {- minWidth: 20,- maxWidth: 400,- minHeight: 10,- maxHeight: 300- }),- leafCase('position and rotation', 'RECTANGLE', { x: 12, y: 34, rotation: 15 }),- leafCase('opacity and blend mode', 'RECTANGLE', { opacity: 0.5, blendMode: 'MULTIPLY' }),- // Figma leaves the uniform radius at 0 when corners differ.- leafCase('independent corners and smoothing', 'RECTANGLE', {- cornerRadius: 0,- independentCorners: true,- topLeftRadius: 4,- topRightRadius: 8,- bottomRightRadius: 12,- bottomLeftRadius: 16,- cornerSmoothing: 0.6- }),- leafCase('single solid fill', 'RECTANGLE', { fills: [solidFill()] }),- leafCase('stacked, hidden, and blended fills', 'RECTANGLE', {- fills: [- solidFill(RED, { visible: false }),- solidFill(BLUE, { opacity: 0.5, blendMode: 'SCREEN' })- ]- }),- leafCase('gradient fill with transform', 'RECTANGLE', {- fills: [- {- type: 'GRADIENT_LINEAR',- color: { r: 0, g: 0, b: 0, a: 0 },- opacity: 1,- visible: true,- gradientStops: [- { color: RED, position: 0 },- { color: BLUE, position: 1 }- ],- gradientTransform: { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }- }- ]- }),- leafCase('gradient fading to transparent', 'RECTANGLE', {- fills: [- {- type: 'GRADIENT_RADIAL',- color: { r: 0, g: 0, b: 0, a: 0 },- opacity: 1,- visible: true,- gradientStops: [- { color: SHADE, position: 0 },- { color: { r: 0, g: 0, b: 0, a: 0 }, position: 1 }- ],- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }- }- ]- }),- leafCase('image fill', 'RECTANGLE', {- fills: [- {- type: 'IMAGE',- color: { r: 0, g: 0, b: 0, a: 1 },- opacity: 1,- visible: true,- imageHash: 'abc123',- imageScaleMode: 'FIT'- }- ]- }),- leafCase('single stroke with every option', 'RECTANGLE', {- strokes: [- stroke({ weight: 3, align: 'OUTSIDE', dashPattern: [4, 2], cap: 'ROUND', join: 'BEVEL' })- ]- }),- leafCase('node-level stroke cap and join under a stroke without its own', 'RECTANGLE', {- strokes: [stroke({ weight: 2 })],- strokeCap: 'ROUND',- strokeJoin: 'BEVEL'- }),- leafCase('stroke cap that differs from the node cap', 'RECTANGLE', {- strokes: [stroke({ cap: 'SQUARE' })],- strokeCap: 'ROUND'- }),- leafCase('node-level dash pattern under a stroke without its own', 'RECTANGLE', {- strokes: [stroke()],- dashPattern: [6, 3]- }),- leafCase('stroke opacity that differs from its colour alpha', 'RECTANGLE', {- strokes: [stroke({ opacity: 0.5 })]- }),- leafCase('fill opacity that differs from its colour alpha', 'RECTANGLE', {- fills: [solidFill(RED, { opacity: 0.5 })]- }),- leafCase('size limits without a fixed width', 'FRAME', {- layoutMode: 'VERTICAL',- primaryAxisSizing: 'HUG',- counterAxisSizing: 'HUG',- minWidth: 40,- maxWidth: 400- }),- leafCase('several strokes, one hidden', 'RECTANGLE', {- strokes: [stroke({ weight: 2 }), stroke({ color: RED, align: 'CENTER', visible: false })]- }),- leafCase('per-side stroke weights', 'RECTANGLE', {- strokes: [stroke()],- independentStrokeWeights: true,- borderTopWeight: 0,- borderRightWeight: 1,- borderBottomWeight: 2,- borderLeftWeight: 0- }),- leafCase('drop shadow and layer blur shorthands', 'RECTANGLE', {- effects: [- {- type: 'DROP_SHADOW',- color: SHADE,- offset: { x: 0, y: 4 },- radius: 8,- spread: 0,- visible: true- },- {- type: 'LAYER_BLUR',- color: { r: 0, g: 0, b: 0, a: 0 },- offset: { x: 0, y: 0 },- radius: 4,- spread: 0,- visible: true- }- ]- }),- leafCase('inner shadow, spread, hidden shadow, background blur', 'RECTANGLE', {- effects: [- {- type: 'INNER_SHADOW',- color: SHADE,- offset: { x: 1, y: 2 },- radius: 3,- spread: 0,- visible: true- },- {- type: 'DROP_SHADOW',- color: SHADE,- offset: { x: 0, y: 8 },- radius: 16,- spread: 4,- visible: false- },- {- type: 'BACKGROUND_BLUR',- color: { r: 0, g: 0, b: 0, a: 0 },- offset: { x: 0, y: 0 },- radius: 12,- spread: 0,- visible: true- }- ]- }),- leafCase('mask', 'RECTANGLE', { isMask: true, maskType: 'LUMINANCE' }),- leafCase('clipping', 'FRAME', { clipsContent: true }),- leafCase('star geometry', 'STAR', { pointCount: 7, starInnerRadius: 0.5 }),- leafCase('text style', 'TEXT', {- text: 'Hello',- fontSize: 20,- fontWeight: 700,- italic: true,- textAlignHorizontal: 'CENTER',- textAlignVertical: 'BOTTOM',- textAutoResize: 'NONE',- letterSpacing: 1,- lineHeight: 28,- textCase: 'UPPER',- textDecoration: 'UNDERLINE'- }),- leafCase('text that wraps at a fixed width', 'TEXT', {- text: 'Wrapped',- textAutoResize: 'HEIGHT'- }),- leafCase('text that hugs its content', 'TEXT', {- text: 'Hug',- textAutoResize: 'WIDTH_AND_HEIGHT'- }),- leafCase('truncated text', 'TEXT', {- text: 'Clipped',- textAutoResize: 'TRUNCATE',- textTruncation: 'ENDING'- }),- {- name: 'absolute child of an auto-layout frame',- build(graph, pageId) {- const root = frame(graph, pageId, { layoutMode: 'VERTICAL', itemSpacing: 8 })- child(graph, root.id, 'RECTANGLE', { name: 'Flow' })- child(graph, root.id, 'RECTANGLE', {- layoutPositioning: 'ABSOLUTE',- x: 10,- y: 20,- horizontalConstraint: 'MAX'- })- return { rootId: root.id, target: 'Target' }- },- fields: ['layoutPositioning', 'x', 'y', 'horizontalConstraint']- },- {- name: 'auto layout',- build(graph, pageId) {- const root = frame(graph, pageId, {- layoutMode: 'HORIZONTAL',- itemSpacing: 12,- paddingTop: 4,- paddingRight: 8,- paddingBottom: 4,- paddingLeft: 8,- primaryAxisAlign: 'SPACE_BETWEEN',- counterAxisAlign: 'CENTER',- primaryAxisSizing: 'FIXED',- counterAxisSizing: 'FIXED'- })- child(graph, root.id, 'RECTANGLE', { name: 'A' })- return { rootId: root.id, target: 'Root' }- },- fields: [- 'layoutMode',- 'itemSpacing',- 'paddingTop',- 'paddingRight',- 'paddingBottom',- 'paddingLeft',- 'primaryAxisAlign',- 'counterAxisAlign',- 'width',- 'height'- ]- },- {- name: 'variable bindings',- build(graph, pageId) {- const collection = graph.createCollection('Tokens')- const brand = graph.createVariable('Brand', 'COLOR', collection.id, RED)- const space = graph.createVariable('Space', 'FLOAT', collection.id, 16)- const root = frame(graph, pageId, {- layoutMode: 'VERTICAL',- itemSpacing: 16,- fills: [solidFill()]- })- graph.bindVariable(root.id, 'fills/0/color', brand.id)- graph.bindVariable(root.id, 'itemSpacing', space.id)- return { rootId: root.id, target: 'Root' }- },- fields: ['boundVariables']- }-]--function findByName(graph: SceneGraph, rootId: string, name: string): SceneNode {- const root = expectDefined(graph.getNode(rootId), 'rendered root')- if (root.name === name) return root- for (const childId of root.childIds) {- const found = graph.getNode(childId)?.name === name ? graph.getNode(childId) : undefined- if (found) return found- }- throw new Error(`No node named ${name} under ${root.name}`)-}-test('size limits are limits, not a width', async () => {const graph = new SceneGraph()const [defaultWidth] = await renderJSX(graph, '<Frame h={10} />')@@ -375,7 +53,7 @@ test('size limits are limits, not a width', async () => {})describe('design JSX export round trip', () => {- test.each(CASES.map((testCase) => [testCase.name, testCase] as const))(+ test.each(PROPERTY_CASES.map((testCase) => [testCase.name, testCase] as const))('%s',async (_, testCase) => {const graph = new SceneGraph()diff --git a/packages/core/tests/helpers/property-cases.ts b/packages/core/tests/helpers/property-cases.tsnew file mode 100644index 000000000..bab8fcbd8--- /dev/null+++ b/packages/core/tests/helpers/property-cases.ts@@ -0,0 +1,330 @@+import type { SceneGraph, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'++import { expectDefined } from './assert'++const RED = { r: 1, g: 0, b: 0, a: 1 }+const BLUE = { r: 0, g: 0, b: 1, a: 1 }+/** Alphas that survive the two-digit hex of exported colors exactly. */+const SHADE = { r: 0, g: 0, b: 0, a: 0.2 }++function solidFill(color = RED, fields: Partial<Fill> = {}): Fill {+ return { type: 'SOLID', color, opacity: color.a, visible: true, ...fields }+}++function stroke(fields: Partial<Stroke> = {}): Stroke {+ return { color: BLUE, weight: 1, opacity: 1, visible: true, align: 'INSIDE', ...fields }+}++export interface RoundTripCase {+ name: string+ /** Builds the exported root under `pageId` and returns the name of the node to compare. */+ build(graph: SceneGraph, pageId: string): { rootId: string; target: string }+ fields: (keyof SceneNode)[]+}++function frame(graph: SceneGraph, parentId: string, fields: Partial<SceneNode> = {}) {+ return graph.createNode('FRAME', parentId, { name: 'Root', width: 300, height: 200, ...fields })+}++function child(+ graph: SceneGraph,+ parentId: string,+ type: SceneNode['type'],+ fields: Partial<SceneNode>+) {+ return graph.createNode(type, parentId, { name: 'Target', width: 40, height: 30, ...fields })+}++/** A leaf under a plain frame, compared on `fields`. */+function leafCase(+ name: string,+ type: SceneNode['type'],+ fields: Partial<SceneNode>,+ compared = Object.keys(fields) as (keyof SceneNode)[]+): RoundTripCase {+ return {+ name,+ build(graph, pageId) {+ const root = frame(graph, pageId)+ child(graph, root.id, type, fields)+ return { rootId: root.id, target: 'Target' }+ },+ fields: compared+ }+}++/**+ * Node properties the JSX export writes, each as a tree to build and the fields of its+ * `target` node that must survive. The export round trip and the diff both run them.+ */+export const PROPERTY_CASES: RoundTripCase[] = [+ leafCase('hidden layer', 'RECTANGLE', { visible: false }),+ leafCase('locked layer', 'RECTANGLE', { locked: true }),+ leafCase('constraints', 'RECTANGLE', {+ horizontalConstraint: 'MAX',+ verticalConstraint: 'STRETCH'+ }),+ leafCase('scale and center constraints', 'RECTANGLE', {+ horizontalConstraint: 'SCALE',+ verticalConstraint: 'CENTER'+ }),+ leafCase('size limits', 'FRAME', {+ minWidth: 20,+ maxWidth: 400,+ minHeight: 10,+ maxHeight: 300+ }),+ leafCase('position and rotation', 'RECTANGLE', { x: 12, y: 34, rotation: 15 }),+ leafCase('opacity and blend mode', 'RECTANGLE', { opacity: 0.5, blendMode: 'MULTIPLY' }),+ // Figma leaves the uniform radius at 0 when corners differ.+ leafCase('independent corners and smoothing', 'RECTANGLE', {+ cornerRadius: 0,+ independentCorners: true,+ topLeftRadius: 4,+ topRightRadius: 8,+ bottomRightRadius: 12,+ bottomLeftRadius: 16,+ cornerSmoothing: 0.6+ }),+ leafCase('single solid fill', 'RECTANGLE', { fills: [solidFill()] }),+ leafCase('stacked, hidden, and blended fills', 'RECTANGLE', {+ fills: [+ solidFill(RED, { visible: false }),+ solidFill(BLUE, { opacity: 0.5, blendMode: 'SCREEN' })+ ]+ }),+ leafCase('gradient fill with transform', 'RECTANGLE', {+ fills: [+ {+ type: 'GRADIENT_LINEAR',+ color: { r: 0, g: 0, b: 0, a: 0 },+ opacity: 1,+ visible: true,+ gradientStops: [+ { color: RED, position: 0 },+ { color: BLUE, position: 1 }+ ],+ gradientTransform: { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }+ }+ ]+ }),+ leafCase('gradient fading to transparent', 'RECTANGLE', {+ fills: [+ {+ type: 'GRADIENT_RADIAL',+ color: { r: 0, g: 0, b: 0, a: 0 },+ opacity: 1,+ visible: true,+ gradientStops: [+ { color: SHADE, position: 0 },+ { color: { r: 0, g: 0, b: 0, a: 0 }, position: 1 }+ ],+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ }+ ]+ }),+ leafCase('image fill', 'RECTANGLE', {+ fills: [+ {+ type: 'IMAGE',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ imageHash: 'abc123',+ imageScaleMode: 'FIT'+ }+ ]+ }),+ leafCase('single stroke with every option', 'RECTANGLE', {+ strokes: [+ stroke({ weight: 3, align: 'OUTSIDE', dashPattern: [4, 2], cap: 'ROUND', join: 'BEVEL' })+ ]+ }),+ leafCase('node-level stroke cap and join under a stroke without its own', 'RECTANGLE', {+ strokes: [stroke({ weight: 2 })],+ strokeCap: 'ROUND',+ strokeJoin: 'BEVEL'+ }),+ leafCase('stroke cap that differs from the node cap', 'RECTANGLE', {+ strokes: [stroke({ cap: 'SQUARE' })],+ strokeCap: 'ROUND'+ }),+ leafCase('node-level dash pattern under a stroke without its own', 'RECTANGLE', {+ strokes: [stroke()],+ dashPattern: [6, 3]+ }),+ leafCase('stroke opacity that differs from its colour alpha', 'RECTANGLE', {+ strokes: [stroke({ opacity: 0.5 })]+ }),+ leafCase('fill opacity that differs from its colour alpha', 'RECTANGLE', {+ fills: [solidFill(RED, { opacity: 0.5 })]+ }),+ leafCase('size limits without a fixed width', 'FRAME', {+ layoutMode: 'VERTICAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ minWidth: 40,+ maxWidth: 400+ }),+ leafCase('several strokes, one hidden', 'RECTANGLE', {+ strokes: [stroke({ weight: 2 }), stroke({ color: RED, align: 'CENTER', visible: false })]+ }),+ leafCase('per-side stroke weights', 'RECTANGLE', {+ strokes: [stroke()],+ independentStrokeWeights: true,+ borderTopWeight: 0,+ borderRightWeight: 1,+ borderBottomWeight: 2,+ borderLeftWeight: 0+ }),+ leafCase('drop shadow and layer blur shorthands', 'RECTANGLE', {+ effects: [+ {+ type: 'DROP_SHADOW',+ color: SHADE,+ offset: { x: 0, y: 4 },+ radius: 8,+ spread: 0,+ visible: true+ },+ {+ type: 'LAYER_BLUR',+ color: { r: 0, g: 0, b: 0, a: 0 },+ offset: { x: 0, y: 0 },+ radius: 4,+ spread: 0,+ visible: true+ }+ ]+ }),+ leafCase('inner shadow, spread, hidden shadow, background blur', 'RECTANGLE', {+ effects: [+ {+ type: 'INNER_SHADOW',+ color: SHADE,+ offset: { x: 1, y: 2 },+ radius: 3,+ spread: 0,+ visible: true+ },+ {+ type: 'DROP_SHADOW',+ color: SHADE,+ offset: { x: 0, y: 8 },+ radius: 16,+ spread: 4,+ visible: false+ },+ {+ type: 'BACKGROUND_BLUR',+ color: { r: 0, g: 0, b: 0, a: 0 },+ offset: { x: 0, y: 0 },+ radius: 12,+ spread: 0,+ visible: true+ }+ ]+ }),+ leafCase('mask', 'RECTANGLE', { isMask: true, maskType: 'LUMINANCE' }),+ leafCase('clipping', 'FRAME', { clipsContent: true }),+ leafCase('star geometry', 'STAR', { pointCount: 7, starInnerRadius: 0.5 }),+ leafCase('text style', 'TEXT', {+ text: 'Hello',+ fontSize: 20,+ fontWeight: 700,+ italic: true,+ textAlignHorizontal: 'CENTER',+ textAlignVertical: 'BOTTOM',+ textAutoResize: 'NONE',+ letterSpacing: 1,+ lineHeight: 28,+ textCase: 'UPPER',+ textDecoration: 'UNDERLINE'+ }),+ leafCase('text that wraps at a fixed width', 'TEXT', {+ text: 'Wrapped',+ textAutoResize: 'HEIGHT'+ }),+ leafCase('text that hugs its content', 'TEXT', {+ text: 'Hug',+ textAutoResize: 'WIDTH_AND_HEIGHT'+ }),+ leafCase('truncated text', 'TEXT', {+ text: 'Clipped',+ textAutoResize: 'TRUNCATE',+ textTruncation: 'ENDING'+ }),+ {+ name: 'absolute child of an auto-layout frame',+ build(graph, pageId) {+ const root = frame(graph, pageId, { layoutMode: 'VERTICAL', itemSpacing: 8 })+ child(graph, root.id, 'RECTANGLE', { name: 'Flow' })+ child(graph, root.id, 'RECTANGLE', {+ layoutPositioning: 'ABSOLUTE',+ x: 10,+ y: 20,+ horizontalConstraint: 'MAX'+ })+ return { rootId: root.id, target: 'Target' }+ },+ fields: ['layoutPositioning', 'x', 'y', 'horizontalConstraint']+ },+ {+ name: 'auto layout',+ build(graph, pageId) {+ const root = frame(graph, pageId, {+ layoutMode: 'HORIZONTAL',+ itemSpacing: 12,+ paddingTop: 4,+ paddingRight: 8,+ paddingBottom: 4,+ paddingLeft: 8,+ primaryAxisAlign: 'SPACE_BETWEEN',+ counterAxisAlign: 'CENTER',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED'+ })+ child(graph, root.id, 'RECTANGLE', { name: 'A' })+ return { rootId: root.id, target: 'Root' }+ },+ fields: [+ 'layoutMode',+ 'itemSpacing',+ 'paddingTop',+ 'paddingRight',+ 'paddingBottom',+ 'paddingLeft',+ 'primaryAxisAlign',+ 'counterAxisAlign',+ 'width',+ 'height'+ ]+ },+ {+ name: 'variable bindings',+ build(graph, pageId) {+ const collection = graph.createCollection('Tokens')+ const brand = graph.createVariable('Brand', 'COLOR', collection.id, RED)+ const space = graph.createVariable('Space', 'FLOAT', collection.id, 16)+ const root = frame(graph, pageId, {+ layoutMode: 'VERTICAL',+ itemSpacing: 16,+ fills: [solidFill()]+ })+ graph.bindVariable(root.id, 'fills/0/color', brand.id)+ graph.bindVariable(root.id, 'itemSpacing', space.id)+ return { rootId: root.id, target: 'Root' }+ },+ fields: ['boundVariables']+ }+]++export function findByName(graph: SceneGraph, rootId: string, name: string): SceneNode {+ const root = expectDefined(graph.getNode(rootId), 'rendered root')+ if (root.name === name) return root+ for (const childId of root.childIds) {+ const found = graph.getNode(childId)?.name === name ? graph.getNode(childId) : undefined+ if (found) return found+ }+ throw new Error(`No node named ${name} under ${root.name}`)+}diff --git a/packages/core/tests/tools/ai-adapter.test.ts b/packages/core/tests/tools/ai-adapter.test.tsnew file mode 100644index 000000000..1b50bb018--- /dev/null+++ b/packages/core/tests/tools/ai-adapter.test.ts@@ -0,0 +1,58 @@+import { describe, expect, test } from 'bun:test'++import * as v from 'valibot'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { defineTool, toolsToAI } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++type ToolFactory = Parameters<typeof toolsToAI>[2]['tool']++// The adapter only forwards definitions to the factory; an identity factory exposes them.+const tool = ((definition: unknown) => definition) as ToolFactory++type ModelOutputTool = {+ toModelOutput(options: { output: unknown }): unknown+}++function adapt(output: unknown): ModelOutputTool {+ const def = defineTool({+ name: 'image_tool',+ description: 'Returns a fixed result',+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({}),+ execute: () => output+ })+ const figma = new FigmaAPI(new SceneGraph())+ const tools = toolsToAI([def], { getFigma: () => figma }, { tool })+ const adapted: unknown = tools.image_tool+ if (!hasModelOutput(adapted)) throw new Error('image_tool has no toModelOutput')+ return adapted+}++function hasModelOutput(value: unknown): value is ModelOutputTool {+ return (+ typeof value === 'object' &&+ value !== null &&+ 'toModelOutput' in value &&+ typeof value.toModelOutput === 'function'+ )+}++describe('AI adapter model output', () => {+ test('sends any image result as media with its metadata as text', () => {+ const output = { mimeType: 'image/png', base64: 'AAAA', changedPixels: 12 }+ expect(adapt(output).toModelOutput({ output })).toEqual({+ type: 'content',+ value: [+ { type: 'text', text: '{"changedPixels":12}' },+ { type: 'media', mediaType: 'image/png', data: 'AAAA' }+ ]+ })+ })++ test('keeps non-image results as JSON', () => {+ const output = { mimeType: 'application/pdf', base64: 'AAAA' }+ expect(adapt(output).toModelOutput({ output })).toEqual({ type: 'json', value: output })+ })+})diff --git a/packages/core/tests/tools/analyze/diff/apply.test.ts b/packages/core/tests/tools/analyze/diff/apply.test.tsnew file mode 100644index 000000000..3d8dd8b8b--- /dev/null+++ b/packages/core/tests/tools/analyze/diff/apply.test.ts@@ -0,0 +1,50 @@+import { describe, expect, test } from 'bun:test'+import { pick } from 'es-toolkit'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import { createDefaultNode, SceneGraph } from '@open-pencil/scene-graph'++import { expectDefined } from '#core-tests/helpers/assert'+import { findByName, PROPERTY_CASES } from '#core-tests/helpers/property-cases'++function tool(name: string) {+ return expectDefined(+ ALL_TOOLS.find((candidate) => candidate.name === name),+ name+ )+}++describe('diff_apply property coverage', () => {+ test.each(PROPERTY_CASES.map((testCase) => [testCase.name, testCase] as const))(+ '%s',+ async (_, testCase) => {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const page = expectDefined(graph.getPages()[0], 'page')+ const goal = testCase.build(graph, page.id)+ const plain = testCase.build(graph, page.id)+ const target = findByName(graph, plain.rootId, plain.target)+ // The same tree with the target's properties at their defaults.+ const defaults = createDefaultNode(() => target.id, target.type)+ graph.updateNode(target.id, pick(defaults, testCase.fields))+ const expected = findByName(graph, goal.rootId, goal.target)+ expect(pick(target, testCase.fields)).not.toEqual(pick(expected, testCase.fields))++ const created = await tool('diff_create').execute(figma, {+ from: plain.rootId,+ to: goal.rootId+ })+ const patch = expectDefined((created as { diff?: string | null }).diff, 'patch')+ const applied = await tool('diff_apply').execute(figma, { patch })+ expect(applied).toMatchObject({ failed: 0 })++ expect(pick(findByName(graph, plain.rootId, plain.target), testCase.fields)).toEqual(+ pick(expected, testCase.fields)+ )+ expect(+ await tool('diff_create').execute(figma, { from: plain.rootId, to: goal.rootId })+ ).toMatchObject({ diff: null })+ }+ )+})diff --git a/packages/core/tests/tools/analyze/diff/engine.test.ts b/packages/core/tests/tools/analyze/diff/engine.test.tsnew file mode 100644index 000000000..537db1c26--- /dev/null+++ b/packages/core/tests/tools/analyze/diff/engine.test.ts@@ -0,0 +1,94 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { SceneGraph } from '@open-pencil/scene-graph'++import { formatOperations, parseOperations } from '#core/tools/analyze/diff/format'+import { deltaOperations, type DiffOperation } from '#core/tools/analyze/diff/operations'+import {+ diffProjections,+ projectTree,+ type DiffMatch+} from '#core/tools/analyze/diff/projection'+import { expectDefined } from '#core-tests/helpers/assert'++/** Operations for what `edit` changes; a projection is plain data, so it snapshots the tree. */+function operations(graph: SceneGraph, rootId: string, match: DiffMatch, edit: () => void) {+ const from = expectDefined(projectTree(graph, rootId, { match }), 'before')+ edit()+ const to = expectDefined(projectTree(graph, rootId, { match }), 'after')+ return deltaOperations(diffProjections(from, to), from, to, () => '<Frame />')+}++function card() {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const root = figma.createFrame()+ root.name = 'Card'+ for (const name of ['A', 'B', 'C']) {+ const child = figma.createRectangle()+ child.name = name+ root.appendChild(child)+ }+ return { graph, figma, root }+}++describe('diff engine', () => {+ test('matching by ID, a rename is an attribute change', () => {+ const { graph, root } = card()+ const child = expectDefined(root.children[0], 'child')++ expect(operations(graph, root.id, 'id', () => (child.name = 'Renamed'))).toEqual([+ { kind: 'update', path: '/Card/A', id: child.id, removed: ['name="A"'], added: ['name="Renamed"'] }+ ])+ })++ test('matching by path, a rename is a removal and an addition', () => {+ const { graph, root } = card()+ const child = expectDefined(root.children[0], 'child')+ const ops = operations(graph, root.id, 'path', () => (child.name = 'Renamed'))++ expect(ops.map((op) => op.kind).toSorted()).toEqual([+ 'add',+ 'remove'+ ])+ })++ test('a reordered child is one move, not a change to every sibling', () => {+ const { graph, root } = card()+ const last = expectDefined(root.children[2], 'last')++ expect(operations(graph, root.id, 'id', () => root.insertChild(0, last))).toEqual([+ { kind: 'move', path: '/Card/C', id: last.id, index: 0 }+ ])+ })++ test('repeated names match their counterparts in order', () => {+ const { graph, root } = card()+ for (const child of root.children) child.name = 'Item'+ const second = expectDefined(root.children[1], 'second')++ expect(operations(graph, root.id, 'path', () => (second.opacity = 0.5))).toEqual([+ { kind: 'update', path: '/Card/Item', id: second.id, removed: [], added: ['opacity={0.5}'] }+ ])+ })+})++describe('patch format', () => {+ test('parses what it prints', () => {+ const ops: DiffOperation[] = [+ { kind: 'update', path: '/Card', id: '1:2', removed: ['w={1}'], added: ['w={2}', 'clipsContent'] },+ { kind: 'move', path: '/Card/Badge', id: '1:3', index: 0 },+ // Names that look like header endings still parse, because headers anchor on the end.+ { kind: 'remove', path: '/Card/Old #9:9 removed', id: '1:4' },+ {+ kind: 'add',+ path: '/Card/Row',+ parentId: '1:2',+ index: 3,+ jsx: '<Frame name="Row">\n <Text>Hi</Text>\n</Frame>'+ }+ ]+ expect(parseOperations(formatOperations(ops))).toEqual(ops)+ })+})diff --git a/packages/core/tests/tools/analyze/diff/tools.test.ts b/packages/core/tests/tools/analyze/diff/tools.test.tsnew file mode 100644index 000000000..0a76a9d76--- /dev/null+++ b/packages/core/tests/tools/analyze/diff/tools.test.ts@@ -0,0 +1,269 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { ALL_TOOLS, diffDocuments } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'++type DiffResult = { diff?: string | null; error?: string }+type ApplyResult = {+ error?: string+ applied?: number+ failed?: number+ results?: { status: string; id: string | null; error?: string; changes?: string[] }[]+}++function tool(name: string) {+ return expectDefined(+ ALL_TOOLS.find((candidate) => candidate.name === name),+ name+ )+}++async function run<Result>(figma: FigmaAPI, name: string, args: Record<string, unknown>) {+ return (await tool(name).execute(figma, args)) as Result+}++function setup() {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const card = figma.createFrame()+ card.name = 'Card'+ card.resize(200, 100)+ card.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }]+ const label = figma.createRectangle()+ label.name = 'Label'+ label.resize(80, 20)+ card.appendChild(label)+ const badge = figma.createEllipse()+ badge.name = 'Badge'+ card.appendChild(badge)+ return { graph, figma, card, label, badge }+}++async function createPatch(figma: FigmaAPI, from: string, to: string): Promise<string> {+ return expectDefined((await run<DiffResult>(figma, 'diff_create', { from, to })).diff, 'patch')+}++describe('diff_create and diff_apply', () => {+ test('a patch from a modified copy makes the original match it', async () => {+ const { graph, figma, card, label, badge } = setup()+ const copy = card.clone()+ copy.name = 'Card copy'+ copy.opacity = 0.5+ copy.cornerRadius = 12+ expectDefined(copy.children[0], 'copied label').resize(120, 24)+ // Move the badge first and add a note at the end.+ copy.insertChild(0, expectDefined(copy.children[1], 'copied badge'))+ const note = figma.createText()+ note.name = 'Note'+ note.characters = 'Sale'+ copy.appendChild(note)++ const patch = await createPatch(figma, card.id, copy.id)+ expect(patch).toContain(`@@ /Card #${card.id}\n+rounded={12}\n+opacity={0.5}`)+ expect(patch).toContain(`@@ /Card/Label #${label.id}\n-w={80}\n-h={20}\n+w={120}\n+h={24}`)+ expect(patch).toContain(`@@ /Card/Badge #${badge.id} moved to 0`)+ expect(patch).toContain(`@@ /Card/Note added to #${card.id} at 2\n+<Text name="Note"`)++ const applied = await run<ApplyResult>(figma, 'diff_apply', { patch })+ expect(applied).toMatchObject({ applied: 4, failed: 0 })+ // Updates and moves keep their nodes; only the added note is new.+ expect(getNodeOrThrow(graph, card.id).childIds.slice(0, 2)).toEqual([badge.id, label.id])+ expect(getNodeOrThrow(graph, label.id).width).toBe(120)+ expect(await run<DiffResult>(figma, 'diff_create', { from: card.id, to: copy.id })).toEqual({+ diff: null,+ message: 'No differences found'+ })+ })++ test('changes only the fields an attribute moves', async () => {+ const { graph, figma, card } = setup()+ card.setPluginData('note', 'kept')+ const copy = card.clone()+ copy.opacity = 0.5++ await run<ApplyResult>(figma, 'diff_apply', { patch: await createPatch(figma, card.id, copy.id) })+ expect(getNodeOrThrow(graph, card.id).opacity).toBe(0.5)+ expect(card.getPluginData('note')).toBe('kept')+ })++ test('rejects a stale patch without changing any node', async () => {+ const { graph, figma, card, label } = setup()+ const copy = card.clone()+ copy.opacity = 0.5+ expectDefined(copy.children[0], 'copied label').resize(120, 24)+ const patch = await createPatch(figma, card.id, copy.id)+ label.resize(90, 20)++ const applied = await run<ApplyResult>(figma, 'diff_apply', { patch })+ expect(applied.error).toBe('Patch does not apply')+ expect(applied.results?.[0]?.error).toContain('w: expected w={80}, found w={90}')+ // The card still matched, but a stale patch must not half-apply.+ expect(getNodeOrThrow(graph, card.id).opacity).toBe(1)+ })++ test.each([false, true])(+ 'rejects a patch with an invalid value without changing any node (force: %p)',+ async (force) => {+ const { graph, figma, card, label } = setup()+ const copy = card.clone()+ copy.opacity = 0.5+ expectDefined(copy.children[0], 'copied label').resize(120, 24)+ const patch = (await createPatch(figma, card.id, copy.id)).replace('+w={120}', '+w={wide}')++ const applied = await run<ApplyResult>(figma, 'diff_apply', { patch, force })+ expect(applied.error).toBe('Patch does not apply')+ // The card's change was valid, but it must not land without the label's.+ expect(getNodeOrThrow(graph, card.id).opacity).toBe(1)+ expect(getNodeOrThrow(graph, label.id).width).toBe(80)+ }+ )++ test('rejects a patch that adds an attribute the node has since gained', async () => {+ const { figma, label } = setup()+ const shown = await run<DiffResult>(figma, 'diff_show', {+ id: label.id,+ attributes: 'opacity={0.5}'+ })+ label.opacity = 0.8++ const applied = await run<ApplyResult>(figma, 'diff_apply', {+ patch: expectDefined(shown.diff, 'patch')+ })+ expect(applied.results?.[0]?.error).toContain('opacity: expected none, found opacity={0.8}')+ })++ test('dry run reports changes without applying them', async () => {+ const { graph, figma, card } = setup()+ const copy = card.clone()+ copy.opacity = 0.25++ const applied = await run<ApplyResult>(figma, 'diff_apply', {+ patch: await createPatch(figma, card.id, copy.id),+ dryRun: true+ })+ expect(applied.results?.[0]?.changes).toEqual(['opacity'])+ expect(getNodeOrThrow(graph, card.id).opacity).toBe(1)+ })++ test('removes children the target no longer has', async () => {+ const { graph, figma, card, label } = setup()+ const copy = card.clone()+ expectDefined(copy.children[0], 'copied label').remove()++ const applied = await run<ApplyResult>(figma, 'diff_apply', {+ patch: await createPatch(figma, card.id, copy.id)+ })+ expect(applied.results?.map((result) => result.status)).toEqual(['removed'])+ expect(graph.getNode(label.id)).toBeUndefined()+ })++ test('rejects an attribute the renderer would ignore', async () => {+ const { graph, figma, card } = setup()+ const patch = `@@ /Card #${card.id}\n+opacity={0.5}\n+bogus={1}`++ const applied = await run<ApplyResult>(figma, 'diff_apply', { patch })+ expect(applied.error).toBe('Patch does not apply')+ expect(applied.results?.[0]?.error).toBe('Unsupported attribute "bogus"')+ expect(getNodeOrThrow(graph, card.id).opacity).toBe(1)+ })++ test('leaves the document as it was when an added node fails to render', async () => {+ const { graph, figma, card } = setup()+ const children = [...getNodeOrThrow(graph, card.id).childIds]+ // The JSX evaluates, so the check passes, but rendering finds no such component.+ const patch = [+ `@@ /Card #${card.id}`,+ '+opacity={0.5}',+ `@@ /Card/Dot added to #${card.id} at 0`,+ '+<Ellipse name="Dot" />',+ `@@ /Card/Button added to #${card.id} at 1`,+ '+<Instance component="Missing" />'+ ].join('\n')++ const applied = await run<ApplyResult>(figma, 'diff_apply', { patch })+ expect(applied.error).toBe('Patch does not apply')+ expect(applied.results?.[0]?.error).toContain('component not found: Missing')+ expect(getNodeOrThrow(graph, card.id).opacity).toBe(1)+ expect(getNodeOrThrow(graph, card.id).childIds).toEqual(children)+ })++ test('reports a hunk it cannot read', async () => {+ const { figma } = setup()+ const applied = await run<ApplyResult>(figma, 'diff_apply', { patch: 'w={1}' })+ expect(applied.error).toBe('Line 1: unexpected line: w={1}')+ })+})++describe('diff_show', () => {+ test('previews attributes without changing the node, as a patch diff_apply applies', async () => {+ const { graph, figma, card } = setup()++ const shown = await run<DiffResult>(figma, 'diff_show', {+ id: card.id,+ attributes: 'bg="#FF0000" w={240} opacity={0.5}'+ })+ const patch = expectDefined(shown.diff, 'patch')+ expect(patch).toBe(+ `@@ /Card #${card.id}\n-bg="#FFFFFF"\n-w={200}\n+bg="#FF0000"\n+w={240}\n+opacity={0.5}`+ )+ expect(getNodeOrThrow(graph, card.id).width).toBe(200)++ await run<ApplyResult>(figma, 'diff_apply', { patch })+ const node = getNodeOrThrow(graph, card.id)+ expect(node.width).toBe(240)+ expect(node.opacity).toBe(0.5)+ expect(node.fills[0]?.color).toEqual({ r: 1, g: 0, b: 0, a: 1 })+ })++ test.each([+ ['w={', 'Invalid JSX attributes'],+ ['opacity={half}', 'half is not defined']+ ])('rejects %p', async (attributes, error) => {+ const { figma, card } = setup()+ const shown = await run<DiffResult>(figma, 'diff_show', { id: card.id, attributes })+ expect(shown.error).toContain(error)+ })+})++describe('diffDocuments', () => {+ test('matches pages by name and nodes by path across documents', () => {+ const before = setup()+ const after = setup()+ after.label.resize(80, 40)+ const extra = after.figma.createEllipse()+ extra.name = 'Dot'++ const result = diffDocuments(before.graph, after.graph)+ expect(result.pages.map((page) => page.status)).toEqual(['changed'])+ const diff = expectDefined(result.diff, 'document diff')+ expect(diff).toContain(`@@ /Page 1/Card/Label #${before.label.id}\n-h={20}\n+h={40}`)+ expect(diff).toContain('@@ /Page 1/Dot added to')+ })++ test('reports identical documents as unchanged', () => {+ const result = diffDocuments(setup().graph, setup().graph)+ expect(result.diff).toBeNull()+ expect(result.changed).toBe(false)+ expect(result.pages.map((page) => page.status)).toEqual(['unchanged'])+ })++ test('reports a page only one document has by status, without a patch', () => {+ const before = setup()+ const after = setup()+ after.graph.addPage('Empty')+ const extra = after.graph.addPage('Extra')+ after.graph.createNode('FRAME', extra.id, { name: 'Card' })++ const result = diffDocuments(before.graph, after.graph)+ expect(result.changed).toBe(true)+ expect(result.diff).toBeNull()+ expect(result.pages.map(({ name, status, diff }) => ({ name, status, diff }))).toEqual([+ { name: 'Page 1', status: 'unchanged', diff: null },+ { name: 'Empty', status: 'added', diff: null },+ { name: 'Extra', status: 'added', diff: null }+ ])+ })+})diff --git a/packages/core/tests/tools/analyze/diff/visual.test.ts b/packages/core/tests/tools/analyze/diff/visual.test.tsnew file mode 100644index 000000000..e13035766--- /dev/null+++ b/packages/core/tests/tools/analyze/diff/visual.test.ts@@ -0,0 +1,91 @@+import { beforeAll, describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import {+ createCanvasKitRasterCodec,+ headlessRenderNodes,+ initCanvasKit+} from '@open-pencil/core/io/formats/raster'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'+import type { Rect } from '@open-pencil/scene-graph/primitives'++import { expectDefined } from '#core-tests/helpers/assert'++type VisualDiff = {+ error?: string+ mimeType?: string+ width?: number+ height?: number+ changedPixels?: number+ changedRatio?: number+ changedBounds?: Rect | null+}++let codec: ReturnType<typeof createCanvasKitRasterCodec>++beforeAll(async () => {+ codec = createCanvasKitRasterCodec(await initCanvasKit())+})++function setup() {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ figma.exportImage = (ids, options) =>+ headlessRenderNodes(graph, options.pageId ?? figma.currentPageId, ids, options)+ figma.rasterCodec = codec++ const card = figma.createFrame()+ card.resize(100, 60)+ card.fills = [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }]+ const swatch = figma.createRectangle()+ swatch.x = 60+ swatch.y = 20+ swatch.resize(20, 20)+ swatch.fills = [{ type: 'SOLID', color: { r: 0, g: 0, b: 1, a: 1 }, opacity: 1, visible: true }]+ card.appendChild(swatch)+ return { figma, card }+}++async function visualDiff(figma: FigmaAPI, args: Record<string, unknown>) {+ const tool = expectDefined(ALL_TOOLS.find((candidate) => candidate.name === 'diff_visual'))+ return (await tool.execute(figma, args)) as VisualDiff+}++describe('diff_visual', () => {+ test('reports no changed pixels for an identical copy', async () => {+ const { figma, card } = setup()+ const copy = card.clone()+ copy.x = 300++ const result = await visualDiff(figma, { from: card.id, to: copy.id })+ expect(result.error).toBeUndefined()+ expect(result.mimeType).toBe('image/png')+ expect(result.changedPixels).toBe(0)+ expect(result.changedBounds).toBeNull()+ })++ test('locates a fill change in source-node coordinates', async () => {+ const { figma, card } = setup()+ const copy = card.clone()+ copy.x = 300+ const copiedSwatch = expectDefined(copy.children[0], 'copied swatch')+ copiedSwatch.fills = [+ { type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }+ ]++ const result = await visualDiff(figma, { from: card.id, to: copy.id, scale: 2 })+ expect(result.width).toBe(200)+ expect(result.changedPixels).toBeGreaterThan(0)+ expect(result.changedRatio).toBeCloseTo((40 * 40) / (200 * 120), 2)+ expect(result.changedBounds).toEqual({ x: 60, y: 20, width: 20, height: 20 })+ })++ test('applies the same max-edge bound as export_image', async () => {+ const { figma, card } = setup()+ const copy = card.clone()++ const result = await visualDiff(figma, { from: card.id, to: copy.id, scale: 4, maxEdge: 64 })+ expect(result.width).toBe(64)+ })+})diff --git a/packages/design-jsx/src/attributes.ts b/packages/design-jsx/src/attributes.tsnew file mode 100644index 000000000..b3150c0ec--- /dev/null+++ b/packages/design-jsx/src/attributes.ts@@ -0,0 +1,30 @@+import { parser } from '@lezer/javascript'++import type { JSXAttributeSource } from './export'++const elementParser = parser.configure({ dialect: 'jsx', top: 'SingleExpression' })++/**+ * Split JSX attributes, such as `w={200} bg="#FF0000"`, into each attribute as written.+ * Throws on a syntax error or a spread, whose props cannot be named.+ */+export function parseJSXAttributes(source: string): JSXAttributeSource[] {+ const element = `<Frame ${source} />`+ const tree = elementParser.parse(element)+ const attributes: JSXAttributeSource[] = []+ const invalid = () => new SyntaxError(`Invalid JSX attributes: ${source}`)+ tree.iterate({+ enter(node) {+ if (node.type.isError || node.name === 'JSXSpreadAttribute') throw invalid()+ if (node.name !== 'JSXAttribute') return undefined+ const key = node.node.firstChild+ if (key?.name !== 'JSXIdentifier') throw invalid()+ attributes.push({+ name: element.slice(key.from, key.to),+ source: element.slice(node.from, node.to)+ })+ return false+ }+ })+ return attributes+}diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.tsindex 72699413d..14dc867fb 100644--- a/packages/design-jsx/src/export/index.ts+++ b/packages/design-jsx/src/export/index.ts@@ -32,6 +32,35 @@ function nodeToJSX(node: SceneNode, graph: SceneGraph, depth: number): SyntaxNodreturn jsx.element(tag, attributes, children, depth)}+/** A JSX attribute as the export prints it: its name and its source, such as `w={320}`. */+export interface JSXAttributeSource {+ name: string+ source: string+}++/** Printed values break lines only between tokens, never inside a string, so joining is lossless. */+function oneLine(source: string): string {+ return source.replace(/\s*\n\s*/g, ' ')+}++/**+ * The attributes `sceneNodeToJSX` prints for a node, each on one line, with a text node's+ * content as a `text` attribute. `null` for a node the export does not write.+ */+export function sceneNodeAttributes(+ nodeId: string,+ graph: SceneGraph+): JSXAttributeSource[] | null {+ const node = graph.getNode(nodeId)+ if (!node || !NODE_TYPE_TO_TAG[node.type]) return null+ const props = collectProps(node, graph)+ if (node.type === 'TEXT') props.push(['text', node.text])+ return props.map((prop) => ({+ name: prop[0],+ source: oneLine(jsx.printJSX(propAttribute(prop)))+ }))+}+export function sceneNodeToJSX(nodeId: string, graph: SceneGraph): string {const node = graph.getNode(nodeId)const syntax = node ? nodeToJSX(node, graph, 0) : nulldiff --git a/packages/design-jsx/src/fields.ts b/packages/design-jsx/src/fields.tsnew file mode 100644index 000000000..acc37cd62--- /dev/null+++ b/packages/design-jsx/src/fields.ts@@ -0,0 +1,43 @@+import { omit } from 'es-toolkit'++import {+ createDefaultNode,+ type NodeType,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++import type { JSXAttributeSource } from './export'+import * as React from './mini-react'+import { buildComponent } from './render'+import { elementOverrides } from './renderer'+import { resolveToTree } from './tree'++export interface JSXNodeFields {+ /** Every field the attributes describe, with defaults for the ones they leave out. */+ fields: Partial<SceneNode>+ /** Variable IDs by bound field, such as `fills/0/color`. */+ bindings: Record<string, string>+}++/**+ * The node state a `nodeType` node under `parentId` gets from `attributes`, as rendering+ * would set it, without creating a node. Diffing two results gives the fields an attribute+ * change moves, so an update leaves state that JSX does not describe untouched.+ */+export function jsxNodeFields(+ graph: SceneGraph,+ nodeType: NodeType,+ attributes: JSXAttributeSource[],+ parentId: string+): JSXNodeFields {+ const source = `<Frame ${attributes.map((attribute) => attribute.source).join(' ')} />`+ const tree = resolveToTree(React.createElement(buildComponent(source), null))+ if (!tree) throw new Error(`Invalid JSX attributes: ${source}`)+ const { overrides, bindings } = elementOverrides(graph, nodeType, tree, parentId)+ const defaults = omit(+ createDefaultNode(() => '', nodeType),+ ['id', 'parentId', 'childIds']+ )+ return { fields: { ...defaults, ...overrides }, bindings }+}diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.tsindex 1c6b3d175..d9c94906f 100644--- a/packages/design-jsx/src/index.ts+++ b/packages/design-jsx/src/index.ts@@ -76,7 +76,14 @@ export {} from './schema'export { transformDesignJSXExpression } from './transform'-export { sceneNodeToJSX, selectionToJSX } from './export'+export {+ sceneNodeAttributes,+ sceneNodeToJSX,+ selectionToJSX,+ type JSXAttributeSource+} from './export'+export { parseJSXAttributes } from './attributes'+export { jsxNodeFields, type JSXNodeFields } from './fields'export { JSX_REFERENCE, AUTHORING_EXAMPLES, type AuthoringExample } from './reference'export {createStreamingJSXParser,diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsindex 7dec4d19c..72e236394 100644--- a/packages/design-jsx/src/renderer.ts+++ b/packages/design-jsx/src/renderer.ts@@ -511,22 +511,20 @@ async function renderArtworkNode<Artwork>(return node}-async function renderNode<Artwork>(- services: DesignJSXServices<Artwork>,+export interface ElementOverrides {+ overrides: Partial<SceneNode>+ /** Variable IDs by bound field, such as `fills/0/color`. */+ bindings: Record<string, string>+}++/** The fields and variable bindings an element's props set on a `nodeType` node under `parentId`. */+export function elementOverrides(graph: SceneGraph,+ nodeType: NodeType,tree: TreeNode,parentId: string-): Promise<SceneNode> {- if (tree.type === 'icon' || tree.type === 'svg')- return renderArtworkNode(services, graph, tree, parentId)- if (tree.type === 'instance') return renderInstanceNode(graph, tree, parentId)-- const nodeType = TYPE_MAP[tree.type]- if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)-- const parent = graph.getNode(parentId)- const parentLayout = parent?.layoutMode ?? 'NONE'-+): ElementOverrides {+ const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'const isText = nodeType === 'TEXT'const { props, bindings } = preparePropsForRender(graph, tree.props, isText, parentId)const overrides = {@@ -541,7 +539,23 @@ async function renderNode<Artwork>(if (childText) overrides.text = childTextelse if (typeof propText === 'string') overrides.text = propText}+ return { overrides, bindings }+}++async function renderNode<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string+): Promise<SceneNode> {+ if (tree.type === 'icon' || tree.type === 'svg')+ return renderArtworkNode(services, graph, tree, parentId)+ if (tree.type === 'instance') return renderInstanceNode(graph, tree, parentId)++ const nodeType = TYPE_MAP[tree.type]+ if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)+ const { overrides, bindings } = elementOverrides(graph, nodeType, tree, parentId)const node = graph.createNode(nodeType, parentId, overrides)applyBindings(graph, node.id, bindings)diff --git a/packages/design-jsx/tests/attributes.test.ts b/packages/design-jsx/tests/attributes.test.tsnew file mode 100644index 000000000..1b8f46ebb--- /dev/null+++ b/packages/design-jsx/tests/attributes.test.ts@@ -0,0 +1,22 @@+import { describe, expect, test } from 'bun:test'++import { parseJSXAttributes } from '#design-jsx/index'++describe('parseJSXAttributes', () => {+ test('splits attributes as written, including nested and bare ones', () => {+ expect(+ parseJSXAttributes(+ 'w={200} name="a=b c" clipsContent strokes={[{ color: "#F00", dash: [4, 2] }]}'+ )+ ).toEqual([+ { name: 'w', source: 'w={200}' },+ { name: 'name', source: 'name="a=b c"' },+ { name: 'clipsContent', source: 'clipsContent' },+ { name: 'strokes', source: 'strokes={[{ color: "#F00", dash: [4, 2] }]}' }+ ])+ })++ test.each(['w={200', '{...props}', 'w=200'])('rejects %p', (source) => {+ expect(() => parseJSXAttributes(source)).toThrow('Invalid JSX attributes')+ })+})diff --git a/packages/design-jsx/tests/export.test.ts b/packages/design-jsx/tests/export.test.tsindex 67c1ddbe5..e5da27394 100644--- a/packages/design-jsx/tests/export.test.ts+++ b/packages/design-jsx/tests/export.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { sceneNodeToJSX, selectionToJSX } from '#design-jsx/index'+import { sceneNodeAttributes, sceneNodeToJSX, selectionToJSX } from '#design-jsx/index'import { SceneGraph } from '@open-pencil/scene-graph'@@ -440,6 +440,56 @@ describe('sceneNodeToJSX', () => {})})+describe('sceneNodeAttributes', () => {+ test('prints each attribute as sceneNodeToJSX does, on one line', () => {+ const graph = makeGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Box',+ width: 100,+ height: 50,+ strokes: [+ {+ color: { r: 1, g: 0, b: 0, a: 1 },+ weight: 2,+ opacity: 1,+ visible: true,+ align: 'OUTSIDE'+ },+ {+ color: { r: 0, g: 0, b: 1, a: 1 },+ weight: 1,+ opacity: 1,+ visible: false,+ align: 'INSIDE'+ }+ ]+ })+ const attributes = sceneNodeAttributes(node.id, graph) ?? []+ expect(attributes.map((attribute) => attribute.name)).toEqual(['name', 'w', 'h', 'strokes'])+ expect(attributes.every((attribute) => !attribute.source.includes('\n'))).toBe(true)+ expect(sceneNodeToJSX(node.id, graph)).toStartWith(+ `<Rectangle ${attributes+ .slice(0, 3)+ .map((attribute) => attribute.source)+ .join(' ')}`+ )+ })++ test("writes a text node's content as a text attribute", () => {+ const graph = makeGraph()+ const node = graph.createNode('TEXT', pageId(graph), { name: 'Note', text: 'Two\nlines' })+ expect(sceneNodeAttributes(node.id, graph)?.at(-1)).toEqual({+ name: 'text',+ source: 'text={"Two\\nlines"}'+ })+ })++ test('is null for a node the export skips', () => {+ const graph = makeGraph()+ expect(sceneNodeAttributes(pageId(graph), graph)).toBeNull()+ })+})+describe('selectionToJSX', () => {test('multiple nodes separated by blank lines', () => {const graph = makeGraph()diff --git a/packages/design-jsx/tests/fields.test.ts b/packages/design-jsx/tests/fields.test.tsnew file mode 100644index 000000000..d046df209--- /dev/null+++ b/packages/design-jsx/tests/fields.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'bun:test'++import { jsxNodeFields, parseJSXAttributes } from '#design-jsx/index'++import { SceneGraph } from '@open-pencil/scene-graph'++function fields(graph: SceneGraph, type: 'FRAME' | 'TEXT', source: string) {+ return jsxNodeFields(graph, type, parseJSXAttributes(source), graph.getPages()[0].id)+}++describe('jsxNodeFields', () => {+ test('sets what the attributes describe and defaults the rest, without creating a node', () => {+ const graph = new SceneGraph()+ const count = graph.nodes.size+ const { fields: result } = fields(graph, 'FRAME', 'w={240} rounded={12} opacity={0.5}')+ expect(result).toMatchObject({ width: 240, cornerRadius: 12, opacity: 0.5, visible: true })+ expect(fields(graph, 'FRAME', 'w={240}').fields.cornerRadius).toBe(0)+ expect(graph.nodes.size).toBe(count)+ })++ test('reads text from the text attribute', () => {+ const graph = new SceneGraph()+ expect(fields(graph, 'TEXT', 'text="Hi"').fields.text).toBe('Hi')+ })++ test('resolves variables to bindings', () => {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Tokens')+ const brand = graph.createVariable('Brand', 'COLOR', collection.id, { r: 1, g: 0, b: 0, a: 1 })+ expect(fields(graph, 'FRAME', 'bg={designVar("Brand")}').bindings).toEqual({+ 'fills/0/color': brand.id+ })+ })+})diff --git a/packages/docs/.vitepress/labels.ts b/packages/docs/.vitepress/labels.tsindex dd1e1849a..06799af08 100644--- a/packages/docs/.vitepress/labels.ts+++ b/packages/docs/.vitepress/labels.ts@@ -30,6 +30,7 @@ export interface ProgrammableLabels {inspecting: stringexporting: stringanalyzing: string+ comparing: stringscripting: stringjsxRenderer: stringmcpServer: string@@ -53,6 +54,7 @@ export const EN_PROG: ProgrammableLabels = {inspecting: 'Inspecting Files',exporting: 'Exporting',analyzing: 'Analyzing Designs',+ comparing: 'Comparing Designs',scripting: 'Scripting',jsxRenderer: 'JSX Renderer',mcpServer: 'MCP Server',@@ -65,6 +67,7 @@ export const DE_PROG: ProgrammableLabels = {inspecting: 'Dateien inspizieren',exporting: 'Exportieren',analyzing: 'Designs analysieren',+ comparing: 'Designs vergleichen',scripting: 'Skripte',jsxRenderer: 'JSX-Renderer',mcpServer: 'MCP-Server',@@ -77,6 +80,7 @@ export const IT_PROG: ProgrammableLabels = {inspecting: 'Ispezione file',exporting: 'Esportazione',analyzing: 'Analisi design',+ comparing: 'Confronto dei design',scripting: 'Scripting',jsxRenderer: 'Renderer JSX',mcpServer: 'Server MCP',@@ -89,6 +93,7 @@ export const FR_PROG: ProgrammableLabels = {inspecting: 'Inspecter les fichiers',exporting: 'Exporter',analyzing: 'Analyser les designs',+ comparing: 'Comparer des designs',scripting: 'Scripts',jsxRenderer: 'Moteur JSX',mcpServer: 'Serveur MCP',@@ -101,6 +106,7 @@ export const ES_PROG: ProgrammableLabels = {inspecting: 'Inspeccionar archivos',exporting: 'Exportar',analyzing: 'Analizar diseños',+ comparing: 'Comparar diseños',scripting: 'Scripts',jsxRenderer: 'Renderizador JSX',mcpServer: 'Servidor MCP',@@ -113,6 +119,7 @@ export const PL_PROG: ProgrammableLabels = {inspecting: 'Inspekcja plików',exporting: 'Eksportowanie',analyzing: 'Analiza projektów',+ comparing: 'Porównywanie projektów',scripting: 'Skrypty',jsxRenderer: 'Renderer JSX',mcpServer: 'Serwer MCP',@@ -125,6 +132,7 @@ export const RU_PROG: ProgrammableLabels = {inspecting: 'Инспекция файлов',exporting: 'Экспорт',analyzing: 'Анализ дизайна',+ comparing: 'Сравнение дизайнов',scripting: 'Скрипты',jsxRenderer: 'JSX-рендерер',mcpServer: 'MCP-сервер',diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.tsindex 28d837e1f..cbb0441bb 100644--- a/packages/docs/.vitepress/sidebars.ts+++ b/packages/docs/.vitepress/sidebars.ts@@ -62,6 +62,7 @@ export const programmableSidebar = ({ text: labels.inspecting, link: `${prefix}/programmable/cli/inspecting` },{ text: labels.exporting, link: `${prefix}/programmable/cli/exporting` },{ text: labels.analyzing, link: `${prefix}/programmable/cli/analyzing` },+ { text: labels.comparing, link: '/programmable/cli/comparing' },{ text: labels.scripting, link: `${prefix}/programmable/cli/scripting` },{ text: labels.jsxRenderer, link: `${prefix}/programmable/jsx-renderer` },{ text: 'Native JavaScript APIs', link: '/programmable/native-api' },diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.mdindex 9a4698fed..65c0717aa 100644--- a/packages/docs/programmable/ai-chat.md+++ b/packages/docs/programmable/ai-chat.md@@ -73,14 +73,14 @@ The configurable tool catalog covers these categories; the tools offered to a mo- **Components** — create components, instances, component sets. Manage overrides.- **Variables** — create/edit variables, collections, modes. Bind to fills.- **Query** — find nodes, XPath selectors, read properties, list pages, fonts, selection.-- **Inspect** — `get_jsx` for JSX roundtrip view, `diff_jsx` for structural diffs, `describe` for semantic role and design issue detection.+- **Inspect** — `get_jsx` for JSX roundtrip view, `diff_create` and `diff_jsx` for structural diffs, `diff_visual` for pixel diffs, `describe` for semantic role and design issue detection.- **Analyze** — color palette, typography audit, spacing consistency, cluster detection.- **Export** — PNG, SVG, JSX with Tailwind classes. Vision-based verification via `export_image`.- **Vector** — boolean operations, path manipulation.## Visual Verification-The assistant can verify its work visually. When `export_image` is enabled, it can capture a screenshot after creating or modifying designs and checks the result against the original request. This catches layout issues, missing elements, and color mismatches that text-only responses would miss.+The assistant can verify its work visually. When `export_image` is enabled, it can capture a screenshot after creating or modifying designs and checks the result against the original request. This catches layout issues, missing elements, and color mismatches that text-only responses would miss. `diff_visual`, enabled by default, compares an edited node with a reference copy and returns the changed pixels and region, so the assistant can confirm an edit stayed within its target.## Example Promptsdiff --git a/packages/docs/programmable/cli/comparing.md b/packages/docs/programmable/cli/comparing.mdnew file mode 100644index 000000000..aae3b1058--- /dev/null+++ b/packages/docs/programmable/cli/comparing.md@@ -0,0 +1,76 @@+---+title: Comparing Designs+description: Diff nodes and documents structurally and visually, and apply patches.+---++# Comparing Designs++The `diff` commands compare two nodes, preview or apply changes as patches, render pixel diffs, and compare whole documents. Each node command works on a file or, without one, on the document open in the running app.++## Patches++```sh+openpencil diff create design.fig --from 1:23 --to 1:87+```++Prints a patch that turns the first tree into the second. Its properties are the JSX attributes the [JSX export](../jsx-renderer#exporting-to-jsx) writes, so it covers everything the export does. Children match by name, and a reordered child reads as one move:++```diff+@@ /Card #1:23+-rounded={8}++rounded={12}+@@ /Card/Header #1:24+-bg="#FFFFFF"++bg="#F4F4F5"+@@ /Card/Badge #1:26 moved to 0+@@ /Card/Note #1:27 removed+@@ /Card/Price added to #1:23 at 3++<Text name="Price" size={24}>$9</Text>+```++Each hunk names a node by path, for reading, and by ID, which locates it. `-` lines hold the old attribute values and `+` lines the new ones; an added node is its JSX.++`diff show` previews setting attributes on a node without changing it, and prints the patch:++```sh+openpencil diff show 1:24 design.fig --attributes 'bg="#F4F4F5" rounded={8}' > header.diff+```++`diff apply` applies a patch to the document whose IDs it names. Every node must still have the patch's old values unless `--force` skips that check, and nothing changes unless every hunk applies, so a patch never half-applies:++```sh+openpencil diff apply header.diff design.fig --dry-run # validate first+openpencil diff apply header.diff design.fig --write # save in place+openpencil diff apply header.diff design.fig -o out.fig # save elsewhere+```++Updates change only the fields their attributes set, so node IDs, instance links, and state JSX does not describe stay intact. Removed nodes are deleted and added nodes are rendered from their JSX.++## JSX diff++```sh+openpencil diff jsx design.fig --from 1:23 --to 1:87+```++Compares two subtrees as a line diff of their design JSX, for reading rather than applying.++## Visual diff++```sh+openpencil diff visual design.fig --from 1:23 --to 1:87 --output diff.png+```++Renders both nodes at the same scale and writes a PNG with changed pixels in red over a faded copy of the source. The report includes the changed pixel ratio and the changed region in source-node coordinates. `--scale` and `--max-edge` bound the render the same way `export_image` does; `--threshold` sets the color tolerance.++## Comparing documents++```sh+openpencil diff files before.fig after.fig+openpencil diff files before.fig after.fig --page "Mobile" --json+```++Compares two documents page by page. Pages match by name and nodes by name path, so two versions of a file compare even though node IDs differ; the patch applies to the first document. Patches do not add or remove pages: a page only one document has is listed by name and status instead. Like `diff(1)`, the command exits with status 1 when the documents differ.++## Agents++The same operations are available as the `diff_create`, `diff_jsx`, `diff_show`, `diff_apply`, and `diff_visual` tools for the built-in AI chat and MCP clients. `diff_visual` returns its image to the model, so an agent can confirm that an edit touched only the intended region.diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 1fb6d017e..60090cbec 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -311,8 +311,11 @@ OpenPencil currently registers 100+ shared design tools, plus MCP-only document| Tool | Description ||------|-------------|-| `diff_create` | Create a snapshot of the current document state |-| `diff_show` | Show differences between the current state and a snapshot |+| `diff_create` | Patch that turns one node tree into another, as JSX attribute changes |+| `diff_jsx` | Structural diff between two nodes as design JSX |+| `diff_show` | Preview the patch that setting JSX attributes on a node would produce |+| `diff_apply` | Apply a patch after checking the nodes still match its old values |+| `diff_visual` | Pixel diff between two rendered nodes, returned as an image |### Navigationdiff --git a/packages/docs/reference/cli.md b/packages/docs/reference/cli.mdindex f50da8458..9a2f12c5c 100644--- a/packages/docs/reference/cli.md+++ b/packages/docs/reference/cli.md@@ -216,3 +216,84 @@ openpencil analyze clusters [file] [options]| `--min-size` | Min node size in px (default: 30) || `--min-count` | Min instances to form a cluster (default: 2) || `--json` | Output as JSON |++## diff create++Patch that turns one node tree into another, as JSX attribute changes plus moved, added, and removed children. Children match by name; see [Comparing designs](/programmable/cli/comparing) for the format.++```sh+openpencil diff create [file] --from <id> --to <id> [options]+```++| Option | Description |+|--------|-------------|+| `--from` | Source node ID |+| `--to` | Target node ID |+| `--depth` | Max tree depth (default: 10) |+| `--json` | Output as JSON |++## diff jsx++Structural diff between two nodes as design JSX.++```sh+openpencil diff jsx [file] --from <id> --to <id> [--json]+```++## diff show++Preview the patch that setting JSX attributes on a node would produce, without changing it.++```sh+openpencil diff show <id> [file] --attributes '<jsx attributes>' [--json]+```++`--attributes` takes attributes as the JSX export writes them, such as `'w={200} bg="#FF0000"'`.++## diff apply++Apply a patch from `diff create`, `diff show`, or `diff files`. Every node must still match the patch's old values unless `--force` is set, and nothing changes unless every hunk applies.++```sh+openpencil diff apply <patch> [file] [options]+```++| Option | Alias | Description |+|--------|-------|-------------|+| `--dry-run` | | Validate and list changes without applying |+| `--force` | | Apply even when current values differ from the patch |+| `--write` | `-w` | Write changes back to the input file |+| `--output` | `-o` | Write to a different file |+| `--json` | | Output as JSON |++Pass `-` as the patch path to read it from stdin.++## diff visual++Pixel diff between two rendered nodes, written as a PNG with changed pixels in red.++```sh+openpencil diff visual [file] --from <id> --to <id> --output <png> [options]+```++| Option | Alias | Description |+|--------|-------|-------------|+| `--output` | `-o` | Diff PNG path |+| `--scale` | | Render scale before the max-edge limit (default: 1) |+| `--max-edge` | | Maximum image width or height (default: 1280) |+| `--threshold` | | Color tolerance 0–1; smaller is stricter (default: 0.1) |+| `--json` | | Output as JSON |++## diff files++Structural diff of two documents, page by page. Pages match by name and nodes by name path, so two versions of a file compare even though their node IDs differ. Exits with status 1 when the documents differ and 2 when the options are invalid, such as a `--page` neither document has.++```sh+openpencil diff files <before> <after> [options]+```++| Option | Description |+|--------|-------------|+| `--page` | Compare only the page with this name |+| `--depth` | Max tree depth below each page (default: unlimited) |+| `--json` | Output as JSON |diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 614e9e52c..64d9bc8d8 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -10,6 +10,7 @@ export * from './instance-overrides'export * from './images'export * from './components/properties'export * from './copy'+export { createDefaultNode } from './node-defaults'export {copyInstanceComponentProps,findInstanceAncestor,diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 14575a6af..80c7bbc3b 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -153,6 +153,20 @@ openpencil eval design.fig -o modified.fig -c '...'echo 'figma.currentPage.children.map(n => n.name)' | openpencil eval design.fig --stdin```+### Diff++Compare nodes and documents, and apply patches:++```bash+openpencil diff create design.fig --from 1:23 --to 1:87 # JSX attribute patch+openpencil diff jsx design.fig --from 1:23 --to 1:87 # JSX structure+openpencil diff show 1:24 design.fig --attributes 'rounded={8}' > fix.diff+openpencil diff apply fix.diff design.fig --dry-run # fails on stale values+openpencil diff apply fix.diff design.fig --write+openpencil diff visual design.fig --from 1:23 --to 1:87 -o diff.png+openpencil diff files before.fig after.fig # exit 1 when different+```+Every command that reports structured data supports `--json` when appropriate.## MCP Server@@ -202,7 +216,7 @@ The CLI defaults the filesystem root to the home directory on Windows and the cu1. **Open/create a document** — `open_file { path }` within the effective filesystem root, or `new_document {}`.2. **Query** — `get_page_tree`, `find_nodes`, `query_nodes`, `get_node`, `list_pages`, `get_current_page`.-3. **Inspect** — `get_jsx`, `diff_jsx`, `describe`, `export_image`, `export_svg`, `export_pdf`.+3. **Inspect** — `get_jsx`, `diff_jsx`, `diff_create`, `diff_visual`, `describe`, `export_image`, `export_svg`, `export_pdf`.4. **Modify** — `render`, `batch_update`, `update_node`, `set_fill`, `set_layout`, `create_shape`, `import_svg`, etc.5. **Navigate** — after creating or editing visible canvas content, call `select_nodes` and `viewport_zoom_to_fit { id }` (or `node_bounds` + `viewport_set`) so the user can see the result in the running editor.6. **Save/export** — `save_file`, `export_image`, `export_svg`, `export_pdf`, or CLI `export`.@@ -226,7 +240,8 @@ Discover available tools and their arguments from the connected server or browse- **`query_nodes`** — XPath selectors to find specific nodes without fetching the full tree.- **`get_jsx`** — inspect any node as JSX in the same format accepted by `render`.-- **`diff_jsx`** — compare two nodes structurally before editing.+- **`diff_jsx` / `diff_create`** — compare two nodes as a JSX line diff or as an appliable patch of JSX attributes; `diff_show` previews setting attributes and `diff_apply` applies a patch only if the nodes still match it.+- **`diff_visual`** — pixel diff between two rendered nodes; use it to confirm an edit changed only the intended region.- **`describe`** — semantic analysis of role, visual style, layout, and design issues.- **`batch_update`** — apply multiple node updates efficiently.- **`export_image` / `export_svg` / `export_pdf`** — visual verification and deliverables.diff --git a/src/app/ai/chat/system-prompt.md b/src/app/ai/chat/system-prompt.mdindex d5b34569d..da443110f 100644--- a/src/app/ai/chat/system-prompt.md+++ b/src/app/ai/chat/system-prompt.md@@ -10,6 +10,8 @@ You are a design assistant inside OpenPencil. Create and modify designs using th- Use `describe` on a relevant subtree to diagnose layout; batch related fixes where appropriate. Reinspect after meaningful changes, not repeatedly without changes. Diagnose a failed edit before replacing content; do not blindly delete nodes after a fixed retry count.- 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.- 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/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.tsindex 8aa95dc61..d0434fcb9 100644--- a/src/app/automation/bridge/figma-factory.ts+++ b/src/app/automation/bridge/figma-factory.ts@@ -1,4 +1,5 @@import { FigmaAPI } from '@open-pencil/core/figma-api'+import { createCanvasKitRasterCodec } from '@open-pencil/core/io/formats/raster'import type { EditorStore } from '@/app/editor/active-store'import { listFamilies, listFonts } from '@/app/editor/fonts'@@ -25,7 +26,8 @@ export function makeFigmaFromStore(zoom: store.state.zoom}api.exportImage = (nodeIds, opts) =>- store.renderExportImage(nodeIds, opts.scale ?? 1, opts.format ?? 'PNG')+ store.renderExportImage(nodeIds, opts.scale ?? 1, opts.format ?? 'PNG', opts.pageId ?? pageId)+ if (store.renderer) api.rasterCodec = createCanvasKitRasterCodec(store.renderer.ck)api.listAvailableFontsAsync = async () => {const [systemFonts, familyOptions] = await Promise.all([listFonts(), listFamilies()])const fonts = systemFonts.flatMap(({ family, styles }) =>