AI-native design editor. Open-source Figma alternative.
AI chat: JSX-first rendering, guardrail tools, workflow from figma-use
Danila Poyarkovaf6a98ca5643
diff --git a/docs/ai-chat-design.md b/docs/ai-chat-design.mdindex be876e151..a1ab8f959 100644--- a/docs/ai-chat-design.md+++ b/docs/ai-chat-design.md@@ -25,7 +25,7 @@│ └──────────────────┘```-Key insight: tools execute **in the browser**, not on the server. The LLM runs server-side (OpenRouter), but when it calls a tool like `create_frame`, the tool execution happens in the Vue app where the editor store lives. This is the inverse of beebro-chat where tools run server-side.+Key insight: tools execute **in the browser**, not on the server. The LLM runs server-side (OpenRouter), but when it calls a tool like `render`, the tool execution happens in the Vue app where the editor store lives. This is the inverse of beebro-chat where tools run server-side.**Flow:**1. User types in chat panel → message sent to backend@@ -59,52 +59,89 @@ Toggle: `⌘J` (matches VS Code/Cursor convention) or click AI icon in toolbar.The `SplitterPanel` on the right switches between `<PropertiesPanel>` and `<ChatPanel>` based on state. Both share the same splitter slot — no extra panel.+## AI Workflow++Ported from figma-use's proven workflow pattern:++```+1. Read → snapshot, get_page_tree, find_nodes, get_selection+2. Create → render (JSX), set_*, move_node+3. Verify → screenshot → AI inspects the image+4. Iterate → diff_create to see what changed, fix issues+5. Export → export_jsx for developer handoff+```++The **render** tool (JSX) is the primary creation tool — not individual `create_frame`/`create_text` calls. Individual create/set tools are for surgical edits. JSX lets the AI describe an entire component tree in one call:++```jsx+<Frame name="Card" w={320} h="hug" flex="col" gap={16} p={24} bg="#FFFFFF" rounded={16}>+ <Rectangle name="Image" w="fill" h={200} bg="#E5E7EB" rounded={12} />+ <Text name="Title" size={18} weight="bold" color="#111">Card Title</Text>+ <Text name="Description" size={14} color="#6B7280">Lorem ipsum dolor sit amet</Text>+</Frame>+```++One tool call instead of 6+ sequential calls. Less noisy in the chat, fewer round-trips, better results.++## Guardrail Tools++These are verification/diff tools the AI should use in its loop — ported from figma-use:++| Tool | Purpose |+|------|---------|+| `screenshot` | Render viewport/node to PNG → AI inspects visually |+| `snapshot` | Compact accessibility-tree representation of the design (text, not image) |+| `diff_create` | Structural diff between two nodes/trees — AI sees what actually changed |+| `diff_visual` | Pixel-level diff between two nodes → image showing differences |+| `diff_show` | Preview what a property change would look like before applying |++The AI workflow becomes self-correcting:+1. AI renders JSX → creates a card+2. AI calls `screenshot` → sees the result+3. AI notices spacing is off → calls `diff_show` to preview fix+4. AI applies the fix → calls `screenshot` again to confirm+## Comments as Context-Users can pin comments on the canvas (like Figma's comment mode). These are NOT the collaboration "comments" feature from Phase 6 — they're **AI context annotations**.+Users can pin comments on the canvas (like Figma's comment mode). These are **AI context annotations** — not the collaboration "comments" feature.-When the user sends a chat message, any comments visible in the current viewport (or on selected nodes) are automatically included as context:+When the user sends a chat message, comments visible in the current viewport (or on selected nodes) are automatically included as context:```System prompt includes:-- Current page structure (node tree summary)+- Current page snapshot (compact tree)- Selected nodes with properties-- Visible comments with their positions and attached node IDs+- Visible comments with positions and attached node IDsUser says: "make the spacing consistent"-→ LLM sees the comments like:+→ LLM sees:Comment on Frame "Header": "This should be 16px gap"Comment on Frame "Cards": "Use 8px grid"→ LLM calls set_layout tools with correct spacing```-Comments are stored on the `SceneNode` (new field: `comments: CommentPin[]`) and saved with the .fig/.openpencil file. They persist across sessions.+Comments are stored on `SceneGraph` (not individual nodes) since they can be pinned to empty canvas areas. They persist in the saved file.## Tool Categories### Read tools (context gathering)| Tool | Description ||------|-------------|-| `get_page_tree` | Current page node tree (truncated) |+| `snapshot` | Compact accessibility-tree representation of current page |+| `get_page_tree` | Full node tree (truncated by depth) || `get_node` | Node properties by ID || `get_selection` | Currently selected nodes || `get_children` | Children of a node || `find_nodes` | Search by name/type || `get_comments` | All comment pins |-| `screenshot` | Render current viewport to image |+| `screenshot` | Render viewport/node to image (AI can inspect) |-### Create tools+### Create tools (JSX-first)| Tool | Description ||------|-------------|-| `create_frame` | Frame with optional auto-layout |-| `create_rectangle` | Rectangle |-| `create_ellipse` | Ellipse |-| `create_text` | Text node |-| `create_line` | Line |-| `create_star` | Star |-| `create_polygon` | Polygon |-| `create_instance` | Component instance |-| `create_component` | Convert to component |+| `render` | **Primary** — render JSX tree to canvas (Frame, Text, Rectangle, Ellipse, etc.) |+| `create_instance` | Create component instance by component ID |+| `create_component` | Convert selection to component |### Modify tools| Tool | Description |@@ -123,6 +160,14 @@ Comments are stored on the `SceneNode` (new field: `comments: CommentPin[]`) and| `set_constraints` | Resize constraints || `reparent_node` | Move to different parent |+### Diff / verify tools+| Tool | Description |+|------|-------------|+| `diff_create` | Structural diff between two nodes (unified patch format) |+| `diff_show` | Preview property changes before applying |+| `diff_visual` | Pixel-level diff between two nodes → image |+| `diff_apply` | Apply a diff patch to nodes |+### Organize tools| Tool | Description ||------|-------------|@@ -141,6 +186,12 @@ Comments are stored on the `SceneNode` (new field: `comments: CommentPin[]`) and| `create_variable` | Create variable || `bind_variable` | Bind to node property |+### Export tools+| Tool | Description |+|------|-------------|+| `export_jsx` | Export node as JSX component (developer handoff) |+| `export_node` | Export node as PNG/SVG |+## Tool Call DisplayTool calls render inline in the chat as a collapsible timeline (like beebro-chat's `ToolTimeline`):@@ -148,28 +199,26 @@ Tool calls render inline in the chat as a collapsible timeline (like beebro-chat```User: Create a card component with title, image, and description-AI: I'll create that card component for you.+AI: I'll create that card for you.- ✓ create_frame "Card" 320×400- ✓ create_rectangle "Image" 320×200- ✓ create_text "Title" — "Card Title"- ✓ create_text "Description" — "Lorem ipsum..."- ✓ set_layout vertical, gap=16, padding=16- ✓ create_component → component 0:42+ ✓ render JSX → Card (4 children)+ ✓ screenshot — verified layout+ ✓ create_component → 0:42-Done! I created a Card component with auto-layout.-The image placeholder is 320×200 at the top,-followed by the title and description with 16px spacing.+Here's the Card component with auto-layout, 16px spacing,+and an image placeholder at the top.```Each tool call shows:-- **Icon** — shape icon for creates, paint icon for fills, layout icon for layout, etc.-- **Label** — human-readable: "Create frame" not "create_frame"-- **Summary** — key params: name, dimensions, color value+- **Icon** — shape icon for render, camera for screenshot, diff icon for diffs, etc.+- **Label** — human-readable: "Render JSX" not "render"+- **Summary** — key output: node name, child count, diff percentage- **State** — spinner while executing, ✓ when done, ✗ on error-- **Expandable** — click to see full params and result JSON+- **Expandable** — click to see full params and result-For `screenshot` tool calls, the captured image renders inline in the chat as a thumbnail.+For `screenshot` and `diff_visual`, the image renders inline as a thumbnail.+For `render`, the expanded view shows the JSX source.+For `diff_create`, the expanded view shows the unified diff with syntax highlighting.## Stack@@ -194,69 +243,42 @@ The `useChat()` composable from AI SDK handles:- Tool call/result roundtrip- Abort/cancel-## Tool Definition Pattern+## JSX Render Pipeline-```typescript-// packages/ai/src/tools/create-frame.ts-import { tool } from 'ai'-import * as v from 'valibot'--export const createFrame = tool({- description: 'Create a frame (container) with optional auto-layout',- parameters: v.object({- x: v.number(),- y: v.number(),- width: v.number(),- height: v.number(),- name: v.optional(v.string()),- parent: v.optional(v.string(), 'Parent node ID'),- fill: v.optional(v.string(), 'Hex color'),- layout: v.optional(v.picklist(['HORIZONTAL', 'VERTICAL', 'NONE'])),- gap: v.optional(v.number()),- padding: v.optional(v.number())- })- // execute is provided client-side, not here-})-```+Ported from figma-use's `packages/cli/src/render/`. The JSX renderer:-The tool `execute` functions live in the Vue app (not the server) because they need access to the editor store:+1. Parses JSX string → mini-React element tree (custom JSX runtime, no real React)+2. Walks the tree → maps elements to `SceneGraph.createNode()` calls+3. Applies style shorthands: `w`, `h`, `bg`, `rounded`, `p`, `px`, `py`, `flex`, `gap`, `justify`, `items`, `size`, `weight`, `color`+4. Resolves variable references: `bg="var:Primary"` → binds to variable+5. Resolves icon references: `<Icon name="lucide:star" />` → SVG path+6. Returns created node IDs-```typescript-// src/composables/use-ai-tools.ts-export function useAITools(store: EditorStore) {- return {- create_frame: {- ...createFrameDef,- execute({ x, y, width, height, name, parent, fill, layout, gap, padding }) {- const parentId = parent ?? store.state.currentPageId- const node = store.createShape('FRAME', parentId, { x, y, width, height })- if (name) store.renameNode(node.id, name)- if (fill) store.updateNode(node.id, { fills: [parseFill(fill)] })- if (layout) store.setLayoutMode(node.id, layout)- // ... gap, padding- return { id: node.id, name: node.name }- }- }- }-}-```+Elements: `Frame`, `Rectangle`, `Ellipse`, `Text`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Icon`, `Instance`, `Component`++The renderer lives in `@open-pencil/core` (no DOM deps) so it works both in-browser and headless.## System Prompt```You are an AI design assistant inside OpenPencil, a design editor.-You can create and modify design elements on the canvas.Current page: {pageName}-Selected nodes: {selectedNodesSummary}+{snapshot — compact tree of current page}+Selected: {selectedNodesSummary}Comments: {visibleComments}-Guidelines:-- Use auto-layout (set_layout) for any container with multiple children-- Use 8px grid for spacing (8, 16, 24, 32, 48)-- Name nodes descriptively (not "Frame 1")-- After creating a complex layout, use screenshot to verify it looks correct-- Read the existing design before making changes (get_page_tree)+WORKFLOW:+1. Read the design first (snapshot is above, use get_node for details)+2. Create with render (JSX) for new layouts, set_* for edits+3. Verify with screenshot after complex changes+4. Use diff_create to check what changed if unsure++GUIDELINES:+- Use auto-layout for containers (flex="col" or flex="row")+- 8px spacing grid: 8, 16, 24, 32, 48+- Name everything descriptively+- Use variables for colors when they exist (bg="var:Primary")```## Comment Pin Data Model@@ -265,7 +287,7 @@ Guidelines:interface CommentPin {id: stringtext: string- x: number // canvas coordinates+ x: numbery: numbernodeId?: string // attached to a specific noderesolved: boolean@@ -273,19 +295,19 @@ interface CommentPin {}```-Stored on `SceneGraph` (not individual nodes) since comments can be pinned to empty canvas areas:+Stored on `SceneGraph`:```typescript-// In SceneGraphcomments = new Map<string, CommentPin>()```## Implementation Order-1. **Backend skeleton** — `packages/ai/` with Bun server, single `/api/chat` streaming endpoint, ToolLoopAgent with 2-3 tools-2. **Chat panel UI** — `ChatPanel.vue` with message list, input, tool timeline, toggle via `⌘J`-3. **Core tools** — create_frame, create_text, create_rectangle, set_fill, set_layout, get_page_tree, get_selection-4. **Screenshot tool** — render viewport to PNG, inline in chat-5. **Comment system** — comment pins on canvas, included in AI context-6. **Full tool set** — port remaining tools from figma-use's MCP definitions-7. **Tauri integration** — bundle AI backend as sidecar+1. **JSX renderer in core** — port figma-use's render pipeline to work with our SceneGraph+2. **Backend skeleton** — `packages/ai/` with Bun server, `/api/chat` endpoint, ToolLoopAgent+3. **Chat panel UI** — `ChatPanel.vue` with message list, input, tool timeline, `⌘J` toggle+4. **Core tools** — render (JSX), set_fill, set_layout, set_text, get_page_tree, get_selection, snapshot+5. **Screenshot + diff tools** — screenshot, diff_create, diff_visual, diff_show+6. **Comment system** — comment pins on canvas, included in AI context+7. **Full tool set** — remaining set_*/organize/variable/export tools+8. **Tauri integration** — bundle AI backend as sidecar