AI-native design editor. Open-source Figma alternative.
Fix RPC bridge review issues: centralize colors, ports, remove non-null assertions
Danila Poyarkov2ec382fc9d69
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 85d4838c2..dd83839f6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@- Homebrew tap — `brew install open-pencil/tap/open-pencil` for macOS (arm64 + x64), auto-updated on each release- Double-click to rename layers — inline rename in layer panel, shared `useInlineRename` composable- New AI/MCP tools: `analyze_colors`, `analyze_typography`, `analyze_spacing`, `analyze_clusters`, `diff_create`, `diff_show`, `get_components`, `get_current_page`, `arrange`, `node_to_component`+- CLI-to-app RPC bridge — all CLI commands work against the running app when no file is specified. Start the app, then run `bun open-pencil tree` to inspect the live document### Improvementsdiff --git a/packages/cli/src/app-client.ts b/packages/cli/src/app-client.tsindex f45145918..2bab21162 100644--- a/packages/cli/src/app-client.ts+++ b/packages/cli/src/app-client.ts@@ -1,6 +1,7 @@-const AUTOMATION_PORT = 7600-const HEALTH_URL = `http://127.0.0.1:${AUTOMATION_PORT}/health`-const RPC_URL = `http://127.0.0.1:${AUTOMATION_PORT}/rpc`+import { AUTOMATION_HTTP_PORT } from '@open-pencil/core'++const HEALTH_URL = `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/health`+const RPC_URL = `http://127.0.0.1:${AUTOMATION_HTTP_PORT}/rpc`let cachedToken: string | null = null@@ -9,7 +10,7 @@ export async function getAppToken(): Promise<string> {const res = await fetch(HEALTH_URL).catch(() => null)if (!res || !res.ok) {throw new Error(- 'Could not connect to OpenPencil app on localhost:7600.\n' ++ `Could not connect to OpenPencil app on localhost:${AUTOMATION_HTTP_PORT}.\n` +'Is the app running? Start it with: bun run tauri dev')}@@ -48,3 +49,8 @@ export async function rpc<T = unknown>(command: string, args: unknown = {}): Proexport function isAppMode(file?: string): boolean {return !file}++export function requireFile(file?: string): string {+ if (!file) throw new Error('File path is required for headless mode')+ return file+}diff --git a/packages/cli/src/commands/analyze/clusters.ts b/packages/cli/src/commands/analyze/clusters.tsindex 60833ded4..b994eba9b 100644--- a/packages/cli/src/commands/analyze/clusters.ts+++ b/packages/cli/src/commands/analyze/clusters.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../../headless'-import { isAppMode, rpc } from '../../app-client'+import { isAppMode, requireFile, rpc } from '../../app-client'import { bold, fmtList, fmtSummary } from '../../format'import { executeRpcCommand } from '@open-pencil/core'@@ -42,7 +42,7 @@ function formatSignature(sig: string): string {async function getData(file: string | undefined, args: { limit?: string; 'min-size'?: string; 'min-count'?: string }): Promise<AnalyzeClustersResult> {const rpcArgs = { limit: Number(args.limit ?? 20), minSize: Number(args['min-size'] ?? 30), minCount: Number(args['min-count'] ?? 2) }if (isAppMode(file)) return rpc<AnalyzeClustersResult>('analyze_clusters', rpcArgs)- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'analyze_clusters', rpcArgs) as AnalyzeClustersResult}diff --git a/packages/cli/src/commands/analyze/colors.ts b/packages/cli/src/commands/analyze/colors.tsindex e4ab811b8..d5f2f102a 100644--- a/packages/cli/src/commands/analyze/colors.ts+++ b/packages/cli/src/commands/analyze/colors.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../../headless'-import { isAppMode, rpc } from '../../app-client'+import { isAppMode, requireFile, rpc } from '../../app-client'import { bold, fmtHistogram, fmtList, fmtSummary } from '../../format'import { executeRpcCommand } from '@open-pencil/core'@@ -10,7 +10,7 @@ import type { AnalyzeColorsResult } from '@open-pencil/core'async function getData(file: string | undefined, args: { limit?: string; threshold?: string; similar?: boolean }): Promise<AnalyzeColorsResult> {const rpcArgs = { limit: Number(args.limit ?? 30), threshold: Number(args.threshold ?? 15), similar: args.similar }if (isAppMode(file)) return rpc<AnalyzeColorsResult>('analyze_colors', rpcArgs)- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'analyze_colors', rpcArgs) as AnalyzeColorsResult}diff --git a/packages/cli/src/commands/analyze/spacing.ts b/packages/cli/src/commands/analyze/spacing.tsindex 6dee18c9b..257f68702 100644--- a/packages/cli/src/commands/analyze/spacing.ts+++ b/packages/cli/src/commands/analyze/spacing.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../../headless'-import { isAppMode, rpc } from '../../app-client'+import { isAppMode, requireFile, rpc } from '../../app-client'import { bold, kv, fmtHistogram, fmtSummary } from '../../format'import { executeRpcCommand } from '@open-pencil/core'@@ -9,7 +9,7 @@ import type { AnalyzeSpacingResult } from '@open-pencil/core'async function getData(file?: string): Promise<AnalyzeSpacingResult> {if (isAppMode(file)) return rpc<AnalyzeSpacingResult>('analyze_spacing')- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'analyze_spacing', undefined) as AnalyzeSpacingResult}diff --git a/packages/cli/src/commands/analyze/typography.ts b/packages/cli/src/commands/analyze/typography.tsindex 61a2cc8bc..d954bed23 100644--- a/packages/cli/src/commands/analyze/typography.ts+++ b/packages/cli/src/commands/analyze/typography.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../../headless'-import { isAppMode, rpc } from '../../app-client'+import { isAppMode, requireFile, rpc } from '../../app-client'import { bold, fmtHistogram, fmtSummary } from '../../format'import { executeRpcCommand } from '@open-pencil/core'@@ -22,7 +22,7 @@ function weightName(w: number): string {async function getData(file: string | undefined, groupBy?: string): Promise<AnalyzeTypographyResult> {const rpcArgs = { groupBy }if (isAppMode(file)) return rpc<AnalyzeTypographyResult>('analyze_typography', rpcArgs)- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'analyze_typography', rpcArgs) as AnalyzeTypographyResult}diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.tsindex ea4d8fc55..bc9197424 100644--- a/packages/cli/src/commands/eval.ts+++ b/packages/cli/src/commands/eval.ts@@ -3,7 +3,7 @@ import { defineCommand } from 'citty'import { FigmaAPI } from '@open-pencil/core'import { loadDocument } from '../headless'-import { isAppMode, rpc } from '../app-client'+import { isAppMode, requireFile, rpc } from '../app-client'import { printError } from '../format'function serializeResult(value: unknown): unknown {@@ -52,7 +52,8 @@ export default defineCommand({return}- const graph = await loadDocument(args.file!)+ const file = requireFile(args.file)+ const graph = await loadDocument(file)const figma = new FigmaAPI(graph)const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor@@ -80,7 +81,7 @@ export default defineCommand({if (args.write || args.output) {const { exportFigFile } = await import('@open-pencil/core')- const outPath = args.output ?? args.file!+ const outPath = args.output ?? fileconst data = await exportFigFile(graph)await Bun.write(outPath, new Uint8Array(data))if (!args.quiet) {diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.tsindex 5dc6dc57d..69e2d37d0 100644--- a/packages/cli/src/commands/export.ts+++ b/packages/cli/src/commands/export.ts@@ -4,7 +4,7 @@ import { basename, extname, resolve } from 'node:path'import { renderNodesToSVG, sceneNodeToJSX, selectionToJSX } from '@open-pencil/core'import { loadDocument, loadFonts, exportNodes, exportThumbnail } from '../headless'-import { isAppMode, rpc } from '../app-client'+import { isAppMode, requireFile, rpc } from '../app-client'import { ok, printError } from '../format'import type { ExportFormat, JSXFormat } from '@open-pencil/core'@@ -71,7 +71,8 @@ export default defineCommand({return}- const graph = await loadDocument(args.file!)+ const file = requireFile(args.file)+ const graph = await loadDocument(file)await loadFonts(graph)const pages = graph.getPages()@@ -84,7 +85,7 @@ export default defineCommand({process.exit(1)}- const defaultName = basename(args.file!, extname(args.file!))+ const defaultName = basename(file, extname(file))if (format === 'JSX') {const jsxFormat = args.style as JSXFormatdiff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.tsindex c2325994f..4de441b2c 100644--- a/packages/cli/src/commands/find.ts+++ b/packages/cli/src/commands/find.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../headless'-import { isAppMode, rpc } from '../app-client'+import { isAppMode, requireFile, rpc } from '../app-client'import { fmtList, printError, bold, entity, formatType } from '../format'import { executeRpcCommand } from '@open-pencil/core'@@ -10,7 +10,7 @@ import type { FindNodeResult } from '@open-pencil/core'async function getData(file: string | undefined, args: { name?: string; type?: string; page?: string; limit?: string }): Promise<FindNodeResult[]> {const rpcArgs = { name: args.name, type: args.type, page: args.page, limit: args.limit ? Number(args.limit) : undefined }if (isAppMode(file)) return rpc<FindNodeResult[]>('find', rpcArgs)- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'find', rpcArgs) as FindNodeResult[]}diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.tsindex 47ca295d9..f611a1148 100644--- a/packages/cli/src/commands/info.ts+++ b/packages/cli/src/commands/info.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../headless'-import { isAppMode, rpc } from '../app-client'+import { isAppMode, requireFile, rpc } from '../app-client'import { bold, fmtHistogram, fmtSummary, kv } from '../format'import type { InfoResult } from '@open-pencil/core'@@ -9,7 +9,7 @@ import { executeRpcCommand } from '@open-pencil/core'async function getData(file?: string): Promise<InfoResult> {if (isAppMode(file)) return rpc<InfoResult>('info')- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'info', undefined) as InfoResult}diff --git a/packages/cli/src/commands/node.ts b/packages/cli/src/commands/node.tsindex f585b1536..c79954bcf 100644--- a/packages/cli/src/commands/node.ts+++ b/packages/cli/src/commands/node.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../headless'-import { isAppMode, rpc } from '../app-client'+import { isAppMode, requireFile, rpc } from '../app-client'import { fmtNode, fmtList, nodeToData, printError, formatType } from '../format'import { executeRpcCommand } from '@open-pencil/core'@@ -9,7 +9,7 @@ import type { NodeResult } from '@open-pencil/core'async function getData(file: string | undefined, id: string): Promise<NodeResult | { error: string }> {if (isAppMode(file)) return rpc<NodeResult>('node', { id })- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'node', { id }) as NodeResult | { error: string }}diff --git a/packages/cli/src/commands/pages.ts b/packages/cli/src/commands/pages.tsindex cb5b837ef..274ad9ec4 100644--- a/packages/cli/src/commands/pages.ts+++ b/packages/cli/src/commands/pages.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../headless'-import { isAppMode, rpc } from '../app-client'+import { isAppMode, requireFile, rpc } from '../app-client'import { bold, fmtList, entity, formatType } from '../format'import type { PageItem } from '@open-pencil/core'@@ -9,7 +9,7 @@ import { executeRpcCommand } from '@open-pencil/core'async function getData(file?: string): Promise<PageItem[]> {if (isAppMode(file)) return rpc<PageItem[]>('pages')- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'pages', undefined) as PageItem[]}diff --git a/packages/cli/src/commands/tree.ts b/packages/cli/src/commands/tree.tsindex bf69d0931..d8daa6321 100644--- a/packages/cli/src/commands/tree.ts+++ b/packages/cli/src/commands/tree.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../headless'-import { isAppMode, rpc } from '../app-client'+import { isAppMode, requireFile, rpc } from '../app-client'import { fmtTree, printError, entity, formatType } from '../format'import { executeRpcCommand } from '@open-pencil/core'@@ -21,7 +21,7 @@ function toAgentfmtTree(node: TreeNodeResult, maxDepth: number, depth = 0): Treeasync function getData(file: string | undefined, args: { page?: string; depth?: string }): Promise<TreeResult | { error: string }> {const rpcArgs = { page: args.page, depth: args.depth ? Number(args.depth) : undefined }if (isAppMode(file)) return rpc<TreeResult>('tree', rpcArgs)- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'tree', rpcArgs) as TreeResult | { error: string }}diff --git a/packages/cli/src/commands/variables.ts b/packages/cli/src/commands/variables.tsindex 9dbb2b622..b0d06b50c 100644--- a/packages/cli/src/commands/variables.ts+++ b/packages/cli/src/commands/variables.ts@@ -1,7 +1,7 @@import { defineCommand } from 'citty'import { loadDocument } from '../headless'-import { isAppMode, rpc } from '../app-client'+import { isAppMode, requireFile, rpc } from '../app-client'import { bold, fmtList, fmtSummary } from '../format'import { executeRpcCommand } from '@open-pencil/core'@@ -10,7 +10,7 @@ import type { VariablesResult } from '@open-pencil/core'async function getData(file: string | undefined, args: { collection?: string; type?: string }): Promise<VariablesResult> {const rpcArgs = { collection: args.collection, type: args.type }if (isAppMode(file)) return rpc<VariablesResult>('variables', rpcArgs)- const graph = await loadDocument(file!)+ const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'variables', rpcArgs) as VariablesResult}diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex 4ef728a8d..f8f69650d 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -132,6 +132,9 @@ export const AI_MODELS: ModelOption[] = [export const DEFAULT_AI_MODEL = AI_MODELS[0].id+export const AUTOMATION_HTTP_PORT = 7600+export const AUTOMATION_WS_PORT = 7601+export const GOOGLE_FONTS_API_KEY = 'AIzaSyD1tYDR_dUEiV-Tw1vksEhZbUytgKW5pc8'export const CJK_FALLBACK_FAMILIES_MACOS = [diff --git a/packages/core/src/rpc/commands.ts b/packages/core/src/rpc/commands.tsindex e64f2cb96..e38bf8b71 100644--- a/packages/core/src/rpc/commands.ts+++ b/packages/core/src/rpc/commands.ts@@ -1,3 +1,5 @@+import { colorToHex, colorDistance as colorDist } from '../color'+import type { Color } from '../types'import type { SceneGraph, SceneNode, Variable } from '../scene-graph'export interface RpcCommand<A = unknown, R = unknown> {@@ -276,8 +278,7 @@ function formatVariableValue(variable: Variable, graph: SceneGraph): string {}if (typeof raw === 'object' && raw !== null && 'r' in raw) {- const { r, g, b } = raw as { r: number; g: number; b: number }- return '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')+ return colorToHex(raw as Color).toLowerCase()}return String(raw)@@ -346,6 +347,7 @@ export interface AnalyzeColorsArgs {interface ColorInfo {hex: string+ color: Colorcount: numbervariableName: string | null}@@ -356,17 +358,6 @@ interface ColorCluster {totalCount: number}-function hexToRgb(hex: string): [number, number, number] {- const clean = hex.replace('#', '')- return [parseInt(clean.slice(0, 2), 16), parseInt(clean.slice(2, 4), 16), parseInt(clean.slice(4, 6), 16)]-}--function colorDistance(hex1: string, hex2: string): number {- const [r1, g1, b1] = hexToRgb(hex1)- const [r2, g2, b2] = hexToRgb(hex2)- return Math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)-}-function clusterColors(colors: ColorInfo[], threshold: number): ColorCluster[] {const clusters: ColorCluster[] = []const used = new Set<string>()@@ -379,7 +370,7 @@ function clusterColors(colors: ColorInfo[], threshold: number): ColorCluster[] {for (const other of sorted) {if (used.has(other.hex)) continue- if (colorDistance(color.hex, other.hex) <= threshold) {+ if (colorDist(color.color, other.color) <= threshold) {cluster.colors.push(other)cluster.totalCount += other.countused.add(other.hex)@@ -392,21 +383,18 @@ function clusterColors(colors: ColorInfo[], threshold: number): ColorCluster[] {return clusters.sort((a, b) => b.colors.length - a.colors.length)}-function toHex(r: number, g: number, b: number): string {- return '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')-}-function collectColors(graph: SceneGraph): { colors: ColorInfo[]; totalNodes: number } {const colorMap = new Map<string, ColorInfo>()let totalNodes = 0- const addColor = (hex: string, variableName: string | null) => {+ const addColor = (c: Color, variableName: string | null) => {+ const hex = colorToHex(c).toLowerCase()const existing = colorMap.get(hex)if (existing) {existing.count++if (variableName && !existing.variableName) existing.variableName = variableName} else {- colorMap.set(hex, { hex, count: 1, variableName })+ colorMap.set(hex, { hex, color: c, count: 1, variableName })}}@@ -416,15 +404,15 @@ function collectColors(graph: SceneGraph): { colors: ColorInfo[]; totalNodes: nufor (const fill of node.fills) {if (!fill.visible || fill.type !== 'SOLID') continue- addColor(toHex(fill.color.r, fill.color.g, fill.color.b), null)+ addColor(fill.color, null)}for (const stroke of node.strokes) {if (!stroke.visible) continue- addColor(toHex(stroke.color.r, stroke.color.g, stroke.color.b), null)+ addColor(stroke.color, null)}for (const effect of node.effects) {if (!effect.visible) continue- addColor(toHex(effect.color.r, effect.color.g, effect.color.b), null)+ addColor(effect.color, null)}for (const [field, varId] of Object.entries(node.boundVariables)) {@@ -433,7 +421,7 @@ function collectColors(graph: SceneGraph): { colors: ColorInfo[]; totalNodes: nuif (variable) {const resolvedColor = graph.resolveColorVariable(varId)if (resolvedColor) {- const hex = toHex(resolvedColor.r, resolvedColor.g, resolvedColor.b)+ const hex = colorToHex(resolvedColor).toLowerCase()const existing = colorMap.get(hex)if (existing) existing.variableName = variable.name}diff --git a/src/automation/bridge.ts b/src/automation/bridge.tsindex 0bcae1b64..14dbedc77 100644--- a/src/automation/bridge.ts+++ b/src/automation/bridge.ts@@ -5,13 +5,18 @@* ws WebSocket server on :7601 for the browser page.** Flow: CLI → HTTP POST /rpc → Hono → WebSocket → browser → execute → response+ *+ * Security model: same-machine trust. Both HTTP and WebSocket bind to 127.0.0.1.+ * The browser generates a random bearer token and registers it via WebSocket.+ * GET /health exposes the token so the CLI can discover it — this is intentional:+ * any local process can access the bridge, and the token only prevents accidental+ * cross-session collisions when multiple instances are running.*/import { Hono } from 'hono'import { cors } from 'hono/cors'import { WebSocketServer, type WebSocket } from 'ws'-const AUTOMATION_PORT = 7600-const AUTOMATION_WS_PORT = 7601+import { AUTOMATION_HTTP_PORT, AUTOMATION_WS_PORT } from '@open-pencil/core'const RPC_TIMEOUT = 30_000interface PendingRequest {@@ -128,17 +133,23 @@ export function startAutomationBridge() {startServer(app)- console.log(`[automation] HTTP http://127.0.0.1:${AUTOMATION_PORT}`)+ console.log(`[automation] HTTP http://127.0.0.1:${AUTOMATION_HTTP_PORT}`)console.log(`[automation] WS ws://127.0.0.1:${AUTOMATION_WS_PORT}`)}+function isBunRuntime(): boolean {+ return 'Bun' in globalThis+}+async function startServer(app: Hono) {- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- runtime detection across Bun/Node- if ((globalThis as any).Bun !== undefined) {- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Bun.serve not in Node types- ;(globalThis as any).Bun.serve({ fetch: app.fetch, port: AUTOMATION_PORT, hostname: '127.0.0.1' })+ if (isBunRuntime()) {+ ;(globalThis as unknown as { Bun: { serve: (opts: object) => void } }).Bun.serve({+ fetch: app.fetch,+ port: AUTOMATION_HTTP_PORT,+ hostname: '127.0.0.1'+ })} else {const { serve } = await import('@hono/node-server')- serve({ fetch: app.fetch, port: AUTOMATION_PORT, hostname: '127.0.0.1' })+ serve({ fetch: app.fetch, port: AUTOMATION_HTTP_PORT, hostname: '127.0.0.1' })}}diff --git a/src/automation/server.ts b/src/automation/server.tsindex b63048d83..28920e9f8 100644--- a/src/automation/server.ts+++ b/src/automation/server.ts@@ -4,8 +4,7 @@* Connects to the bridge via WebSocket, receives RPC requests,* executes them against the live EditorStore, and sends results back.*/-import { ALL_TOOLS, FigmaAPI, executeRpcCommand } from '@open-pencil/core'-const AUTOMATION_WS_PORT = 7601+import { ALL_TOOLS, AUTOMATION_WS_PORT, FigmaAPI, executeRpcCommand } from '@open-pencil/core'import type { EditorStore } from '@/stores/editor'import type { ExportFormat } from '@open-pencil/core'