Skip to content

AI-native design editor. Open-source Figma alternative.

fix(core): refuse agent tool parents inside an instance, as appendChild does (#1734)

Danila Poyarkov98b37f743402
diff --git a/changes/1734/fixed.md b/changes/1734/fixed.md
new file mode 100644
index 000000000..476f19802
--- /dev/null
+++ b/changes/1734/fixed.md
@@ -0,0 +1 @@
+- AI and MCP agents can no longer add layers inside an instance with `render`, `import_svg`, `import_mermaid`, `insert_icon`, or `insert_library_component`, which left the document unable to save as `.fig`; layers rendered into an instance's slot save too.
diff --git a/packages/core/src/figma-api/slots.ts b/packages/core/src/figma-api/slots.ts
index 2f04ff463..26d7dfeb7 100644
--- a/packages/core/src/figma-api/slots.ts
+++ b/packages/core/src/figma-api/slots.ts
@@ -76,15 +76,24 @@ export function prepareSlotMove(
childId: string,
method: 'appendChild' | 'insertChild'
): void {
+ const sourceParentId = g.getNode(childId)?.parentId
+ const source = sourceParentId ? slotScope(g, sourceParentId) : undefined
+ prepareSlotInsertion(g, parentId, method)
+ if (source?.kind === 'slot') claimSlotContent(g, source)
+}
+
+/**
+ * Ready adding new layers under `parentId`, as a tool that builds layers in place does, by the
+ * rule appendChild follows: the locked part of an instance refuses them, since its layers come
+ * from the component, and a slot's content becomes the instance's own first.
+ */
+export function prepareSlotInsertion(g: SceneGraph, parentId: string, method: string): void {
const target = slotScope(g, parentId)
if (target.kind === 'locked')
throw new Error(
`in ${method}: Cannot move node. New parent is an instance or is inside of an instance`
)
- const sourceParentId = g.getNode(childId)?.parentId
- const source = sourceParentId ? slotScope(g, sourceParentId) : undefined
if (target.kind === 'slot') claimSlotContent(g, target)
- if (source?.kind === 'slot') claimSlotContent(g, source)
}
/**
diff --git a/packages/core/src/tools/create/basic.ts b/packages/core/src/tools/create/basic.ts
index 4eb34ce4f..0922e8cd0 100644
--- a/packages/core/src/tools/create/basic.ts
+++ b/packages/core/src/tools/create/basic.ts
@@ -1,6 +1,7 @@
import * as v from 'valibot'
import type { FigmaNodeProxy } from '#core/figma-api'
+import { prepareSlotInsertion } from '#core/figma-api/slots'
import { toolNumber, positionInputs, defineTool, nodeSummary } from '#core/tools/schema'
export const createShape = defineTool({
@@ -23,6 +24,8 @@ export const createShape = defineTool({
execute: (figma, args) => {
const parentId = args.parent_id
const parent = parentId ? figma.getNodeById(parentId) : null
+ // Refuse before creating, so a refused parent leaves no layer behind on the page.
+ if (parent) prepareSlotInsertion(figma.graph, parent.id, 'create_shape')
const createMap: Record<string, () => FigmaNodeProxy> = {
FRAME: () => figma.createFrame(),
RECTANGLE: () => figma.createRectangle(),
@@ -71,16 +74,15 @@ export const createSlice = defineTool({
parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID')))
}),
execute: (figma, args) => {
+ const parent = args.parent_id ? figma.getNodeById(args.parent_id) : null
+ if (parent) prepareSlotInsertion(figma.graph, parent.id, 'create_slice')
const node = figma.createFrame()
node.x = args.x
node.y = args.y
node.resize(args.width, args.height)
node.name = args.name ?? 'Slice'
node.fills = []
- if (args.parent_id) {
- const parent = figma.getNodeById(args.parent_id)
- if (parent) parent.appendChild(node)
- }
+ if (parent) parent.appendChild(node)
return nodeSummary(node)
}
})
diff --git a/packages/core/src/tools/create/icons.ts b/packages/core/src/tools/create/icons.ts
index 59d7db91c..33edbb47a 100644
--- a/packages/core/src/tools/create/icons.ts
+++ b/packages/core/src/tools/create/icons.ts
@@ -2,6 +2,7 @@ import * as v from 'valibot'
import { parseColor } from '@open-pencil/scene-graph/color'
+import { prepareSlotInsertion } from '#core/figma-api/slots'
import { placeIcon } from '#core/icons'
import { toolNumber, defineTool } from '#core/tools/schema'
@@ -83,13 +84,14 @@ export const insertIcon = defineTool({
const inserted: { id: string; name: string; icon: string }[] = []
const notFound: string[] = []
+ const parentId = args.parent_id ?? figma.currentPage.id
+ prepareSlotInsertion(figma.graph, parentId, 'insert_icon')
for (const name of names) {
const icon = icons.get(name)
if (!icon || icon.paths.length === 0) {
notFound.push(name)
continue
}
- const parentId = args.parent_id ?? figma.currentPage.id
const frame = placeIcon(figma.graph, parentId, icon, { size, color: parsedColor })
inserted.push({ id: frame.id, name: frame.name, icon: name })
}
diff --git a/packages/core/src/tools/create/mermaid.ts b/packages/core/src/tools/create/mermaid.ts
index 5da4fc935..52d6c10f4 100644
--- a/packages/core/src/tools/create/mermaid.ts
+++ b/packages/core/src/tools/create/mermaid.ts
@@ -3,6 +3,7 @@ import * as v from 'valibot'
import { detectMermaidDiagram, parseFlowchart } from '@open-pencil/mermaid'
import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'
+import { prepareSlotInsertion } from '#core/figma-api/slots'
import { addFlowchart } from '#core/io/formats/mermaid'
import { toolNumber, defineTool } from '#core/tools/schema'
@@ -39,6 +40,7 @@ export const importMermaid = defineTool({
const { graph } = figma
const parentId = args.parent_id ?? figma.currentPage.id
if (!graph.getNode(parentId)) return { error: `Parent ${parentId} not found` }
+ prepareSlotInsertion(graph, parentId, 'import_mermaid')
const content = graph.getNode(parentId)?.childIds ?? []
const bounds =
content.length > 0
diff --git a/packages/core/src/tools/create/render.ts b/packages/core/src/tools/create/render.ts
index 227a33b01..6d184179f 100644
--- a/packages/core/src/tools/create/render.ts
+++ b/packages/core/src/tools/create/render.ts
@@ -1,6 +1,7 @@
import * as v from 'valibot'
import { finishRenderPlacement, resolveRenderPlacement } from '#core/design-jsx/placement'
+import { prepareSlotInsertion } from '#core/figma-api/slots'
import { toolNumber, defineTool } from '#core/tools/schema'
export const render = defineTool({
@@ -36,6 +37,7 @@ export const render = defineTool({
const { renderJSX } = designJSXRenderer(figma.icons)
const placement = resolveRenderPlacement(figma.graph, args, figma.currentPageId)
+ prepareSlotInsertion(figma.graph, placement.parentId, 'render')
const results = await renderJSX(figma.graph, args.jsx, placement)
finishRenderPlacement(figma.graph, results, placement)
const result = results[0]
diff --git a/packages/core/src/tools/create/svg.ts b/packages/core/src/tools/create/svg.ts
index 5999c97df..df10123f9 100644
--- a/packages/core/src/tools/create/svg.ts
+++ b/packages/core/src/tools/create/svg.ts
@@ -1,5 +1,6 @@
import * as v from 'valibot'
+import { prepareSlotInsertion } from '#core/figma-api/slots'
import { createSVGNodesFromImport, prepareSVGImport, svgImportFonts } from '#core/io/formats/svg'
import { toolNumber, defineTool } from '#core/tools/schema'
@@ -42,9 +43,11 @@ export const importSVG = defineTool({
figma.loadFontAsync({ family, style })
)
)
+ const parentId = args.parent_id ?? figma.currentPage.id
+ if (data) prepareSlotInsertion(figma.graph, parentId, 'import_svg')
const frame =
data &&
- createSVGNodesFromImport(figma.graph, args.parent_id ?? figma.currentPage.id, data, {
+ createSVGNodesFromImport(figma.graph, parentId, data, {
name: args.name,
x: args.x,
y: args.y
diff --git a/packages/core/src/tools/create/vector.ts b/packages/core/src/tools/create/vector.ts
index 5bafc2a8f..e9d7c2a13 100644
--- a/packages/core/src/tools/create/vector.ts
+++ b/packages/core/src/tools/create/vector.ts
@@ -5,6 +5,7 @@ import { parseColor } from '@open-pencil/scene-graph/color'
import { parseSVGPath } from '@open-pencil/scene-graph/parse-path'
import { transformVectorNetwork } from '@open-pencil/scene-graph/vector-network'
+import { prepareSlotInsertion } from '#core/figma-api/slots'
import { defineTool, nodeSummary, positionInputs, toolNumber } from '#core/tools/schema'
import { parseVectorNetworkJSON } from '#core/tools/vector/network'
import { computeAccurateBounds } from '#core/vector/curve-math'
@@ -68,6 +69,8 @@ export const createVector = defineTool({
if ('error' in parsed) return parsed
parsedPath = parsed
}
+ const parent = args.parent_id ? figma.getNodeById(args.parent_id) : null
+ if (parent) prepareSlotInsertion(figma.graph, parent.id, 'create_vector')
const node = figma.createVector()
node.x = args.x
@@ -94,10 +97,7 @@ export const createVector = defineTool({
]
})
}
- if (args.parent_id) {
- const parent = figma.getNodeById(args.parent_id)
- if (parent) parent.appendChild(node)
- }
+ if (parent) parent.appendChild(node)
return nodeSummary(node)
}
})
diff --git a/packages/core/src/tools/read/libraries.ts b/packages/core/src/tools/read/libraries.ts
index e69257478..1697a3b61 100644
--- a/packages/core/src/tools/read/libraries.ts
+++ b/packages/core/src/tools/read/libraries.ts
@@ -1,5 +1,6 @@
import * as v from 'valibot'
+import { prepareSlotInsertion } from '#core/figma-api/slots'
import { getComponentCatalog } from '#core/tools/component-catalog'
import { toolNumber, defineTool } from '#core/tools/schema'
@@ -34,6 +35,8 @@ export const insertLibraryComponent = defineTool({
)
}),
execute: async (figma, args) => {
+ if (args.parent_id)
+ prepareSlotInsertion(figma.graph, args.parent_id, 'insert_library_component')
const catalog = getComponentCatalog(figma.graph)
if (!catalog) throw new Error('No component library catalog is configured')
let variantValues: Record<string, string> | undefined
diff --git a/packages/core/tests/tools/create/parent.test.ts b/packages/core/tests/tools/create/parent.test.ts
new file mode 100644
index 000000000..4555e0efc
--- /dev/null
+++ b/packages/core/tests/tools/create/parent.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
+import { ALL_TOOLS, type ToolDef } from '@open-pencil/core/tools'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+const io = new IORegistry(BUILTIN_IO_FORMATS)
+
+/** Mutating tools that build or move layers under a `parent_id`. */
+const parentTools = ALL_TOOLS.filter(
+ (def) => def.mutates && 'parent_id' in (def.input as { entries: object }).entries
+)
+
+interface Fixture {
+ figma: FigmaAPI
+ /** A layer of the instance that comes from its component. */
+ locked: string
+ /** The instance's copy of a slot frame, whose content the instance owns. */
+ slot: string
+ /** A layer on the page, for tools that move one. */
+ loose: string
+}
+
+type ArgsFor = (parent: string, f: Fixture) => Record<string, unknown>
+
+/** Each tool's arguments for `parent`; the key set must be every tool that takes a parent. */
+const ARGS: Partial<Record<string, ArgsFor>> = {
+ create_shape: (parent) => ({
+ type: 'RECTANGLE',
+ x: 0,
+ y: 0,
+ width: 10,
+ height: 10,
+ parent_id: parent
+ }),
+ create_vector: (parent) => ({ x: 0, y: 0, path: 'M0 0 L10 10', parent_id: parent }),
+ create_slice: (parent) => ({ x: 0, y: 0, width: 10, height: 10, parent_id: parent }),
+ reparent_node: (parent, f) => ({ id: f.loose, parent_id: parent }),
+ render: (parent) => ({ jsx: '<Frame w={20} h={20} bg="#f00" />', parent_id: parent }),
+ import_svg: (parent) => ({
+ svg: '<svg width="10" height="10"><rect width="10" height="10"/></svg>',
+ parent_id: parent
+ }),
+ import_mermaid: (parent) => ({ mermaid: 'graph TD; A-->B', parent_id: parent }),
+ insert_icon: (parent) => ({ name: 'lucide:heart', parent_id: parent }),
+ insert_library_component: (parent) => ({
+ library_id: 'library',
+ asset_key: 'asset',
+ parent_id: parent
+ })
+}
+
+/** Tools that need more than the document to succeed, such as a library catalog. */
+const NEEDS_SERVICES = new Set(['insert_library_component'])
+
+const cases = parentTools.flatMap((def) => {
+ const args = ARGS[def.name]
+ return args ? [[def.name, def, args] as const] : []
+})
+
+function build(): Fixture {
+ const figma = new FigmaAPI(new SceneGraph())
+ const component = figma.createComponent()
+ const body = figma.createFrame()
+ component.appendChild(body)
+ body.appendChild(figma.createRectangle())
+ const slot = figma.createFrame()
+ component.appendChild(slot)
+ const createSlot = ALL_TOOLS.find((def) => def.name === 'create_slot')
+ if (!createSlot) throw new Error('No create_slot tool')
+ createSlot.execute(figma, { id: slot.id })
+ const instance = component.createInstance()
+ const [lockedCopy, slotCopy] = instance.children
+ return { figma, locked: lockedCopy.id, slot: slotCopy.id, loose: figma.createRectangle().id }
+}
+
+async function run(def: ToolDef, figma: FigmaAPI, args: Record<string, unknown>) {
+ try {
+ const result: unknown = await def.execute(figma, args)
+ const error = result && typeof result === 'object' && 'error' in result ? result.error : null
+ if (error === null) return { error: null }
+ return { error: typeof error === 'string' ? error : JSON.stringify(error) }
+ } catch (error) {
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+describe('tools that take a parent', () => {
+ test('every tool that takes a parent has arguments here', () => {
+ expect(Object.keys(ARGS).toSorted()).toEqual(parentTools.map((def) => def.name).toSorted())
+ })
+
+ test.each(cases)(
+ '%s refuses a parent inside an instance and leaves the document as it was',
+ async (_name: string, def: ToolDef, args: ArgsFor) => {
+ const fixture = build()
+ const { graph } = fixture.figma
+ const before = [...graph.nodes.keys()]
+ const { error } = await run(def, fixture.figma, args(fixture.locked, fixture))
+ expect(error).toContain('New parent is an instance or is inside of an instance')
+ expect([...graph.nodes.keys()]).toEqual(before)
+ expect(graph.getNode(fixture.loose)?.parentId).toBe(fixture.figma.currentPage.id)
+ // Layers the component does not know would leave the instance unsaveable.
+ await io.writeDocument('fig', graph)
+ }
+ )
+
+ test.each(cases.filter(([name]) => !NEEDS_SERVICES.has(name)))(
+ '%s adds to a slot of an instance, which stays saveable',
+ async (_name: string, def: ToolDef, args: ArgsFor) => {
+ const fixture = build()
+ const { graph } = fixture.figma
+ const { error } = await run(def, fixture.figma, args(fixture.slot, fixture))
+ expect(error).toBeNull()
+ expect(graph.getNode(fixture.slot)?.childIds.length).toBeGreaterThan(0)
+ await io.writeDocument('fig', graph)
+ }
+ )
+})