AI-native design editor. Open-source Figma alternative.
feat: control documents, history, settings, and tools from the CLI and MCP (#871)
Danila Poyarkovb52d7e265198
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1eb9fdb4f..cacdfc42f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,8 @@- 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.+- `openpencil documents` is now a command group: list open documents with `openpencil documents list`.+- The MCP `close_file` tool no longer asks in the app whether to save unsaved changes, a question an agent could not answer and that left the call timing out. With unsaved changes it now fails unless `unsaved` is `"save"` or `"discard"`, and it is marked as a write tool.### Added@@ -40,6 +42,7 @@- 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.+- Control the running app from the CLI and MCP: `openpencil documents` opens, creates, saves, closes, and brings documents to the front, `openpencil undo` and `redo` step back through changes made through the CLI and MCP, refusing to revert edits made in the editor, and `openpencil settings get` and `set` read and change theme, language, animations, snapping, canvas rendering, recovery, chat, and design check settings. MCP clients get the same through `activate_document`, `undo`, `redo`, `get_settings`, and `update_settings`; credentials, models, MCP connections, storage, and tool access stay out of reach. `openpencil tool list`, `describe`, and `call` run any MCP tool from the shell, against the running app or headlessly on a file.### Changed@@ -56,6 +59,8 @@### Fixed+- Report a failed MCP `save_file` or `new_document` save as an error instead of success, and ask for a path rather than opening a Save dialog when the document has never been saved.+- Undo layers that MCP clients and the CLI create, delete, or rearrange in the running app, including `render` and `eval` changes, with Edit → Undo. Previously only their property edits were undoable.- Save a `.fig` file that was opened and not edited yet. In the app the save never finished, and MCP `save_file` timed out without writing the file.- Show `.fig` thumbnails in the desktop app's recent files, which the app was not permitted to read.- Give paints set through the plugin API, `eval`, and AI and MCP scripts an opacity of 1 and make them visible when the script leaves those out, as Figma does. Such paints were stored without them, which the Design panel could not show.diff --git a/README.md b/README.mdindex a9ee77c87..2d6ec2cfe 100644--- a/README.md+++ b/README.md@@ -162,6 +162,10 @@ When the desktop app is running, omit the file argument — the CLI connects viaopenpencil tree # Inspect the live documentopenpencil export -f png # Screenshot the current canvasopenpencil eval -c "figma.currentPage.name" # Query the editor+openpencil documents list # Open tabs; also open/new/save/close/activate+openpencil tool call set_fill --args '{"id":"0:5","color":"#2563eb"}' # Any MCP tool+openpencil undo # Undo the newest automation change+openpencil settings set appearance.theme light```All commands support `--json` for machine-readable output.diff --git a/bun.lock b/bun.lockindex db540eb20..61d0e64f0 100644--- a/bun.lock+++ b/bun.lock@@ -176,6 +176,7 @@"@open-pencil/dom-css": "workspace:*","@open-pencil/mcp": "workspace:*","@open-pencil/scene-graph": "workspace:*",+ "@valibot/to-json-schema": "^1.8.0","agentfmt": "^0.1.3","canvaskit-wasm": "^0.41.1","citty": "^0.1.6",diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.mdindex 3186e1430..8dc6c4fc4 100644--- a/packages/cli/AGENTS.md+++ b/packages/cli/AGENTS.md@@ -4,5 +4,6 @@ Headless `.fig` inspection, export, linting, and scripting with `citty`. `bun op- Format all output with the `agentfmt` helpers re-exported from `packages/cli/src/format.ts`; do not hand-roll terminal formatting.- Data and inspection commands support `--json`.+- App-only commands (`documents`, `undo`, `redo`, `settings`) print through `runAppCommand` in `packages/cli/src/app/command.ts`; `tool` lists and calls the same MCP-exposed Core tools as the app bridge, so add operations as tools rather than new RPC commands where they act on a document.- Commands own their CLI UX independently of tools; `eval` exposes operations through `FigmaAPI` (`packages/core/AGENTS.md`, Figma API). Keep the public docs under `packages/docs/programmable/cli/` and the skill examples current when commands change.- The MCP `--root` default is the current directory on macOS and Linux and the home directory on Windows; see `packages/mcp/AGENTS.md`.diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 797a5bd5e..3b3978ce4 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -41,6 +41,7 @@"@open-pencil/dom-css": "workspace:*","@open-pencil/mcp": "workspace:*","@open-pencil/scene-graph": "workspace:*",+ "@valibot/to-json-schema": "^1.8.0","agentfmt": "^0.1.3","canvaskit-wasm": "^0.41.1","citty": "^0.1.6",diff --git a/packages/cli/src/app-client.ts b/packages/cli/src/app/client.tssimilarity index 84%rename from packages/cli/src/app-client.tsrename to packages/cli/src/app/client.tsindex 29f887c8d..a96e277e7 100644--- a/packages/cli/src/app-client.ts+++ b/packages/cli/src/app/client.ts@@ -5,6 +5,8 @@ import { readDiscoveryFile } from '@open-pencil/mcp/discovery'import type { DiscoveryInfo } from '@open-pencil/mcp/discovery'import { platformHasUnixSockets } from '@open-pencil/mcp/transport'+import type { AppTarget } from '#cli/app/target'+/** Maximum time to wait for a single RPC request before giving up. */const RPC_TIMEOUT_MS = 30_000@@ -78,12 +80,18 @@ function doRequest(})}+/** A successful app response: the command result plus the document it ran against, if any. */+export interface RPCResponse<T> {+ result: T+ target?: AppTarget+}+async function doRPC<T>(info: DiscoveryInfo,command: string,args: unknown,forceTcp = false-): Promise<T> {+): Promise<RPCResponse<T>> {const { status, data } = await doRequest(info, '/rpc', 'POST', { command, args }, forceTcp)if (status === 401) {@@ -96,9 +104,9 @@ async function doRPC<T>(throw new Error(errData.error ?? `RPC failed: HTTP ${status}`)}- const body = data as { ok?: boolean; result?: T; error?: string }+ const body = data as { ok?: boolean; result?: T; target?: AppTarget; error?: string }if (body.ok === false) throw new Error(body.error ?? 'RPC failed')- return body.result as T+ return { result: body.result as T, ...(body.target ? { target: body.target } : {}) }}/** Error class to distinguish auth failures for retry logic. */@@ -121,7 +129,11 @@ function isSocketConnectionError(error: unknown): boolean {)}-async function rpcWithFallback<T>(info: DiscoveryInfo, command: string, args: unknown): Promise<T> {+async function rpcWithFallback<T>(+ info: DiscoveryInfo,+ command: string,+ args: unknown+): Promise<RPCResponse<T>> {try {return await doRPC<T>(info, command, args)} catch (error) {@@ -138,6 +150,14 @@ async function rpcWithFallback<T>(info: DiscoveryInfo, command: string, args: un}export async function rpc<T = unknown>(command: string, args: unknown = {}): Promise<T> {+ return (await rpcResponse<T>(command, args)).result+}++/** Like `rpc`, but keeps the target document the app resolved for the command. */+export async function rpcResponse<T = unknown>(+ command: string,+ args: unknown = {}+): Promise<RPCResponse<T>> {try {return await rpcWithFallback<T>(await resolveDiscovery(), command, args)} catch (error) {diff --git a/packages/cli/src/app/command.ts b/packages/cli/src/app/command.tsnew file mode 100644index 000000000..6f49e95a5--- /dev/null+++ b/packages/cli/src/app/command.ts@@ -0,0 +1,37 @@+import { rpcResponse } from '#cli/app/client'+import type { AppTarget } from '#cli/app/target'+import { entity, fmtList, printError } from '#cli/format'++function targetDetails(target: AppTarget): Record<string, string> {+ return {+ document: entity('document', target.documentName, target.documentId),+ page: `${target.pageName} (${target.pageId})`,+ ...(target.path ? { path: target.path } : {})+ }+}++/**+ * Send one command to the running app and print its outcome: the whole response with+ * `--json`, otherwise `message(result)` followed by the document it ran against.+ */+export async function runAppCommand(+ command: string,+ args: Record<string, unknown>,+ options: { json?: boolean; message: (result: unknown) => string }+): Promise<void> {+ try {+ const response = await rpcResponse(command, args)+ if (options.json) {+ console.log(JSON.stringify(response, null, 2))+ return+ }+ const header = options.message(response.result)+ const details = response.target ? targetDetails(response.target) : undefined+ console.log('')+ console.log(fmtList([{ header, details }], { compact: true }))+ console.log('')+ } catch (error) {+ printError(error)+ process.exit(1)+ }+}diff --git a/packages/cli/src/app-target.ts b/packages/cli/src/app/target.tssimilarity index 78%rename from packages/cli/src/app-target.tsrename to packages/cli/src/app/target.tsindex 6533ef9d9..5decf98c7 100644--- a/packages/cli/src/app-target.ts+++ b/packages/cli/src/app/target.ts@@ -1,3 +1,12 @@+/** The document and page the running app resolved for a command. */+export type AppTarget = {+ documentId: string+ documentName: string+ path?: string+ pageId: string+ pageName: string+}+export type AppTargetCLIArgs = {'document-id'?: string'page-id'?: stringdiff --git a/packages/cli/src/commands/analyze/clusters.ts b/packages/cli/src/commands/analyze/clusters.tsindex 0c808e2c8..aa8cf5559 100644--- a/packages/cli/src/commands/analyze/clusters.ts+++ b/packages/cli/src/commands/analyze/clusters.ts@@ -3,7 +3,7 @@ import { defineCommand } from 'citty'import type { AnalyzeClustersResult } from '@open-pencil/core/rpc'import { calcClusterConfidence } from '@open-pencil/core/tools'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { bold, fmtList, fmtSummary } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/analyze/colors.ts b/packages/cli/src/commands/analyze/colors.tsindex 230fafd12..aad9e09a0 100644--- a/packages/cli/src/commands/analyze/colors.ts+++ b/packages/cli/src/commands/analyze/colors.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import type { AnalyzeColorsResult } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { bold, fmtHistogram, fmtList, fmtSummary } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/analyze/spacing.ts b/packages/cli/src/commands/analyze/spacing.tsindex 41274f62d..c06a6022b 100644--- a/packages/cli/src/commands/analyze/spacing.ts+++ b/packages/cli/src/commands/analyze/spacing.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import type { AnalyzeSpacingResult } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { bold, kv, fmtHistogram, fmtSummary } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/analyze/typography.ts b/packages/cli/src/commands/analyze/typography.tsindex 54a6fc200..20365783c 100644--- a/packages/cli/src/commands/analyze/typography.ts+++ b/packages/cli/src/commands/analyze/typography.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import type { AnalyzeTypographyResult } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { bold, fmtHistogram, fmtSummary } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/convert.ts b/packages/cli/src/commands/convert.tsindex abc4b48e6..1883846e3 100644--- a/packages/cli/src/commands/convert.ts+++ b/packages/cli/src/commands/convert.ts@@ -5,7 +5,7 @@ import { defineCommand } from 'citty'import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'-import { requireFile } from '#cli/app-client'+import { requireFile } from '#cli/app/client'import { ok, printError } from '#cli/format'import { loadDocument, populateWholeDocument } from '#cli/headless'diff --git a/packages/cli/src/commands/diff/apply.ts b/packages/cli/src/commands/diff/apply.tsindex 6ab76bf61..3187ebdd9 100644--- a/packages/cli/src/commands/diff/apply.ts+++ b/packages/cli/src/commands/diff/apply.ts@@ -1,10 +1,9 @@-import { readFile } from 'node:fs/promises'-import { defineCommand } from 'citty'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { dim, entity, fail, fmtList, ok, printError, warn } from '#cli/format'import { documentWriteOptions, writeFigDocument } from '#cli/headless'+import { readTextSource } from '#cli/input'import { runToolData } from '#cli/tool-data'interface PatchResult {@@ -23,13 +22,6 @@ interface ApplyResult {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(', ') }@@ -75,7 +67,7 @@ export default defineCommand({const { result, graph } = await runToolData(args.file,'diff_apply',- { patch: await readPatch(args.patch), dryRun, force: !!args.force },+ { patch: await readTextSource(args.patch), dryRun, force: !!args.force },args)const report = result as ApplyResultdiff --git a/packages/cli/src/commands/diff/args.ts b/packages/cli/src/commands/diff/args.tsindex 26aa771b0..3e30ce5b9 100644--- a/packages/cli/src/commands/diff/args.ts+++ b/packages/cli/src/commands/diff/args.ts@@ -1,4 +1,4 @@-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'/** The document and node pair every two-node diff command takes. */export const nodePairArgs = {diff --git a/packages/cli/src/commands/diff/show.ts b/packages/cli/src/commands/diff/show.tsindex ef9c232e6..ef0cd2da8 100644--- a/packages/cli/src/commands/diff/show.ts+++ b/packages/cli/src/commands/diff/show.ts@@ -1,6 +1,6 @@import { defineCommand } from 'citty'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { runToolData } from '#cli/tool-data'import { printDiffResult, type DiffResult } from './output'diff --git a/packages/cli/src/commands/documents/files.ts b/packages/cli/src/commands/documents/files.tsnew file mode 100644index 000000000..6328641d9--- /dev/null+++ b/packages/cli/src/commands/documents/files.ts@@ -0,0 +1,104 @@+import { resolve } from 'node:path'++import { defineCommand } from 'citty'++import { runAppCommand } from '#cli/app/command'+import { appTargetOptions, appTargetRPCArgs } from '#cli/app/target'+import { ok, printError } from '#cli/format'++const json = { type: 'boolean', description: 'Output as JSON' } as const++// The app resolves paths against its own working directory, so send absolute ones.+function absolutePath(path: string | undefined): { path?: string } {+ return path ? { path: resolve(path) } : {}+}++export const open = defineCommand({+ meta: { description: 'Open a .fig or .pen file in a new tab of the running app' },+ args: {+ file: { type: 'positional', description: 'Design file to open', required: true },+ json+ },+ run: ({ args }) =>+ runAppCommand('open_file', absolutePath(args.file), {+ json: args.json,+ message: () => ok(`Opened ${args.file}`)+ })+})++export const create = defineCommand({+ meta: { description: 'Create an empty document in a new tab of the running app' },+ args: {+ path: { type: 'string', description: 'Save the new document to this .fig path' },+ json+ },+ run: ({ args }) =>+ runAppCommand('new_document', absolutePath(args.path), {+ json: args.json,+ message: () => ok('Created document')+ })+})++export const save = defineCommand({+ meta: { description: 'Save a document open in the running app' },+ args: {+ path: { type: 'string', description: 'Save to this .fig path instead of the current one' },+ ...appTargetOptions,+ json+ },+ run: ({ args }) =>+ runAppCommand(+ 'save_file',+ { ...appTargetRPCArgs(args), ...absolutePath(args.path) },+ {+ json: args.json,+ message: () => ok('Saved document')+ }+ )+})++export const close = defineCommand({+ meta: {+ description:+ 'Close a document tab; with unsaved changes, pass --save or --discard (it never prompts in the app)'+ },+ args: {+ save: { type: 'boolean', description: 'Save unsaved changes first' },+ discard: { type: 'boolean', description: 'Close without saving, losing unsaved changes' },+ path: { type: 'string', description: 'With --save: .fig path for a document never saved' },+ ...appTargetOptions,+ json+ },+ run: ({ args }) => {+ if (args.save && args.discard) {+ printError('Pass either --save or --discard, not both')+ process.exit(1)+ }+ const rpcArgs: Record<string, unknown> = {+ ...appTargetRPCArgs(args),+ ...absolutePath(args.path)+ }+ if (args.save) rpcArgs.unsaved = 'save'+ if (args.discard) rpcArgs.unsaved = 'discard'+ return runAppCommand('close_file', rpcArgs, {+ json: args.json,+ message: (result) =>+ (result as { closed?: boolean }).closed ? ok('Closed document') : 'Document stayed open'+ })+ }+})++export const activate = defineCommand({+ meta: { description: 'Bring a document tab to the front, optionally on a given page' },+ args: {+ id: { type: 'positional', description: 'Document ID from `documents list`', required: true },+ 'page-id': appTargetOptions['page-id'],+ json+ },+ run: ({ args }) =>+ runAppCommand(+ 'activate_document',+ appTargetRPCArgs({ 'document-id': args.id, 'page-id': args['page-id'] }),+ { json: args.json, message: () => ok('Activated document') }+ )+})diff --git a/packages/cli/src/commands/documents/index.ts b/packages/cli/src/commands/documents/index.tsnew file mode 100644index 000000000..912e8e7af--- /dev/null+++ b/packages/cli/src/commands/documents/index.ts@@ -0,0 +1,9 @@+import { defineCommand } from 'citty'++import { activate, close, create, open, save } from './files'+import list from './list'++export default defineCommand({+ meta: { description: 'List, open, create, save, close, and switch documents in the running app' },+ subCommands: { list, open, new: create, save, close, activate }+})diff --git a/packages/cli/src/commands/documents.ts b/packages/cli/src/commands/documents/list.tssimilarity index 92%rename from packages/cli/src/commands/documents.tsrename to packages/cli/src/commands/documents/list.tsindex 189f5ca0a..ad09f5d74 100644--- a/packages/cli/src/commands/documents.ts+++ b/packages/cli/src/commands/documents/list.ts@@ -2,11 +2,11 @@ import { defineCommand } from 'citty'import type { AutomationDocumentSummary } from '@open-pencil/core/rpc'-import { rpc } from '#cli/app-client'+import { rpc } from '#cli/app/client'import { bold, entity, fmtList, kv, printError } from '#cli/format'export default defineCommand({- meta: { description: 'List open documents in the running app' },+ meta: { description: 'List open documents (tabs) in the running app' },args: {json: { type: 'boolean', description: 'Output as JSON' }},diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.tsindex e06a23b96..0139cf33d 100644--- a/packages/cli/src/commands/eval.ts+++ b/packages/cli/src/commands/eval.ts@@ -2,8 +2,8 @@ import { defineCommand } from 'citty'import { FigmaAPI } from '@open-pencil/core/figma-api'-import { isAppMode, requireFile, rpc } from '#cli/app-client'-import { appTargetOptions, appTargetRPCArgs } from '#cli/app-target'+import { isAppMode, requireFile, rpc } from '#cli/app/client'+import { appTargetOptions, appTargetRPCArgs } from '#cli/app/target'import { printError } from '#cli/format'import {documentWriteOptions,diff --git a/packages/cli/src/commands/export/index.ts b/packages/cli/src/commands/export/index.tsindex 173f4b946..01068f8a7 100644--- a/packages/cli/src/commands/export/index.ts+++ b/packages/cli/src/commands/export/index.ts@@ -7,8 +7,8 @@ import { toUint8Array } from 'js-base64'import { BUILTIN_IO_FORMATS, IORegistry, type ExportResult } from '@open-pencil/core/io'import type { AutomationDocumentSummary } from '@open-pencil/core/rpc'-import { isAppMode, requireFile, rpc } from '#cli/app-client'-import { appTargetOptions, appTargetRPCArgs } from '#cli/app-target'+import { isAppMode, requireFile, rpc } from '#cli/app/client'+import { appTargetOptions, appTargetRPCArgs } from '#cli/app/target'import { ok, printError } from '#cli/format'import {loadDocument,diff --git a/packages/cli/src/commands/export/storybook/index.ts b/packages/cli/src/commands/export/storybook/index.tsindex 226e4cc69..d960aea4c 100644--- a/packages/cli/src/commands/export/storybook/index.ts+++ b/packages/cli/src/commands/export/storybook/index.ts@@ -20,7 +20,7 @@ import {type StorybookFramework} from '@open-pencil/dom-css'-import { requireFile } from '#cli/app-client'+import { requireFile } from '#cli/app/client'import { applyExportFontPolicy } from '#cli/commands/export/font-policy'import { ok, printError } from '#cli/format'import { loadDocument, populateWholeDocument, requirePage } from '#cli/headless'diff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.tsindex 2b5129c7d..559dda494 100644--- a/packages/cli/src/commands/find.ts+++ b/packages/cli/src/commands/find.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import type { FindNodeResult } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { printNodeResults } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/fonts.ts b/packages/cli/src/commands/fonts.tsindex 964470ed5..ebfdc168f 100644--- a/packages/cli/src/commands/fonts.ts+++ b/packages/cli/src/commands/fonts.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import { fontManager, prepareGraphFonts, type DocumentFontStatus } from '@open-pencil/core/text'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { bold, entity, fmtList, kv, printError } from '#cli/format'import { loadDocument } from '#cli/headless'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/history.ts b/packages/cli/src/commands/history.tsnew file mode 100644index 000000000..da1f53341--- /dev/null+++ b/packages/cli/src/commands/history.ts@@ -0,0 +1,35 @@+import { defineCommand } from 'citty'++import { runAppCommand } from '#cli/app/command'+import { appTargetOptions, appTargetRPCArgs } from '#cli/app/target'+import { ok } from '#cli/format'++interface HistoryResult {+ applied: boolean+ label: string | null+}++function historyCommand(command: 'undo' | 'redo', verb: string) {+ return defineCommand({+ meta: {+ description: `${verb} the last change made through automation in a document open in the running app`+ },+ args: {+ ...appTargetOptions,+ json: { type: 'boolean', description: 'Output as JSON' }+ },+ run: ({ args }) =>+ runAppCommand(command, appTargetRPCArgs(args), {+ json: args.json,+ message: (response) => {+ const result = response as HistoryResult+ if (!result.applied) return `Nothing to ${command}`+ const label = result.label ? `: ${result.label}` : ''+ return ok(`${verb === 'Undo' ? 'Undid' : 'Redid'}${label}`)+ }+ })+ })+}++export const undo = historyCommand('undo', 'Undo')+export const redo = historyCommand('redo', 'Redo')diff --git a/packages/cli/src/commands/import.ts b/packages/cli/src/commands/import.tsindex c17e36243..2cacee6e7 100644--- a/packages/cli/src/commands/import.ts+++ b/packages/cli/src/commands/import.ts@@ -13,7 +13,7 @@ import {type DesignDocument} from '@open-pencil/dom-css'-import { requireFile } from '#cli/app-client'+import { requireFile } from '#cli/app/client'import { fmtList, ok, printError } from '#cli/format'const io = new IORegistry(BUILTIN_IO_FORMATS)diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.tsindex 5c24936c4..7af733af0 100644--- a/packages/cli/src/commands/info.ts+++ b/packages/cli/src/commands/info.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import type { InfoResult } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { bold, fmtHistogram, fmtSummary, kv } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/node.ts b/packages/cli/src/commands/node.tsindex 2fd1bbf23..339516884 100644--- a/packages/cli/src/commands/node.ts+++ b/packages/cli/src/commands/node.ts@@ -4,7 +4,7 @@ import type { NodeResult } from '@open-pencil/core/rpc'import { colorToHex } from '@open-pencil/scene-graph/color'import type { Color } from '@open-pencil/scene-graph/primitives'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { fmtNode, printError, formatType } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/pages.ts b/packages/cli/src/commands/pages.tsindex 2433b03f1..d4cbf3ab2 100644--- a/packages/cli/src/commands/pages.ts+++ b/packages/cli/src/commands/pages.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import type { PageItem } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { bold, fmtList, entity } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/query.ts b/packages/cli/src/commands/query.tsindex 1327f9e9a..d529d1168 100644--- a/packages/cli/src/commands/query.ts+++ b/packages/cli/src/commands/query.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import type { QueryNodeResult } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { printNodeResults, printError } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/selection.ts b/packages/cli/src/commands/selection.tsindex 55a82d6d5..02e115160 100644--- a/packages/cli/src/commands/selection.ts+++ b/packages/cli/src/commands/selection.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'-import { rpc } from '#cli/app-client'-import { appTargetOptions, appTargetRPCArgs } from '#cli/app-target'+import { rpc } from '#cli/app/client'+import { appTargetOptions, appTargetRPCArgs } from '#cli/app/target'import { bold, entity, fmtList, formatType, printError } from '#cli/format'interface SelectionNode {diff --git a/packages/cli/src/commands/settings.ts b/packages/cli/src/commands/settings.tsnew file mode 100644index 000000000..0e52e647b--- /dev/null+++ b/packages/cli/src/commands/settings.ts@@ -0,0 +1,103 @@+import { defineCommand } from 'citty'+import { flattenObject } from 'es-toolkit'++import { rpc } from '#cli/app/client'+import { bold, kv, ok, printError } from '#cli/format'++type Settings = Record<string, unknown>++const json = { type: 'boolean', description: 'Output as JSON' } as const++function readPath(settings: Settings, key: string): unknown {+ let value: unknown = settings+ for (const part of key.split('.')) {+ if (!value || typeof value !== 'object' || !Object.hasOwn(value, part)) {+ throw new Error(`Unknown setting "${key}"`)+ }+ value = (value as Settings)[part]+ }+ return value+}++/** `editing.snapping.objects` + `false` → `{ editing: { snapping: { objects: false } } }`. */+function patchFor(key: string, value: unknown): Settings {+ return key+ .split('.')+ .reduceRight<unknown>((inner, part) => ({ [part]: inner }), value) as Settings+}++// Values are JSON when they parse (`false`, `50`, `"auto"`), plain strings otherwise (`light`).+function parseValue(raw: string): unknown {+ try {+ return JSON.parse(raw)+ } catch {+ return raw+ }+}++function printSettings(settings: Settings): void {+ for (const [key, value] of Object.entries(flattenObject(settings))) {+ console.log(kv(key, value))+ }+}++const get = defineCommand({+ meta: { description: 'Show editor settings, or one setting by dotted key' },+ args: {+ key: { type: 'positional', description: 'Dotted key, e.g. appearance.theme', required: false },+ json+ },+ async run({ args }) {+ try {+ const { settings } = await rpc<{ settings: Settings }>('get_settings')+ const value = args.key ? readPath(settings, args.key) : settings+ if (args.json) {+ console.log(JSON.stringify(value, null, 2))+ } else if (value && typeof value === 'object') {+ printSettings(value as Settings)+ } else {+ console.log(String(value))+ }+ } catch (error) {+ printError(error)+ process.exit(1)+ }+ }+})++const set = defineCommand({+ meta: { description: 'Change one editor setting by dotted key' },+ args: {+ key: {+ type: 'positional',+ description: 'Dotted key, e.g. editing.snapping.pixelGrid',+ required: true+ },+ value: {+ type: 'positional',+ description: 'New value, e.g. false, 100, or light',+ required: true+ },+ json+ },+ async run({ args }) {+ try {+ const { settings } = await rpc<{ settings: Settings }>('update_settings', {+ settings: patchFor(args.key, parseValue(args.value))+ })+ if (args.json) {+ console.log(JSON.stringify(settings, null, 2))+ return+ }+ console.log(ok(`${bold(args.key)} = ${JSON.stringify(readPath(settings, args.key))}`))+ } catch (error) {+ printError(error)+ process.exit(1)+ }+ }+})++export default defineCommand({+ meta: { description: 'Read and change editor settings in the running app' },+ subCommands: { get, set }+})diff --git a/packages/cli/src/commands/tool.ts b/packages/cli/src/commands/tool.tsnew file mode 100644index 000000000..91b4c2536--- /dev/null+++ b/packages/cli/src/commands/tool.ts@@ -0,0 +1,173 @@+// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.+import { toJsonSchema as toJSONSchema } from '@valibot/to-json-schema'+import { defineCommand } from 'citty'+import * as v from 'valibot'++import {+ ALL_TOOLS,+ isToolExposed,+ toolChangesDocument,+ type ToolDef+} from '@open-pencil/core/tools'++import { appTargetOptions } from '#cli/app/target'+import { bold, dim, entity, fmtList, kv, printError, warn } from '#cli/format'+import { documentWriteOptions, writeFigDocument } from '#cli/headless'+import { readTextSource } from '#cli/input'+import { runToolData } from '#cli/tool-data'++const json = { type: 'boolean', description: 'Output as JSON' } as const++const toolArgsSchema = v.record(v.string(), v.unknown())++// The running app accepts the same tools as MCP, so the CLI lists and calls that set.+const TOOLS = ALL_TOOLS.filter((def) => isToolExposed(def, 'mcp'))++function findTool(name: string): ToolDef {+ const def = TOOLS.find((candidate) => candidate.name === name)+ if (!def) throw new Error(`Unknown tool "${name}". Run \`openpencil tool list\` to see tools.`)+ return def+}++function effectOf(def: ToolDef): 'read' | 'write' {+ return toolChangesDocument(def) ? 'write' : 'read'+}++function summaryOf(def: ToolDef): string {+ return def.description.split(/(?<=\.)\s/)[0] ?? def.description+}++const list = defineCommand({+ meta: { description: 'List the tools available to `tool call`' },+ args: { json },+ run({ args }) {+ if (args.json) {+ const rows = TOOLS.map((def) => ({+ name: def.name,+ effect: effectOf(def),+ description: def.description+ }))+ console.log(JSON.stringify(rows, null, 2))+ return+ }+ console.log('')+ console.log(bold(` ${TOOLS.length} tools`))+ console.log('')+ console.log(+ fmtList(+ TOOLS.map((def) => ({+ header: `${def.name} ${dim(`[${effectOf(def)}]`)}`,+ details: { about: summaryOf(def) }+ })),+ { compact: true }+ )+ )+ console.log('')+ }+})++const describe = defineCommand({+ meta: { description: "Show a tool's description and JSON Schema for its arguments" },+ args: {+ name: { type: 'positional', description: 'Tool name', required: true },+ json+ },+ run({ args }) {+ try {+ const def = findTool(args.name)+ const schema = toJSONSchema(def.input, { errorMode: 'ignore' })+ if (args.json) {+ const info = { name: def.name, effect: effectOf(def), description: def.description, schema }+ console.log(JSON.stringify(info, null, 2))+ return+ }+ const header = entity('tool', def.name)+ console.log('')+ console.log(fmtList([{ header, details: { effect: effectOf(def), about: def.description } }]))+ console.log('')+ console.log(bold(' Arguments (JSON Schema)'))+ console.log(JSON.stringify(schema, null, 2))+ console.log('')+ } catch (error) {+ printError(error)+ process.exit(1)+ }+ }+})++async function readToolArgs(args: {+ args?: string+ 'args-file'?: string+}): Promise<Record<string, unknown>> {+ const source = args['args-file'] ? await readTextSource(args['args-file']) : args.args+ if (!source) return {}+ const value: unknown = JSON.parse(source)+ // Valibot records accept arrays as index-keyed objects; tools never take them.+ const parsed = v.safeParse(toolArgsSchema, value)+ if (Array.isArray(value) || !parsed.success)+ throw new Error('Tool arguments must be a JSON object')+ return parsed.output+}++function printResult(result: unknown): void {+ const binary = result as { base64?: unknown; mimeType?: unknown } | null+ if (binary && typeof binary.base64 === 'string' && typeof binary.mimeType === 'string') {+ const bytes = Math.floor((binary.base64.length * 3) / 4)+ console.log(kv(binary.mimeType, `${bytes} bytes; use openpencil export to write files`))+ return+ }+ console.log(JSON.stringify(result, null, 2))+}++const call = defineCommand({+ meta: {+ description: 'Run one tool against the running app, or headlessly against a document file'+ },+ args: {+ name: { type: 'positional', description: 'Tool name from `tool list`', required: true },+ file: {+ type: 'positional',+ description: 'Document file path (omit to connect to running app)',+ required: false+ },+ args: { type: 'string', description: 'Tool arguments as a JSON object' },+ 'args-file': {+ type: 'string',+ description: 'Read tool arguments from a JSON file, or - for stdin'+ },+ ...documentWriteOptions,+ ...appTargetOptions,+ json+ },+ async run({ args }) {+ try {+ if (!args.file && (args.write || args.output)) {+ throw new Error(+ '--write and --output need a document file; in the running app, use `openpencil documents save`'+ )+ }+ const def = findTool(args.name)+ const toolArgs = await readToolArgs(args)+ const { result, graph } = await runToolData(args.file, def.name, toolArgs, args)+ if (args.json) console.log(JSON.stringify(result, null, 2))+ else printResult(result)++ const outPath = args.output || (args.write ? args.file : undefined)+ if (!graph || !toolChangesDocument(def)) return+ if (outPath) {+ await writeFigDocument(graph, outPath)+ if (!args.json) console.error(dim(`Written to ${outPath}`))+ } else if (!args.json) {+ console.error(warn('Changes were not saved; pass --write or --output'))+ }+ } catch (error) {+ printError(error)+ process.exit(1)+ }+ }+})++export default defineCommand({+ meta: { description: 'List, describe, and call editor tools (the same set MCP exposes)' },+ subCommands: { list, describe, call }+})diff --git a/packages/cli/src/commands/tree.ts b/packages/cli/src/commands/tree.tsindex 15ad09534..c82a915bb 100644--- a/packages/cli/src/commands/tree.ts+++ b/packages/cli/src/commands/tree.ts@@ -3,7 +3,7 @@ import { defineCommand } from 'citty'import type { TreeNodeResult, TreeResult } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { fmtTree, printError, entity, formatType } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/commands/variables.ts b/packages/cli/src/commands/variables.tsindex 679f66bcd..055164e46 100644--- a/packages/cli/src/commands/variables.ts+++ b/packages/cli/src/commands/variables.ts@@ -2,7 +2,7 @@ import { defineCommand } from 'citty'import type { VariablesResult } from '@open-pencil/core/rpc'-import { appTargetOptions } from '#cli/app-target'+import { appTargetOptions } from '#cli/app/target'import { bold, entity, fmtList, fmtSummary } from '#cli/format'import { loadRPCData } from '#cli/rpc-data'diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 0bf6f3dbc..7b6b4dcb1 100755--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -10,6 +10,7 @@ import exportCmd from './commands/export'import find from './commands/find'import fonts from './commands/fonts'import formats from './commands/formats'+import { redo, undo } from './commands/history'import importCmd from './commands/import'import info from './commands/info'import libraries from './commands/libraries'@@ -18,6 +19,8 @@ import node from './commands/node'import pages from './commands/pages'import query from './commands/query'import selection from './commands/selection'+import settings from './commands/settings'+import tool from './commands/tool'import tree from './commands/tree'import variables from './commands/variables'@@ -26,7 +29,8 @@ const { version } = await import('../package.json')const main = defineCommand({meta: {name: 'openpencil',- description: 'OpenPencil CLI — inspect, export, and lint OpenPencil design documents',+ description:+ 'OpenPencil CLI — inspect, export, and lint design documents, and drive the running app',version},subCommands: {@@ -46,8 +50,12 @@ const main = defineCommand({query,node,pages,+ redo,selection,+ settings,+ tool,tree,+ undo,variables}})diff --git a/packages/cli/src/input.ts b/packages/cli/src/input.tsnew file mode 100644index 000000000..dcbade08c--- /dev/null+++ b/packages/cli/src/input.ts@@ -0,0 +1,9 @@+import { readFile } from 'node:fs/promises'++/** Read a text file, or standard input when the source is `-`. */+export async function readTextSource(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')+}diff --git a/packages/cli/src/rpc-data.ts b/packages/cli/src/rpc-data.tsindex 0efdc8d95..26ad0610d 100644--- a/packages/cli/src/rpc-data.ts+++ b/packages/cli/src/rpc-data.ts@@ -1,7 +1,7 @@import { executeRPCCommand } from '@open-pencil/core/rpc'-import { isAppMode, requireFile, rpc } from '#cli/app-client'-import { appTargetRPCArgs, type AppTargetCLIArgs } from '#cli/app-target'+import { isAppMode, requireFile, rpc } from '#cli/app/client'+import { appTargetRPCArgs, type AppTargetCLIArgs } from '#cli/app/target'import { loadDocument, prepareDocumentForRPC } from '#cli/headless'type RPCArgs = { [key: string]: unknown }diff --git a/packages/cli/src/tool-data.ts b/packages/cli/src/tool-data.tsindex 562d16cbf..145bb6ea9 100644--- a/packages/cli/src/tool-data.ts+++ b/packages/cli/src/tool-data.ts@@ -7,8 +7,8 @@ import {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 { 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. */diff --git a/packages/cli/tests/commands/app.test.ts b/packages/cli/tests/commands/app.test.tsnew file mode 100644index 000000000..67b59bca7--- /dev/null+++ b/packages/cli/tests/commands/app.test.ts@@ -0,0 +1,153 @@+import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from 'bun:test'+import { mkdtemp, writeFile } from 'node:fs/promises'+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'++import { CLI_ENTRY } from '#cli-tests/helpers/paths'++setDefaultTimeout(60_000)++const TOKEN = 'cli-app-test-token'+const TARGET = {+ documentId: 'doc-2',+ documentName: 'Landing',+ pageId: '0:1',+ pageName: 'Page 1'+}++type Request = { command: string; args: Record<string, unknown> }++const requests: Request[] = []+const responses = new Map<string, unknown>()+let server: Server+let discoveryPath: string++beforeAll(async () => {+ server = createServer((request, response) => {+ let body = ''+ request.on('data', (chunk: Buffer) => {+ body += chunk.toString()+ })+ request.on('end', () => {+ const parsed = JSON.parse(body) as Request+ requests.push(parsed)+ response.writeHead(200, { 'Content-Type': 'application/json' })+ response.end(+ JSON.stringify({ ok: true, result: responses.get(parsed.command) ?? {}, target: TARGET })+ )+ })+ })+ await new Promise<void>((done) => {+ server.listen(0, '127.0.0.1', done)+ })+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-cli-app-'))+ discoveryPath = join(dir, 'discovery.json')+ await writeFile(+ discoveryPath,+ JSON.stringify({+ pid: process.pid,+ socketPath: join(dir, 'missing.sock'),+ httpPort: (server.address() as AddressInfo).port,+ authRequired: true,+ authToken: TOKEN,+ version: '0.0.0-test',+ startedAt: new Date().toISOString()+ })+ )+})++afterAll(() => {+ server.close()+})++beforeEach(() => {+ requests.length = 0+ responses.clear()+})++async function cli(args: string[]) {+ const proc = Bun.spawn([process.execPath, CLI_ENTRY, ...args], {+ stdout: 'pipe',+ stderr: 'pipe',+ env: { ...process.env, OPENPENCIL_MCP_DISCOVERY_PATH: discoveryPath }+ })+ 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('documents CLI', () => {+ test('opens files by absolute path and reports the target document', async () => {+ const opened = await cli(['documents', 'open', 'designs/landing.fig', '--json'])+ expect(opened.exitCode).toBe(0)+ expect(requests).toEqual([+ { command: 'open_file', args: { path: resolve('designs/landing.fig') } }+ ])+ expect(JSON.parse(opened.stdout)).toEqual({ result: {}, target: TARGET })+ })++ test('saves, closes, and activates a targeted document', async () => {+ await cli(['documents', 'save', '--document-id', 'doc-2', '--path', 'out.fig'])+ await cli(['documents', 'close', '--document-id', 'doc-2', '--discard'])+ await cli(['documents', 'activate', 'doc-2', '--page-id', '0:1'])+ expect(requests).toEqual([+ { command: 'save_file', args: { document_id: 'doc-2', path: resolve('out.fig') } },+ { command: 'close_file', args: { document_id: 'doc-2', unsaved: 'discard' } },+ { command: 'activate_document', args: { document_id: 'doc-2', page_id: '0:1' } }+ ])+ })++ test('close --save forwards the save choice and an absolute path', async () => {+ await cli(['documents', 'close', '--save', '--path', 'draft.fig'])+ expect(requests).toEqual([+ { command: 'close_file', args: { unsaved: 'save', path: resolve('draft.fig') } }+ ])+ const both = await cli(['documents', 'close', '--save', '--discard'])+ expect(both.exitCode).toBe(1)+ })+})++describe('history CLI', () => {+ test('reports the undone change', async () => {+ responses.set('undo', { applied: true, label: 'Agent: set_opacity' })+ const undone = await cli(['undo', '--document-id', 'doc-2'])+ expect(undone.exitCode).toBe(0)+ expect(undone.stdout).toContain('Undid: Agent: set_opacity')+ expect(requests).toEqual([{ command: 'undo', args: { document_id: 'doc-2' } }])+ })+})++describe('settings CLI', () => {+ test('sets a dotted key as a nested patch with a JSON or string value', async () => {+ responses.set('update_settings', {+ settings: { appearance: { theme: 'light' }, editing: { snapping: { pixelGrid: false } } }+ })+ await cli(['settings', 'set', 'editing.snapping.pixelGrid', 'false'])+ const theme = await cli(['settings', 'set', 'appearance.theme', 'light'])+ expect(theme.exitCode).toBe(0)+ expect(requests).toEqual([+ {+ command: 'update_settings',+ args: { settings: { editing: { snapping: { pixelGrid: false } } } }+ },+ { command: 'update_settings', args: { settings: { appearance: { theme: 'light' } } } }+ ])+ })++ test('reads one setting by dotted key and rejects unknown keys', async () => {+ responses.set('get_settings', { settings: { appearance: { theme: 'auto' } } })+ const theme = await cli(['settings', 'get', 'appearance.theme'])+ expect(theme.stdout).toBe('auto')++ const inherited = await cli(['settings', 'get', 'appearance.constructor'])+ expect(inherited.exitCode).toBe(1)++ const missing = await cli(['settings', 'get', 'appearance.font'])+ expect(missing.exitCode).toBe(1)+ expect(missing.stderr).toContain('Unknown setting "appearance.font"')+ })+})diff --git a/packages/cli/tests/commands/tool.test.ts b/packages/cli/tests/commands/tool.test.tsnew file mode 100644index 000000000..54999cde8--- /dev/null+++ b/packages/cli/tests/commands/tool.test.ts@@ -0,0 +1,69 @@+import { describe, expect, setDefaultTimeout, test } from 'bun:test'+import { mkdtemp } 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')++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('tool CLI', () => {+ test('lists and describes tools with their effect and argument schema', async () => {+ const listed = await cli(['tool', 'list', '--json'])+ expect(listed.exitCode).toBe(0)+ const tools = JSON.parse(listed.stdout) as Array<{ name: string; effect: string }>+ expect(tools).toContainEqual(expect.objectContaining({ name: 'set_fill', effect: 'write' }))+ expect(tools).toContainEqual(expect.objectContaining({ name: 'list_pages', effect: 'read' }))++ const described = await cli(['tool', 'describe', 'create_page', '--json'])+ expect(described.exitCode).toBe(0)+ const info = JSON.parse(described.stdout) as { schema: { properties: object } }+ expect(info.schema.properties).toHaveProperty('name')+ })++ test('calls a write tool headlessly and saves the result with --output', async () => {+ const outPath = join(await mkdtemp(join(tmpdir(), 'open-pencil-tool-')), 'out.fig')+ const created = await cli([+ 'tool',+ 'call',+ 'create_page',+ FIXTURE,+ '--args',+ '{"name":"From CLI"}',+ '--output',+ outPath,+ '--json'+ ])+ expect(created.exitCode).toBe(0)+ expect(JSON.parse(created.stdout)).toMatchObject({ name: 'From CLI' })++ const pages = await cli(['tool', 'call', 'list_pages', outPath, '--json'])+ const result = JSON.parse(pages.stdout) as { pages: Array<{ name: string }> }+ expect(result.pages.map((page) => page.name)).toContain('From CLI')+ })++ test('rejects unknown tools and non-object arguments', async () => {+ const unknown = await cli(['tool', 'call', 'not_a_tool', FIXTURE])+ expect(unknown.exitCode).toBe(1)+ expect(unknown.stderr + unknown.stdout).toContain('Unknown tool "not_a_tool"')++ const appWrite = await cli(['tool', 'call', 'create_page', '--output', 'out.fig'])+ expect(appWrite.exitCode).toBe(1)+ expect(appWrite.stderr).toContain('--write and --output need a document file')++ const badArgs = await cli(['tool', 'call', 'list_pages', FIXTURE, '--args', '[1]'])+ expect(badArgs.exitCode).toBe(1)+ expect(badArgs.stderr + badArgs.stdout).toContain('Tool arguments must be a JSON object')+ })+})diff --git a/packages/core/src/tools/schema.ts b/packages/core/src/tools/schema.tsindex f6967124c..c82ac379a 100644--- a/packages/core/src/tools/schema.ts+++ b/packages/core/src/tools/schema.ts@@ -18,6 +18,8 @@ export type ToolCapability =| 'filesystem:write'| 'network:access'| 'code:execute'+ | 'settings:read'+ | 'settings:write'export type ToolExecution =| { kind: 'sync'; mutation: 'none' | 'view' | 'properties' | 'document' }diff --git a/packages/docs/.vitepress/labels.ts b/packages/docs/.vitepress/labels.tsindex 93ed24399..a3cd12534 100644--- a/packages/docs/.vitepress/labels.ts+++ b/packages/docs/.vitepress/labels.ts@@ -32,6 +32,7 @@ export interface ProgrammableLabels {exporting: stringanalyzing: stringcomparing: string+ appControl: stringscripting: stringjsxRenderer: stringmcpServer: string@@ -56,6 +57,7 @@ export const EN_PROG: ProgrammableLabels = {exporting: 'Exporting',analyzing: 'Analyzing Designs',comparing: 'Comparing Designs',+ appControl: 'Controlling the App',scripting: 'Scripting',jsxRenderer: 'JSX Renderer',mcpServer: 'MCP Server',@@ -69,6 +71,7 @@ export const DE_PROG: ProgrammableLabels = {exporting: 'Exportieren',analyzing: 'Designs analysieren',comparing: 'Designs vergleichen',+ appControl: 'App steuern',scripting: 'Skripte',jsxRenderer: 'JSX-Renderer',mcpServer: 'MCP-Server',@@ -82,6 +85,7 @@ export const IT_PROG: ProgrammableLabels = {exporting: 'Esportazione',analyzing: 'Analisi design',comparing: 'Confronto dei design',+ appControl: 'Controllare l’app',scripting: 'Scripting',jsxRenderer: 'Renderer JSX',mcpServer: 'Server MCP',@@ -95,6 +99,7 @@ export const FR_PROG: ProgrammableLabels = {exporting: 'Exporter',analyzing: 'Analyser les designs',comparing: 'Comparer des designs',+ appControl: 'Piloter l’application',scripting: 'Scripts',jsxRenderer: 'Moteur JSX',mcpServer: 'Serveur MCP',@@ -108,6 +113,7 @@ export const ES_PROG: ProgrammableLabels = {exporting: 'Exportar',analyzing: 'Analizar diseños',comparing: 'Comparar diseños',+ appControl: 'Controlar la app',scripting: 'Scripts',jsxRenderer: 'Renderizador JSX',mcpServer: 'Servidor MCP',@@ -121,6 +127,7 @@ export const PL_PROG: ProgrammableLabels = {exporting: 'Eksportowanie',analyzing: 'Analiza projektów',comparing: 'Porównywanie projektów',+ appControl: 'Sterowanie aplikacją',scripting: 'Skrypty',jsxRenderer: 'Renderer JSX',mcpServer: 'Serwer MCP',@@ -134,6 +141,7 @@ export const RU_PROG: ProgrammableLabels = {exporting: 'Экспорт',analyzing: 'Анализ дизайна',comparing: 'Сравнение дизайнов',+ appControl: 'Управление приложением',scripting: 'Скрипты',jsxRenderer: 'JSX-рендерер',mcpServer: 'MCP-сервер',diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.tsindex b929c7d27..67b92e1fb 100644--- a/packages/docs/.vitepress/sidebars.ts+++ b/packages/docs/.vitepress/sidebars.ts@@ -65,6 +65,7 @@ export const programmableSidebar = ({ 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.appControl, link: '/programmable/cli/app-control' },{ 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/de/programmable/cli/inspecting.md b/packages/docs/de/programmable/cli/inspecting.mdindex 1fd046e9a..e6f7373fb 100644--- a/packages/docs/de/programmable/cli/inspecting.md+++ b/packages/docs/de/programmable/cli/inspecting.md@@ -54,11 +54,11 @@ openpencil variables design.fig## Geöffnetes Dokument```sh-openpencil documents+openpencil documents listopenpencil tree --document-id tab-123 --page-id 0:1```-Für automatisierte Abläufe zuerst `openpencil documents --json` aufrufen und anschließend `--document-id` und `--page-id` ausdrücklich übergeben.+Für automatisierte Abläufe zuerst `openpencil documents list --json` aufrufen und anschließend `--document-id` und `--page-id` ausdrücklich übergeben. Dokumente öffnen, speichern, wechseln und schließen, Rückgängig machen, Einstellungen ändern und beliebige Editor-Werkzeuge aufrufen: siehe [Controlling the App](/programmable/cli/app-control).## Qualitätsprüfungdiff --git a/packages/docs/pl/programmable/cli/inspecting.md b/packages/docs/pl/programmable/cli/inspecting.mdindex 01b9d2fc5..481f3f182 100644--- a/packages/docs/pl/programmable/cli/inspecting.md+++ b/packages/docs/pl/programmable/cli/inspecting.md@@ -83,13 +83,13 @@ openpencil variables design.figJeśli aplikacja komputerowa jest uruchomiona, nie podawaj ścieżki pliku. CLI połączy się przez RPC z otwartym dokumentem:```sh-openpencil documents+openpencil documents listopenpencil treeopenpencil tree --document-id tab-123 --page-id 0:1openpencil eval --document-id tab-123 --page-id 0:1 -c "..."```-W procesach automatycznych najpierw wywołaj `openpencil documents --json`, a potem jawnie przekazuj `--document-id` i `--page-id`.+W procesach automatycznych najpierw wywołaj `openpencil documents list --json`, a potem jawnie przekazuj `--document-id` i `--page-id`. Otwieranie, zapisywanie, przełączanie i zamykanie dokumentów, cofanie zmian, ustawienia i wywoływanie dowolnych narzędzi edytora opisuje [Controlling the App](/programmable/cli/app-control).## Kontrola jakościdiff --git a/packages/docs/programmable/cli/app-control.md b/packages/docs/programmable/cli/app-control.mdnew file mode 100644index 000000000..6ead078cd--- /dev/null+++ b/packages/docs/programmable/cli/app-control.md@@ -0,0 +1,112 @@+---+title: Controlling the App+description: Open, save, switch, and close documents, undo and redo, change settings, and call any editor tool in the running app from the CLI.+---++# Controlling the App++While the desktop app is running, the CLI drives it over the same automation bridge as the [MCP server](/programmable/mcp-server). Every command on this page except headless `tool call` needs the running app.++## Documents++Each open tab is a document with a stable ID. List them, then pass `--document-id` (and `--page-id`) to aim a command at a background tab without switching to it:++```sh+openpencil documents list --json+openpencil tree --document-id tab-123 --page-id 0:1+```++Open, create, save, and close documents:++```sh+openpencil documents open designs/landing.fig # opens in a new tab+openpencil documents new --path designs/draft.fig # empty document, saved to the path+openpencil documents save --document-id tab-123+openpencil documents save --document-id tab-123 --path designs/copy.fig+openpencil documents close --document-id tab-123+openpencil documents close --document-id tab-123 --save # or --discard+```++Relative paths resolve against the shell's working directory. These commands never open a dialog in the app, because nobody may be there to answer it. Closing a document with unsaved changes fails unless you pass `--save` or `--discard`, and saving a document that has never been saved needs `--path`. Each command prints the document and page it acted on; with `--json` it prints `{ "result", "target" }`, so a script can read the new document's ID from `target.documentId`.++To bring a tab to the front, optionally on a specific page:++```sh+openpencil documents activate tab-123 --page-id 0:4+```++## Undo and redo++Step back through changes made through the CLI and MCP, like **Edit → Undo** and **Edit → Redo**:++```sh+openpencil undo --document-id tab-123+openpencil redo --document-id tab-123 --json+```++```json+{+ "result": { "applied": true, "label": "Set opacity", "scope": "document" },+ "target": { "documentId": "tab-123", "documentName": "Landing", "pageId": "0:1", "pageName": "Page 1" }+}+```++When there is nothing to undo or redo, the command says so and `result.applied` is `false`.++The editor has one history, shared by you and every automation client, so **Edit → Undo** in the app steps back through any change, newest first. Automation is narrower: `undo` and `redo` only act on a step that the CLI or MCP made, and only while it is the newest one. If the newest change was made in the editor, the command fails and leaves it alone, so an agent can't revert your work. They also fail while the document is in vector edit mode, whose history belongs to the editing session.++Each CLI or MCP command that edits the document is one undo step. An `eval` script is recorded against its target page: if it switches `figma.currentPage` and edits another page, those edits are not part of the undo step.++## Settings++Read and change editor settings by dotted key:++```sh+openpencil settings get+openpencil settings get appearance.theme+openpencil settings set appearance.theme light+openpencil settings set editing.snapping.pixelGrid false+openpencil settings set chat.maxAgentSteps 100+```++Values are read as JSON when they parse (`false`, `100`, `"auto"`) and as plain strings otherwise. Invalid keys and values are rejected without changing anything.++| Key | Values |+|-----|--------|+| `appearance.theme` | `dark`, `light`, `auto` |+| `appearance.language` | `en`, `de`, `es`, `fr`, `it`, `ja`, `pl`, `ru`, `zh-CN` |+| `appearance.animations` | `system`, `off` |+| `editing.snapping.geometry` | `true`, `false` |+| `editing.snapping.objects` | `true`, `false` |+| `editing.snapping.pixelGrid` | `true`, `false` |+| `rendering.canvasMode` | `retained`, `tiled` (applies after a reload) |+| `recovery.enabled` | `true`, `false` |+| `chat.reasoningDisplay` | `collapsed`, `while-thinking`, `expanded` |+| `chat.maxAgentSteps` | integer 1–1000 |+| `chat.changePreviewSize` | `off`, `small`, `medium`, `large` |+| `designCheck.showOnCanvas` | `true`, `false` |+| `designCheck.preset` | `recommended`, `strict`, `accessibility` |+| `designCheck.disabledRules` | JSON array of rule IDs, e.g. `["no-default-names"]`; see `openpencil lint --list-rules` |++Credentials, AI models, MCP connections, storage, and tool access are deliberately not available here: an automation client can't read secrets or grant itself access.++## Calling tools++Every editor tool the MCP server exposes is also available from the CLI. List them, inspect a tool's arguments as JSON Schema, and call it with a JSON object:++```sh+openpencil tool list+openpencil tool describe set_fill+openpencil tool call set_fill --args '{"id":"0:5","color":"#2563eb"}'+openpencil tool call set_fill --document-id tab-123 --args-file fill.json+echo '{"name":"Icons"}' | openpencil tool call create_page --args-file -+```++Pass a file to run a tool headlessly instead. Changes to a file are kept only with `--write` (back to the input) or `--output`:++```sh+openpencil tool call create_page design.fig --args '{"name":"Icons"}' --write+openpencil tool call get_page_tree design.fig --json+```++For multi-step edits, [`eval`](./scripting) runs a whole script against the same Figma-compatible API.diff --git a/packages/docs/programmable/cli/inspecting.md b/packages/docs/programmable/cli/inspecting.mdindex 0abc9a9ab..d0e8e48c1 100644--- a/packages/docs/programmable/cli/inspecting.md+++ b/packages/docs/programmable/cli/inspecting.md@@ -160,13 +160,13 @@ openpencil variables design.figWhen the desktop app is running, omit the file argument — the CLI connects via RPC and operates on the live canvas:```sh-openpencil documents # list open document/page IDs+openpencil documents list # list open document/page IDsopenpencil tree # inspect the active live documentopenpencil tree --document-id tab-123 --page-id 0:1openpencil eval --document-id tab-123 --page-id 0:1 -c "..."```-Use `openpencil documents --json` in agent workflows, then pass `--document-id` and `--page-id` explicitly instead of relying on the visible active tab/page.+Use `openpencil documents list --json` in agent workflows, then pass `--document-id` and `--page-id` explicitly instead of relying on the visible active tab/page. To open, save, switch, and close documents, undo, change settings, or call any editor tool, see [Controlling the App](/programmable/cli/app-control).## Lint Designsdiff --git a/packages/docs/programmable/index.md b/packages/docs/programmable/index.mdindex 72eb1de52..11bacf7a7 100644--- a/packages/docs/programmable/index.md+++ b/packages/docs/programmable/index.md@@ -48,9 +48,9 @@ Going the other direction, export any selection back to JSX with Tailwind classeInspect, lint, export, and analyze design documents without opening the editor. List pages, search nodes, extract design tokens, catch layout or accessibility issues, and render to PNG — all from the terminal with machine-readable JSON output.-The CLI also connects to the running desktop app via RPC, so you can script the editor while you're using it.+The CLI also connects to the running desktop app via RPC, so you can script the editor while you're using it: open, save, and switch documents, undo, change settings, and call any MCP tool.-[Inspecting Files](./cli/inspecting) · [Exporting](./cli/exporting) · [Analyzing Designs](./cli/analyzing) · [Scripting](./cli/scripting)+[Inspecting Files](./cli/inspecting) · [Exporting](./cli/exporting) · [Analyzing Designs](./cli/analyzing) · [Scripting](./cli/scripting) · [Controlling the App](./cli/app-control)## MCP Serverdiff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 3d214a234..5bbcbabd3 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -149,7 +149,9 @@ Endpoints are available over both active transports:5. **Modify** — `set_fill`, `set_stroke`, `set_layout`, `update_node`, `set_effects`6. **Structure** — `reparent_node`, `group_nodes`, `clone_node`, `delete_node`7. **Save** — `save_file` to write back to `.fig`-8. **Close** — `close_file` to close an open document tab; it prompts to save unsaved changes.+8. **Close** — `close_file` to close an open document tab. With unsaved changes it fails unless `unsaved` is `"save"` or `"discard"`; it never prompts in the app.++`undo` and `redo` step back through the agent's own changes, and `activate_document` brings a tab to the front when the user should see it.Most tools accept optional `document_id` and `page_id` fields. Pass them explicitly for agent workflows instead of relying on the visible active tab/page. `create_page` only creates a page; call `switch_page` separately when the workflow should change the active page.@@ -172,10 +174,29 @@ OpenPencil currently registers 100+ shared design tools, plus MCP-only document| Tool | Description ||------|-------------|| `open_file` | Open a `.fig` file for editing |-| `close_file` | Close an open document tab, prompting to save unsaved changes |+| `close_file` | Close an open document tab; `unsaved: "save"` or `"discard"` decides what happens to unsaved changes || `save_file` | Save the current document to a `.fig` file || `new_document` | Create a new empty document || `list_documents` | List open app documents/tabs and their pages |+| `activate_document` | Bring a document tab to the front, optionally on a given page |++### History++| Tool | Description |+|------|-------------|+| `undo` | Undo the newest change made through MCP or the CLI |+| `redo` | Redo the newest change undone through MCP or the CLI |++The history is shared with the person in the editor. `undo` and `redo` refuse when the newest step was made in the editor, so an agent never reverts the user's work. Each editing tool call is one undo step. An `eval` script is recorded against its target page, so edits it makes after switching `figma.currentPage` are not undoable.++### Settings++| Tool | Description |+|------|-------------|+| `get_settings` | Read editor settings: appearance, snapping, canvas rendering, recovery, AI chat, and design check preferences |+| `update_settings` | Change settings with a partial object shaped like `get_settings` output; invalid keys and values are rejected |++Settings tools never expose credentials, AI models, MCP connections, storage, or tool access. The available keys are listed in [Controlling the App](/programmable/cli/app-control#settings).### Readdiff --git a/packages/docs/reference/cli.md b/packages/docs/reference/cli.mdindex 9a2f12c5c..9a05fa5d8 100644--- a/packages/docs/reference/cli.md+++ b/packages/docs/reference/cli.md@@ -5,7 +5,7 @@ description: Complete reference for all openpencil commands, options, and flags.# CLI Reference-All commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC.+Document commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. `documents`, `undo`, `redo`, and `settings` always act on the running app.## info@@ -297,3 +297,65 @@ openpencil diff files <before> <after> [options]| `--page` | Compare only the page with this name || `--depth` | Max tree depth below each page (default: unlimited) || `--json` | Output as JSON |++## documents++Manage documents (tabs) in the running app. See [Controlling the App](/programmable/cli/app-control).++```sh+openpencil documents list [--json]+openpencil documents open <file> [--json]+openpencil documents new [--path <file>] [--json]+openpencil documents save [--path <file>] [--document-id <id>] [--json]+openpencil documents close [--save | --discard] [--path <file>] [--document-id <id>] [--json]+openpencil documents activate <document-id> [--page-id <id>] [--json]+```++| Option | Description |+|--------|-------------|+| `--path` | `.fig` path to create or save to; relative to the current directory |+| `--save` | `close`: save unsaved changes first |+| `--discard` | `close`: close without saving; unsaved changes are lost |+| `--document-id` | Target document; defaults to the active tab |+| `--page-id` | Page to switch the activated document to |+| `--json` | Output the result and target document as JSON |++## undo / redo++Undo or redo the newest change made through the CLI or MCP in the running app. Fails when the newest change was made in the editor; see [Controlling the App](/programmable/cli/app-control#undo-and-redo).++```sh+openpencil undo [--document-id <id>] [--json]+openpencil redo [--document-id <id>] [--json]+```++## settings++Read and change editor settings in the running app by dotted key. Values parse as JSON, falling back to plain strings.++```sh+openpencil settings get [key] [--json]+openpencil settings set <key> <value> [--json]+```++See [Controlling the App](/programmable/cli/app-control#settings) for the available keys.++## tool++List, describe, and call the editor tools that the MCP server exposes.++```sh+openpencil tool list [--json]+openpencil tool describe <name> [--json]+openpencil tool call <name> [file] [options]+```++| Option | Alias | Description |+|--------|-------|-------------|+| `--args` | | Tool arguments as a JSON object |+| `--args-file` | | Read arguments from a JSON file, or `-` for stdin |+| `--write` | `-w` | Headless: write changes back to the input file |+| `--output` | `-o` | Headless: write changes to a different file |+| `--document-id` | | App: target document |+| `--page-id` | | App: target page |+| `--json` | | Output as JSON |diff --git a/packages/docs/ru/programmable/cli/inspecting.md b/packages/docs/ru/programmable/cli/inspecting.mdindex ce120cf5e..8674ab702 100644--- a/packages/docs/ru/programmable/cli/inspecting.md+++ b/packages/docs/ru/programmable/cli/inspecting.md@@ -110,13 +110,13 @@ openpencil variables design.figЕсли настольное приложение запущено, не указывайте путь к файлу. CLI подключится по RPC к открытому документу:```sh-openpencil documents+openpencil documents listopenpencil treeopenpencil tree --document-id tab-123 --page-id 0:1openpencil eval --document-id tab-123 --page-id 0:1 -c "..."```-Для автоматизированных процессов сначала вызовите `openpencil documents --json`, а затем явно передавайте `--document-id` и `--page-id`, не полагаясь на видимую активную вкладку или страницу.+Для автоматизированных процессов сначала вызовите `openpencil documents list --json`, а затем явно передавайте `--document-id` и `--page-id`, не полагаясь на видимую активную вкладку или страницу. Как открывать, сохранять, переключать и закрывать документы, отменять изменения, менять настройки и вызывать любые инструменты редактора, описано в [Controlling the App](/programmable/cli/app-control).## Проверка качестваdiff --git a/packages/mcp/src/tool/manifest.ts b/packages/mcp/src/tool/manifest.tsindex 926aac9ea..589006a64 100644--- a/packages/mcp/src/tool/manifest.ts+++ b/packages/mcp/src/tool/manifest.ts@@ -79,12 +79,58 @@ export function createToolDescriptors(filesystemEnabled: boolean): ToolDescripto: []),{name: 'close_file',- description: 'Close an open document tab, prompting to save unsaved changes.',+ description:+ 'Close an open document tab. With unsaved changes it fails unless unsaved is "save" or "discard"; it never prompts in the app.',+ effect: 'write',+ availability: 'default',+ capabilities: ['document:write', 'filesystem:write'],+ enabled: true+ },+ {+ name: 'activate_document',+ description:+ 'Bring an open document tab to the front in the app, optionally switching it to a page.',effect: 'read',availability: 'default',capabilities: ['document:read'],enabled: true},+ {+ name: 'undo',+ description:+ "Undo the newest change made through MCP or the CLI in a document. Fails if the newest change was made in the editor, so the user's work is never reverted.",+ effect: 'write',+ availability: 'default',+ capabilities: ['document:write'],+ enabled: true+ },+ {+ name: 'redo',+ description:+ 'Redo the newest change undone through MCP or the CLI. Fails if the newest undone change was made in the editor.',+ effect: 'write',+ availability: 'default',+ capabilities: ['document:write'],+ enabled: true+ },+ {+ name: 'get_settings',+ description:+ 'Read editor settings: appearance (theme, language, animations), snapping, canvas rendering, recovery, AI chat, and design check preferences.',+ effect: 'read',+ availability: 'default',+ capabilities: ['settings:read'],+ enabled: true+ },+ {+ name: 'update_settings',+ description:+ 'Change editor settings with a partial object shaped like get_settings output. Returns the applied patch. Credentials, models, MCP connections, storage, and tool access are not exposed.',+ effect: 'write',+ availability: 'default',+ capabilities: ['settings:write'],+ enabled: true+ },{name: 'get_codegen_prompt',description:diff --git a/packages/mcp/src/tool/metadata.ts b/packages/mcp/src/tool/metadata.tsindex 8191c5cfe..8988e20bc 100644--- a/packages/mcp/src/tool/metadata.ts+++ b/packages/mcp/src/tool/metadata.ts@@ -33,7 +33,9 @@ const TOOL_CAPABILITIES: ReadonlySet<string> = new Set<ToolCapability>(['filesystem:read','filesystem:write','network:access',- 'code:execute'+ 'code:execute',+ 'settings:read',+ 'settings:write'])export function parseToolDescriptor(value: unknown): ToolDescriptor | null {diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.tsindex a1aae2028..ca465c94e 100644--- a/packages/mcp/src/tool/registration.ts+++ b/packages/mcp/src/tool/registration.ts@@ -37,6 +37,22 @@ function splitAutomationTarget(args: Record<string, unknown>): {return { target, args: rest }}+type RPCResponse = { ok?: boolean; result?: unknown; target?: unknown; error?: string }++async function sendCommand(+ sendRPC: RPCSender,+ command: string,+ args: Record<string, unknown>+): Promise<RPCResponse> {+ const res = (await sendRPC({ command, args })) as RPCResponse+ if (res.ok === false) throw new Error(res.error)+ return res+}++function withTarget<T extends object>(body: T, res: RPCResponse): T & { target?: unknown } {+ return res.target ? { ...body, target: res.target } : body+}+export interface RegisterToolsOptions {policy: ToolPolicymcpRoot?: string | null@@ -60,7 +76,7 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOptionconst descriptors = descriptorByName(createToolDescriptors(resolvedRoot !== null))const register = <InputArgs extends v.GenericSchema>(name: string,- toolOptions: { description: string; inputSchema: InputArgs },+ toolOptions: { description?: string; inputSchema: InputArgs },handler: ToolCallback<ReturnType<typeof toStandardJSONSchema<InputArgs>>>) => {const descriptor = descriptors.get(name)@@ -69,7 +85,7 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOptionmcpServer.registerTool(name,{- ...toolOptions,+ description: toolOptions.description ?? descriptor.description,inputSchema: toStandardJSONSchema(toolOptions.inputSchema),annotations: toolAnnotations(descriptor.effect),_meta: { 'openpencil/capabilities': descriptor.capabilities }@@ -263,28 +279,117 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOption)}+ const closeEntries = {+ unsaved: v.optional(+ v.pipe(+ v.picklist(['error', 'save', 'discard']),+ v.description(+ 'What to do with unsaved changes: "error" (default) fails, "save" saves first, "discard" drops them'+ )+ )+ ),+ ...automationTargetSchema+ }+register('close_file',{- description: 'Close an open document tab, prompting to save unsaved changes.',- inputSchema: v.object({ ...automationTargetSchema })+ inputSchema: resolvedRoot+ ? v.object({+ ...closeEntries,+ path: v.optional(+ v.pipe(+ v.string(),+ v.minLength(1),+ v.description(+ 'With unsaved "save": .fig path for a document never saved, inside the MCP root'+ )+ )+ )+ })+ : v.object(closeEntries)},- async (args: { document_id?: string; page_id?: string }) => {+ async (args: {+ unsaved?: 'error' | 'save' | 'discard'+ path?: string+ document_id?: string+ page_id?: string+ }) => {try {+ const safePath =+ args.path !== undefined && resolvedRoot+ ? await resolveSafePath(args.path, resolvedRoot)+ : undefinedconst { target } = splitAutomationTarget(args)- const result = await sendRPC({ command: 'close_file', args: target })- const res = result as {- ok?: boolean- result?: { closed?: boolean }- target?: unknown- error?: string- }- if (res.ok === false) return fail(new Error(res.error))- const response: { closed: boolean; target?: unknown } = {- closed: res.result?.closed === true- }- if (res.target) response.target = res.target- return ok(response)+ const rpcArgs: Record<string, unknown> = { ...target }+ if (args.unsaved) rpcArgs.unsaved = args.unsaved+ if (safePath) rpcArgs.path = safePath.realPath+ const res = await sendCommand(sendRPC, 'close_file', rpcArgs)+ const closed = (res.result as { closed?: boolean } | undefined)?.closed === true+ return ok(withTarget({ closed }, res))+ } catch (e) {+ return fail(e)+ }+ }+ )++ register(+ 'activate_document',+ {+ inputSchema: v.object({+ document_id: v.pipe(v.string(), v.description('Document/tab ID from list_documents')),+ page_id: automationTargetSchema.page_id+ })+ },+ async (args: { document_id: string; page_id?: string }) => {+ try {+ const { target } = splitAutomationTarget(args)+ const res = await sendCommand(sendRPC, 'activate_document', target)+ return ok(withTarget({ activated: true }, res))+ } catch (e) {+ return fail(e)+ }+ }+ )++ for (const command of ['undo', 'redo'] as const) {+ register(command, { inputSchema: v.object({ ...automationTargetSchema }) }, async (args) => {+ try {+ const { target } = splitAutomationTarget(args)+ const res = await sendCommand(sendRPC, command, target)+ return ok(withTarget({ ...(res.result as RPCJSONObject | undefined) }, res))+ } catch (e) {+ return fail(e)+ }+ })+ }++ register('get_settings', { inputSchema: v.object({}) }, async () => {+ try {+ const res = await sendCommand(sendRPC, 'get_settings', {})+ return ok(res.result ?? {})+ } catch (e) {+ return fail(e)+ }+ })++ register(+ 'update_settings',+ {+ inputSchema: v.object({+ settings: v.pipe(+ v.record(v.string(), v.unknown()),+ v.description(+ 'Partial settings, e.g. {"appearance":{"theme":"light"},"editing":{"snapping":{"pixelGrid":false}}}. Unknown keys and invalid values are rejected.'+ )+ )+ })+ },+ async (args: { settings: Record<string, unknown> }) => {+ try {+ // Echo only the applied patch: with get_settings disabled, writing must not read.+ await sendCommand(sendRPC, 'update_settings', { settings: args.settings })+ return ok({ updated: args.settings })} catch (e) {return fail(e)}diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 0e65d4979..425f5278b 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -60,6 +60,10 @@ Common commands:- `lint` — consistency, structure, and accessibility checks- `formats` — supported document/export formats- `eval` — execute JavaScript with the Figma Plugin API+- `tool` — list, describe, and call any MCP tool from the shell, in app or headless mode+- `documents` — list, open, create, save, close, and activate documents in the running app+- `undo` / `redo` — step back through your own (automation) changes in the running app+- `settings` — read and change editor settings in the running app### Inspect@@ -170,6 +174,29 @@ openpencil diff visual design.fig --from 1:23 --to 1:87 -o diff.pngopenpencil diff files before.fig after.fig # exit 1 when different```+### Control the running app++```bash+openpencil documents list --json # tab IDs, paths, pages+openpencil documents open designs/landing.fig # new tab; --json returns target.documentId+openpencil documents new --path designs/draft.fig+openpencil documents activate tab-123 --page-id 0:4 # bring a tab to the front+openpencil documents save --document-id tab-123+openpencil documents close --document-id tab-123 --save # or --discard; fails on unsaved changes otherwise+openpencil undo --document-id tab-123 # also: redo+openpencil settings get --json+openpencil settings set editing.snapping.pixelGrid false+```++`tool` exposes every MCP tool, so the CLI is never limited to its dedicated commands:++```bash+openpencil tool list+openpencil tool describe set_fill # JSON Schema for the arguments+openpencil tool call set_fill --document-id tab-123 --args '{"id":"0:5","color":"#2563eb"}'+openpencil tool call create_page design.fig --args '{"name":"Icons"}' --write # headless+```+Every command that reports structured data supports `--json` when appropriate.## MCP Server@@ -217,13 +244,15 @@ The CLI defaults the filesystem root to the home directory on Windows and the cu### MCP workflow-1. **Open/create a document** — `open_file { path }` within the effective filesystem root, or `new_document {}`.+1. **Find or open a document** — `list_documents` for open tabs and their IDs; `open_file { path }` within the effective filesystem root, or `new_document {}`. Pass `document_id` and `page_id` explicitly instead of relying on the active tab; `activate_document { document_id }` brings a tab to the front when the user should see it.2. **Query** — `get_page_tree`, `find_nodes`, `query_nodes`, `get_node`, `list_pages`, `get_current_page`.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`.-7. **Close** — `close_file { document_id }` closes a document tab after the workflow; it prompts to save unsaved changes.+7. **Close** — `close_file { document_id, unsaved }` closes a document tab after the workflow. With unsaved changes it fails unless `unsaved` is `"save"` or `"discard"`; automation never prompts in the app.++Use `undo` / `redo { document_id }` to step back your own changes. They refuse when the newest step was made by the user in the editor; never work around that. `get_settings` and `update_settings { settings }` read and change editor preferences such as theme, language, and snapping; they never expose credentials, models, or tool access.### Browser-native WebMCP (experimental)@@ -250,6 +279,8 @@ Discover available tools and their arguments from the connected server or browse- **`export_image` / `export_svg` / `export_pdf`** — visual verification and deliverables.- **`viewport_zoom_to_fit` / `viewport_set` / `viewport_get`** — keep the live editor focused on the created or edited design.- **`get_codegen_prompt`** — retrieve OpenPencil's current JSX/codegen guidance.+- **`undo` / `redo`** — revert or reapply your newest change; they refuse to touch the user's edits.+- **`list_documents` / `activate_document`** — discover open tabs and show the one you worked on.## JSX Rendering@@ -267,6 +298,6 @@ Use the `render` tool for JSX strings. Use only the APIs exposed by the installe- After creating a visible design, select it and zoom the editor to it: `select_nodes { ids: [id] }` then `viewport_zoom_to_fit { id }`.- If zoom-to-fit is unavailable in a client, use `node_bounds` to calculate the center and call `viewport_set { x, y, zoom }`.- Use `analyze colors --similar` to find near-duplicate colors.-- Use `eval` for Figma Plugin API operations not covered by a dedicated CLI/MCP tool.+- Use `openpencil tool call` for MCP tools without a dedicated CLI command, and `eval` for Figma Plugin API operations not covered by any tool.- Use `--json` when piping CLI output to scripts.- In app mode, `eval` and MCP modifications are reflected live in the editor.diff --git a/src/app/ai/acp/design-context.md b/src/app/ai/acp/design-context.mdindex d8ed74794..b9b8979c7 100644--- a/src/app/ai/acp/design-context.md+++ b/src/app/ai/acp/design-context.md@@ -1 +1 @@-You are inside OpenPencil, an open-source design editor (like Figma). Use the open-pencil MCP tools to create and modify designs on the live canvas. Key tools: render (JSX to design), create_shape, set_fill, set_layout, find_nodes, get_page_tree, export_image. The render tool accepts JSX with components: Frame, Text, Rectangle, Ellipse, Icon, Group, Section. Props: w, h, bg, flex, gap, p, rounded, color, size, weight, items, justify, stroke, opacity, shadow. Do NOT write HTML files or use terminal commands — draw directly on the canvas using the MCP tools.+You are inside OpenPencil, an open-source design editor (like Figma). Use the open-pencil MCP tools to create and modify designs on the live canvas. Key tools: render (JSX to design), create_shape, set_fill, set_layout, find_nodes, get_page_tree, export_image. The render tool accepts JSX with components: Frame, Text, Rectangle, Ellipse, Icon, Group, Section. Props: w, h, bg, flex, gap, p, rounded, color, size, weight, items, justify, stroke, opacity, shadow. When several documents are open, call list_documents and pass document_id instead of relying on the active tab. To revert a change, call undo rather than rebuilding the previous state by hand. Do NOT write HTML files or use terminal commands — draw directly on the canvas using the MCP tools.diff --git a/src/app/automation/bridge/app-handlers.ts b/src/app/automation/bridge/app-handlers.tsnew file mode 100644index 000000000..7276edbed--- /dev/null+++ b/src/app/automation/bridge/app-handlers.ts@@ -0,0 +1,55 @@+import type { AutomationTarget } from '@/app/automation/bridge/target'+import { isAutomationUndoLabel } from '@/app/automation/execution/editor'+import { readAutomationSettings, updateAutomationSettings } from '@/app/settings/automation'+import { switchTab } from '@/app/tabs'++export async function handleActivateDocument(+ target: AutomationTarget,+ _args: unknown+): Promise<unknown> {+ switchTab(target.documentId)+ if (target.store.state.currentPageId !== target.pageId) {+ await target.store.switchPage(target.pageId)+ }+ return { ok: true, result: { activated: true } }+}++type HistoryDirection = 'undo' | 'redo'++// The history is shared with the person in the editor, so automation steps back only+// through its own changes, and only while they are on top.+function stepHistory(target: AutomationTarget, direction: HistoryDirection) {+ const store = target.store+ if (store.state.nodeEditState) {+ throw new Error('The document is in vector edit mode; finish editing in the app first')+ }+ const available = direction === 'undo' ? store.undo.canUndo : store.undo.canRedo+ if (!available) return { applied: false, label: null }+ const label = direction === 'undo' ? store.undo.undoLabel : store.undo.redoLabel+ if (!isAutomationUndoLabel(label)) {+ const change = direction === 'undo' ? 'last change' : 'last undone change'+ throw new Error(+ `The ${change}${label ? ` ("${label}")` : ''} was made in the editor, not through automation; ${direction} it there`+ )+ }+ if (direction === 'undo') store.undoAction()+ else store.redoAction()+ return { applied: true, label }+}++export async function handleUndo(target: AutomationTarget, _args: unknown): Promise<unknown> {+ return { ok: true, result: stepHistory(target, 'undo') }+}++export async function handleRedo(target: AutomationTarget, _args: unknown): Promise<unknown> {+ return { ok: true, result: stepHistory(target, 'redo') }+}++export function handleGetSettings(): unknown {+ return { ok: true, result: { settings: readAutomationSettings() } }+}++export function handleUpdateSettings(args: unknown): unknown {+ const settings = (args as { settings?: unknown } | undefined)?.settings+ return { ok: true, result: { settings: updateAutomationSettings(settings ?? {}) } }+}diff --git a/src/app/automation/bridge/eval-handler.ts b/src/app/automation/bridge/eval-handler.tsindex 3f415e430..69e173289 100644--- a/src/app/automation/bridge/eval-handler.ts+++ b/src/app/automation/bridge/eval-handler.ts@@ -2,6 +2,7 @@ import type { FigmaAPI } from '@open-pencil/core/figma-api'import { wrapEvalCode } from '@open-pencil/core/tools'import type { AutomationTarget } from '@/app/automation/bridge/target'+import { automationUndoLabel, executeWithPageUndo } from '@/app/automation/execution/editor'import { ensureGraphFonts } from '@/app/editor/fonts'type FigmaFactory = (store: AutomationTarget['store'], pageId?: string) => FigmaAPI@@ -15,13 +16,20 @@ export function createAutomationEvalHandler(makeFigma: FigmaFactory) {/* noop */}).constructorconst fn = new AsyncFunction('figma', wrapEvalCode(code))- const result = await target.store.runMutationWithLayout(- () => fn(figma),+ const result = await executeWithPageUndo(+ target.store,target.pageId,- async () => {- const page = target.store.graph.getNode(target.pageId)- if (page) await ensureGraphFonts(target.store.graph, page.childIds, target.store.renderer)- }+ automationUndoLabel('eval'),+ () =>+ target.store.runMutationWithLayout(+ () => fn(figma),+ target.pageId,+ async () => {+ const page = target.store.graph.getNode(target.pageId)+ if (page)+ await ensureGraphFonts(target.store.graph, page.childIds, target.store.renderer)+ }+ ))target.store.requestRender()return { ok: true, result: result ?? null }diff --git a/src/app/automation/bridge/file-handlers.ts b/src/app/automation/bridge/file-handlers.tsindex 2f0db5981..d285e8c51 100644--- a/src/app/automation/bridge/file-handlers.ts+++ b/src/app/automation/bridge/file-handlers.ts@@ -1,3 +1,5 @@+import * as v from 'valibot'+import {resolveAutomationTarget,responseWithTarget,@@ -9,16 +11,29 @@ import { openFileFromPath } from '@/app/shell/menu/use'import { closeTab, createTab, getActiveStore, getTabById } from '@/app/tabs'import { isTauri } from '@/app/tauri/env'-export async function handleSaveFile(target: AutomationTarget, args: unknown): Promise<unknown> {- const store = target.store- const path = (args as { path?: string }).path- if (path) {- store.setPlannedFilePath(path)- await ensureTauriParentDirectory(path)+const saveArgsSchema = v.object({ path: v.optional(v.string()) })++const closeArgsSchema = v.object({+ path: v.optional(v.string()),+ unsaved: v.optional(v.picklist(['error', 'save', 'discard']), 'error')+})++// Automation never opens the Save dialog: nobody may be there to answer it.+async function saveWithoutPrompt(store: AutomationTarget['store'], path?: string): Promise<void> {+ const name = store.state.documentName+ if (!path && !store.hasWritableSource()) {+ throw new Error(`"${name}" has not been saved to a file yet; pass a path to save it`)}- await store.saveFigFile()- if (path) store.startWatchingCurrentFile()- return { ok: true }+ if (path) await ensureTauriParentDirectory(path)+ // A failed save to a new path leaves the document with the source it had.+ const saved = path ? await store.saveFigFileToPath(path) : await store.saveFigFile()+ if (!saved) throw new Error(`Could not save "${name}"`)+}++export async function handleSaveFile(target: AutomationTarget, args: unknown): Promise<unknown> {+ const { path } = v.parse(saveArgsSchema, args)+ await saveWithoutPrompt(target.store, path)+ return { ok: true, result: { saved: true } }}export async function ensureTauriParentDirectory(path: string): Promise<void> {@@ -32,8 +47,19 @@ export async function ensureTauriParentDirectory(path: string): Promise<void> {await mkdir(dir, { recursive: true })}-export async function handleCloseFile(target: AutomationTarget, _args: unknown): Promise<unknown> {- await closeTab(target.documentId)+export async function handleCloseFile(target: AutomationTarget, args: unknown): Promise<unknown> {+ const { path, unsaved } = v.parse(closeArgsSchema, args)+ const store = target.store+ if (store.hasUnsavedChanges()) {+ if (unsaved === 'error') {+ throw new Error(+ `"${store.state.documentName}" has unsaved changes. ` ++ 'Save or discard them: CLI --save or --discard, MCP unsaved "save" or "discard"'+ )+ }+ if (unsaved === 'save') await saveWithoutPrompt(store, path)+ }+ await closeTab(target.documentId, unsaved === 'discard' ? 'discard' : 'save')return { ok: true, result: { closed: getTabById(target.documentId) === undefined } }}@@ -41,13 +67,15 @@ export async function handleNewDocument(_target: AutomationTarget,args: unknown): Promise<unknown> {- const path = (args as { path?: string }).path+ const { path } = v.parse(saveArgsSchema, args)const tab = createTab()if (path) {- tab.store.setPlannedFilePath(path)- await ensureTauriParentDirectory(path)- await tab.store.saveFigFile()- tab.store.startWatchingCurrentFile()+ try {+ await saveWithoutPrompt(tab.store, path)+ } catch (error) {+ await closeTab(tab.id, 'discard')+ throw error+ }}const target = resolveAutomationTarget(tab.store, { document_id: tab.id })return responseWithTarget({ ok: true, result: { created: true } }, target)diff --git a/src/app/automation/bridge/handlers.ts b/src/app/automation/bridge/handlers.tsindex e99002951..5757f2818 100644--- a/src/app/automation/bridge/handlers.ts+++ b/src/app/automation/bridge/handlers.ts@@ -1,5 +1,12 @@import type { FigmaAPI } from '@open-pencil/core/figma-api'+import {+ handleActivateDocument,+ handleGetSettings,+ handleRedo,+ handleUndo,+ handleUpdateSettings+} from '@/app/automation/bridge/app-handlers'import { createAutomationEvalHandler } from '@/app/automation/bridge/eval-handler'import { handleExport, handleExportJSX } from '@/app/automation/bridge/export-handlers'import {@@ -39,7 +46,10 @@ export function createAutomationCommandHandlers(makeFigma: FigmaFactory) {save_file: handleSaveFile,close_file: handleCloseFile,new_document: handleNewDocument,- open_file: handleOpenFile+ open_file: handleOpenFile,+ activate_document: handleActivateDocument,+ undo: handleUndo,+ redo: handleRedo}/** Runs a command on a resolved document page, loading the page first if it was never shown. */@@ -66,6 +76,8 @@ export function createAutomationCommandHandlers(makeFigma: FigmaFactory) {if (command === 'list_documents') {return { ok: true, result: { documents: listAutomationDocuments(store) } }}+ if (command === 'get_settings') return handleGetSettings()+ if (command === 'update_settings') return handleUpdateSettings(args)if (command === 'open_file' || command === 'new_document') {const handler = commandHandlers[command]diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.tsindex e655b5a65..c23672d65 100644--- a/src/app/automation/bridge/tool-handlers.ts+++ b/src/app/automation/bridge/tool-handlers.ts@@ -4,12 +4,18 @@ import {ALL_TOOLS,registerComponentCatalog,isAtomicTool,- isToolExposed+ isToolExposed,+ toolChangesDocument} from '@open-pencil/core/tools'import type { JSONObject } from '@open-pencil/scene-graph/primitives'import type { AutomationTarget } from '@/app/automation/bridge/target'-import { executeAtomicEditorTool } from '@/app/automation/execution/editor'+import {+ AUTOMATION_UNDO_LABEL,+ automationUndoLabel,+ executeAtomicEditorTool,+ executeWithPageUndo+} from '@/app/automation/execution/editor'import { ensureGraphFonts } from '@/app/editor/fonts'import { useLibraryService } from '@/app/libraries'@@ -22,17 +28,22 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {): Promise<unknown> {const store = target.storeconst tree = toolArgs.tree as Parameters<typeof renderTree>[1]- const result = await store.runMutationWithLayout(- () =>- renderTree(store.graph, tree, {- parentId: (toolArgs.parent_id as string | undefined) ?? target.pageId,- x: toolArgs.x as number | undefined,- y: toolArgs.y as number | undefined- }),- target.pageId,- async (node) => {- await ensureGraphFonts(store.graph, [node.id], store.renderer)- }+ const parentId = (toolArgs.parent_id as string | undefined) ?? target.pageId+ // A parent on another page puts the new layers there, so that page's history records them.+ const undoPageId = pageIdOf(store.graph, parentId) ?? target.pageId+ const result = await executeWithPageUndo(store, undoPageId, automationUndoLabel('render'), () =>+ store.runMutationWithLayout(+ () =>+ renderTree(store.graph, tree, {+ parentId,+ x: toolArgs.x as number | undefined,+ y: toolArgs.y as number | undefined+ }),+ target.pageId,+ async (node) => {+ await ensureGraphFonts(store.graph, [node.id], store.renderer)+ }+ ))store.requestRender()store.flashNodes([result.id])@@ -60,16 +71,24 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {const figma = makeFigma(store, target.pageId)let result: unknownif (isAtomicTool(def)) {- result = await executeAtomicEditorTool(store, figma, def, toolArgs)+ result = await executeAtomicEditorTool(store, figma, def, toolArgs, {+ label: AUTOMATION_UNDO_LABEL+ })} else if (def.mutates) {- result = await store.runMutationWithLayout(- () => def.execute(figma, toolArgs),- figma.currentPageId,- async () => {- const pageNode = store.graph.getNode(figma.currentPageId)- if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)- }- )+ const pageId = figma.currentPageId+ const mutate = () =>+ store.runMutationWithLayout(+ () => def.execute(figma, toolArgs),+ figma.currentPageId,+ async () => {+ const pageNode = store.graph.getNode(figma.currentPageId)+ if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)+ }+ )+ // View tools (selection, viewport, pages) leave the document and its history alone.+ result = toolChangesDocument(def)+ ? await executeWithPageUndo(store, pageId, automationUndoLabel(def.name), mutate)+ : await mutate()} else {result = await def.execute(figma, toolArgs)}@@ -82,6 +101,13 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {}}+function pageIdOf(graph: AutomationTarget['store']['graph'], nodeId: string): string | null {+ let node = graph.getNode(nodeId)+ while (node && node.type !== 'CANVAS')+ node = node.parentId ? graph.getNode(node.parentId) : undefined+ return node?.id ?? null+}+function extractNodeIds(result: unknown): string[] {if (!result || typeof result !== 'object') return []const obj = result as JSONObjectdiff --git a/src/app/automation/execution/editor.ts b/src/app/automation/execution/editor.tsindex 9495677c1..71b1e84af 100644--- a/src/app/automation/execution/editor.ts+++ b/src/app/automation/execution/editor.ts@@ -1,3 +1,5 @@+import { isEqual } from 'es-toolkit'+import { executeAtomicTool } from '@open-pencil/core/editor'import type { FigmaAPI } from '@open-pencil/core/figma-api'import type { ToolDef } from '@open-pencil/core/tools'@@ -5,6 +7,17 @@ import type { ToolDef } from '@open-pencil/core/tools'import type { EditorStore } from '@/app/editor/active-store'import { ensureGraphFonts } from '@/app/editor/fonts'+/** Undo steps made through the automation bridge (MCP, CLI) start with this label. */+export const AUTOMATION_UNDO_LABEL = 'Agent'++export function automationUndoLabel(operation: string): string {+ return `${AUTOMATION_UNDO_LABEL}: ${operation}`+}++export function isAutomationUndoLabel(label: string | null): boolean {+ return label?.startsWith(`${AUTOMATION_UNDO_LABEL}: `) === true+}+/** Commit first; asynchronous font availability is presentation work, not a transaction. */export async function executeAtomicEditorTool(store: EditorStore,@@ -29,3 +42,29 @@ export async function executeAtomicEditorTool(}return result}++/**+ * Run a structural edit as one undo step by snapshotting its page around it, as the AI chat+ * does, so `undo` reverts what an automation client created, moved, or deleted.+ */+export async function executeWithPageUndo<T>(+ store: EditorStore,+ pageId: string,+ label: string,+ run: () => Promise<T>+): Promise<T> {+ const before = store.snapshotPage(pageId)+ try {+ return await run()+ } finally {+ const after = store.snapshotPage(pageId)+ // Read-only scripts and no-op edits must not leave empty steps in the user's history.+ if (!isEqual(before, after)) {+ store.pushUndoEntry({+ label,+ forward: () => store.restorePageFromSnapshot(after),+ inverse: () => store.restorePageFromSnapshot(before)+ })+ }+ }+}diff --git a/src/app/document/io/create.ts b/src/app/document/io/create.tsindex cf75a43bb..fa38a5ee0 100644--- a/src/app/document/io/create.ts+++ b/src/app/document/io/create.ts@@ -77,6 +77,11 @@ export function createDocumentIOActions(getDocumentFilePath: sourceState.getFilePath,getSourceIdentity: sourceState.getSourceIdentity,getStorageBinding: sourceState.getStorageBinding,+ /** Whether saving writes in place rather than asking for a location. */+ hasWritableSource: () =>+ !!sourceState.getFilePath() ||+ !!sourceState.getFileHandle() ||+ !!sourceState.getStorageBinding(),getRecoveryId: sourceActions.getRecoveryId,adoptRecoverySnapshot: sourceActions.adoptRecoverySnapshot,persistRecoveryNow: sourceActions.persistRecoveryNow,@@ -84,6 +89,7 @@ export function createDocumentIOActions(setDocumentSource: sourceActions.setDocumentSource,setStorageDocumentSource: sourceActions.setStorageDocumentSource,setPlannedFilePath: sourceActions.setPlannedFilePath,+ saveFigFileToPath: sourceActions.saveFigFileToPath,startWatchingCurrentFile: sourceActions.startWatchingCurrentFile,disposeDocumentIO: sourceActions.disposeDocumentIO,openFigFile,diff --git a/src/app/document/io/source.ts b/src/app/document/io/source.tsindex 0cf0dd115..5214a7aa9 100644--- a/src/app/document/io/source.ts+++ b/src/app/document/io/source.ts@@ -151,6 +151,35 @@ export function createDocumentSourceActions({state.documentName = documentNameFromFigPath(downloadName)}+ /** Save to a new path; when the write fails, the document keeps the source it had. */+ async function saveFigFileToPath(path: string): Promise<boolean> {+ const previous = {+ filePath: getFilePath(),+ fileHandle: getFileHandle(),+ storageBinding: getStorageBinding(),+ downloadName: getDownloadName(),+ documentName: state.documentName+ }+ const restore = () => {+ setStorageBinding(previous.storageBinding)+ setFileHandle(previous.fileHandle)+ setFilePath(previous.filePath)+ setDownloadName(previous.downloadName)+ state.documentName = previous.documentName+ if (previous.filePath || previous.fileHandle) void startWatchingFile()+ }+ setPlannedFilePath(path)+ try {+ const saved = await saveAndTrack(saveFigFile)+ if (saved) void startWatchingFile()+ else restore()+ return saved+ } catch (error) {+ restore()+ throw error+ }+ }+function startWatchingCurrentFile() {void startWatchingFile()}@@ -166,6 +195,7 @@ export function createDocumentSourceActions({setDocumentSource,setStorageDocumentSource,setPlannedFilePath,+ saveFigFileToPath,startWatchingCurrentFile,disposeDocumentIO,saveFigFile: () => saveAndTrack(saveFigFile),diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.tsindex 80b78e998..12ba76935 100644--- a/src/app/editor/session/modules.ts+++ b/src/app/editor/session/modules.ts@@ -81,6 +81,7 @@ export function createEditorStoreModules(saveFigFile: documentIO.saveFigFile,saveFigFileAs: documentIO.saveFigFileAs,getDocumentFilePath: documentIO.getDocumentFilePath,+ hasWritableSource: documentIO.hasWritableSource,getSourceIdentity: documentIO.getSourceIdentity,getStorageBinding: documentIO.getStorageBinding,getRecoveryId: documentIO.getRecoveryId,@@ -90,6 +91,7 @@ export function createEditorStoreModules(setDocumentSource: documentIO.setDocumentSource,setStorageDocumentSource: documentIO.setStorageDocumentSource,setPlannedFilePath: documentIO.setPlannedFilePath,+ saveFigFileToPath: documentIO.saveFigFileToPath,startWatchingCurrentFile: documentIO.startWatchingCurrentFile,designCheck,dispose: () => {diff --git a/src/app/settings/automation.ts b/src/app/settings/automation.tsnew file mode 100644index 000000000..cd44d9b32--- /dev/null+++ b/src/app/settings/automation.ts@@ -0,0 +1,130 @@+import * as v from 'valibot'++import { allRules } from '@open-pencil/core/lint'+import { AVAILABLE_LOCALES, locale, setLocale, type Locale } from '@open-pencil/vue'++import { agentStepLimitSchema } from '@/app/ai/chat/step-limit'+import { applySnappingPreferences, setDesignIssuesOnCanvas } from '@/app/settings/preferences/apply'+import {+ ANIMATION_PREFERENCES,+ appPreferences,+ CANVAS_RENDERING_MODES,+ CHANGE_PREVIEW_SIZES,+ DESIGN_CHECK_PRESETS,+ REASONING_DISPLAYS,+ updateDesignCheckPreferences,+ type AppPreferences+} from '@/app/settings/preferences/store'+import { APP_THEMES, getAppTheme, setAppTheme, type AppTheme } from '@/app/shell/theme'++/**+ * The editor preferences that automation clients (CLI, MCP) may read and change.+ * Credentials, model profiles, MCP connections, storage, and tool access stay out:+ * an agent must not be able to grant itself access or read secrets.+ */+export interface AutomationSettings {+ appearance: {+ theme: AppTheme+ language: Locale+ animations: AppPreferences['appearance']['animations']+ }+ editing: AppPreferences['editing']+ rendering: AppPreferences['rendering']+ recovery: AppPreferences['recovery']+ chat: AppPreferences['chat']+ designCheck: AppPreferences['designCheck']+}++const optionalBoolean = v.optional(v.boolean())++export const automationSettingsPatchSchema = v.strictObject({+ appearance: v.optional(+ v.strictObject({+ theme: v.optional(v.picklist(APP_THEMES)),+ language: v.optional(v.picklist(AVAILABLE_LOCALES)),+ animations: v.optional(v.picklist(ANIMATION_PREFERENCES))+ })+ ),+ editing: v.optional(+ v.strictObject({+ snapping: v.optional(+ v.strictObject({+ geometry: optionalBoolean,+ objects: optionalBoolean,+ pixelGrid: optionalBoolean+ })+ )+ })+ ),+ rendering: v.optional(+ v.strictObject({ canvasMode: v.optional(v.picklist(CANVAS_RENDERING_MODES)) })+ ),+ recovery: v.optional(v.strictObject({ enabled: optionalBoolean })),+ chat: v.optional(+ v.strictObject({+ reasoningDisplay: v.optional(v.picklist(REASONING_DISPLAYS)),+ maxAgentSteps: v.optional(agentStepLimitSchema),+ changePreviewSize: v.optional(v.picklist(CHANGE_PREVIEW_SIZES))+ })+ ),+ designCheck: v.optional(+ v.strictObject({+ showOnCanvas: optionalBoolean,+ preset: v.optional(v.picklist(DESIGN_CHECK_PRESETS)),+ disabledRules: v.optional(v.array(v.picklist(Object.keys(allRules))))+ })+ )+})++export type AutomationSettingsPatch = v.InferOutput<typeof automationSettingsPatchSchema>++export function readAutomationSettings(): AutomationSettings {+ // Copy leaf groups: stored preferences can hold reactive proxies that cannot be cloned.+ const preferences = appPreferences.value+ return {+ appearance: {+ theme: getAppTheme(),+ language: locale.get(),+ animations: preferences.appearance.animations+ },+ editing: { snapping: { ...preferences.editing.snapping } },+ rendering: { ...preferences.rendering },+ recovery: { ...preferences.recovery },+ chat: { ...preferences.chat },+ designCheck: {+ ...preferences.designCheck,+ disabledRules: [...preferences.designCheck.disabledRules]+ }+ }+}++/** Validates a partial settings object, applies it through the owning stores, and returns the result. */+export function updateAutomationSettings(input: unknown): AutomationSettings {+ const result = v.safeParse(automationSettingsPatchSchema, input)+ if (!result.success) {+ const issue = result.issues[0]+ const path = v.getDotPath(issue)+ throw new Error(`Invalid settings${path ? ` at "${path}"` : ''}: ${issue.message}`)+ }+ const patch = result.output++ const { theme, language, ...appearance } = patch.appearance ?? {}+ if (theme) setAppTheme(theme)+ if (language) setLocale(language)++ const current = appPreferences.value+ appPreferences.value = {+ ...current,+ appearance: { ...current.appearance, ...appearance },+ rendering: { ...current.rendering, ...patch.rendering },+ recovery: { ...current.recovery, ...patch.recovery },+ chat: { ...current.chat, ...patch.chat }+ }+ if (patch.editing?.snapping) applySnappingPreferences(patch.editing.snapping)+ const { showOnCanvas, ...designCheck } = patch.designCheck ?? {}+ if (Object.keys(designCheck).length > 0) updateDesignCheckPreferences(designCheck)+ // Through the menu's setter, so the native View menu checkmark follows.+ if (showOnCanvas !== undefined) setDesignIssuesOnCanvas(showOnCanvas)++ return readAutomationSettings()+}diff --git a/src/app/settings/preferences/apply.ts b/src/app/settings/preferences/apply.tsindex 43edbaa9c..71027fcd8 100644--- a/src/app/settings/preferences/apply.ts+++ b/src/app/settings/preferences/apply.ts@@ -14,7 +14,12 @@ export function setSnappingPreference(preference: keyof SnappingPreferences,enabled: boolean): void {- updateSnappingPreferences({ [preference]: enabled })+ applySnappingPreferences({ [preference]: enabled })+}++/** Stores snapping changes and pushes them to every open editor and the native menu. */+export function applySnappingPreferences(changes: Partial<SnappingPreferences>): void {+ updateSnappingPreferences(changes)const snapping = appPreferences.value.editing.snappingfor (const tab of getTabsSnapshot()) {tab.store.state.snappingPreferences = { ...snapping }diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.tsindex d2c1ee431..1d134171b 100644--- a/src/app/settings/preferences/store.ts+++ b/src/app/settings/preferences/store.ts@@ -4,15 +4,18 @@ import { DEFAULT_SNAPPING_PREFERENCES, type SnappingPreferences } from '@open-peimport { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'-export type AnimationPreference = 'system' | 'off'+export const ANIMATION_PREFERENCES = ['system', 'off'] as const+export type AnimationPreference = (typeof ANIMATION_PREFERENCES)[number]-export type ReasoningDisplay = 'collapsed' | 'while-thinking' | 'expanded'+export const REASONING_DISPLAYS = ['collapsed', 'while-thinking', 'expanded'] as const+export type ReasoningDisplay = (typeof REASONING_DISPLAYS)[number]export const CHANGE_PREVIEW_SIZES = ['off', 'small', 'medium', 'large'] as const/** How large the before/after images kept for each AI edit are; `off` keeps only the JSX diff. */export type ChangePreviewSize = (typeof CHANGE_PREVIEW_SIZES)[number]-export type CanvasRenderingMode = 'retained' | 'tiled'+export const CANVAS_RENDERING_MODES = ['retained', 'tiled'] as const+export type CanvasRenderingMode = (typeof CANVAS_RENDERING_MODES)[number]export const DESIGN_CHECK_PRESETS = ['recommended', 'strict', 'accessibility'] as constexport type DesignCheckPreset = (typeof DESIGN_CHECK_PRESETS)[number]diff --git a/src/app/shell/theme.ts b/src/app/shell/theme.tsindex 5cec6b852..510b6a5fd 100644--- a/src/app/shell/theme.ts+++ b/src/app/shell/theme.ts@@ -7,7 +7,8 @@ import { parseColor } from '@open-pencil/scene-graph/color'import { getActiveEditorStoreOrNull, useActiveEditorStoreRef } from '@/app/editor/active-store'-export type AppTheme = 'dark' | 'light' | 'auto'+export const APP_THEMES = ['dark', 'light', 'auto'] as const+export type AppTheme = (typeof APP_THEMES)[number]const THEME_STORAGE_KEY = 'open-pencil:theme'const DEFAULT_THEME: AppTheme = 'dark'@@ -38,6 +39,14 @@ function updateCanvasTheme(): void {store.requestRepaint()}+export function getAppTheme(): AppTheme {+ return theme.value+}++export function setAppTheme(value: AppTheme): void {+ theme.value = value+}+function applyTheme(value: 'dark' | 'light', setting: AppTheme): void {if (!IS_BROWSER || !('document' in globalThis)) returndocument.documentElement.dataset.theme = value@@ -58,15 +67,11 @@ export function useAppTheme() {const isLight = computed(() => resolvedAppTheme.value === 'light')- function setTheme(value: AppTheme): void {- theme.value = value- }-function toggleTheme(): void {theme.value = isLight.value ? 'dark' : 'light'}- return { theme, resolvedTheme: resolvedAppTheme, isLight, setTheme, toggleTheme }+ return { theme, resolvedTheme: resolvedAppTheme, isLight, setTheme: setAppTheme, toggleTheme }}applyTheme(resolvedAppTheme.value, theme.value)diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex cd2e0280c..57496f9d0 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -10,6 +10,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'import { setOpenPencilStore } from '@/app/browser-bridge'import { describeDiagnosticError, recordStorageFailure } from '@/app/diagnostics'import { confirmAllDocuments } from '@/app/document/close/all'+import { confirmDocumentClose } from '@/app/document/close/controller'import { requestDocumentClose } from '@/app/document/close/prompt'import { readFigDocument } from '@/app/document/io/fig'import { applyImportedDocument } from '@/app/document/io/imported-document'@@ -153,13 +154,19 @@ export function switchTab(tabId: string): boolean {return true}-export async function closeTab(tabId: string): Promise<void> {+/**+ * Close a tab, asking whether to save unsaved changes. Pass `unsaved` to decide without+ * asking, as automation must: nobody may be there to answer.+ */+export async function closeTab(tabId: string, unsaved?: 'save' | 'discard'): Promise<void> {const idx = tabsRef.value.findIndex((t) => t.id === tabId)if (idx === -1) returnconst closingTab = tabsRef.value[idx]if (closingTab.kind === 'home' && tabsRef.value.length === 1) return- const choice = await requestDocumentClose(closingTab.store, closingTab.store.state.documentName)+ const choice = unsaved+ ? await confirmDocumentClose(closingTab.store, async () => unsaved)+ : await requestDocumentClose(closingTab.store, closingTab.store.state.documentName)if (choice === 'cancel') returnif (choice === 'discard') await closingTab.store.discardRecovery()else await closingTab.store.persistRecoveryNow()diff --git a/tests/app/automation/bridge/handlers.test.ts b/tests/app/automation/bridge/handlers.test.tsnew file mode 100644index 000000000..13e6f71bc--- /dev/null+++ b/tests/app/automation/bridge/handlers.test.ts@@ -0,0 +1,223 @@+import 'fake-indexeddb/auto'+import { afterEach, beforeEach, describe, expect, test, vi } from 'bun:test'++import * as layoutModule from '@open-pencil/core/layout'++import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'+import { createTab, getActiveStore, getActiveTabId, getTabById, getTabsSnapshot } from '@/app/tabs'++function setupGlobals() {+ globalThis.window = {+ innerWidth: 1024,+ innerHeight: 768,+ requestAnimationFrame: (callback: FrameRequestCallback) => {+ callback(0)+ return 0+ },+ cancelAnimationFrame: vi.fn(),+ openPencil: {},+ location: { href: 'http://localhost/' } as Location,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn()+ } as Window & typeof globalThis+ globalThis.document = {+ fonts: { add: vi.fn(), ready: Promise.resolve() }+ } as Document+ globalThis.requestAnimationFrame = window.requestAnimationFrame+ globalThis.cancelAnimationFrame = window.cancelAnimationFrame+}++const { handleRequest } = createAutomationCommandHandlers(makeFigmaFromStore)++// Page switches wait for the canvas to present; nothing renders here, so acknowledge it.+async function settle<T>(pending: Promise<T>): Promise<T> {+ const idle = Symbol('idle')+ for (const tab of getTabsSnapshot()) {+ if (tab.store.state.preparation?.phase !== 'preparing-render') continue+ tab.store.preparationController.acknowledgePresentation(tab.store.state.sceneVersion)+ }+ const result = await Promise.race([+ pending,+ new Promise<typeof idle>((resolve) => {+ setTimeout(() => resolve(idle), 0)+ })+ ])+ return result === idle ? settle(pending) : (result as T)+}++function request(command: string, args: Record<string, unknown> = {}) {+ return handleRequest(getActiveStore(), command, args) as Promise<{+ ok: boolean+ result: Record<string, unknown>+ target?: { documentId: string; pageId: string }+ }>+}++beforeEach(() => {+ setupGlobals()+ vi.spyOn(layoutModule, 'computeAllLayouts').mockReturnValue(undefined)+})++afterEach(() => {+ vi.restoreAllMocks()+ Reflect.deleteProperty(globalThis, 'window')+ Reflect.deleteProperty(globalThis, 'document')+ Reflect.deleteProperty(globalThis, 'requestAnimationFrame')+ Reflect.deleteProperty(globalThis, 'cancelAnimationFrame')+})++describe('activate_document', () => {+ test('brings a background tab to the front on the requested page', async () => {+ const background = createTab()+ const pageId = background.store.graph.addPage('Second').id+ createTab()+ expect(getActiveTabId()).not.toBe(background.id)++ const response = await settle(+ request('activate_document', { document_id: background.id, page_id: pageId })+ )++ expect(response.result).toEqual({ activated: true })+ expect(response.target).toMatchObject({ documentId: background.id, pageId })+ expect(getActiveTabId()).toBe(background.id)+ expect(background.store.state.currentPageId).toBe(pageId)+ })++ test('rejects an unknown document', async () => {+ createTab()+ await expect(request('activate_document', { document_id: 'missing' })).rejects.toThrow(+ 'Document "missing" not found'+ )+ })+})++describe('undo and redo', () => {+ test('step through automation changes and report their labels', async () => {+ const tab = createTab()+ const store = tab.store+ const node = store.createShape('RECTANGLE', 0, 0, 100, 100)+ await request('tool', {+ document_id: tab.id,+ name: 'set_opacity',+ args: { id: node, value: 0.5 }+ })++ const undone = await request('undo', { document_id: tab.id })+ expect(undone.result).toEqual({ applied: true, label: 'Agent: set_opacity' })+ expect(store.graph.getNode(node)?.opacity).toBe(1)++ const redone = await request('redo', { document_id: tab.id })+ expect(redone.result).toEqual({ applied: true, label: 'Agent: set_opacity' })+ expect(store.graph.getNode(node)?.opacity).toBe(0.5)+ })++ test('refuse to undo or redo a change made in the editor', async () => {+ const tab = createTab()+ const store = tab.store+ const node = store.createShape('RECTANGLE', 0, 0, 100, 100)+ store.updateNodeWithUndo(node, { opacity: 0.5 }, 'Set opacity')++ await expect(request('undo', { document_id: tab.id })).rejects.toThrow(+ 'The last change ("Set opacity") was made in the editor'+ )+ expect(store.graph.getNode(node)?.opacity).toBe(0.5)++ store.undoAction()+ await expect(request('redo', { document_id: tab.id })).rejects.toThrow(+ 'The last undone change ("Set opacity") was made in the editor'+ )+ expect(store.graph.getNode(node)?.opacity).toBe(1)+ })++ test('report nothing to redo on a fresh history', async () => {+ const tab = createTab()+ const response = await request('redo', { document_id: tab.id })+ expect(response.result).toEqual({ applied: false, label: null })+ })++ test('undo reverts a layer an automation tool created', async () => {+ const tab = createTab()+ const created = await request('tool', {+ document_id: tab.id,+ name: 'create_shape',+ args: { type: 'RECTANGLE', x: 0, y: 0, width: 40, height: 40, name: 'Card' }+ })+ const id = String(created.result.id)+ expect(tab.store.graph.getNode(id)).toBeDefined()++ const undone = await request('undo', { document_id: tab.id })+ expect(undone.result).toMatchObject({ applied: true, label: 'Agent: create_shape' })+ expect(tab.store.graph.getNode(id)).toBeUndefined()+ })++ test('undo reverts a render into a frame on another page', async () => {+ const tab = createTab()+ const graph = tab.store.graph+ const otherPage = graph.addPage('Other')+ const frame = graph.createNode('FRAME', otherPage.id, { width: 200, height: 200 })+ const rendered = await request('tool', {+ document_id: tab.id,+ name: 'render',+ args: {+ parent_id: frame.id,+ tree: { type: 'frame', props: { name: 'Rendered', w: 40, h: 40 }, children: [] }+ }+ })+ const id = String(rendered.result.id)+ expect(graph.getNode(id)?.parentId).toBe(frame.id)++ await request('undo', { document_id: tab.id })+ expect(graph.getNode(id)).toBeUndefined()+ expect(graph.getNode(frame.id)?.childIds).toEqual([])+ })++ test('a read-only eval leaves the history unchanged', async () => {+ const tab = createTab()+ await request('eval', { document_id: tab.id, code: 'return figma.currentPage.name' })+ expect(tab.store.undo.canUndo).toBe(false)+ })+})++describe('close_file and save_file never prompt', () => {+ function dirtyTab() {+ const tab = createTab()+ tab.store.createShape('RECTANGLE', 0, 0, 10, 10)+ expect(tab.store.hasUnsavedChanges()).toBe(true)+ return tab+ }++ test('closing unsaved changes fails unless the caller chooses', async () => {+ const tab = dirtyTab()+ await expect(request('close_file', { document_id: tab.id })).rejects.toThrow(+ 'has unsaved changes'+ )+ expect(getTabById(tab.id)).toBeDefined()++ const closed = await request('close_file', { document_id: tab.id, unsaved: 'discard' })+ expect(closed.result).toEqual({ closed: true })+ expect(getTabById(tab.id)).toBeUndefined()+ })++ test('saving a document that has no file asks for a path instead of a dialog', async () => {+ const tab = dirtyTab()+ await expect(request('save_file', { document_id: tab.id })).rejects.toThrow(+ 'has not been saved to a file yet'+ )+ await expect(request('close_file', { document_id: tab.id, unsaved: 'save' })).rejects.toThrow(+ 'has not been saved to a file yet'+ )+ expect(getTabById(tab.id)).toBeDefined()+ })++ test('a failed save to a path keeps the document source it had', async () => {+ const tab = dirtyTab()+ // Outside Tauri a path cannot be written, so the save fails.+ await expect(+ request('save_file', { document_id: tab.id, path: '/tmp/never-written.fig' })+ ).rejects.toThrow('Could not save')+ expect(tab.store.state.documentName).toBe('Untitled')+ expect(tab.store.getDocumentFilePath()).toBeNull()+ expect(tab.store.hasWritableSource()).toBe(false)+ })+})diff --git a/tests/app/settings/automation.test.ts b/tests/app/settings/automation.test.tsnew file mode 100644index 000000000..37fef2f17--- /dev/null+++ b/tests/app/settings/automation.test.ts@@ -0,0 +1,83 @@+import { afterEach, beforeEach, expect, test } from 'bun:test'++import { toRaw } from 'vue'++import { allRules } from '@open-pencil/core/lint'+import { locale, setLocale } from '@open-pencil/vue'++import { readAutomationSettings, updateAutomationSettings } from '@/app/settings/automation'+import { appPreferences } from '@/app/settings/preferences/store'+import { getAppTheme, setAppTheme } from '@/app/shell/theme'++let previousPreferences: typeof appPreferences.value+let previousTheme: ReturnType<typeof getAppTheme>+let previousLocale: ReturnType<typeof locale.get>++beforeEach(() => {+ previousPreferences = structuredClone(toRaw(appPreferences.value))+ previousTheme = getAppTheme()+ previousLocale = locale.get()+})++afterEach(() => {+ appPreferences.value = previousPreferences+ setAppTheme(previousTheme)+ setLocale(previousLocale)+})++test('reads appearance from the theme and locale stores alongside app preferences', () => {+ setAppTheme('light')+ setLocale('de')+ const settings = readAutomationSettings()+ expect(settings.appearance).toEqual({+ theme: 'light',+ language: 'de',+ animations: appPreferences.value.appearance.animations+ })+ expect(settings.editing).toEqual(appPreferences.value.editing)+ expect(settings).not.toHaveProperty('version')+})++test('applies a nested partial update and keeps sibling settings', () => {+ const before = readAutomationSettings()+ const after = updateAutomationSettings({+ appearance: { theme: 'auto' },+ editing: { snapping: { pixelGrid: !before.editing.snapping.pixelGrid } },+ chat: { maxAgentSteps: 120 }+ })++ expect(after.appearance).toEqual({ ...before.appearance, theme: 'auto' })+ expect(after.editing.snapping).toEqual({+ ...before.editing.snapping,+ pixelGrid: !before.editing.snapping.pixelGrid+ })+ expect(after.chat).toEqual({ ...before.chat, maxAgentSteps: 120 })+ expect(after.recovery).toEqual(before.recovery)+ expect(appPreferences.value.chat.maxAgentSteps).toBe(120)+ expect(getAppTheme()).toBe('auto')+})++test('changes design check settings and lists them', () => {+ const rule = Object.keys(allRules)[0]+ const after = updateAutomationSettings({+ designCheck: { preset: 'strict', disabledRules: [rule], showOnCanvas: false }+ })+ expect(after.designCheck).toEqual({+ preset: 'strict',+ disabledRules: [rule],+ showOnCanvas: false+ })+ expect(appPreferences.value.designCheck.disabledRules).toEqual([rule])+})++test.each([+ [{ appearance: { theme: 'sepia' } }, 'appearance.theme'],+ [{ chat: { maxAgentSteps: 0 } }, 'chat.maxAgentSteps'],+ [{ editing: { snapping: { grid: true } } }, 'editing.snapping.grid'],+ [{ credentials: {} }, 'credentials'],+ [{ designCheck: { disabledRules: ['not-a-rule'] } }, 'designCheck.disabledRules.0']+])('rejects %p without changing anything', (patch, path) => {+ const before = readAutomationSettings()+ expect(() => updateAutomationSettings(patch)).toThrow(`Invalid settings at "${path}"`)+ expect(readAutomationSettings()).toEqual(before)+})diff --git a/tests/engine/cli/app-client.test.ts b/tests/engine/cli/app-client.test.tsindex b705b6c43..76645cc1c 100644--- a/tests/engine/cli/app-client.test.ts+++ b/tests/engine/cli/app-client.test.ts@@ -5,7 +5,7 @@ import { join } from 'node:path'import { removeDiscoveryFile, writeDiscoveryFile } from '@open-pencil/mcp/discovery'-import { rpc } from '#cli/app-client'+import { rpc } from '#cli/app/client'let server: Server | null = nulldiff --git a/tests/engine/mcp/server/index.test.ts b/tests/engine/mcp/server/index.test.tsindex e1d32493f..e7f31ca45 100644--- a/tests/engine/mcp/server/index.test.ts+++ b/tests/engine/mcp/server/index.test.ts@@ -181,9 +181,14 @@ describe('MCP server', () => {expect(byName.get('save_file')?.effect).toBe('write')expect(byName.get('open_file')?.effect).toBe('read')expect(byName.get('open_file')?.capabilities).toEqual(['filesystem:read', 'document:read'])- expect(byName.get('close_file')?.effect).toBe('read')+ expect(byName.get('close_file')?.effect).toBe('write')expect(byName.get('update_node')?.effect).toBe('write')expect(byName.get('new_document')?.capabilities).toEqual(['document:write', 'filesystem:write'])+ expect(byName.get('activate_document')?.effect).toBe('read')+ expect(byName.get('undo')?.capabilities).toEqual(['document:write'])+ expect(byName.get('redo')?.effect).toBe('write')+ expect(byName.get('get_settings')?.capabilities).toEqual(['settings:read'])+ expect(byName.get('update_settings')?.capabilities).toEqual(['settings:write'])expect(byName.get('eval')?.availability).toBe('eval')expect(byName.get('eval')?.capabilities).toContain('code:execute')})@@ -366,23 +371,68 @@ describe('MCP server with mcpRoot', () => {})})- test('registers close_file as read-only and forwards its document target', async () => {+ test('registers close_file as destructive and forwards its unsaved choice and target', async () => {await withMCPRootServer(TEST_MCP_ROOT, async (client, browser) => {const { tools } = await client.listTools()const closeFile = tools.find((tool) => tool.name === 'close_file')- expect(closeFile?.annotations?.readOnlyHint).toBe(true)+ expect(closeFile?.annotations?.destructiveHint).toBe(true)const result = await client.callTool({name: 'close_file',- arguments: { document_id: 'doc-1' }+ arguments: { document_id: 'doc-1', unsaved: 'discard' }})expect(result.isError).not.toBe(true)expect(browser.requests.find((item) => item.command === 'close_file')?.args).toEqual({- document_id: 'doc-1'+ document_id: 'doc-1',+ unsaved: 'discard'})})})+ test('close_file keeps a save path inside mcpRoot', async () => {+ await withMCPRootServer(TEST_MCP_ROOT, async (client, browser) => {+ const outside = await client.callTool({+ name: 'close_file',+ arguments: { unsaved: 'save', path: '/etc/escape.fig' }+ })+ expect(outside.isError).toBe(true)+ expect(browser.requests.some((item) => item.command === 'close_file')).toBe(false)+ })+ })++ test('forwards document activation and history steps with their target', async () => {+ await withMCPRootServer(TEST_MCP_ROOT, async (client, browser) => {+ const activated = await client.callTool({+ name: 'activate_document',+ arguments: { document_id: 'doc-2', page_id: '0:5' }+ })+ expect(activated.isError).not.toBe(true)+ expect(browser.requests.find((item) => item.command === 'activate_document')?.args).toEqual({+ document_id: 'doc-2',+ page_id: '0:5'+ })++ const undone = await client.callTool({ name: 'undo', arguments: { document_id: 'doc-2' } })+ expect(undone.isError).not.toBe(true)+ expect(JSON.stringify(undone.content)).toContain('Agent: mock')+ expect(browser.requests.find((item) => item.command === 'undo')?.args).toEqual({+ document_id: 'doc-2'+ })+ })+ })++ test('forwards settings updates and returns the resulting settings', async () => {+ await withMCPRootServer(TEST_MCP_ROOT, async (client, browser) => {+ const settings = { appearance: { theme: 'light' } }+ const result = await client.callTool({ name: 'update_settings', arguments: { settings } })+ expect(result.isError).not.toBe(true)+ expect(browser.requests.find((item) => item.command === 'update_settings')?.args).toEqual({+ settings+ })+ expect(JSON.stringify(result.content)).toContain('light')+ })+ })+test('save_file accepts an explicit path inside mcpRoot', async () => {await withMCPRootServer(TEST_MCP_ROOT, async (client, browser) => {await mkdir(join(TEST_MCP_ROOT, 'unicode'), { recursive: true })diff --git a/tests/helpers/mcp/server.ts b/tests/helpers/mcp/server.tsindex da1a34bbe..3d0ff89e2 100644--- a/tests/helpers/mcp/server.ts+++ b/tests/helpers/mcp/server.ts@@ -174,6 +174,17 @@ function randomHex(bytes: number): string {.join('')}+// App commands whose mock result does not depend on the graph or arguments.+const FIXED_MOCK_RESULTS: Partial<Record<string, object>> = {+ save_file: {},+ new_document: {},+ open_file: {},+ close_file: { closed: true },+ activate_document: { activated: true },+ undo: { applied: true, label: 'Agent: mock' },+ redo: { applied: true, label: 'Agent: mock' }+}+async function handleMockCommand(graph: SceneGraph,command: string,@@ -210,12 +221,12 @@ async function handleMockCommand(}}- if (command === 'save_file' || command === 'new_document' || command === 'open_file') {- return {}- }+ const fixed = FIXED_MOCK_RESULTS[command]+ if (fixed) return fixed- if (command === 'close_file') {- return { closed: true }+ if (command === 'get_settings' || command === 'update_settings') {+ const settings = (rawArgs as { settings?: unknown } | undefined)?.settings+ return { settings: settings ?? { appearance: { theme: 'dark' } } }}return executeRPCCommand(graph, command, args ?? {})