AI-native design editor. Open-source Figma alternative.
Add step budget warnings and Continue button for AI chat
Anton A S733321fbb534
diff --git a/bun.lock b/bun.lockindex 5b29edb7a..0281fb9b4 100644--- a/bun.lock+++ b/bun.lock@@ -117,6 +117,7 @@"fzstd": "^0.1.1","nanoevents": "^9.1.0","sucrase": "^3.35.1",+ "svgpath": "^2.6.0","yoga-layout": "npm:@open-pencil/[email protected]",},"devDependencies": {@@ -2257,6 +2258,8 @@"supports-preserve-symlinks-flag": ["[email protected]", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="],+ "svgpath": ["[email protected]", "", {}, "sha512-OIWR6bKzXvdXYyO4DK/UWa1VA1JeKq8E+0ug2DG98Y/vOmMpfZNj+TIG988HjfYSqtcy/hFOtZq/n/j5GSESNg=="],+"swrv": ["[email protected]", "", { "peerDependencies": { "vue": ">=3.2.26 < 4" } }, "sha512-pjllRDr2s0iTwiE5Isvip51dZGR7GjLH1gCSVyE8bQnbAx6xackXsFdojau+1O5u98yHF5V73HQGOFxKUXO9gQ=="],"tabbable": ["[email protected]", "", {}, "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg=="],diff --git a/packages/core/package.json b/packages/core/package.jsonindex e07c9f3e3..68e48cff9 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -165,6 +165,7 @@"fzstd": "^0.1.1","nanoevents": "^9.1.0","sucrase": "^3.35.1",+ "svgpath": "^2.6.0","yoga-layout": "npm:@open-pencil/[email protected]"},"devDependencies": {diff --git a/packages/core/src/iconify.ts b/packages/core/src/iconify.tsnew file mode 100644index 000000000..a205a1a03--- /dev/null+++ b/packages/core/src/iconify.ts@@ -0,0 +1,286 @@+import svgpath from 'svgpath'++import { parseSVGPath } from './svg-path-parse'++import type { VectorNetwork, WindingRule } from './scene-graph'++const ICONIFY_API = 'https://api.iconify.design'+const FETCH_TIMEOUT_MS = 10_000++interface PathInfo {+ d: string+ fill: string | null+ fillExplicit: boolean+ stroke: string | null+ strokeExplicit: boolean+ strokeWidth: number+ strokeWidthExplicit: boolean+ strokeCap: string+ strokeCapExplicit: boolean+ strokeJoin: string+ strokeJoinExplicit: boolean+ fillRule: WindingRule+}++export interface IconPath {+ vectorNetwork: VectorNetwork+ fill: string | null+ stroke: string | null+ strokeWidth: number+ strokeCap: string+ strokeJoin: string+}++export interface IconData {+ prefix: string+ name: string+ width: number+ height: number+ paths: IconPath[]+}++interface IconifyIconEntry {+ body: string+ width?: number+ height?: number+}++interface IconifyResponse {+ prefix: string+ width?: number+ height?: number+ icons: { [key: string]: IconifyIconEntry | undefined }+ aliases?: { [key: string]: { parent: string } | undefined }+}++const iconCache = new Map<string, IconData>()++export function clearIconCache(): void {+ iconCache.clear()+}++function parseIconName(name: string): { prefix: string; iconName: string } {+ const colonIdx = name.indexOf(':')+ if (colonIdx === -1) {+ throw new Error(`Invalid icon name "${name}". Use prefix:name format (e.g. lucide:heart, mdi:home)`)+ }+ return { prefix: name.slice(0, colonIdx), iconName: name.slice(colonIdx + 1) }+}++function attrValue(tag: string, attr: string): string | null {+ const re = new RegExp(`\\b${attr}="([^"]*)"`)+ const m = tag.match(re)+ return m ? m[1] : null+}++function extractPaths(svgBody: string): PathInfo[] {+ const result: PathInfo[] = []+ const pathRe = /<path\b[^>]*>/g+ let match+ while ((match = pathRe.exec(svgBody)) !== null) {+ const tag = match[0]+ const d = attrValue(tag, 'd')+ if (!d) continue++ const fillAttr = attrValue(tag, 'fill')+ const strokeAttr = attrValue(tag, 'stroke')+ const strokeWidthAttr = attrValue(tag, 'stroke-width')+ const strokeCapAttr = attrValue(tag, 'stroke-linecap')+ const strokeJoinAttr = attrValue(tag, 'stroke-linejoin')+ const fillRuleAttr = attrValue(tag, 'fill-rule')++ result.push({+ d,+ fill: fillAttr === 'none' ? null : (fillAttr ?? null),+ fillExplicit: fillAttr !== null,+ stroke: strokeAttr === 'none' ? null : (strokeAttr ?? null),+ strokeExplicit: strokeAttr !== null,+ strokeWidth: strokeWidthAttr ? parseFloat(strokeWidthAttr) : 1,+ strokeWidthExplicit: strokeWidthAttr !== null,+ strokeCap: strokeCapAttr ?? 'butt',+ strokeCapExplicit: strokeCapAttr !== null,+ strokeJoin: strokeJoinAttr ?? 'miter',+ strokeJoinExplicit: strokeJoinAttr !== null,+ fillRule: fillRuleAttr === 'evenodd' ? 'EVENODD' : 'NONZERO'+ })+ }+ return result+}++interface GroupAttrs {+ fill: string | null+ stroke: string | null+ strokeWidth: string | null+ strokeCap: string | null+ strokeJoin: string | null+}++function collectGroupAttrs(svgBody: string): GroupAttrs {+ const attrs: GroupAttrs = { fill: null, stroke: null, strokeWidth: null, strokeCap: null, strokeJoin: null }+ const groupRe = /<g\b[^>]*>/g+ let gMatch+ while ((gMatch = groupRe.exec(svgBody)) !== null) {+ const gTag = gMatch[0]+ attrs.fill ??= attrValue(gTag, 'fill')+ attrs.stroke ??= attrValue(gTag, 'stroke')+ attrs.strokeWidth ??= attrValue(gTag, 'stroke-width')+ attrs.strokeCap ??= attrValue(gTag, 'stroke-linecap')+ attrs.strokeJoin ??= attrValue(gTag, 'stroke-linejoin')+ }+ return attrs+}++function resolveAttr(value: string | null): string | null {+ return value === 'none' ? null : value+}++function inheritGroupAttrs(svgBody: string, paths: PathInfo[]): void {+ const g = collectGroupAttrs(svgBody)++ for (const p of paths) {+ if (!p.fillExplicit) p.fill = g.fill ? resolveAttr(g.fill) : (p.fill ?? 'currentColor')+ if (!p.strokeExplicit && g.stroke) p.stroke = resolveAttr(g.stroke)+ if (!p.strokeWidthExplicit && g.strokeWidth) p.strokeWidth = parseFloat(g.strokeWidth)+ if (!p.strokeCapExplicit && g.strokeCap) p.strokeCap = g.strokeCap+ if (!p.strokeJoinExplicit && g.strokeJoin) p.strokeJoin = g.strokeJoin+ }+}++function scalePaths(paths: PathInfo[], srcW: number, srcH: number, targetSize: number): PathInfo[] {+ if (srcW === targetSize && srcH === targetSize) return paths+ const sx = targetSize / srcW+ const sy = targetSize / srcH+ return paths.map((p) => ({+ ...p,+ d: svgpath(p.d).scale(sx, sy).round(2).toString(),+ strokeWidth: p.strokeWidth * Math.min(sx, sy)+ }))+}++function fetchWithTimeout(url: string): Promise<Response> {+ return fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })+}++function buildIconData(+ iconEntry: IconifyIconEntry,+ prefix: string,+ iconName: string,+ defaultW: number,+ defaultH: number,+ size: number+): IconData {+ const srcW = iconEntry.width ?? defaultW+ const srcH = iconEntry.height ?? defaultH++ let pathInfos = extractPaths(iconEntry.body)+ inheritGroupAttrs(iconEntry.body, pathInfos)+ pathInfos = scalePaths(pathInfos, srcW, srcH, size)++ return {+ prefix,+ name: iconName,+ width: size,+ height: size,+ paths: pathInfos.map((p) => ({+ vectorNetwork: parseSVGPath(p.d, p.fillRule),+ fill: p.fill,+ stroke: p.stroke,+ strokeWidth: p.strokeWidth,+ strokeCap: p.strokeCap,+ strokeJoin: p.strokeJoin+ }))+ }+}++export async function fetchIcon(name: string, size = 24): Promise<IconData> {+ const results = await fetchIcons([name], size)+ const result = results.get(name)+ if (!result) throw new Error(`Icon "${name}" not found. Check the name at https://icon-sets.iconify.design/`)+ return result+}++/**+ * Batch-fetch multiple icons. Groups by prefix to minimize HTTP requests+ * (one request per prefix, e.g. `lucide.json?icons=heart,home,star`).+ */+export async function fetchIcons(names: string[], size = 24): Promise<Map<string, IconData>> {+ const results = new Map<string, IconData>()+ const toFetch = new Map<string, string[]>()++ for (const name of names) {+ const cacheKey = `${name}@${size}`+ const cached = iconCache.get(cacheKey)+ if (cached) {+ results.set(name, cached)+ continue+ }+ const { prefix, iconName } = parseIconName(name)+ const group = toFetch.get(prefix) ?? []+ group.push(iconName)+ toFetch.set(prefix, group)+ }++ const fetches = [...toFetch.entries()].map(async ([prefix, iconNames]) => {+ const url = `${ICONIFY_API}/${prefix}.json?icons=${iconNames.map(encodeURIComponent).join(',')}`+ const response = await fetchWithTimeout(url)+ if (!response.ok) throw new Error(`Iconify API error: ${response.status} for prefix "${prefix}"`)+ const data = (await response.json()) as IconifyResponse+ const defaultW = data.width ?? 24+ const defaultH = data.height ?? 24++ for (const iconName of iconNames) {+ const fullName = `${prefix}:${iconName}`+ let entry = data.icons[iconName]+ if (!entry) {+ const alias = data.aliases?.[iconName]+ if (alias) entry = data.icons[alias.parent]+ }+ if (!entry) continue+ const iconData = buildIconData(entry, prefix, iconName, defaultW, defaultH, size)+ iconCache.set(`${fullName}@${size}`, iconData)+ results.set(fullName, iconData)+ }+ })++ await Promise.all(fetches)+ return results+}++export interface IconSearchResult {+ icons: string[]+ total: number+ collections: Record<string, { name: string; total: number; category?: string }>+}++export async function searchIcons(query: string, options?: {+ limit?: number+ prefix?: string+}): Promise<IconSearchResult> {+ const params = new URLSearchParams({ query })+ if (options?.limit) params.set('limit', String(options.limit))+ if (options?.prefix) params.set('prefix', options.prefix)++ const response = await fetchWithTimeout(`${ICONIFY_API}/search?${params}`)+ if (!response.ok) throw new Error(`Iconify search error: ${response.status}`)+ const data = await response.json()+ return {+ icons: data.icons ?? [],+ total: data.total ?? 0,+ collections: data.collections ?? {}+ }+}++/**+ * Batch-search multiple queries in parallel.+ */+export async function searchIconsBatch(queries: string[], options?: {+ limit?: number+ prefix?: string+}): Promise<Map<string, IconSearchResult>> {+ const results = new Map<string, IconSearchResult>()+ await Promise.all(queries.map(async (query) => {+ const result = await searchIcons(query, options)+ results.set(query, result)+ }))+ return results+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex c59e152e0..0f608cf68 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -53,7 +53,7 @@ export {export { FigmaAPI, FigmaNodeProxy, computeImageHash, type FigmaFontName } from './figma-api'export { ALL_TOOLS, defineTool, toolsToAI, buildDebugLog } from './tools'-export type { ToolDef, ParamDef, ParamType, ToolLogEntry, ToolDebugLog, AIAdapterOptions } 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'export type { XPathQueryOptions } from './xpath'@@ -139,6 +139,8 @@ export {type SVGExportOptions} from './svg-export'export { svg, renderSVGNode, type SVGNode } from './svg-node'+export { parseSVGPath } from './svg-path-parse'+export { fetchIcon, fetchIcons, searchIcons, searchIconsBatch, clearIconCache, type IconData, type IconPath, type IconSearchResult } from './iconify'export { exportFigFile, compressFigData, compressFigDataSync } from './fig-export'export {FIG_KIWI_VERSION,diff --git a/packages/core/src/svg-path-parse.ts b/packages/core/src/svg-path-parse.tsnew file mode 100644index 000000000..f9e755e79--- /dev/null+++ b/packages/core/src/svg-path-parse.ts@@ -0,0 +1,134 @@+import svgpath from 'svgpath'++import type { VectorNetwork, VectorVertex, VectorSegment, VectorRegion, WindingRule } from './scene-graph'++interface SubPath {+ startVertexIndex: number+ segmentIndices: number[]+ closed: boolean+}++/**+ * Parse an SVG path `d` attribute into a VectorNetwork.+ *+ * Uses `svgpath` to normalize all commands to absolute M/L/C/Z+ * (arcs → cubics via `.unarc()`, smooth curves → explicit via `.unshort()`).+ */+export function parseSVGPath(d: string, windingRule: WindingRule = 'NONZERO'): VectorNetwork {+ const vertices: VectorVertex[] = []+ const segments: VectorSegment[] = []+ const subPaths: SubPath[] = []++ let currentSubPath: SubPath | null = null+ let cx = 0+ let cy = 0++ const vertexMap = new Map<string, number>()++ function getOrCreateVertex(x: number, y: number): number {+ const key = `${x},${y}`+ const existing = vertexMap.get(key)+ if (existing !== undefined) return existing+ const idx = vertices.length+ vertices.push({ x, y })+ vertexMap.set(key, idx)+ return idx+ }++ function addSegment(+ x1: number, y1: number,+ x2: number, y2: number,+ tx1: number, ty1: number,+ tx2: number, ty2: number+ ): void {+ const startIdx = getOrCreateVertex(x1, y1)+ const endIdx = getOrCreateVertex(x2, y2)+ const segIdx = segments.length+ segments.push({+ start: startIdx,+ end: endIdx,+ tangentStart: { x: tx1 - x1, y: ty1 - y1 },+ tangentEnd: { x: tx2 - x2, y: ty2 - y2 }+ })+ if (currentSubPath) {+ currentSubPath.segmentIndices.push(segIdx)+ }+ }++ function addLine(x1: number, y1: number, x2: number, y2: number): void {+ addSegment(x1, y1, x2, y2, x1, y1, x2, y2)+ }++ function addCubic(+ x1: number, y1: number,+ cp1x: number, cp1y: number,+ cp2x: number, cp2y: number,+ x2: number, y2: number+ ): void {+ addSegment(x1, y1, x2, y2, cp1x, cp1y, cp2x, cp2y)+ }++ const normalized = svgpath(d).abs().unshort().unarc()++ normalized.iterate((seg) => {+ const cmd = seg[0]++ if (cmd === 'M') {+ cx = seg[1]+ cy = seg[2]+ currentSubPath = {+ startVertexIndex: getOrCreateVertex(cx, cy),+ segmentIndices: [],+ closed: false+ }+ subPaths.push(currentSubPath)+ } else if (cmd === 'L') {+ addLine(cx, cy, seg[1], seg[2])+ cx = seg[1]+ cy = seg[2]+ } else if (cmd === 'H') {+ addLine(cx, cy, seg[1], cy)+ cx = seg[1]+ } else if (cmd === 'V') {+ addLine(cx, cy, cx, seg[1])+ cy = seg[1]+ } else if (cmd === 'C') {+ addCubic(cx, cy, seg[1], seg[2], seg[3], seg[4], seg[5], seg[6])+ cx = seg[5]+ cy = seg[6]+ } else if (cmd === 'Q') {+ const qx = seg[1]+ const qy = seg[2]+ const ex = seg[3]+ const ey = seg[4]+ const cp1x = cx + (2 / 3) * (qx - cx)+ const cp1y = cy + (2 / 3) * (qy - cy)+ const cp2x = ex + (2 / 3) * (qx - ex)+ const cp2y = ey + (2 / 3) * (qy - ey)+ addCubic(cx, cy, cp1x, cp1y, cp2x, cp2y, ex, ey)+ cx = ex+ cy = ey+ } else if (cmd === 'Z' || cmd === 'z') {+ if (currentSubPath) {+ const startVert = vertices[currentSubPath.startVertexIndex]+ if (Math.abs(cx - startVert.x) > 0.001 || Math.abs(cy - startVert.y) > 0.001) {+ addLine(cx, cy, startVert.x, startVert.y)+ }+ currentSubPath.closed = true+ cx = startVert.x+ cy = startVert.y+ }+ }+ })++ const regions: VectorRegion[] = []+ const closedPaths = subPaths.filter((sp) => sp.closed && sp.segmentIndices.length > 0)+ if (closedPaths.length > 0) {+ regions.push({+ windingRule,+ loops: closedPaths.map((sp) => sp.segmentIndices)+ })+ }++ return { vertices, segments, regions }+}diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.tsindex 0ce94c073..f828310a3 100644--- a/packages/core/src/tools/ai-adapter.ts+++ b/packages/core/src/tools/ai-adapter.ts@@ -37,12 +37,30 @@ export interface ToolDebugLog {totalResultBytes: number}+export interface StepBudget {+ current: number+ max: number+}+export interface AIAdapterOptions {getFigma: () => FigmaAPIonBeforeExecute?: (def: ToolDef) => voidonAfterExecute?: (def: ToolDef) => voidonFlashNodes?: (nodeIds: string[]) => voidonToolLog?: (entry: ToolLogEntry) => void+ getStepBudget?: () => StepBudget+}++const STEP_WARNING_THRESHOLD = 5++function appendStepWarning(result: unknown, budget: StepBudget): unknown {+ const remaining = budget.max - budget.current+ if (remaining > STEP_WARNING_THRESHOLD) return result+ const warning = `⚠ ${remaining} steps remaining out of ${budget.max}. Wrap up: finish critical fixes, skip polish. User can send "continue" for more steps.`+ if (result && typeof result === 'object' && !Array.isArray(result)) {+ return { ...result, _warning: warning }+ }+ return { result, _warning: warning }}function extractIdsFromArray(arr: unknown[]): string[] {@@ -152,6 +170,9 @@ export function toolsToAI(if (ids.length > 0) options.onFlashNodes(ids)}emitToolLog(options, def, args, startTime, figma, nodeBefore, execResult)+ if (options.getStepBudget) {+ execResult = appendStepWarning(execResult, options.getStepBudget())+ }return execResult} catch (err) {const errorMsg = err instanceof Error ? err.message : String(err)diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex 05af69d3c..0acea1690 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -1,9 +1,11 @@import { parseColor } from '../color'+import { fetchIcon, fetchIcons, searchIconsBatch } from '../iconify'import type { SceneNode } from '../scene-graph'import { defineTool, nodeSummary } from './schema'import type { FigmaNodeProxy } from '../figma-api'+import type { Stroke, StrokeCap, StrokeJoin } from '../scene-graph'export const createShape = defineTool({name: 'create_shape',@@ -187,3 +189,158 @@ export const createSlice = defineTool({return nodeSummary(node)}})++const STROKE_CAP_MAP: Record<string, StrokeCap> = {+ butt: 'NONE',+ round: 'ROUND',+ square: 'SQUARE'+}++const STROKE_JOIN_MAP: Record<string, StrokeJoin> = {+ miter: 'MITER',+ round: 'ROUND',+ bevel: 'BEVEL'+}++export const fetchIconsTool = defineTool({+ name: 'fetch_icons',+ description:+ 'Pre-fetch icons from Iconify into cache. Batches by prefix (one HTTP request per set). Call this once with all needed icons, then use insert_icon to place them instantly. Popular sets: lucide (outline), mdi (filled), heroicons, tabler, solar, mingcute, ri (remix).',+ params: {+ names: {+ type: 'string[]',+ description: 'Icon names as prefix:name (e.g. ["lucide:heart", "lucide:home", "mdi:star"])',+ required: true+ },+ size: { type: 'number', description: 'Icon size in pixels (default: 24)' }+ },+ execute: async (_figma, args) => {+ const size = args.size ?? 24+ try {+ const icons = await fetchIcons(args.names, size)+ const fetched = [...icons.keys()]+ const notFound = args.names.filter((n) => !icons.has(n))+ const result: Record<string, unknown> = { fetched, count: fetched.length }+ if (notFound.length > 0) result.not_found = notFound+ return result+ } catch (e) {+ return { error: (e as Error).message }+ }+ }+})++export const insertIcon = defineTool({+ name: 'insert_icon',+ mutates: true,+ description:+ 'Insert a vector icon onto the canvas. If already cached by fetch_icons — instant, no network request. Otherwise fetches on demand.',+ params: {+ name: {+ type: 'string',+ description: 'Icon name as prefix:name (e.g. lucide:heart, mdi:home)',+ required: true+ },+ size: { type: 'number', description: 'Icon size in pixels (default: 24)' },+ color: { type: 'color', description: 'Icon color hex (replaces currentColor). Default: #000000' },+ x: { type: 'number', description: 'X position' },+ y: { type: 'number', description: 'Y position' },+ parent_id: { type: 'string', description: 'Parent node ID' }+ },+ execute: async (figma, args) => {+ const size = args.size ?? 24+ const color = args.color ?? '#000000'++ let icon+ try {+ icon = await fetchIcon(args.name, size)+ } catch (e) {+ return { error: (e as Error).message }+ }++ if (icon.paths.length === 0) {+ return { error: `Icon "${args.name}" has no path data` }+ }++ const frame = figma.createFrame()+ frame.name = `Icon / ${args.name}`+ frame.resize(size, size)+ frame.fills = []+ if (args.x !== undefined) frame.x = args.x+ if (args.y !== undefined) frame.y = args.y++ if (args.parent_id) {+ const parent = figma.getNodeById(args.parent_id)+ if (parent) parent.appendChild(frame)+ }++ const parsedColor = parseColor(color)++ for (const path of icon.paths) {+ const vector = figma.createVector()+ vector.name = 'path'+ vector.resize(size, size)+ frame.appendChild(vector)++ figma.graph.updateNode(vector.id, {+ vectorNetwork: path.vectorNetwork+ } as Record<string, unknown>)++ if (path.fill) {+ vector.fills = [{+ type: 'SOLID',+ color: path.fill === 'currentColor' ? parsedColor : parseColor(path.fill),+ opacity: 1,+ visible: true+ }]+ } else {+ vector.fills = []+ }++ if (path.stroke) {+ const strokeColor = path.stroke === 'currentColor' ? parsedColor : parseColor(path.stroke)+ const stroke: Stroke = {+ color: strokeColor,+ weight: path.strokeWidth,+ opacity: 1,+ visible: true,+ align: 'CENTER',+ cap: STROKE_CAP_MAP[path.strokeCap] ?? 'NONE',+ join: STROKE_JOIN_MAP[path.strokeJoin] ?? 'MITER'+ }+ vector.strokes = [stroke]+ }+ }++ return nodeSummary(frame)+ }+})++export const searchIconsTool = defineTool({+ name: 'search_icons',+ description:+ 'Search Iconify for icons by keyword. Accepts multiple queries — all searched in parallel. Returns results keyed by query.',+ params: {+ queries: {+ type: 'string[]',+ description: 'Search keywords (e.g. ["heart", "arrow", "settings"])',+ required: true+ },+ limit: { type: 'number', description: 'Max results per query (default: 20)' },+ 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,+ prefix: args.prefix+ })+ const output: Record<string, { icons: string[]; total: number }> = {}+ for (const [query, result] of results) {+ output[query] = { icons: result.icons, total: result.total }+ }+ return output+ } catch (e) {+ return { error: (e as Error).message }+ }+ }+})diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex 8dd5be2ce..72fefc2d9 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -2,4 +2,4 @@ export { ALL_TOOLS } from './registry'export { defineTool, nodeToResult, nodeSummary } from './schema'export type { ToolDef, ParamDef, ParamType } from './schema'export { toolsToAI, buildDebugLog } from './ai-adapter'-export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions } from './ai-adapter'+export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'diff --git a/packages/core/src/tools/registry.ts b/packages/core/src/tools/registry.tsindex ff6fcb02b..4f40973f3 100644--- a/packages/core/src/tools/registry.ts+++ b/packages/core/src/tools/registry.ts@@ -7,7 +7,7 @@ import {} from './read'import {createShape, render, createComponent, createInstance,- createPage, createVector, createSlice+ createPage, createVector, createSlice, fetchIconsTool, insertIcon, searchIconsTool} from './create'import {setFill, setStroke, setEffects, updateNode, setLayout, setConstraints,@@ -63,6 +63,9 @@ export const ALL_TOOLS: ToolDef[] = [createPage,createVector,createSlice,+ fetchIconsTool,+ insertIcon,+ searchIconsTool,// ModifysetFill,setStroke,diff --git a/src/ai/system-prompt.md b/src/ai/system-prompt.mdindex 281c91abe..6638ca8f4 100644--- a/src/ai/system-prompt.md+++ b/src/ai/system-prompt.md@@ -187,7 +187,42 @@ A vertical divider (`w={1} h={N}`) must be a sibling inside the same `flex="row"Never place vertical dividers outside their row container. Horizontal dividers (`h={1} w="fill"`) go between sections in a `flex="col"` parent.-## Icons and shapes+## Icons++Three tools for Iconify icons (200k+ icons):++- `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: `names=["lucide:heart","lucide:home","lucide:star"]`.+- `insert_icon` — place one icon on the canvas. Instant if already cached by `fetch_icons`.++**Workflow:** search → fetch batch → insert one by one as you build.++```+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...+4. insert_icon(name="lucide:heart", parent_id=..., color="#FFF")+5. insert_icon(name="lucide:home", parent_id=..., color="#FFF")+ ... (each insert_icon is instant — no network wait)+```++**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.++## ShapesAll visual elements (Rectangle, Ellipse, Star, Polygon, Line) have **no fill by default** — they render as invisible without `bg="#hex"` or `stroke="#hex"`.@@ -240,3 +275,7 @@ Typically **3 renders + 3 describes** for a full design. `describe` the **root f🧮 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` between renders. Do NOT call `describe` on individual children when `depth=2` on the root would show the same info.++## 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.diff --git a/src/ai/tools.ts b/src/ai/tools.tsindex eccd1b28f..5cbd0e6fe 100644--- a/src/ai/tools.ts+++ b/src/ai/tools.ts@@ -6,9 +6,12 @@ import { makeFigmaFromStore } from '@/automation/figma-factory'import { ALL_TOOLS, computeAllLayouts, toolsToAI } from '@open-pencil/core'import type { EditorStore } from '@/stores/editor'-import type { SceneNode, ToolLogEntry } from '@open-pencil/core'+import type { SceneNode, StepBudget, ToolLogEntry } from '@open-pencil/core'++export const MAX_AGENT_STEPS = 50let _toolLogEntries: ToolLogEntry[] = []+let _currentRunSteps = 0export interface StepUsage {inputTokens: number@@ -30,6 +33,15 @@ export function getStepUsages(): StepUsage[] {export function recordStepUsage(usage: StepUsage): void {_stepUsages.push(usage)+ _currentRunSteps+++}++export function resetRunSteps(): void {+ _currentRunSteps = 0+}++export function didHitStepLimit(): boolean {+ return _currentRunSteps >= MAX_AGENT_STEPS}export function clearToolLogEntries(): void {@@ -70,7 +82,11 @@ export function createAITools(store: EditorStore) {},onToolLog: (entry) => {_toolLogEntries.push(entry)- }+ },+ getStepBudget: (): StepBudget => ({+ current: _currentRunSteps,+ max: MAX_AGENT_STEPS+ })},{ v, valibotSchema, tool })diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vueindex 3dd812e02..0011f849a 100644--- a/src/components/ChatPanel.vue+++ b/src/components/ChatPanel.vue@@ -3,7 +3,7 @@ import { ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaThumb, ScrollAreaViewporimport { computed, markRaw, nextTick, ref, watch } from 'vue'import { copyChatLog } from '@/ai/chat-debug'-import { clearToolLogEntries } from '@/ai/tools'+import { clearToolLogEntries, didHitStepLimit } from '@/ai/tools'import ChatInput from '@/components/chat/ChatInput.vue'import ChatMessage from '@/components/chat/ChatMessage.vue'import ProviderSetup from '@/components/chat/ProviderSetup.vue'@@ -23,6 +23,12 @@ const debugCopied = ref(false)const messages = computed(() => chat.value?.messages ?? [])const status = computed(() => chat.value?.status ?? 'ready')+const showContinue = computed(() => {+ if (status.value !== 'ready') return false+ if (messages.value.length === 0) return false+ const last = messages.value[messages.value.length - 1]+ return last.role === 'assistant' && didHitStepLimit()+})function scrollToBottom() {nextTick(() => {@@ -108,6 +114,17 @@ function handleClearChat() {</div></div>+ <!-- Continue button when step limit reached -->+ <div v-if="showContinue" class="flex justify-center py-2">+ <button+ class="flex items-center gap-1.5 rounded-full bg-accent/10 px-4 py-1.5 text-xs font-medium text-accent transition-colors hover:bg-accent/20"+ @click="handleSubmit('Continue where you left off')"+ >+ <icon-lucide-play class="size-3" />+ Continue+ </button>+ </div>+<div ref="messagesEnd" /></div></ScrollAreaViewport>diff --git a/src/composables/use-chat.ts b/src/composables/use-chat.tsindex 23ba0b667..8678caa03 100644--- a/src/composables/use-chat.ts+++ b/src/composables/use-chat.ts@@ -4,11 +4,11 @@ import { createOpenAI } from '@ai-sdk/openai'import { Chat } from '@ai-sdk/vue'import { createOpenRouter } from '@openrouter/ai-sdk-provider'import { useLocalStorage } from '@vueuse/core'-import { DirectChatTransport, ToolLoopAgent } from 'ai'+import { DirectChatTransport, stepCountIs, ToolLoopAgent } from 'ai'import { computed, ref, watch } from 'vue'import SYSTEM_PROMPT from '@/ai/system-prompt.md?raw'-import { createAITools, recordStepUsage } from '@/ai/tools'+import { MAX_AGENT_STEPS, createAITools, recordStepUsage, resetRunSteps } from '@/ai/tools'import { useEditorStore } from '@/stores/editor'import { AI_PROVIDERS, DEFAULT_AI_MODEL, DEFAULT_AI_PROVIDER } from '@open-pencil/core'@@ -180,13 +180,17 @@ function createTransport() {model: createModel(),instructions: SYSTEM_PROMPT,tools,+ stopWhen: stepCountIs(MAX_AGENT_STEPS),maxOutputTokens: maxOutputTokens.value,providerOptions: cacheProviderOptions,- prepareCall: (options) => ({- ...options,- maxOutputTokens: maxOutputTokens.value,- providerOptions: cacheProviderOptions- }),+ prepareCall: (options) => {+ resetRunSteps()+ return {+ ...options,+ maxOutputTokens: maxOutputTokens.value,+ providerOptions: cacheProviderOptions+ }+ },onStepFinish: ({ usage }) => {recordStepUsage({inputTokens: usage.inputTokens ?? 0,diff --git a/tests/engine/iconify.test.ts b/tests/engine/iconify.test.tsnew file mode 100644index 000000000..4f042eae2--- /dev/null+++ b/tests/engine/iconify.test.ts@@ -0,0 +1,111 @@+import { describe, expect, test } from 'bun:test'++import { fetchIcon, fetchIcons, searchIcons, searchIconsBatch } from '@open-pencil/core'++describe('fetchIcon', () => {+ test('fetches mdi:home', async () => {+ const icon = await fetchIcon('mdi:home', 24)+ expect(icon.prefix).toBe('mdi')+ expect(icon.name).toBe('home')+ expect(icon.width).toBe(24)+ expect(icon.height).toBe(24)+ expect(icon.paths.length).toBeGreaterThan(0)++ const path = icon.paths[0]+ expect(path.vectorNetwork.vertices.length).toBeGreaterThan(3)+ expect(path.vectorNetwork.segments.length).toBeGreaterThan(3)+ expect(path.fill).toBe('currentColor')+ expect(path.stroke).toBeNull()+ })++ test('fetches lucide:heart (stroked icon)', async () => {+ const icon = await fetchIcon('lucide:heart', 24)+ expect(icon.paths.length).toBeGreaterThan(0)++ const path = icon.paths[0]+ expect(path.vectorNetwork.vertices.length).toBeGreaterThan(3)+ expect(path.stroke).toBe('currentColor')+ expect(path.strokeWidth).toBe(2)+ expect(path.strokeCap).toBe('round')+ expect(path.strokeJoin).toBe('round')+ })++ test('scales to custom size', async () => {+ const icon = await fetchIcon('mdi:home', 48)+ expect(icon.width).toBe(48)+ expect(icon.height).toBe(48)+ })++ test('caches repeated fetches', async () => {+ const a = await fetchIcon('mdi:home', 24)+ const b = await fetchIcon('mdi:home', 24)+ expect(a).toBe(b)+ })++ test('throws on invalid icon name format', async () => {+ await expect(fetchIcon('invalid')).rejects.toThrow('prefix:name')+ })++ test('throws on non-existent icon', async () => {+ await expect(fetchIcon('mdi:this-icon-definitely-does-not-exist-xyz123')).rejects.toThrow('not found')+ })++ test('heroicons:eye — multi-path icon with group attrs', async () => {+ const icon = await fetchIcon('heroicons:eye', 24)+ expect(icon.paths.length).toBeGreaterThanOrEqual(2)+ })+})++describe('fetchIcons (batch)', () => {+ test('fetches multiple icons from same prefix in one request', async () => {+ const icons = await fetchIcons(['lucide:star', 'lucide:home', 'lucide:search'], 24)+ expect(icons.size).toBe(3)+ expect(icons.get('lucide:star')).toBeDefined()+ expect(icons.get('lucide:home')).toBeDefined()+ expect(icons.get('lucide:search')).toBeDefined()+ })++ test('fetches icons across multiple prefixes', async () => {+ const icons = await fetchIcons(['mdi:heart', 'lucide:heart'], 24)+ expect(icons.size).toBe(2)+ expect(icons.get('mdi:heart')?.prefix).toBe('mdi')+ expect(icons.get('lucide:heart')?.prefix).toBe('lucide')+ })++ test('skips non-existent icons without failing', async () => {+ const icons = await fetchIcons(['mdi:home', 'mdi:nonexistent-xyz-999'], 24)+ expect(icons.has('mdi:home')).toBe(true)+ expect(icons.has('mdi:nonexistent-xyz-999')).toBe(false)+ })++ test('populates cache for subsequent fetchIcon calls', async () => {+ await fetchIcons(['mdi:star'], 24)+ const icon = await fetchIcon('mdi:star', 24)+ expect(icon.prefix).toBe('mdi')+ })+})++describe('searchIcons', () => {+ test('searches for heart icons', async () => {+ const result = await searchIcons('heart', { limit: 10 })+ expect(result.icons.length).toBeGreaterThan(0)+ expect(result.total).toBeGreaterThan(0)+ expect(result.icons[0]).toContain(':')+ })++ test('filters by prefix', async () => {+ const result = await searchIcons('home', { limit: 5, prefix: 'lucide' })+ for (const icon of result.icons) {+ expect(icon.startsWith('lucide:')).toBe(true)+ }+ })+})++describe('searchIconsBatch', () => {+ test('searches multiple queries in parallel', async () => {+ const results = await searchIconsBatch(['heart', 'arrow'], { limit: 5 })+ expect(results.size).toBe(2)+ expect(results.get('heart')!.icons.length).toBeGreaterThan(0)+ expect(results.get('arrow')!.icons.length).toBeGreaterThan(0)+ })+})diff --git a/tests/engine/svg-path-parse.test.ts b/tests/engine/svg-path-parse.test.tsnew file mode 100644index 000000000..108289777--- /dev/null+++ b/tests/engine/svg-path-parse.test.ts@@ -0,0 +1,108 @@+import { describe, expect, test } from 'bun:test'++import { parseSVGPath, vectorNetworkToSVGPaths } from '@open-pencil/core'++describe('parseSVGPath', () => {+ test('simple rectangle M L L L Z', () => {+ const vn = parseSVGPath('M0 0 L10 0 L10 10 L0 10 Z')+ expect(vn.vertices.length).toBe(4)+ expect(vn.segments.length).toBe(4)+ expect(vn.regions.length).toBe(1)+ expect(vn.regions[0].windingRule).toBe('NONZERO')+ expect(vn.regions[0].loops.length).toBe(1)+ expect(vn.regions[0].loops[0].length).toBe(4)+ })++ test('H and V commands', () => {+ const vn = parseSVGPath('M0 0 H10 V10 H0 Z')+ expect(vn.vertices.length).toBe(4)+ expect(vn.segments.length).toBe(4)+ })++ test('relative commands (m l h v z)', () => {+ const vn = parseSVGPath('m0 0 l10 0 l0 10 l-10 0 z')+ expect(vn.vertices.length).toBe(4)+ expect(vn.segments.length).toBe(4)+ expect(vn.regions[0].loops[0].length).toBe(4)+ })++ test('cubic bezier C command', () => {+ const vn = parseSVGPath('M0 0 C10 0 10 10 0 10')+ expect(vn.vertices.length).toBe(2)+ expect(vn.segments.length).toBe(1)+ const seg = vn.segments[0]+ expect(seg.tangentStart.x).toBeCloseTo(10)+ expect(seg.tangentStart.y).toBeCloseTo(0)+ expect(seg.tangentEnd.x).toBeCloseTo(10)+ expect(seg.tangentEnd.y).toBeCloseTo(0)+ })++ test('smooth cubic S command → expanded to C', () => {+ const vn = parseSVGPath('M0 0 C5 0 10 5 10 10 S20 20 20 10')+ expect(vn.segments.length).toBe(2)+ })++ test('quadratic Q command → converted to cubic', () => {+ const vn = parseSVGPath('M0 0 Q10 10 20 0')+ expect(vn.segments.length).toBe(1)+ const seg = vn.segments[0]+ expect(seg.tangentStart.x).not.toBe(0)+ expect(seg.tangentEnd.x).not.toBe(0)+ })++ test('arc A command → converted to cubics', () => {+ const vn = parseSVGPath('M10 0 A10 10 0 0 1 0 10')+ expect(vn.segments.length).toBeGreaterThanOrEqual(1)+ expect(vn.vertices.length).toBeGreaterThanOrEqual(2)+ })++ test('evenodd winding rule', () => {+ const vn = parseSVGPath('M0 0 L10 0 L10 10 Z', 'EVENODD')+ expect(vn.regions[0].windingRule).toBe('EVENODD')+ })++ test('multiple subpaths → multiple loops in one region', () => {+ const vn = parseSVGPath('M0 0 L10 0 L10 10 Z M20 20 L30 20 L30 30 Z')+ expect(vn.regions.length).toBe(1)+ expect(vn.regions[0].loops.length).toBe(2)+ })++ test('open subpath → no region', () => {+ const vn = parseSVGPath('M0 0 L10 0 L10 10')+ expect(vn.regions.length).toBe(0)+ expect(vn.segments.length).toBe(2)+ })++ test('straight segments have zero tangents', () => {+ const vn = parseSVGPath('M0 0 L10 10')+ const seg = vn.segments[0]+ expect(seg.tangentStart.x).toBe(0)+ expect(seg.tangentStart.y).toBe(0)+ expect(seg.tangentEnd.x).toBe(0)+ expect(seg.tangentEnd.y).toBe(0)+ })++ test('real icon: mdi:home path', () => {+ const d = 'M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8z'+ const vn = parseSVGPath(d)+ expect(vn.vertices.length).toBeGreaterThan(3)+ expect(vn.segments.length).toBeGreaterThan(3)+ expect(vn.regions.length).toBe(1)+ })++ test('real icon: lucide heart path (arcs + curves)', () => {+ const d = 'M2 9.5a5.5 5.5 0 0 1 9.591-3.676a.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5'+ const vn = parseSVGPath(d)+ expect(vn.vertices.length).toBeGreaterThan(5)+ expect(vn.segments.length).toBeGreaterThan(5)+ })++ test('round-trip: parse → export produces valid SVG paths', () => {+ const d = 'M0 0 L100 0 L100 100 L0 100 Z'+ const vn = parseSVGPath(d)+ const exported = vectorNetworkToSVGPaths(vn)+ expect(exported.length).toBe(1)+ expect(exported[0]).toContain('M')+ expect(exported[0]).toContain('Z')+ })+})