AI-native design editor. Open-source Figma alternative.
Fix all code review issues in RPC bridge
Danila Poyarkovb6c922e3357c
diff --git a/packages/cli/src/commands/analyze/colors.ts b/packages/cli/src/commands/analyze/colors.tsindex d5f2f102a..382fff191 100644--- a/packages/cli/src/commands/analyze/colors.ts+++ b/packages/cli/src/commands/analyze/colors.ts@@ -7,8 +7,8 @@ import { executeRpcCommand } from '@open-pencil/core'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 }+async function getData(file: string | undefined, args: { threshold?: string; similar?: boolean }): Promise<AnalyzeColorsResult> {+ const rpcArgs = { threshold: Number(args.threshold ?? 15), similar: args.similar }if (isAppMode(file)) return rpc<AnalyzeColorsResult>('analyze_colors', rpcArgs)const graph = await loadDocument(requireFile(file))return executeRpcCommand(graph, 'analyze_colors', rpcArgs) as AnalyzeColorsResultdiff --git a/packages/cli/src/commands/analyze/typography.ts b/packages/cli/src/commands/analyze/typography.tsindex d954bed23..6cbe72361 100644--- a/packages/cli/src/commands/analyze/typography.ts+++ b/packages/cli/src/commands/analyze/typography.ts@@ -19,11 +19,10 @@ function weightName(w: number): string {return 'Black'}-async function getData(file: string | undefined, groupBy?: string): Promise<AnalyzeTypographyResult> {- const rpcArgs = { groupBy }- if (isAppMode(file)) return rpc<AnalyzeTypographyResult>('analyze_typography', rpcArgs)+async function getData(file?: string): Promise<AnalyzeTypographyResult> {+ if (isAppMode(file)) return rpc<AnalyzeTypographyResult>('analyze_typography')const graph = await loadDocument(requireFile(file))- return executeRpcCommand(graph, 'analyze_typography', rpcArgs) as AnalyzeTypographyResult+ return executeRpcCommand(graph, 'analyze_typography', {}) as AnalyzeTypographyResult}export default defineCommand({@@ -35,7 +34,7 @@ export default defineCommand({json: { type: 'boolean', description: 'Output as JSON' }},async run({ args }) {- const data = await getData(args.file, args['group-by'])+ const data = await getData(args.file)const limit = Number(args.limit)const groupBy = args['group-by']diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.tsindex 69e2d37d0..9001ff619 100644--- a/packages/cli/src/commands/export.ts+++ b/packages/cli/src/commands/export.ts@@ -40,21 +40,30 @@ export default defineCommand({}if (isAppMode(args.file)) {- if (format === 'JSX' || format === 'SVG') {- const toolName = format === 'SVG' ? 'export_svg' : 'eval'- const toolArgs = format === 'SVG'- ? { ids: args.node ? [args.node] : undefined }- : { code: `return selectionToJSX([${args.node ? `"${args.node}"` : '...figma.currentPage.children.map(n => n.id)'}], figma.graph, "${args.style}")` }-- const result = await rpc<{ svg?: string; result?: string }>('tool', { name: toolName, args: toolArgs })- const content = format === 'SVG' ? (result as { svg: string }).svg : (result as { result: string }).result- if (!content) {+ if (format === 'SVG') {+ const result = await rpc<{ svg: string }>('tool', { name: 'export_svg', args: { ids: args.node ? [args.node] : undefined } })+ if (!result.svg) {printError('Nothing to export.')process.exit(1)}- const output = resolve(args.output ?? `export.${format.toLowerCase()}`)- await Bun.write(output, content)- console.log(ok(`Exported ${output} (${(content.length / 1024).toFixed(1)} KB)`))+ const output = resolve(args.output ?? 'export.svg')+ await Bun.write(output, result.svg)+ console.log(ok(`Exported ${output} (${(result.svg.length / 1024).toFixed(1)} KB)`))+ return+ }++ if (format === 'JSX') {+ const result = await rpc<{ jsx: string }>('export_jsx', {+ nodeIds: args.node ? [args.node] : undefined,+ style: args.style+ })+ if (!result.jsx) {+ printError('Nothing to export.')+ process.exit(1)+ }+ const output = resolve(args.output ?? 'export.jsx')+ await Bun.write(output, result.jsx)+ console.log(ok(`Exported ${output} (${(result.jsx.length / 1024).toFixed(1)} KB)`))return}diff --git a/packages/cli/src/commands/node.ts b/packages/cli/src/commands/node.tsindex c79954bcf..43a21d6d1 100644--- a/packages/cli/src/commands/node.ts+++ b/packages/cli/src/commands/node.ts@@ -2,8 +2,8 @@ import { defineCommand } from 'citty'import { loadDocument } from '../headless'import { isAppMode, requireFile, rpc } from '../app-client'-import { fmtNode, fmtList, nodeToData, printError, formatType } from '../format'-import { executeRpcCommand } from '@open-pencil/core'+import { fmtNode, printError, formatType } from '../format'+import { executeRpcCommand, colorToHex } from '@open-pencil/core'import type { NodeResult } from '@open-pencil/core'@@ -47,11 +47,10 @@ export default defineCommand({if (data.parent) details.parent = `${data.parent.name} (${data.parent.id})`if (data.text) details.text = data.textif (data.fills.length > 0) {- const solid = (data.fills as Array<{ type: string; visible: boolean; color: { r: number; g: number; b: number }; opacity: number }>)+ const solid = (data.fills as Array<{ type: string; visible: boolean; color: { r: number; g: number; b: number; a: number }; opacity: number }>).find((f) => f.type === 'SOLID' && f.visible)if (solid) {- const { r, g, b } = solid.color- const hex = '#' + [r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, '0')).join('')+ const hex = colorToHex(solid.color)details.fill = solid.opacity < 1 ? `${hex} ${Math.round(solid.opacity * 100)}%` : hex}}diff --git a/packages/core/src/rpc/commands.ts b/packages/core/src/rpc/commands.tsindex e38bf8b71..910475e9c 100644--- a/packages/core/src/rpc/commands.ts+++ b/packages/core/src/rpc/commands.ts@@ -7,17 +7,21 @@ export interface RpcCommand<A = unknown, R = unknown> {execute: (graph: SceneGraph, args: A) => R}-function walkNodes(graph: SceneGraph, rootId: string, fn: (node: SceneNode) => void) {+/** Walk descendants. Callback returns `false` to stop traversal. */+function walkNodes(graph: SceneGraph, rootId: string, fn: (node: SceneNode) => boolean): boolean {const node = graph.getNode(rootId)- if (!node) return- fn(node)- for (const childId of node.childIds) walkNodes(graph, childId, fn)+ if (!node) return true+ if (!fn(node)) return false+ for (const childId of node.childIds) {+ if (!walkNodes(graph, childId, fn)) return false+ }+ return true}function countNodes(graph: SceneGraph, pageId: string): number {let count = 0const page = graph.getNode(pageId)- if (page) for (const cid of page.childIds) walkNodes(graph, cid, () => count++)+ if (page) for (const cid of page.childIds) walkNodes(graph, cid, () => { count++; return true })return count}@@ -48,6 +52,7 @@ export const infoCommand: RpcCommand<void, InfoResult> = {pageCount++types[node.type] = (types[node.type] ?? 0) + 1if (node.fontFamily) fonts.add(node.fontFamily)+ return true})}pageCounts[page.name] = pageCount@@ -160,8 +165,8 @@ export const findCommand: RpcCommand<FindArgs, FindNodeResult[]> = {const searchPage = (page: SceneNode) => {for (const cid of page.childIds) {- walkNodes(graph, cid, (node) => {- if (results.length >= max) return+ const cont = walkNodes(graph, cid, (node) => {+ if (results.length >= max) return falseconst matchesName = !namePattern || node.name.toLowerCase().includes(namePattern)const matchesType = !typeFilter || node.type === typeFilterif (matchesName && matchesType) {@@ -170,7 +175,9 @@ export const findCommand: RpcCommand<FindArgs, FindNodeResult[]> = {width: Math.round(node.width), height: Math.round(node.height)})}+ return true})+ if (!cont) break}}@@ -340,7 +347,6 @@ export const variablesCommand: RpcCommand<VariablesArgs, VariablesResult> = {// ── analyze colors ──export interface AnalyzeColorsArgs {- limit?: numberthreshold?: numbersimilar?: boolean}@@ -449,9 +455,7 @@ export const analyzeColorsCommand: RpcCommand<AnalyzeColorsArgs, AnalyzeColorsRe// ── analyze typography ──-export interface AnalyzeTypographyArgs {- groupBy?: string-}+export interface AnalyzeTypographyArgs {}export interface TypographyStyle {family: stringdiff --git a/src/ai/tools.ts b/src/ai/tools.tsindex e1bbe1209..996391e5d 100644--- a/src/ai/tools.ts+++ b/src/ai/tools.ts@@ -2,25 +2,16 @@ import { valibotSchema } from '@ai-sdk/valibot'import { tool } from 'ai'import * as v from 'valibot'-import { ALL_TOOLS, FigmaAPI, toolsToAI } from '@open-pencil/core'+import { makeFigmaFromStore } from '@/automation/figma-factory'+import { ALL_TOOLS, toolsToAI } from '@open-pencil/core'import type { EditorStore } from '@/stores/editor'-import type { ExportFormat } from '@open-pencil/core'export function createAITools(store: EditorStore) {return toolsToAI(ALL_TOOLS,{- getFigma: () => {- const api = new FigmaAPI(store.graph)- api.currentPage = api.wrapNode(store.state.currentPageId)- api.currentPage.selection = [...store.state.selectedIds]- .map((id) => api.getNodeById(id))- .filter((n): n is NonNullable<typeof n> => n !== null)- api.exportImage = (nodeIds, opts) =>- store.renderExportImage(nodeIds, opts.scale ?? 1, (opts.format ?? 'PNG') as ExportFormat)- return api- },+ getFigma: () => makeFigmaFromStore(store),onAfterExecute: () => {store.requestRender()},diff --git a/src/automation/bridge.ts b/src/automation/bridge.tsindex 5f84ee5c3..60640b2bd 100644--- a/src/automation/bridge.ts+++ b/src/automation/bridge.ts@@ -29,62 +29,76 @@ interface PendingRequest {timer: ReturnType<typeof setTimeout>}-const pending = new Map<string, PendingRequest>()-let browserWs: WebSocket | null = null-let authToken: string | null = null--function sendToBrowser(body: Record<string, unknown>): Promise<unknown> {- return new Promise((resolve, reject) => {- if (!browserWs || browserWs.readyState !== browserWs.OPEN) {- reject(new Error('OpenPencil app is not connected'))- return- }- const id = crypto.randomUUID()- const timer = setTimeout(() => {- pending.delete(id)- reject(new Error('RPC timeout (30s)'))- }, RPC_TIMEOUT)- pending.set(id, { resolve, reject, timer })- browserWs.send(JSON.stringify({ type: 'request', id, ...body }))- })-}+type ViteServer = { ssrLoadModule: (id: string) => Promise<Record<string, unknown>> }-function handleBrowserMessage(data: string) {- try {- const msg = JSON.parse(data) as {- type: string- id?: string- token?: string- result?: unknown- error?: string- ok?: boolean- }- if (msg.type === 'register' && msg.token) {- authToken = msg.token- return+export function startAutomationBridge(server: ViteServer) {+ const pending = new Map<string, PendingRequest>()+ let browserWs: WebSocket | null = null+ let authToken: string | null = null++ function sendToBrowser(body: Record<string, unknown>): Promise<unknown> {+ return new Promise((resolve, reject) => {+ if (!browserWs || browserWs.readyState !== browserWs.OPEN) {+ reject(new Error('OpenPencil app is not connected'))+ return+ }+ const id = crypto.randomUUID()+ const timer = setTimeout(() => {+ pending.delete(id)+ reject(new Error('RPC timeout (30s)'))+ }, RPC_TIMEOUT)+ pending.set(id, { resolve, reject, timer })+ browserWs.send(JSON.stringify({ type: 'request', id, ...body }))+ })+ }++ function handleBrowserMessage(data: string) {+ try {+ const msg = JSON.parse(data) as {+ type: string+ id?: string+ token?: string+ result?: unknown+ error?: string+ ok?: boolean+ }+ if (msg.type === 'register' && msg.token) {+ authToken = msg.token+ return+ }+ if (msg.type === 'response' && msg.id) {+ const req = pending.get(msg.id)+ if (!req) return+ pending.delete(msg.id)+ clearTimeout(req.timer)+ if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))+ else {+ const { type: _, id: __, ...payload } = msg+ req.resolve(payload)+ }+ }+ } catch {+ // ignore malformed messages}- if (msg.type === 'response' && msg.id) {- const req = pending.get(msg.id)- if (!req) return- pending.delete(msg.id)+ }++ function rejectAllPending(reason: string) {+ for (const [id, req] of pending) {clearTimeout(req.timer)- if (msg.ok === false) req.reject(new Error(msg.error ?? 'RPC failed'))- else {- const { type: _, id: __, ...payload } = msg- req.resolve(payload)- }+ req.reject(new Error(reason))+ pending.delete(id)}- } catch {- // ignore malformed messages}-}-export function startAutomationBridge(server: ViteServer) {- viteServer = serverconst wss = new WebSocketServer({ port: AUTOMATION_WS_PORT, host: '127.0.0.1' })wss.on('connection', (ws) => {+ if (browserWs && browserWs.readyState === browserWs.OPEN) {+ browserWs.close()+ }+ rejectAllPending('Browser reconnected')browserWs = ws+ authToken = nullws.on('message', (raw) => {handleBrowserMessage(typeof raw === 'string' ? raw : raw.toString('utf-8'))@@ -94,15 +108,35 @@ export function startAutomationBridge(server: ViteServer) {if (browserWs === ws) {browserWs = nullauthToken = null- for (const [id, req] of pending) {- clearTimeout(req.timer)- req.reject(new Error('Browser disconnected'))- pending.delete(id)- }+ rejectAllPending('Browser disconnected')}})})+ async function jsxToTree(jsx: string): Promise<unknown> {+ const core = await server.ssrLoadModule('@open-pencil/core')+ const buildComponent = core.buildComponent as (jsx: string) => Promise<() => unknown>+ const resolveToTree = core.resolveToTree as (el: unknown) => unknown+ const createElement = core.createElement as (type: unknown, props: unknown) => unknown+ const Component = await buildComponent(jsx)+ const element = createElement(Component, null)+ return resolveToTree(element)+ }++ async function preprocessRpc(body: Record<string, unknown>): Promise<Record<string, unknown>> {+ if (body.command !== 'tool') return body+ const args = body.args as { name?: string; args?: Record<string, unknown> } | undefined+ if (args?.name !== 'render' || !args.args?.jsx) return body+ const tree = await jsxToTree(args.args.jsx as string)+ return {+ ...body,+ args: {+ ...args,+ args: { ...args.args, jsx: undefined, tree }+ }+ }+ }+const app = new Hono()app.use('*', cors())@@ -146,34 +180,6 @@ export function startAutomationBridge(server: ViteServer) {console.log(`[automation] WS ws://127.0.0.1:${AUTOMATION_WS_PORT}`)}-type ViteServer = { ssrLoadModule: (id: string) => Promise<Record<string, unknown>> }-let viteServer: ViteServer | null = null--async function jsxToTree(jsx: string): Promise<unknown> {- if (!viteServer) throw new Error('Vite server not initialized')- const core = await viteServer.ssrLoadModule('@open-pencil/core')- const buildComponent = core.buildComponent as (jsx: string) => Promise<() => unknown>- const resolveToTree = core.resolveToTree as (el: unknown) => unknown- const createElement = core.createElement as (type: unknown, props: unknown) => unknown- const Component = await buildComponent(jsx)- const element = createElement(Component, null)- return resolveToTree(element)-}--async function preprocessRpc(body: Record<string, unknown>): Promise<Record<string, unknown>> {- if (body.command !== 'tool') return body- const args = body.args as { name?: string; args?: Record<string, unknown> } | undefined- if (args?.name !== 'render' || !args.args?.jsx) return body- const tree = await jsxToTree(args.args.jsx as string)- return {- ...body,- args: {- ...args,- args: { ...args.args, jsx: undefined, tree }- }- }-}-function isBunRuntime(): boolean {return 'Bun' in globalThis}diff --git a/src/automation/figma-factory.ts b/src/automation/figma-factory.tsnew file mode 100644index 000000000..aff4f1ede--- /dev/null+++ b/src/automation/figma-factory.ts@@ -0,0 +1,22 @@+import { FigmaAPI } from '@open-pencil/core'++import type { EditorStore } from '@/stores/editor'+import type { ExportFormat } from '@open-pencil/core'++export function makeFigmaFromStore(store: EditorStore): FigmaAPI {+ const api = new FigmaAPI(store.graph)+ api.currentPage = api.wrapNode(store.state.currentPageId)+ api.currentPage.selection = [...store.state.selectedIds]+ .map((id) => api.getNodeById(id))+ .filter((n): n is NonNullable<typeof n> => n !== null)+ api.viewport = {+ center: {+ x: (-store.state.panX + window.innerWidth / 2) / store.state.zoom,+ y: (-store.state.panY + window.innerHeight / 2) / store.state.zoom+ },+ zoom: store.state.zoom+ }+ api.exportImage = (nodeIds, opts) =>+ store.renderExportImage(nodeIds, opts.scale ?? 1, (opts.format ?? 'PNG') as ExportFormat)+ return api+}diff --git a/src/automation/server.ts b/src/automation/server.tsindex bf9e316ff..46bbee9bb 100644--- a/src/automation/server.ts+++ b/src/automation/server.ts@@ -1,10 +1,19 @@+import { makeFigmaFromStore } from '@/automation/figma-factory'/*** Browser-side automation handler.** Connects to the bridge via WebSocket, receives RPC requests,* executes them against the live EditorStore, and sends results back.*/-import { ALL_TOOLS, AUTOMATION_WS_PORT, FigmaAPI, executeRpcCommand, renderTreeNode, computeAllLayouts } from '@open-pencil/core'+import {+ ALL_TOOLS,+ AUTOMATION_WS_PORT,+ executeRpcCommand,+ renderTreeNode,+ computeAllLayouts,+ selectionToJSX,+ sceneNodeToJSX+} from '@open-pencil/core'import type { EditorStore } from '@/stores/editor'import type { ExportFormat } from '@open-pencil/core'@@ -22,23 +31,8 @@ export function connectAutomation(getStore: () => EditorStore) {let ws: WebSocket | null = nulllet reconnectTimer: ReturnType<typeof setTimeout> | undefined- function makeFigma(): FigmaAPI {- const store = getStore()- const api = new FigmaAPI(store.graph)- api.currentPage = api.wrapNode(store.state.currentPageId)- api.currentPage.selection = [...store.state.selectedIds]- .map((id) => api.getNodeById(id))- .filter((n): n is NonNullable<typeof n> => n !== null)- api.viewport = {- center: {- x: (-store.state.panX + window.innerWidth / 2) / store.state.zoom,- y: (-store.state.panY + window.innerHeight / 2) / store.state.zoom- },- zoom: store.state.zoom- }- api.exportImage = (nodeIds, opts) =>- store.renderExportImage(nodeIds, opts.scale ?? 1, (opts.format ?? 'PNG') as ExportFormat)- return api+ function makeFigma() {+ return makeFigmaFromStore(getStore())}async function handleRequest(_id: string, command: string, args: unknown): Promise<unknown> {@@ -73,7 +67,10 @@ export function connectAutomation(getStore: () => EditorStore) {computeAllLayouts(store.graph, store.state.currentPageId)store.requestRender()store.flashNodes([result.id])- return { ok: true, result: { id: result.id, name: result.name, type: result.type, children: result.childIds } }+ return {+ ok: true,+ result: { id: result.id, name: result.name, type: result.type, children: result.childIds }+ }}const def = ALL_TOOLS.find((t) => t.name === toolName)@@ -98,8 +95,24 @@ export function connectAutomation(getStore: () => EditorStore) {(exportArgs?.format ?? 'PNG') as ExportFormat)if (!data) throw new Error('Export failed')- const base64 = btoa(String.fromCharCode(...data))- return { ok: true, base64, mimeType: `image/${(exportArgs?.format ?? 'png').toLowerCase()}` }+ let binary = ''+ for (let i = 0; i < data.length; i++) binary += String.fromCharCode(data[i])+ const base64 = btoa(binary)+ return {+ ok: true,+ result: { base64, mimeType: `image/${(exportArgs?.format ?? 'png').toLowerCase()}` }+ }+ }++ if (command === 'export_jsx') {+ const jsxArgs = args as { nodeIds?: string[]; style?: string } | undefined+ const style = (jsxArgs?.style ?? 'openpencil') as 'openpencil' | 'tailwind'+ const nodeIds = jsxArgs?.nodeIds ?? store.graph.getPages()[0]?.childIds ?? []+ const jsx =+ nodeIds.length === 1+ ? sceneNodeToJSX(nodeIds[0], store.graph, style)+ : selectionToJSX(nodeIds, store.graph, style)+ return { ok: true, result: { jsx: jsx ?? '' } }}const result = executeRpcCommand(store.graph, command, args ?? {})diff --git a/src/views/EditorView.vue b/src/views/EditorView.vueindex 852953dff..fc053ce85 100644--- a/src/views/EditorView.vue+++ b/src/views/EditorView.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { provide } from 'vue'+import { provide, onUnmounted } from 'vue'import { useBreakpoints, useEventListener, useUrlSearchParams } from '@vueuse/core'import { useRoute } from 'vue-router'import { useHead } from '@unhead/vue'@@ -30,7 +30,8 @@ const breakpoints = useBreakpoints({ mobile: 768 })const isMobile = breakpoints.smaller('mobile')useKeyboard()useMenu()-connectAutomation(getActiveStore)+const { disconnect: disconnectAutomation } = connectAutomation(getActiveStore)+onUnmounted(disconnectAutomation)const collab = useCollab(firstTab.store)provide(COLLAB_KEY, collab)