AI-native design editor. Open-source Figma alternative.
Optimize AI token usage: ~61% reduction in per-step context
Anton A S1454afc03671
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 0f608cf68..1f97a038e 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -52,7 +52,7 @@ export {} from './scene-graph'export { FigmaAPI, FigmaNodeProxy, computeImageHash, type FigmaFontName } from './figma-api'-export { ALL_TOOLS, defineTool, toolsToAI, buildDebugLog } from './tools'+export { ALL_TOOLS, CORE_TOOLS, EXTENDED_TOOLS, defineTool, toolsToAI, buildDebugLog } from './tools'export type { ToolDef, ParamDef, ParamType, ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './tools'export { executeRpcCommand, ALL_RPC_COMMANDS } from './rpc'export { queryByXPath, matchByXPath } from './xpath'diff --git a/packages/core/src/render/render-jsx.ts b/packages/core/src/render/render-jsx.tsindex 309b84770..fc72bd9e1 100644--- a/packages/core/src/render/render-jsx.ts+++ b/packages/core/src/render/render-jsx.ts@@ -16,6 +16,7 @@ export function buildComponent(jsxString: string): () => unknown {const Frame = 'frame', Text = 'text', Rectangle = 'rectangle', Ellipse = 'ellipse'const Line = 'line', Star = 'star', Polygon = 'polygon', Vector = 'vector'const Group = 'group', Section = 'section', View = 'frame', Rect = 'rectangle'+ const Icon = 'icon'return function Component() { return ${jsxString.trim()} }`@@ -38,11 +39,11 @@ interface RenderJSXOptions {* Render a JSX string into the scene graph.* Works in both Node/Bun and the browser.*/-export function renderJSX(+export async function renderJSX(graph: SceneGraph,jsxString: string,options?: RenderJSXOptions-): RenderResult {+): Promise<RenderResult> {const Component = buildComponent(jsxString)const element = React.createElement(Component, null)const tree = resolveToTree(element)@@ -57,10 +58,10 @@ export function renderJSX(/*** Render a pre-built TreeNode into the scene graph.*/-export function renderTreeNode(+export async function renderTreeNode(graph: SceneGraph,tree: TreeNode,options?: RenderJSXOptions-): RenderResult {+): Promise<RenderResult> {return renderTree(graph, tree, options)}diff --git a/packages/core/src/render/renderer.ts b/packages/core/src/render/renderer.tsindex 3506da64c..306218ddd 100644--- a/packages/core/src/render/renderer.ts+++ b/packages/core/src/render/renderer.ts@@ -1,8 +1,11 @@import { parseColor, colorToFill } from '../color'import { TRANSPARENT } from '../constants'+import { fetchIcons } from '../iconify'import { isTreeNode } from './tree'+import type { IconData } from '../iconify'import type { SceneGraph, SceneNode, NodeType, LayoutMode, GridTrack, Stroke } from '../scene-graph'+import type { Color } from '../types'import type { TreeNode } from './tree'const TYPE_MAP: Partial<Record<string, NodeType>> = {@@ -78,14 +81,14 @@ export interface RenderResult {childIds: string[]}-export function renderTree(+export async function renderTree(graph: SceneGraph,tree: TreeNode,options: RenderOptions = {}-): RenderResult {+): Promise<RenderResult> {const parentId = options.parentId ?? graph.getPages()[0].id- const result = renderNode(graph, tree, parentId)+ const result = await renderNode(graph, tree, parentId)if (options.x !== undefined) graph.updateNode(result.id, { x: options.x })if (options.y !== undefined) graph.updateNode(result.id, { y: options.y })@@ -98,7 +101,99 @@ export function renderTree(}}-function renderNode(graph: SceneGraph, tree: TreeNode, parentId: string): SceneNode {+async function renderIconNode(+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string+): Promise<SceneNode> {+ const props = tree.props+ const iconName = props.name as string | undefined+ if (!iconName) throw new Error('<Icon> requires a name prop (e.g. name="lucide:heart")')++ const size = (props.size as number | undefined) ?? 24+ const colorHex = (props.color as string | undefined) ?? '#000000'+ const parsedColor = parseColor(colorHex)++ const icons = await fetchIcons([iconName], size)+ const icon = icons.get(iconName)+ if (!icon || icon.paths.length === 0) {+ throw new Error(`Icon "${iconName}" not found`)+ }++ return createIconNode(graph, icon, iconName, size, parsedColor, parentId, props)+}++function createIconNode(+ graph: SceneGraph,+ icon: IconData,+ iconName: string,+ size: number,+ color: Color,+ parentId: string,+ props: Record<string, unknown>+): SceneNode {+ const parent = graph.getNode(parentId)+ const parentLayout = parent?.layoutMode ?? 'NONE'+ const overrides: Partial<SceneNode> = {+ name: (props.label as string | undefined) ?? `Icon / ${iconName}`,+ width: size,+ height: size,+ fills: []+ }+ const { w, h } = applySizeOverrides(props, overrides, parentLayout)+ if (typeof w !== 'number') overrides.width = size+ if (typeof h !== 'number') overrides.height = size+ const frame = graph.createNode('FRAME', parentId, overrides)++ for (const path of icon.paths) {+ const vector = graph.createNode('VECTOR', frame.id, {+ name: 'path',+ width: size,+ height: size,+ vectorNetwork: path.vectorNetwork+ })+ vector.x = 0+ vector.y = 0++ if (path.fill) {+ const fillColor = path.fill === 'currentColor' ? color : parseColor(path.fill)+ graph.updateNode(vector.id, {+ fills: [{ type: 'SOLID', color: fillColor, opacity: 1, visible: true }]+ })+ } else {+ graph.updateNode(vector.id, { fills: [] })+ }++ if (path.stroke) {+ const strokeColor = path.stroke === 'currentColor' ? color : parseColor(path.stroke)+ graph.updateNode(vector.id, {+ strokes: [{+ color: strokeColor,+ weight: path.strokeWidth,+ opacity: 1,+ visible: true,+ align: 'CENTER' as const,+ cap: ICON_STROKE_CAP[path.strokeCap] ?? 'NONE',+ join: ICON_STROKE_JOIN[path.strokeJoin] ?? 'MITER'+ }]+ })+ }+ }++ return frame+}++const ICON_STROKE_CAP: Record<string, SceneNode['strokeCap']> = {+ round: 'ROUND', square: 'SQUARE', butt: 'NONE'+}++const ICON_STROKE_JOIN: Record<string, SceneNode['strokeJoin']> = {+ miter: 'MITER', round: 'ROUND', bevel: 'BEVEL'+}++async function renderNode(graph: SceneGraph, tree: TreeNode, parentId: string): Promise<SceneNode> {+ if (tree.type === 'icon') return renderIconNode(graph, tree, parentId)+const nodeType = TYPE_MAP[tree.type]if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)@@ -118,7 +213,7 @@ function renderNode(graph: SceneGraph, tree: TreeNode, parentId: string): SceneNfor (const child of tree.children) {if (typeof child === 'string') continueif (isTreeNode(child)) {- renderNode(graph, child, node.id)+ await renderNode(graph, child, node.id)}}diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.tsindex 16ce58d7f..7251fc4cf 100644--- a/packages/core/src/tools/analyze.ts+++ b/packages/core/src/tools/analyze.ts@@ -596,6 +596,7 @@ export const evalCode = defineTool({params: {code: { type: 'string', description: 'JavaScript code to execute', required: true }},+ mutates: true,execute: async (figma, { code }) => {// eslint-disable-next-line no-empty-functionconst AsyncFunction = Object.getPrototypeOf(async function () {}).constructor@@ -603,6 +604,7 @@ export const evalCode = defineTool({const fn = new AsyncFunction('figma', wrapped)const result = await fn(figma)if (result && typeof result === 'object' && 'toJSON' in result) return result.toJSON()- return result ?? null+ if (result !== undefined && result !== null) return result+ return { ok: true, message: 'Code executed (no return value)' }}})diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex 441fe3d8e..a61102af2 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -62,7 +62,7 @@ export const render = defineTool({},execute: async (figma, args) => {const { renderJSX } = await import('../render/render-jsx.js')- const result = renderJSX(figma.graph, args.jsx, {+ const result = await renderJSX(figma.graph, args.jsx, {parentId: args.parent_id ?? figma.currentPageId,x: args.x,y: args.y@@ -360,13 +360,13 @@ export const searchIconsTool = defineTool({description: 'Search keywords (e.g. ["heart", "arrow", "settings"])',required: true},- limit: { type: 'number', description: 'Max results per query (default: 20)' },+ limit: { type: 'number', description: 'Max results per query (default: 5)' },prefix: { type: 'string', description: 'Filter by icon set prefix (e.g. "lucide", "mdi")' }},execute: async (_figma, args) => {try {const results = await searchIconsBatch(args.queries, {- limit: args.limit ?? 20,+ limit: args.limit ?? 5,prefix: args.prefix})const output: Record<string, { icons: string[]; total: number }> = {}diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex 72fefc2d9..ba6987743 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -1,4 +1,4 @@-export { ALL_TOOLS } from './registry'+export { ALL_TOOLS, CORE_TOOLS, EXTENDED_TOOLS } from './registry'export { defineTool, nodeToResult, nodeSummary } from './schema'export type { ToolDef, ParamDef, ParamType } from './schema'export { toolsToAI, buildDebugLog } from './ai-adapter'diff --git a/packages/core/src/tools/read.ts b/packages/core/src/tools/read.tsindex 836fa65b7..d5ce3f46a 100644--- a/packages/core/src/tools/read.ts+++ b/packages/core/src/tools/read.ts@@ -16,16 +16,33 @@ export const getSelection = defineTool({}})+interface TreeEntry {+ id: string+ type: string+ name: string+ w: number+ h: number+ children?: TreeEntry[]+}++function nodeToTreeEntry(node: FigmaNodeProxy): TreeEntry {+ const entry: TreeEntry = { id: node.id, type: node.type, name: node.name, w: node.width, h: node.height }+ if (node.children.length > 0) {+ entry.children = node.children.map(nodeToTreeEntry)+ }+ return entry+}+export const getPageTree = defineTool({name: 'get_page_tree',description:- 'Get the node tree of the current page. Returns all nodes with hierarchy, types, positions, and sizes.',+ 'Get the node tree of the current page. Returns lightweight hierarchy: id, type, name, size. Use get_node for full properties of a specific node.',params: {},execute: (figma) => {const page = figma.currentPagereturn {page: page.name,- children: page.children.map(nodeToResult)+ children: page.children.map(nodeToTreeEntry)}}})diff --git a/packages/core/src/tools/registry.ts b/packages/core/src/tools/registry.tsindex bd15c911c..3a49fc988 100644--- a/packages/core/src/tools/registry.ts+++ b/packages/core/src/tools/registry.ts@@ -39,67 +39,87 @@ import { describe } from './describe'import { designToTokens, designToComponentMap } from './codegen'import { calc } from './calc'-export const ALL_TOOLS: ToolDef[] = [+/**+ * Core tools registered by default in AI chat (~30 tools, ~3K schema tokens).+ * Covers 90%+ of design sessions: render, describe, modify, structure, icons.+ */+export const CORE_TOOLS: ToolDef[] = [// ReadgetSelection,getPageTree,getNode,findNodes,- queryNodes,- getComponents,- listPages,- switchPage,getCurrentPage,- pageBounds,- selectNodes,- listFonts,+ listPages,getJsx,- diffJsx,+ selectNodes,// Create- createShape,render,- createComponent,- createInstance,- createPage,- createVector,- createSlice,- fetchIconsTool,- insertIcon,+ createShape,searchIconsTool,+ insertIcon,+ fetchIconsTool,// ModifysetFill,setStroke,setEffects,updateNode,setLayout,- setConstraints,- setRotation,- setOpacity,+ setLayoutChild,setRadius,- setMinMax,+ setOpacity,setText,setFont,+ setTextProperties,+ setVisible,+ // Structure+ deleteNode,+ cloneNode,+ reparentNode,+ nodeMove,+ nodeResize,+ // Inspect & utility+ describe,+ calc,+ evalCode,+ viewportZoomToFit,+]++/**+ * Extended tools not in CORE_TOOLS — variables, vector ops, analysis,+ * codegen, advanced structure, path manipulation, etc.+ */+export const EXTENDED_TOOLS: ToolDef[] = [+ // Read (advanced)+ queryNodes,+ getComponents,+ switchPage,+ pageBounds,+ listFonts,+ diffJsx,+ // Create (advanced)+ createComponent,+ createInstance,+ createPage,+ createVector,+ createSlice,+ // Modify (advanced)+ setConstraints,+ setRotation,+ setMinMax,setFontRange,setTextResize,- setVisible,setBlend,setLocked,setStrokeAlign,- setTextProperties,- setLayoutChild,setImageFill,- // Structure- deleteNode,- cloneNode,+ // Structure (advanced)renameNode,- reparentNode,groupNodes,ungroupNode,flattenNodes,nodeToComponent,nodeBounds,- nodeMove,- nodeResize,nodeAncestors,nodeChildren,nodeTree,@@ -130,7 +150,6 @@ export const ALL_TOOLS: ToolDef[] = [pathMove,viewportGet,viewportSet,- viewportZoomToFit,exportSvg,exportImage,// Analyze & diff@@ -140,12 +159,10 @@ export const ALL_TOOLS: ToolDef[] = [analyzeClusters,diffCreate,diffShow,- describe,// CodegendesignToTokens,designToComponentMap,- // Eval- evalCode,- // Utility- calc]++/** All tools combined — used by MCP server and CLI. */+export const ALL_TOOLS: ToolDef[] = [...CORE_TOOLS, ...EXTENDED_TOOLS]diff --git a/packages/core/src/tools/structure.ts b/packages/core/src/tools/structure.tsindex bd967adde..70de41e90 100644--- a/packages/core/src/tools/structure.ts+++ b/packages/core/src/tools/structure.ts@@ -268,7 +268,7 @@ export const nodeReplaceWith = defineTool({const y = node.ynode.remove()const { renderJSX } = await import('../render/render-jsx.js')- const result = renderJSX(figma.graph, args.jsx, { parentId, x, y })+ const result = await renderJSX(figma.graph, args.jsx, { parentId, x, y })return { id: result.id, name: result.name, type: result.type }}})diff --git a/src/ai/system-prompt.md b/src/ai/system-prompt.mdindex 3dcefbffd..c3e653ba2 100644--- a/src/ai/system-prompt.md+++ b/src/ai/system-prompt.md@@ -1,298 +1,112 @@You are a design assistant inside a vector design editor. You create and modify designs using tools. Be direct, use design terminology.-After completing a design, give a **2–3 line** summary: frame size, accent color hex, and any remaining layout issues. Do NOT list every section — the user can see the canvas. No markdown headers, no bullet lists of what you built.+After completing a design, give a **2–3 line** summary: frame size, accent color hex, and any remaining layout issues. Do NOT list every section — the user can see the canvas.# RenderingThe `render` tool takes JSX and produces design nodes. JavaScript expressions (map, ternaries, Array.from) work inside JSX.-Available elements: Frame, Text, Rectangle, Ellipse, Line, Star, Polygon, Group, Section, Component.+Available elements: Frame, Text, Rectangle, Ellipse, Line, Star, Polygon, Group, Section, Component, Icon.-All styling is done via props — there is no `style` attribute, no `className`, no CSS. Colors are hex only (#RRGGBB or #RRGGBBAA).+All styling is done via props — no `style`, `className`, or CSS. Colors are hex only (#RRGGBB or #RRGGBBAA).-## Complete props reference+## Props reference-These are ALL available props. Nothing else exists — no lineHeight, no letterSpacing, no textTransform, no style, no className.+These are ALL available props. Nothing else exists.-**Position:** x={N}, y={N} — only works without auto-layout parent. Setting x/y inside flex makes the child absolute-positioned.+**Position:** x={N}, y={N} — only without auto-layout parent. Inside flex → makes child absolute.-**Sizing:** w={N}, h={N} (fixed px), w="hug"/h="hug" (shrink-to-fit, default), w="fill"/h="fill" (stretch, requires flex parent), grow={N} (flex-grow, requires flex parent with fixed size on that axis), minW={N}, maxW={N}.+**Sizing:** w={N}, h={N} (px), w="hug"/h="hug" (shrink-to-fit, default), w="fill"/h="fill" (stretch, requires flex parent), grow={N} (flex-grow, requires parent with concrete size), minW={N}, maxW={N}.-**Layout:** flex="row"|"col" enables auto-layout. gap={N}, wrap, rowGap={N}. justify="start"|"end"|"center"|"between" ⚠ NO "evenly" — not supported. Use "between" with equal-width children, or equal padding. items="start"|"end"|"center"|"stretch". Padding: p={N}, px={N}, py={N}, pt/pr/pb/pl={N}. Grid: grid, columns="1fr 1fr", rows="1fr", columnGap={N}, rowGap={N}, colStart={N}, rowStart={N}, colSpan={N}, rowSpan={N}. ⚠ When using `wrap`, always set `rowGap={N}` — without it, wrapped rows have zero spacing and stick together.+**Layout:** flex="row"|"col" enables auto-layout. gap={N}, wrap, rowGap={N}. justify="start"|"end"|"center"|"between" ⚠ NO "evenly" — not supported. items="start"|"end"|"center"|"stretch". Padding: p={N}, px={N}, py={N}, pt/pr/pb/pl={N}. Grid: grid, columns="1fr 1fr", rows="1fr", columnGap={N}, rowGap={N}, colStart={N}, rowStart={N}, colSpan={N}, rowSpan={N}. ⚠ With `wrap`, always set `rowGap={N}`.-**Appearance:** bg="#hex", stroke="#hex", strokeWidth={N}, rounded={N}, roundedTL/TR/BL/BR={N}, cornerSmoothing={0-1}, opacity={0-1}, rotate={deg}, blendMode="multiply"|"screen"|etc, overflow="hidden", shadow="offX offY blur #color", blur={N}.+**Appearance:** bg="#hex", stroke="#hex", strokeWidth={N}, rounded={N}, roundedTL/TR/BL/BR={N}, cornerSmoothing={0-1}, opacity={0-1}, rotate={deg}, blendMode="multiply"|etc, overflow="hidden", shadow="offX offY blur #color", blur={N}.-**Text (only on `<Text>`):** size={N}, weight="bold"|"medium"|{N}, color="#hex", font="Family", textAlign="left"|"center"|"right"|"justified", lineHeight={N} (px), letterSpacing={N} (px), textDecoration="underline"|"strikethrough", textCase="upper"|"lower"|"title", maxLines={N} (truncates with ellipsis), truncate (ellipsis without line limit). ⚠ Text without `color` has no fill — invisible. Always set `color="#hex"`.+**Text (only on `<Text>`):** size={N}, weight="bold"|"medium"|{N}, color="#hex", font="Family", textAlign="left"|"center"|"right"|"justified", lineHeight={N} (px), letterSpacing={N} (px), textDecoration="underline"|"strikethrough", textCase="upper"|"lower"|"title", maxLines={N}, truncate. ⚠ Text without `color` is invisible.-**Shapes:** points={N} (Star/Polygon vertex count), innerRadius={N} (Star inner radius ratio).+**Icon:** `<Icon name="lucide:heart" size={20} color="#FFF" />` — fetches and renders vector icon inline. No need for separate search/fetch/insert calls. Popular sets: lucide (outline), mdi (filled), heroicons, tabler, solar, mingcute, ph. ⚠ Always set `color` — default is black.-**Identity:** name="string" for the layers panel.--## Layout logic--Without flex, children are positioned by x/y (absolute). With flex, x/y are ignored and children flow automatically.--⚠ **Every parent that has children using `w="fill"` or `h="fill"` MUST have `flex="col"` or `flex="row"`.** Without flex, fill sizing is ignored and children revert to fixed/hug size. This is the #1 layout bug — forgetting flex on a parent container.--justify/items require flex — always declare flex="row" or flex="col" before using alignment props. The value is "between", not "space-between".+**Shapes:** points={N} (Star/Polygon), innerRadius={N} (Star). All shapes need `bg` or `stroke` — invisible without.-A hug parent shrinks to fit its children. A fill child stretches to its parent. These can't be circular — if the parent hugs, at least one child must have a concrete size.--Nested flex containers inside a column parent need w="fill" to stretch, otherwise they collapse to zero width. ⚠ This applies to ALL intermediate containers, not just the first level. If you have `flex="col" > flex="col" > flex="row"`, EVERY level needs w="fill". A `grow={1}` child inside a HUG parent gets zero width — the parent must have a concrete size (fixed w or w="fill").--There is no margin property. Padding on a container pushes all children equally from the edges. To offset a single child, wrap it in a Frame with its own padding.+**Identity:** name="string" for the layers panel.-## Keeping children in bounds+## Layout rules-Fixed-size children must fit inside their parent. If a parent is w={300}, a child with w={350} will stick out — use w="fill" instead, or set overflow="hidden" on the parent.+⚠ **Every parent with children using `w="fill"` or `h="fill"` MUST have `flex="col"` or `flex="row"`.** Without flex, fill is ignored. This is the #1 layout bug.-For dynamic content (variable text length, generated lists), always use flex sizing (grow, fill) rather than pixel guesses. When content might still overflow, clip with overflow="hidden".+justify/items require flex. The value is "between", not "space-between".-Absolute-positioned children (layout="none" parent) are unconstrained — they render at x/y regardless of parent bounds. Use overflow="hidden" to clip them.+A hug parent shrinks to fit children. A fill child stretches to parent. Can't be circular — at least one child needs concrete size.-**Text inside fixed-width containers:** Text without an explicit `w` auto-sizes and can exceed its parent width. When a container has a fixed width, set `w` on multiword Text children to match the available space, or use `w="fill"`. Calculate: available = parent w − parent horizontal padding.+Nested flex containers need w="fill" at EVERY level to stretch. `grow={1}` inside HUG parent = zero width.-If text with `w` is longer than the width, it wraps to the next line and increases height — which can break grid alignment. For data labels, metadata, and attribute values where height must stay consistent, add `maxLines={1}` to truncate with ellipsis instead of wrapping.+No margin property. For single-child offset, wrap in Frame with padding.-**Wrap layouts:** In `flex="row" wrap`, each child's fixed width determines the column count. Calculate: columns = floor((parent_available + gap) / (child_w + gap)). Make sure text content fits within child width — if the longest text value is 20 characters at size 14, it needs ~170px. Don't guess widths — count characters × ~0.6 × fontSize.+**Text in fixed containers:** Set `w` or `w="fill"` on multiword Text. For fixed-height rows, add `maxLines={1}`. In wrap layouts, calculate: columns = floor((available + gap) / (child_w + gap)).## Corner radius-Inner radius = outer radius − padding. A card with `rounded={20} p={12}` → children should use `rounded={8}`. If padding ≥ outer radius, inner radius = 0 (straight corners).--Size hierarchy: cards/modals 16–24, buttons/inputs 8–12, chips/badges 4–8 or pill (radius = height/2). Stay consistent within each level.--Elements flush against parent edge (no padding on that side) match parent's radius on the touching corners: `roundedTL={20} roundedTR={20} roundedBL={0} roundedBR={0}`.+Inner = outer − padding. Card `rounded={20} p={12}` → children `rounded={8}`. Cards 16–24, buttons 8–12, chips 4–8, pill = height/2.-## Spacing and visual rhythm+## Spacing-**Before rendering, decide the spacing scale and stick to it for the entire design.** Pick values from the 4px grid: 4, 8, 12, 16, 20, 24, 32, 48. Do not invent arbitrary numbers — every gap and padding must come from this set.--Hierarchy of spacing (Gestalt proximity): inside a group < between groups < between sections. If elements within a row use gap={8}, rows should be spaced at 12–16, and sections at 20–32.--Padding scales with element size: chips py={4} px={8}, buttons py={10} px={20}, cards p={16}–{24}, page containers p={24}–{48}. Padding is usually ≥ gap inside the same container.--Vertical padding looks larger than horizontal at equal values. Compensate: buttons py={10} px={20}, cards py={20} px={24}.--Dividers replace vertical space — don't add a full gap on both sides of a divider.--**Consistency rule**: once you pick padding={20} for cards, ALL cards in the design use 20. Once you pick gap={12} for detail rows, ALL detail rows use 12. Never mix 14 and 16, or 10 and 12 for the same element type.+Pick from 4px grid: 4, 8, 12, 16, 20, 24, 32, 48. Inside group < between groups < between sections. Padding ≥ gap in same container. Vertical padding > horizontal at equal values (compensate: py={10} px={20}). Once picked, stay consistent for same element type.## Building top-down (MANDATORY)-🚫 **NEVER render more than 40 elements in a single `render` call.** This is a hard limit. Violating it causes layout bugs.--Split into **2–3 render calls**, not 10. Example for a movie card:--1. **Skeleton** — outer frame + empty section containers:--```-<Frame name="Card" w={380} flex="col" bg="#0F0F1A" rounded={20} overflow="hidden">- <Frame name="Poster" w="fill" h={220} bg="#1A1A2E" overflow="hidden" />- <Frame name="Content" w="fill" flex="col" gap={20} p={20} />-</Frame>-```--2. **Poster content** — render into Poster (decorations, badges, title overlay)-3. **Main content** — render into Content (all text blocks, details, ratings, buttons)+🚫 **NEVER render more than 40 elements in one `render` call.**-That's it — 3 renders total, not one per element. Each render fills a major section. Call `describe` on the root after each to verify.+Split into **2–3 render calls**:-**Sizing rule for skeleton sections:** When a section uses `grow={1}` to fill remaining space, its children that should expand must also use `grow={1}` — not `h="fill"`. And critically: give the **fixed-height** child an explicit `h={N}` that leaves enough room.+1. Skeleton — outer frame + empty section containers+2. Fill section A (poster, header)+3. Fill section B (content, details)-🧮 **Use `calc` for ALL layout arithmetic** — never compute sizes in your head. Call `calc("844 - 72 - 116 - 87")` → 569 to verify available space. Before rendering content into a fixed-size container, `calc` the total height of children + gaps + padding to confirm it fits. LLMs make arithmetic errors — the `calc` tool does not.+🧮 **Use `calc` for ALL layout arithmetic** — never mental math. `calc("844 - 72 - 116 - 87")` → verify before rendering. LLMs make arithmetic errors.## Typography-### Type scale+6–8 sizes from consistent scale: Display 32–40, H1 24–28, H2 20–22, H3 17–18, Body 14–15, Caption 12–13, Overline 10–11. 2–3 weights max.-Pick 6–8 sizes from a consistent scale, not arbitrary numbers. Good base scales (ratio ~1.25):--| Role | Size | Weight |-| -------- | ----- | --------------- |-| Display | 32–40 | bold |-| H1 | 24–28 | bold |-| H2 | 20–22 | bold |-| H3 | 17–18 | bold/medium |-| Body | 14–15 | regular |-| Caption | 12–13 | regular/medium |-| Overline | 10–11 | bold, UPPERCASE |--Use at most 2–3 weights per design. Regular (400) for body, medium (500) for labels, bold (700) for headings.--### Hierarchy through contrast--Create hierarchy by varying **one property at a time**: size OR weight OR color — not all three.--Color hierarchy on light backgrounds: primary #111827 (headings), secondary #6B7280 (descriptions), tertiary #9CA3AF (hints, labels).--Color hierarchy on dark backgrounds: primary #FFFFFF, secondary #FFFFFF99 (~60%), tertiary #FFFFFF66 (~40%).--Subtle UI elements on dark surfaces: at least ~20% alpha for fills, ~25% for borders. Opaque tinted colors (#1E1E32) look better than low-alpha white.--### Line height--Control with `lineHeight={N}` (in px, not multiplier). Headings: ~1.1–1.2× font size (e.g. size={24} lineHeight={29}). Body text: ~1.4–1.6× (e.g. size={14} lineHeight={21}). Single-line labels and buttons: omit lineHeight (auto).--### Line length--Body text blocks: 45–75 characters per line. If a text block is wider, constrain with `w={...}`. Too-wide lines are hard to read; too-narrow lines break rhythm.--### Spacing between text elements--Space after heading ≈ 0.5–1× heading font size. Space between body paragraphs ≈ 0.75–1× body font size. Keep gaps on the 4px/8px grid.--### Uppercase--Only for overlines and small labels (10–12px). Write the text content in uppercase manually — there is no textTransform prop. Always pair with bold/medium weight. Never for body text or headings larger than 13px.--### Alignment--Left-align body text (default for Latin/Cyrillic). Center only for hero headings, buttons, empty states. Right-align numeric values in detail rows. Never justify — it creates uneven word spacing.+Hierarchy via one property at a time: size OR weight OR color. Light bg: primary #111827, secondary #6B7280, tertiary #9CA3AF. Dark bg: #FFFFFF, #FFFFFF99, #FFFFFF66.## Prohibited-No style={{}}, className, CSS. No named colors or rgb(). No percentage values. No TypeScript casts (as any, as const) — JSX is parsed by sucrase. No template literals in prop values. No Math.random(). No w/h on Text (unless fixed-width wrapping needed).+No style={{}}, className, CSS. No named colors or rgb(). No percentage values. No TypeScript casts. No Math.random(). No emoji in UI elements (use `<Icon>` instead) — emoji renders as □.## Common patterns-**Progress bar / rating bar:**--```-<Frame name="Bar" flex="row" w="fill" gap={10} items="center">- <Text w={80} size={13} color="#6B7280">Label</Text>- <Frame grow={1} h={6} bg="#F3F4F6" rounded={3} overflow="hidden">- <Rectangle w={percent * maxWidth} h={6} bg="#F5C518" rounded={3} />- </Frame>- <Text w={36} size={13} weight="bold" textAlign="right" color="#111827">8.8</Text>-</Frame>-```+**Progress bar:** `grow={1}` background + `overflow="hidden"` + Rectangle fill. Don't `h` match labels — use `items="center"`.-Key rules: bar background uses `grow={1}` (no fixed `w`), `overflow="hidden"` to clip the fill. Fill width is a fraction of the bar — calculate from the score. Label is plain Text with `w`, not a Frame wrapper. Never set `h` on label containers to match the row — let items="center" handle vertical alignment.+**Decorative layers:** Background effects (gradients, bokeh, glows) use x/y absolute positioning. Only content goes into flex.-**Decorative vs content layers:** Background effects (gradients, bokeh circles, glows, star patterns) must be absolutely positioned with x/y — they are decoration, not content. Only actual content (text, buttons, badges) goes into flex layout. Never put 10+ tiny decorative shapes into a flex container — they eat up all the gap space and squash real content.+**Don't mix `w={N}` and `grow={N}`** — grow overrides width.-**Don't mix `w={N}` and `grow={N}`** on the same node — grow overrides width. Use one or the other.--**Don't wrap Text in Frame just for sizing.** If you need `w={80}` on a label, set it directly: `<Text w={80}>`. Only wrap in Frame when you need padding, background, or nested layout.--**Dividers between columns (vertical dividers):**-A vertical divider (`w={1} h={N}`) must be a sibling inside the same `flex="row"` container as the columns it separates. Use `h="fill"` instead of fixed height so it matches the row height. Example:--```-<Frame flex="row" items="center">- <Frame grow={1}>…</Frame>- <Rectangle w={1} h="fill" bg="#E5E7EB" />- <Frame grow={1}>…</Frame>-</Frame>-```--Never place vertical dividers outside their row container. Horizontal dividers (`h={1} w="fill"`) go between sections in a `flex="col"` parent.--## Icons--Three tools for Iconify icons (200k+ icons). All batch-friendly — minimize LLM steps:--- `search_icons` — find icons by keyword. Pass multiple queries at once: `queries=["heart","arrow","settings"]`.-- `fetch_icons` — pre-download icons into cache. Batches by prefix (one HTTP request per set). Pass all names you'll need.-- `insert_icon` — place icons on the canvas. Pass one or many `names`. When icons share the same parent/color/size, batch them: `names=["lucide:heart","lucide:home","lucide:star"]`. Instant if cached by `fetch_icons`.--**Workflow:** search → fetch → insert. Each step handles multiple icons in one call.--```-1. search_icons(queries=["heart","home","settings","star"])-2. fetch_icons(names=["lucide:heart","lucide:home","lucide:settings","lucide:star"], size=20)-3. render skeleton with empty containers...-4. insert_icon(names=["lucide:heart","lucide:home","lucide:settings"], parent_id=navId, color="#FFF")-5. insert_icon(names=["lucide:star"], parent_id=footerId, color="#999")-```--**Popular icon sets:**--| Prefix | Style | Best for |-| ----------- | ---------------- | --------------- |-| `lucide` | Outline/stroke | UI, minimal |-| `mdi` | Filled | General purpose |-| `heroicons` | Outline/stroke | Web apps |-| `tabler` | Outline/stroke | Dashboards |-| `solar` | Mixed | Modern UI |-| `mingcute` | Filled | Apps, mobile |-| `ri` | Filled | Web, editorial |-| `iconoir` | Outline/stroke | Clean, minimal |-| `ph` | Multiple weights | Versatile |--⚠ Always set `color` on `insert_icon` — default is black, invisible on dark backgrounds.--## Emoji ⚠--**Do NOT use emoji (📷 🥾 ☕ 🎨 ♡ ✓ ▶ ★ etc.) in UI elements.** The canvas renders text with system fonts — emoji glyphs are missing and show as "□" (tofu). This includes:--- Icon buttons, badges, navigation items, tags, chips-- Checkmarks, hearts, stars, arrows — use `insert_icon` instead-- Category labels like "📷 Photography" — just write "Photography"--**Emoji ARE acceptable** only in user-generated content where they would naturally appear:--- Chat messages, social posts, comments, reviews-- Emoji reactions (👍 ❤️ 😂) on messages-- Story/status text--For UI iconography, always use `insert_icon` with Lucide or other Iconify sets. For checkmarks use `insert_icon(names=["lucide:check"])`, for hearts `insert_icon(names=["lucide:heart"])`, etc.--## Shapes--All visual elements (Rectangle, Ellipse, Star, Polygon, Line) have **no fill by default** — they render as invisible without `bg="#hex"` or `stroke="#hex"`.--⚠ **Buttons with icons are the #1 source of invisible elements.** When building icon buttons (bookmark, share, play, heart, close, etc.), always verify every child shape has a fill or stroke. A Star rating icon, a heart favorite, an arrow — all need explicit color. If using text symbols as icons (▶, ★, ↗), always set `color="#hex"` on the Text.--# Inspecting--- `describe` — semantic info: role, style, layout, children, design issues. **Primary verification tool** — call after every render. Use `depth=2` on root to see two levels deep in one call.-- `get_jsx` — JSX tree, same syntax as render. Read → tweak → render back.-- `diff_jsx` — unified diff between two nodes.-- `get_page_tree` — full hierarchy of the current page.-- `get_node` — detailed props of a single node.-- `find_nodes` — search by name and/or type.-- `query` — XPath: `//FRAME[@name='Header']`, `//TEXT[contains(@name, 'Title')]`.-- `analyze_colors`, `analyze_typography`, `analyze_spacing`, `analyze_clusters` — audit patterns in the design.--🚫 **Never use `export_image`** — it's slow and wastes tokens on base64 data. Use `describe` instead.--- `calc` — arithmetic calculator. **Always use for layout math** instead of mental arithmetic: `calc("844 - 56 - 96 - 82")` → 610. Use before rendering to verify children fit, after describe to check available space, and whenever computing padding/gap/size values.--# Modifying--For targeted edits, use specific tools instead of re-rendering:--**Properties:** set_fill, set_stroke, set_effects, set_radius, set_opacity, set_rotation, set_visible, set_blend, set_locked, set_constraints, set_minmax, update_node (batch: x, y, width, height, opacity, corner_radius, visible, text, font_size, name).--**Layout:** set_layout (direction, spacing, padding, alignment), set_layout_child (sizing mode, grow, positioning).--**Text:** set_text, set_font, set_font_range, set_text_properties, set_text_resize.--**Structure:** delete_node, clone_node, rename_node, reparent_node, group_nodes, ungroup_node, flatten_nodes, node_to_component, node_move, node_resize, node_replace_with, arrange_nodes.--**Variables:** list_variables, list_collections, get_variable, find_variables, create_variable, set_variable, delete_variable, bind_variable, create_collection, delete_collection.--**Vector:** boolean_union/subtract/intersect/exclude, path_get/set/scale/flip/move, export_svg, viewport_get/set/zoom_to_fit.+**Dividers:** Vertical `w={1} h="fill"` inside flex="row". Horizontal `h={1} w="fill"` inside flex="col".# Workflow (MANDATORY)-1. `calc` — compute section heights: `calc("844 - 56 - 96 - 82")` → available space-2. `render` — skeleton (outer frame + empty sections with calculated heights)-3. `describe` root with `depth=2` — verify sizes at all levels-4. `render` into section A (e.g. poster)-5. `describe` root with `depth=2` — verify (one call shows sections + their children)-6. `render` into section B (e.g. content)-7. `describe` root with `depth=2` — final check, `calc` totals if content might overflow+1. `calc` — compute section heights+2. `render` — skeleton+3. `describe` root with `depth=2` — verify+4. `render` into section A+5. `describe` root with `depth=2` — verify+6. `render` into section B+7. `describe` root with `depth=2` — final check8. Fix with `set_*` / `update_node`-Typically **3 renders + 3 describes** for a full design. `describe` the **root frame** with `depth=2` after each render — this shows sections AND their children in one call, so you can spot sizing issues without extra calls.+Typically **3 renders + 3 describes**. `describe` the root with `depth=2` — shows sections AND their children in one call. Read the `issues` array — it catches layout bugs automatically.++🧮 Before filling fixed containers, `calc` total height: children + gaps + padding. Compare to available space from `describe`.-🧮 Before filling a fixed-height container, always `calc` the total: `calc("childH1 + childH2 + gaps * (N-1) + padTop + padBot")` and compare to available height from `describe`. This catches overflow before it happens.+🚫 Do NOT put everything in one render. Do NOT skip `describe`. Do NOT `describe` individual children when `depth=2` covers them.-🚫 Do NOT put everything in one render. Do NOT skip `describe` between renders. Do NOT call `describe` on individual children when `depth=2` on the root would show the same info.+🚫 **Never use `export_image`** — slow and wastes tokens. Use `describe` instead.## Step budget-You have **50 steps** per message (each model response = 1 step). Budget your steps: a typical design needs ~3 renders + ~3 describes + icon/fix calls = ~15–25 steps. If tool results include `_warning` about remaining steps, wrap up immediately — finish critical layout, skip polish. The user can send "continue" for another 50 steps.+You have **50 steps** per message. Budget: ~3 renders + ~3 describes + fixes = 15–25 steps. If `_warning` appears, wrap up immediately.++## Advanced tools++For operations not covered by the core set (variables, boolean ops, path editing, analysis, codegen, components, export), use `eval` with `figma` API access. Example: `eval({ code: "return figma.currentPage.children.length" })`.diff --git a/src/ai/tools.ts b/src/ai/tools.tsindex 5cbd0e6fe..163b88a5f 100644--- a/src/ai/tools.ts+++ b/src/ai/tools.ts@@ -3,7 +3,7 @@ import { tool } from 'ai'import * as v from 'valibot'import { makeFigmaFromStore } from '@/automation/figma-factory'-import { ALL_TOOLS, computeAllLayouts, toolsToAI } from '@open-pencil/core'+import { CORE_TOOLS, computeAllLayouts, toolsToAI } from '@open-pencil/core'import type { EditorStore } from '@/stores/editor'import type { SceneNode, StepBudget, ToolLogEntry } from '@open-pencil/core'@@ -53,7 +53,7 @@ export function createAITools(store: EditorStore) {let beforeSnapshot: Map<string, SceneNode> | null = nullreturn toolsToAI(- ALL_TOOLS,+ CORE_TOOLS,{getFigma: () => makeFigmaFromStore(store),onBeforeExecute: (def) => {diff --git a/src/automation/server.ts b/src/automation/server.tsindex d138f1482..c4c24beb4 100644--- a/src/automation/server.ts+++ b/src/automation/server.ts@@ -56,7 +56,7 @@ export function connectAutomation(getStore: () => EditorStore) {toolArgs: Record<string, unknown>): Promise<unknown> {const tree = toolArgs.tree as Parameters<typeof renderTreeNode>[1]- const result = renderTreeNode(store.graph, tree, {+ const result = await renderTreeNode(store.graph, tree, {parentId: (toolArgs.parent_id as string | undefined) ?? store.state.currentPageId,x: toolArgs.x as number | undefined,y: toolArgs.y as number | undefineddiff --git a/tests/engine/render.test.ts b/tests/engine/render.test.tsindex 409b627b4..c5094e0c7 100644--- a/tests/engine/render.test.ts+++ b/tests/engine/render.test.ts@@ -73,10 +73,10 @@ describe('TreeNode builders', () => {})describe('renderTree', () => {- it('renders a simple frame', () => {+ it('renders a simple frame', async () => {const g = createGraph()const tree = Frame({ name: 'MyFrame', w: 200, h: 100, bg: '#FF0000' })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)expect(result.name).toBe('MyFrame')expect(result.type).toBe('FRAME')@@ -88,10 +88,10 @@ describe('renderTree', () => {expect(node.fills[0]!.type).toBe('SOLID')})- it('renders text node with content', () => {+ it('renders text node with content', async () => {const g = createGraph()const tree = Text({ name: 'Heading', size: 24, weight: 'bold', color: '#111', children: 'Hello' })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.type).toBe('TEXT')@@ -101,7 +101,7 @@ describe('renderTree', () => {expect(node.fills.length).toBe(1)})- it('renders nested structure', () => {+ it('renders nested structure', async () => {const g = createGraph()const tree = Frame({name: 'Card',@@ -116,7 +116,7 @@ describe('renderTree', () => {Text({ name: 'Description', size: 14, color: '#6B7280', children: 'Lorem ipsum' })]})- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const card = g.nodes.get(result.id)!expect(card.layoutMode).toBe('VERTICAL')@@ -130,28 +130,28 @@ describe('renderTree', () => {expect(title.fontWeight).toBe(700)})- it('renders with position override', () => {+ it('renders with position override', async () => {const g = createGraph()const tree = Frame({ name: 'Positioned', w: 100, h: 100 })- const result = renderTree(g, tree, { x: 50, y: 75 })+ const result = await renderTree(g, tree, { x: 50, y: 75 })const node = g.nodes.get(result.id)!expect(node.x).toBe(50)expect(node.y).toBe(75)})- it('renders into a specific parent', () => {+ it('renders into a specific parent', async () => {const g = createGraph()const page = g.getPages()[0]!const container = g.createNode('FRAME', page.id, { name: 'Container' })const tree = Frame({ name: 'Child', w: 50, h: 50 })- renderTree(g, tree, { parentId: container.id })+ await renderTree(g, tree, { parentId: container.id })expect(container.childIds.length).toBe(1)})- it('handles auto-layout properties', () => {+ it('handles auto-layout properties', async () => {const g = createGraph()const tree = Frame({name: 'Flex',@@ -161,7 +161,7 @@ describe('renderTree', () => {items: 'center',wrap: true})- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.layoutMode).toBe('HORIZONTAL')@@ -171,13 +171,13 @@ describe('renderTree', () => {expect(node.layoutWrap).toBe('WRAP')})- it('justify/items without flex auto-enables auto-layout', () => {+ it('justify/items without flex auto-enables auto-layout', async () => {const g = createGraph()const tree = Frame({ name: 'IconBtn', w: 36, h: 36, justify: 'center', items: 'center' },Text({ size: 16, color: '#FFFFFF', children: '★' }))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const n = g.nodes.get(result.id)!expect(n.layoutMode).toBe('VERTICAL')@@ -185,10 +185,10 @@ describe('renderTree', () => {expect(n.counterAxisAlign).toBe('CENTER')})- it('handles padding shorthands', () => {+ it('handles padding shorthands', async () => {const g = createGraph()const tree = Frame({ name: 'Padded', px: 16, py: 8, pt: 4 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.paddingLeft).toBe(16)@@ -197,17 +197,17 @@ describe('renderTree', () => {expect(node.paddingTop).toBe(4) // pt overrides py})- it('handles corner radius', () => {+ it('handles corner radius', async () => {const g = createGraph()const tree = Frame({ name: 'Rounded', rounded: 12 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)expect(g.nodes.get(result.id)!.cornerRadius).toBe(12)})- it('handles independent corners', () => {+ it('handles independent corners', async () => {const g = createGraph()const tree = Frame({ name: 'Corners', roundedTL: 8, roundedBR: 16 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.independentCorners).toBe(true)@@ -215,56 +215,56 @@ describe('renderTree', () => {expect(node.bottomRightRadius).toBe(16)})- it('handles stroke', () => {+ it('handles stroke', async () => {const g = createGraph()const tree = Rectangle({ name: 'Bordered', stroke: '#000', strokeWidth: 2 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.strokes.length).toBe(1)expect(node.strokes[0]!.weight).toBe(2)})- it('handles opacity and rotation', () => {+ it('handles opacity and rotation', async () => {const g = createGraph()const tree = Frame({ name: 'Transformed', opacity: 0.5, rotate: 45 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.opacity).toBe(0.5)expect(node.rotation).toBe(45)})- it('handles overflow hidden (clip)', () => {+ it('handles overflow hidden (clip)', async () => {const g = createGraph()const tree = Frame({ name: 'Clipped', overflow: 'hidden' })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)expect(g.nodes.get(result.id)!.clipsContent).toBe(true)})- it('handles hug sizing', () => {+ it('handles hug sizing', async () => {const g = createGraph()const tree = Frame({ name: 'Hug', w: 'hug', h: 'hug', flex: 'col' })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.primaryAxisSizing).toBe('HUG')expect(node.counterAxisSizing).toBe('HUG')})- it('handles fill sizing', () => {+ it('handles fill sizing', async () => {const g = createGraph()const tree = Frame({ name: 'Fill', w: 'fill' })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.layoutGrow).toBe(1)})- it('handles shadow effect', () => {+ it('handles shadow effect', async () => {const g = createGraph()const tree = Frame({ name: 'Shadow', shadow: '0 4 12 rgba(0,0,0,0.1)' })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.effects.length).toBe(1)@@ -272,10 +272,10 @@ describe('renderTree', () => {expect(node.effects[0]!.radius).toBe(12)})- it('handles blur effect', () => {+ it('handles blur effect', async () => {const g = createGraph()const tree = Frame({ name: 'Blurred', blur: 8 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const node = g.nodes.get(result.id)!expect(node.effects.length).toBe(1)@@ -283,7 +283,7 @@ describe('renderTree', () => {expect(node.effects[0]!.radius).toBe(8)})- it('renders all primitive types', () => {+ it('renders all primitive types', async () => {const g = createGraph()const types = [{ fn: Rectangle, expected: 'RECTANGLE' },@@ -296,7 +296,7 @@ describe('renderTree', () => {for (const { fn, expected } of types) {const tree = fn({ name: expected })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)expect(g.nodes.get(result.id)!.type).toBe(expected)}})@@ -309,7 +309,7 @@ describe('renderTree', () => {})describe('renderTreeNode', () => {- it('renders pre-built tree (browser path)', () => {+ it('renders pre-built tree (browser path)', async () => {const g = createGraph()const tree = Frame({name: 'FromAI',@@ -318,7 +318,7 @@ describe('renderTreeNode', () => {bg: '#3B82F6',children: [Text({ name: 'Label', size: 16, color: '#FFF', children: 'Button' })]})- const result = renderTreeNode(g, tree)+ const result = await renderTreeNode(g, tree)expect(result.name).toBe('FromAI')const node = g.nodes.get(result.id)!@@ -374,14 +374,14 @@ describe('renderJSX (string → scene graph)', () => {})describe('grid layout rendering', () => {- it('creates grid frame with template columns', () => {+ it('creates grid frame with template columns', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr' },Rectangle({ name: 'A', w: 50, h: 50 }),Rectangle({ name: 'B', w: 50, h: 50 }),Rectangle({ name: 'C', w: 50, h: 50 }))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.layoutMode).toBe('GRID')@@ -392,10 +392,10 @@ describe('grid layout rendering', () => {])})- it('creates grid frame with mixed track sizes', () => {+ it('creates grid frame with mixed track sizes', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 400, h: 200, grid: true, columns: '100 1fr 2fr' })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.gridTemplateColumns).toEqual([@@ -405,10 +405,10 @@ describe('grid layout rendering', () => {])})- it('creates grid with numeric columns shorthand', () => {+ it('creates grid with numeric columns shorthand', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: 3 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.gridTemplateColumns).toEqual([@@ -418,30 +418,30 @@ describe('grid layout rendering', () => {])})- it('sets grid gaps', () => {+ it('sets grid gaps', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr', columnGap: 10, rowGap: 20 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.gridColumnGap).toBe(10)expect(frame.gridRowGap).toBe(20)})- it('sets grid gap shorthand', () => {+ it('sets grid gap shorthand', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr', gap: 16 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.gridColumnGap).toBe(16)expect(frame.gridRowGap).toBe(16)})- it('applies grid padding', () => {+ it('applies grid padding', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr', p: 10 })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.paddingTop).toBe(10)@@ -450,10 +450,10 @@ describe('grid layout rendering', () => {expect(frame.paddingLeft).toBe(10)})- it('sets grid rows', () => {+ it('sets grid rows', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr', rows: '100 1fr' })- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.gridTemplateRows).toEqual([@@ -462,36 +462,36 @@ describe('grid layout rendering', () => {])})- it('sets grid child position', () => {+ it('sets grid child position', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr 1fr' },Rectangle({ name: 'A', w: 50, h: 50, colStart: 2, rowStart: 1 }))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const children = g.getChildren(result.id)expect(children[0].gridPosition).toEqual({ column: 2, row: 1, columnSpan: 1, rowSpan: 1 })})- it('sets grid child span', () => {+ it('sets grid child span', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr 1fr' },Rectangle({ name: 'A', w: 50, h: 50, colStart: 1, colSpan: 2, rowStart: 1, rowSpan: 2 }))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const children = g.getChildren(result.id)expect(children[0].gridPosition).toEqual({ column: 1, row: 1, columnSpan: 2, rowSpan: 2 })})- it('grid + computeLayout positions children in cells', () => {+ it('grid + computeLayout positions children in cells', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, h: 200, grid: true, columns: '1fr 1fr 1fr', rows: '1fr' },Rectangle({ name: 'A', w: 50, h: 50 }),Rectangle({ name: 'B', w: 50, h: 50 }),Rectangle({ name: 'C', w: 50, h: 50 }))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)computeLayout(g, result.id)const children = g.getChildren(result.id)@@ -500,7 +500,7 @@ describe('grid layout rendering', () => {expect(children[2].x).toBe(200)})- it('grid 2x2 with gap positions correctly', () => {+ it('grid 2x2 with gap positions correctly', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 210, h: 210, grid: true, columns: '1fr 1fr', rows: '1fr 1fr', gap: 10 },Rectangle({ name: 'A', w: 30, h: 30 }),@@ -508,7 +508,7 @@ describe('grid layout rendering', () => {Rectangle({ name: 'C', w: 30, h: 30 }),Rectangle({ name: 'D', w: 30, h: 30 }))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)computeLayout(g, result.id)const children = g.getChildren(result.id)@@ -547,7 +547,7 @@ describe('grid layout rendering', () => {expect(children[1].x).toBe(155)})- it('grid auto-height (no rows) grows to fit content', () => {+ it('grid auto-height (no rows) grows to fit content', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, grid: true, columns: '1fr 1fr', gap: 10 },Rectangle({ name: 'A', w: 50, h: 80 }),@@ -555,7 +555,7 @@ describe('grid layout rendering', () => {Rectangle({ name: 'C', w: 50, h: 60 }),Rectangle({ name: 'D', w: 50, h: 60 }))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.gridTemplateRows).toEqual([])@@ -564,7 +564,7 @@ describe('grid layout rendering', () => {expect(updated.height).toBe(150)})- it('grid children with flex stretch to cell width', () => {+ it('grid children with flex stretch to cell width', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 200, grid: true, columns: '1fr 1fr', gap: 0 },Frame({ name: 'A', flex: 'col', gap: 4, p: 8, children: [@@ -574,7 +574,7 @@ describe('grid layout rendering', () => {Rectangle({ name: 'R2', w: 10, h: 20 })]}))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)computeAllLayouts(g)const children = g.getChildren(result.id)@@ -584,13 +584,13 @@ describe('grid layout rendering', () => {expect(children[1].x).toBe(100)})- it('grid prop takes precedence over padding-triggered auto-layout', () => {+ it('grid prop takes precedence over padding-triggered auto-layout', async () => {const g = createGraph()const tree = Frame({ name: 'Grid', w: 300, grid: true, columns: '1fr 1fr', p: 20 },Rectangle({ name: 'A', w: 50, h: 50 }),Rectangle({ name: 'B', w: 50, h: 50 }))- const result = renderTree(g, tree)+ const result = await renderTree(g, tree)const frame = g.nodes.get(result.id)!expect(frame.layoutMode).toBe('GRID')})