AI-native design editor. Open-source Figma alternative.
fix: prevent unbounded duplication of Figma-imported instance children
Joseph Cuminesa4350396a8f8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex be2a0b649..c660f4e24 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -105,6 +105,7 @@- Preserve component links when pasting Figma instances so later component edits continue to update them.- Stop local MCP servers after the app disconnects instead of leaving orphaned background processes. (#494)+- Prevent unbounded instance duplication when editing Figma-imported or pasted components with serialized or renamed children, keep extra instance children stable instead of yanking them to the front, and avoid pasted instances re-linking pre-existing instances during clipboard import.### Performance- Scope automation and Figma API layout reconciliation to graph nodes and parent containers actually changed by each mutation.diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex 4ea2b5dc0..1000d200b 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -12,6 +12,8 @@ import type { GUID, NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/cimport { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { linkImportedInstanceChildren } from '#core/kiwi/fig/import-linkage'+import { decodeBase64, decodeBase64Text, encodeBase64, encodeBase64Text } from './bytes'import { shapeTextForClipboard } from './canvas/text/clipboard'import {@@ -298,6 +300,19 @@ export function importClipboardNodes(detachOrphanedInstances(created, graph)+ // Link pasted instance children so a later component sync does not re-clone them.+ // Pasted Figma instances can carry serialized children with componentId: null, and+ // syncChildren's name+type fallback cannot match renamed children. Scoped to the+ // freshly pasted instances so pre-existing, user-modified instances in the target+ // document are never re-linked. Non-INSTANCE children are only stamped when+ // componentId is missing; sub-instance sourceComponentId overrides are re-stamped+ // with the positional component child (same value as the .fig import path).+ const pastedInstanceIds = new Set<string>()+ for (const ourId of created.values()) {+ if (graph.getNode(ourId)?.type === 'INSTANCE') pastedInstanceIds.add(ourId)+ }+ if (pastedInstanceIds.size > 0) linkImportedInstanceChildren(graph, pastedInstanceIds)+return createdIds}diff --git a/packages/core/src/kiwi/fig/import-linkage.ts b/packages/core/src/kiwi/fig/import-linkage.tsnew file mode 100644index 000000000..82e1d6785--- /dev/null+++ b/packages/core/src/kiwi/fig/import-linkage.ts@@ -0,0 +1,92 @@+import { type SceneGraph, type SceneNode, setInstanceOverride } from '@open-pencil/scene-graph'++function linkSubtree(+ graph: SceneGraph,+ compParentId: string,+ instParentId: string,+ instRootId: string+): void {+ const compParent = graph.getNode(compParentId)+ const instParent = graph.getNode(instParentId)+ if (!compParent || !instParent) return++ const instRoot = graph.getNode(instRootId)+ const overrides = instRoot?.instanceOverrides++ const compChildren = compParent.childIds+ .map((id) => graph.getNode(id))+ .filter((n): n is SceneNode => n !== undefined)+ const instChildren = instParent.childIds+ .map((id) => graph.getNode(id))+ .filter((n): n is SceneNode => n !== undefined)++ const linkedComp = new Set<string>()+ const linkedInst = new Set<string>()++ const linkPair = (compChild: SceneNode, instChild: SceneNode): void => {+ if (instChild.type === 'INSTANCE') {+ if (overrides) {+ setInstanceOverride(overrides, instRootId, instChild.id, 'sourceComponentId', compChild.id)+ }+ } else if (!instChild.componentId) {+ instChild.componentId = compChild.id+ }+ linkedComp.add(compChild.id)+ linkedInst.add(instChild.id)+ // Do not recurse across INSTANCE boundaries. The sub-instance's descendants+ // are linked to their own main component by the outer getAllNodes() loop in+ // linkImportedInstanceChildren, which calls linkSubtree with the sub-instance's+ // componentId. Recursing here would stamp descendant componentIds with proxy+ // nodes inside the parent component's sub-instance rather than the canonical+ // main component children.+ if (+ instChild.type !== 'INSTANCE' &&+ compChild.childIds.length > 0 &&+ instChild.childIds.length > 0+ ) {+ linkSubtree(graph, compChild.id, instChild.id, instRootId)+ }+ }++ // Pass 1: match by stable overrideKey before position. This survives renames+ // and guards against an extra same-type child inserted before a renamed+ // serialized child — positional matching would otherwise mis-assign it.+ for (const instChild of instChildren) {+ if (!instChild.overrideKey || linkedInst.has(instChild.id)) continue+ const compChild = compChildren.find(+ (c) =>+ !linkedComp.has(c.id) &&+ c.overrideKey === instChild.overrideKey &&+ c.type === instChild.type+ )+ if (!compChild) continue+ linkPair(compChild, instChild)+ }++ // Pass 2: positional matching for remaining nodes (preserves order for nodes+ // without stable keys, and for legacy files without overrideKey).+ const remainingComp = compChildren.filter((c) => !linkedComp.has(c.id))+ const remainingInst = instChildren.filter((c) => !linkedInst.has(c.id))+ const count = Math.min(remainingComp.length, remainingInst.length)+ for (let i = 0; i < count; i++) {+ const compChild = remainingComp[i]+ const instChild = remainingInst[i]+ if (compChild.type !== instChild.type) continue+ linkPair(compChild, instChild)+ }+}++export function linkImportedInstanceChildren(graph: SceneGraph, instanceIds?: Set<string>): void {+ graph.preserveSourceMetadataDuring(() => {+ for (const node of graph.getAllNodes()) {+ if (node.type !== 'INSTANCE' || !node.componentId) continue+ // When scoped to a set of instance ids (e.g. freshly pasted nodes), only link+ // those instances — never re-link pre-existing, user-modified instances in the+ // target document. Unscoped (import path) links every instance.+ if (instanceIds && !instanceIds.has(node.id)) continue+ const comp = graph.getNode(node.componentId)+ if (!comp) continue+ linkSubtree(graph, comp.id, node.id, node.id)+ }+ })+}diff --git a/packages/core/src/kiwi/fig/import.ts b/packages/core/src/kiwi/fig/import.tsindex ae0cfcd6e..98a5b7747 100644--- a/packages/core/src/kiwi/fig/import.ts+++ b/packages/core/src/kiwi/fig/import.ts@@ -23,6 +23,7 @@ import type {} from '@open-pencil/scene-graph'import { BLACK } from '#core/constants'+import { linkImportedInstanceChildren } from '#core/kiwi/fig/import-linkage'import { setLazyFigImportContext } from '#core/kiwi/fig/lazy-import'type AssetRef = { key: string; version?: string }@@ -586,14 +587,13 @@ export function importNodeChanges(})}+ // Link imported instance children after population so linkage operates on the final tree state.+ linkImportedInstanceChildren(graph)+if (activeRootIds)rememberLazyFigImportContext(graph, changeMap, guidToNodeId, blobs, activeRootIds)setVariableColorResolver(null)-- if (graph.getPages(true).length === 0) {- graph.addPage('Page 1')- }-+ if (graph.getPages(true).length === 0) graph.addPage('Page 1')return graph}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 8c925d7db..c578de09a 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -84,6 +84,17 @@ export function generateId(): string {return `0:${nextLocalID++}`}+function stripUndefinedProps<T extends object>(obj: T): T {+ const result = {} as T+ for (const key of Object.keys(obj) as (keyof T)[]) {+ const val = obj[key]+ if (val !== undefined) {+ result[key] = val+ }+ }+ return result+}+export class SceneGraph {nodes = new Map<string, SceneNode>()images = new Map<string, Uint8Array>()@@ -407,6 +418,7 @@ export class SceneGraph {const appliedChanges = updateNodePreview(this, id, changes)if (appliedChanges) this.emitter.emit('node:previewUpdated', id, appliedChanges)}+updateNode(id: string, changes: Partial<SceneNode>): void {if (this.previewMutationDepth > 0) {this.updateNodePreview(id, changes)@@ -415,15 +427,7 @@ export class SceneGraph {const node = this.nodes.get(id)if (!node) return- let entries = Object.entries(changes) as Array<[string, unknown]>- changes = Object.fromEntries(- entries.filter(([, value]) => value !== undefined)- ) as Partial<SceneNode>- changes = styleDetachmentChanges(node, changes)- entries = Object.entries(changes) as Array<[string, unknown]>- changes = Object.fromEntries(- entries.filter(([, value]) => value !== undefined)- ) as Partial<SceneNode>+ changes = stripUndefinedProps(styleDetachmentChanges(node, stripUndefinedProps(changes)))// Only clear absPosCache when layout-affecting properties change.// Fills, strokes, effects, plugin data changes do NOT affect absolute position.diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.tsindex 1b662f65b..5adeed8e0 100644--- a/packages/scene-graph/src/instances.ts+++ b/packages/scene-graph/src/instances.ts@@ -108,6 +108,11 @@ function cloneChildrenWithMapping(destParentId: string,mode: NodeCloneMode = 'deep'): void {+ // Guard against cloning a subtree into itself or its own descendant. Without this,+ // a self-referential or cyclic component (e.g. an INSTANCE whose componentId points+ // to an ancestor) causes unbounded recursion and eventual stack overflow / OOM.+ if (sourceParentId === destParentId || graph.isDescendant(destParentId, sourceParentId)) return+const sourceParent = graph.nodes.get(sourceParentId)if (!sourceParent) return@@ -123,17 +128,113 @@ function cloneChildrenWithMapping(}}+function linkMatchedChild(+ overrides: InstanceOverrideState,+ instParentId: string,+ instChild: SceneNode,+ compChildId: string+): void {+ if (instChild.type === 'INSTANCE') {+ setInstanceOverride(overrides, instParentId, instChild.id, 'sourceComponentId', compChildId)+ } else {+ instChild.componentId = compChildId+ }+}++function matchFallbackChildren(+ graph: SceneGraph,+ compParent: SceneNode,+ instParent: SceneNode,+ instParentId: string,+ overrides: InstanceOverrideState,+ instChildMap: Map<string, SceneNode>,+ usedInstChildIds: Set<string>+): void {+ const unmatchedCompChildIds = compParent.childIds.filter((id) => !instChildMap.has(id))+ const unmatchedInstChildren = instParent.childIds+ .map((id) => graph.nodes.get(id))+ .filter((n): n is SceneNode => n !== undefined && !usedInstChildIds.has(n.id))++ if (unmatchedCompChildIds.length === 0 || unmatchedInstChildren.length === 0) return++ // Match by name and type with forward (FIFO) iteration to preserve sibling order.+ for (const compChildId of unmatchedCompChildIds) {+ const compChild = graph.nodes.get(compChildId)+ if (!compChild) continue+ const matchIdx = unmatchedInstChildren.findIndex(+ (instChild) => instChild.type === compChild.type && instChild.name === compChild.name+ )+ if (matchIdx !== -1) {+ const [instChild] = unmatchedInstChildren.splice(matchIdx, 1)+ instChildMap.set(compChildId, instChild)+ usedInstChildIds.add(instChild.id)+ linkMatchedChild(overrides, instParentId, instChild, compChildId)+ }+ }+}++function sortInstanceChildren(+ graph: SceneGraph,+ instParent: SceneNode,+ instParentId: string,+ compChildOrder: string[],+ overrides: InstanceOverrideState+): void {+ const orderMap = new Map<string, number>()+ for (let i = 0; i < compChildOrder.length; i++) orderMap.set(compChildOrder[i], i)++ // Children whose resolved mapping (sourceComponentId override, else componentId)+ // is one of this component's children sort in component order; children with no+ // such mapping (e.g. imported extras or user-added nodes inside the instance)+ // sort to the END rather than the front, keeping their relative order among+ // themselves. This keeps component children in canonical order instead of yanking+ // unmapped extras to the front on every sync.+ instParent.childIds.sort((a, b) => {+ const nodeA = graph.nodes.get(a)+ const nodeB = graph.nodes.get(b)+ const sourceA = nodeA+ ? getInstanceOverride(overrides, instParentId, nodeA.id, 'sourceComponentId')+ : undefined+ const sourceB = nodeB+ ? getInstanceOverride(overrides, instParentId, nodeB.id, 'sourceComponentId')+ : undefined++ const mappedA = typeof sourceA === 'string' ? sourceA : nodeA?.componentId+ const mappedB = typeof sourceB === 'string' ? sourceB : nodeB?.componentId+ const idxA = mappedA ? (orderMap.get(mappedA) ?? -1) : -1+ const idxB = mappedB ? (orderMap.get(mappedB) ?? -1) : -1+ if (idxA === -1 && idxB === -1) return 0+ if (idxA === -1) return 1+ if (idxB === -1) return -1+ return idxA - idxB+ })+}++/** True when syncing `compParentId` into `instParentId` would form a cycle. */+function isCyclicSync(graph: SceneGraph, compParentId: string, instParentId: string): boolean {+ return compParentId === instParentId || graph.isDescendant(instParentId, compParentId)+}+function syncChildren(graph: SceneGraph,compParentId: string,instParentId: string,overrides: InstanceOverrideState): void {+ // Guard against cyclic sync: if the instance parent is inside the component's own+ // subtree, syncing would clone the component into itself — a self-referential cycle+ // that causes unbounded recursion and OOM.+ if (isCyclicSync(graph, compParentId, instParentId)) return+const compParent = graph.nodes.get(compParentId)const instParent = graph.nodes.get(instParentId)if (!compParent || !instParent) returnconst instChildMap = new Map<string, SceneNode>()+ const usedInstChildIds = new Set<string>()+ const compChildIdSet = new Set(compParent.childIds)++ // Pass 1: Direct matching via sourceComponentId or componentIdfor (const childId of instParent.childIds) {const child = graph.nodes.get(childId)if (!child) continue@@ -146,9 +247,24 @@ function syncChildren(const mappedComponentId =typeof sourceComponentId === 'string' ? sourceComponentId : child.componentId- if (mappedComponentId) instChildMap.set(mappedComponentId, child)+ if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {+ instChildMap.set(mappedComponentId, child)+ usedInstChildIds.add(child.id)+ }}+ // Pass 2: Fallback matching for unmatched children (e.g. from Figma imports)+ matchFallbackChildren(+ graph,+ compParent,+ instParent,+ instParentId,+ overrides,+ instChildMap,+ usedInstChildIds+ )++ // Pass 3: Clone only genuinely missing component childrenfor (const compChildId of compParent.childIds) {if (!instChildMap.has(compChildId)) {const src = graph.nodes.get(compChildId)@@ -158,9 +274,11 @@ function syncChildren(cloneChildrenWithMapping(graph, compChildId, clone.id)}instChildMap.set(compChildId, clone)+ usedInstChildIds.add(clone.id)}}+ // Pass 4: Synchronize properties and recursefor (const compChildId of compParent.childIds) {const compChild = graph.nodes.get(compChildId)const instChild = instChildMap.get(compChildId)@@ -180,23 +298,8 @@ function syncChildren(}}- const compChildOrder = compParent.childIds- instParent.childIds.sort((a, b) => {- const nodeA = graph.nodes.get(a)- const nodeB = graph.nodes.get(b)- const sourceA = nodeA- ? getInstanceOverride(overrides, instParentId, nodeA.id, 'sourceComponentId')- : undefined- const sourceB = nodeB- ? getInstanceOverride(overrides, instParentId, nodeB.id, 'sourceComponentId')- : undefined-- const mappedA = typeof sourceA === 'string' ? sourceA : nodeA?.componentId- const mappedB = typeof sourceB === 'string' ? sourceB : nodeB?.componentId- const idxA = mappedA ? compChildOrder.indexOf(mappedA) : -1- const idxB = mappedB ? compChildOrder.indexOf(mappedB) : -1- return idxA - idxB- })+ // Pass 5: Sort instance children to match component child order+ sortInstanceChildren(graph, instParent, instParentId, compParent.childIds, overrides)}export function copyInstanceComponentProps(component: SceneNode): Partial<SceneNode> {@@ -263,17 +366,29 @@ export function swapInstanceComponent(cloneChildrenWithMapping(graph, componentId, instanceId)}+const syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()+export function syncInstances(graph: SceneGraph, componentId: string): void {const component = graph.nodes.get(componentId)if (component?.type !== 'COMPONENT') return-- for (const instance of getInstances(graph, componentId)) {- for (const key of INSTANCE_SYNC_PROPS) {- if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key))- continue- copyProp(instance, component, key)+ let syncing = syncingComponentsByGraph.get(graph)+ if (!syncing) {+ syncing = new Set()+ syncingComponentsByGraph.set(graph, syncing)+ }+ if (syncing.has(componentId)) return+ syncing.add(componentId)+ try {+ for (const instance of getInstances(graph, componentId)) {+ for (const key of INSTANCE_SYNC_PROPS) {+ if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key))+ continue+ copyProp(instance, component, key)+ }+ syncChildren(graph, component.id, instance.id, instance.instanceOverrides)}- syncChildren(graph, component.id, instance.id, instance.instanceOverrides)+ } finally {+ syncing.delete(componentId)}}diff --git a/tests/engine/editor/clipboard/import-nodes/instance-linkage.test.ts b/tests/engine/editor/clipboard/import-nodes/instance-linkage.test.tsnew file mode 100644index 000000000..314cebeef--- /dev/null+++ b/tests/engine/editor/clipboard/import-nodes/instance-linkage.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from 'bun:test'++import { importClipboardNodes, SceneGraph } from '@open-pencil/core'+import type { NodeChange } from '@open-pencil/core'++import { getNodeOrThrow } from '#tests/helpers/assert'++describe('importClipboardNodes: instance child linkage', () => {+ it('links serialized instance children so a later component sync does not duplicate them', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Test')+ const pageId = page.id++ // Component with one FRAME child, plus an INSTANCE referencing it that carries a+ // SERIALIZED child (as Figma exports instances with their instantiated subtree).+ // The instance child is renamed ('Header v2') — exactly the case the sync-time+ // name+type fallback cannot match, so paste-time linkage is required.+ const nodeChanges = [+ { guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT', name: 'Doc' },+ {+ guid: { sessionID: 0, localID: 1 },+ parentIndex: { guid: { sessionID: 0, localID: 0 }, position: '!' },+ type: 'CANVAS',+ name: 'Page'+ },+ {+ guid: { sessionID: 1, localID: 10 },+ parentIndex: { guid: { sessionID: 0, localID: 1 }, position: '!' },+ type: 'SYMBOL',+ name: 'Card',+ size: { x: 200, y: 60 },+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ },+ {+ guid: { sessionID: 1, localID: 11 },+ parentIndex: { guid: { sessionID: 1, localID: 10 }, position: '!' },+ type: 'FRAME',+ name: 'Header',+ size: { x: 200, y: 40 },+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ },+ {+ guid: { sessionID: 2, localID: 20 },+ parentIndex: { guid: { sessionID: 0, localID: 1 }, position: '"' },+ type: 'INSTANCE',+ name: 'Card',+ size: { x: 200, y: 60 },+ transform: { m00: 1, m01: 0, m02: 300, m10: 0, m11: 1, m12: 0 },+ symbolData: { symbolID: { sessionID: 1, localID: 10 } }+ },+ {+ guid: { sessionID: 2, localID: 21 },+ parentIndex: { guid: { sessionID: 2, localID: 20 }, position: '!' },+ type: 'FRAME',+ name: 'Header v2',+ size: { x: 200, y: 40 },+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ }+ ] as NodeChange[]++ const created = importClipboardNodes(nodeChanges, graph, pageId)+ expect(created).toHaveLength(2)++ const component = getNodeOrThrow(graph, created[0])+ expect(component.type).toBe('COMPONENT')+ const compChild = graph.getChildren(component.id)[0]+ expect(compChild?.name).toBe('Header')++ const instance = getNodeOrThrow(graph, created[1])+ expect(instance.type).toBe('INSTANCE')+ expect(instance.componentId).toBe(component.id)+ expect(instance.childIds).toHaveLength(1)++ // Paste-time linkage: the serialized instance child is stamped with its component+ // child's id — name-independent (positional + type), so renames do not defeat it.+ const instChild = getNodeOrThrow(graph, instance.childIds[0])+ expect(instChild.name).toBe('Header v2')+ expect(instChild.componentId).toBe(compChild.id)++ // A later component edit must sync props, not duplicate children.+ graph.updateNode(compChild.id, { height: 50 })+ graph.syncInstances(component.id)++ expect(instance.childIds).toHaveLength(1)+ expect(instChild.height).toBe(50)+ })++ it('does not mis-link an extra same-type child inserted before a renamed serialized child (overrideKey)', async () => {+ const { linkImportedInstanceChildren } = await import('#core/kiwi/fig/import-linkage')+ const { SceneGraph } = await import('@open-pencil/scene-graph')+ const graph = new SceneGraph()+ const page = graph.addPage('Test')++ const comp = graph.createNode('COMPONENT', page.id, { name: 'Card' })+ const compHeader = graph.createNode('FRAME', comp.id, {+ name: 'Header',+ overrideKey: '1:100',+ width: 200,+ height: 40+ })++ const inst = graph.createNode('INSTANCE', page.id, {+ name: 'Card',+ componentId: comp.id+ })+ const extra = graph.createNode('FRAME', inst.id, {+ name: 'Badge',+ width: 60,+ height: 20,+ componentId: null+ })+ const renamed = graph.createNode('FRAME', inst.id, {+ name: 'Header v2',+ overrideKey: '1:100',+ width: 200,+ height: 40,+ componentId: null+ })++ expect(inst.childIds).toEqual([extra.id, renamed.id])++ linkImportedInstanceChildren(graph, new Set([inst.id]))++ expect(extra.componentId).toBeNull()+ expect(renamed.componentId).toBe(compHeader.id)++ graph.updateNode(compHeader.id, { height: 50 })+ graph.syncInstances(comp.id)++ expect(inst.childIds).toHaveLength(2)+ expect(graph.getNode(extra.id)?.name).toBe('Badge')+ expect(graph.getNode(extra.id)?.componentId).toBeNull()+ expect(graph.getNode(renamed.id)?.height).toBe(50)+ // Extra sorts to the end, mapped child first.+ expect(inst.childIds[0]).toBe(renamed.id)+ expect(inst.childIds[1]).toBe(extra.id)+ })+})diff --git a/tests/engine/editor/clipboard/import-nodes/paste-scope.test.ts b/tests/engine/editor/clipboard/import-nodes/paste-scope.test.tsnew file mode 100644index 000000000..e79321c38--- /dev/null+++ b/tests/engine/editor/clipboard/import-nodes/paste-scope.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it } from 'bun:test'++import { importClipboardNodes } from '@open-pencil/core'+import type { NodeChange } from '@open-pencil/core'+import { SceneGraph } from '@open-pencil/scene-graph'++describe('importClipboardNodes: paste linkage scoping', () => {+ // This suite proves scoped paste linkage is load-bearing. Test 1 locks the+ // empty-set early return (paste with zero instances skips linkage entirely);+ // it passes under scoped, whole-graph-with-guard, and no-linkage, so it does+ // not by itself prove scoping — it discriminates unconditional whole-graph+ // linkage (no empty-set guard). Test 2 is the true scoping discriminator+ // (whole-graph corrupts the pre-existing Badge). See 05 debunking / 09 §19.+ it('does not re-link pre-existing instances when pasting content without instances (empty-set guard)', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Test')++ // Pre-existing component A with child 'Item 1', and instance instA with a+ // user-added extra child 'Badge' (componentId null) at index 0. This paste+ // carries zero instances, so pastedInstanceIds is empty and linkage is+ // skipped via the size>0 guard — the assertion below locks that guard.+ const comp = graph.createNode('COMPONENT', page.id, { name: 'A', width: 200, height: 60 })+ const compItem1 = graph.createNode('FRAME', comp.id, { name: 'Item 1', width: 100, height: 30 })+ const inst = graph.createNode('INSTANCE', page.id, {+ name: 'A Inst',+ componentId: comp.id,+ width: 200,+ height: 60+ })+ const badge = graph.createNode('FRAME', inst.id, {+ name: 'Badge',+ width: 20,+ height: 20,+ componentId: null+ })+ const instItem1 = graph.createNode('FRAME', inst.id, {+ name: 'Item 1',+ width: 100,+ height: 30,+ componentId: null+ })+ // badge at index 0, instItem1 at index 1 — badge sits at the positional slot+ // where a whole-graph linkage would have stamped it with compItem1.id.++ // Paste an unrelated rectangle (no instances) — exercises the empty-set path.+ const nodeChanges = [+ { guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT', name: 'Doc' },+ {+ guid: { sessionID: 0, localID: 1 },+ parentIndex: { guid: { sessionID: 0, localID: 0 }, position: '!' },+ type: 'CANVAS',+ name: 'Page'+ },+ {+ guid: { sessionID: 3, localID: 30 },+ parentIndex: { guid: { sessionID: 0, localID: 1 }, position: '!' },+ type: 'RECTANGLE',+ name: 'Rect',+ size: { x: 50, y: 50 },+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ }+ ] as NodeChange[]++ importClipboardNodes(nodeChanges, graph, page.id)++ // Pre-existing instance untouched by the paste: badge still unlinked, still+ // at its original position. With an unconditional whole-graph linkage (no+ // size guard) this would have stamped badge with compItem1.id positionally+ // and a later sync would rename/overwrite it. With the empty-set guard the+ // paste is a no-op for linkage.+ expect(badge.componentId).toBeNull()+ expect(inst.childIds[0]).toBe(badge.id)+ expect(inst.childIds[1]).toBe(instItem1.id)++ // A later sync links instItem1 by name+type (fallback) and leaves badge alone.+ graph.syncInstances(comp.id)+ expect(badge.name).toBe('Badge')+ expect(badge.componentId).toBeNull()+ expect(instItem1.componentId).toBe(compItem1.id)+ expect(inst.childIds.length).toBe(2) // no duplication+ expect(inst.childIds[0]).toBe(instItem1.id) // mapped sorts first+ expect(inst.childIds[1]).toBe(badge.id) // unmapped extra sorts last+ })++ it('links pasted instances but not pre-existing instances in the same paste', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Test')++ // Pre-existing component + instance with a user-added extra child that must+ // survive the paste untouched.+ const preComp = graph.createNode('COMPONENT', page.id, {+ name: 'Pre',+ width: 200,+ height: 60+ })+ graph.createNode('FRAME', preComp.id, { name: 'Slot', width: 100, height: 30 })+ const preInst = graph.createNode('INSTANCE', page.id, {+ name: 'Pre Inst',+ componentId: preComp.id,+ width: 200,+ height: 60+ })+ const preExtra = graph.createNode('FRAME', preInst.id, {+ name: 'Badge',+ width: 20,+ height: 20,+ componentId: null+ })+ const preSlot = graph.createNode('FRAME', preInst.id, {+ name: 'Slot',+ width: 100,+ height: 30,+ componentId: null+ })++ // Paste a component 'Card' (FRAME child 'Header') plus an INSTANCE of it with a+ // serialized renamed child 'Header v2' — the pasted instance MUST be linked.+ const nodeChanges = [+ { guid: { sessionID: 0, localID: 0 }, type: 'DOCUMENT', name: 'Doc' },+ {+ guid: { sessionID: 0, localID: 1 },+ parentIndex: { guid: { sessionID: 0, localID: 0 }, position: '!' },+ type: 'CANVAS',+ name: 'Page'+ },+ {+ guid: { sessionID: 4, localID: 40 },+ parentIndex: { guid: { sessionID: 0, localID: 1 }, position: '!' },+ type: 'SYMBOL',+ name: 'Card',+ size: { x: 200, y: 60 },+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ },+ {+ guid: { sessionID: 4, localID: 41 },+ parentIndex: { guid: { sessionID: 4, localID: 40 }, position: '!' },+ type: 'FRAME',+ name: 'Header',+ size: { x: 200, y: 40 },+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ },+ {+ guid: { sessionID: 4, localID: 42 },+ parentIndex: { guid: { sessionID: 0, localID: 1 }, position: '"' },+ type: 'INSTANCE',+ name: 'Card',+ size: { x: 200, y: 60 },+ transform: { m00: 1, m01: 0, m02: 300, m10: 0, m11: 1, m12: 0 },+ symbolData: { symbolID: { sessionID: 4, localID: 40 } }+ },+ {+ guid: { sessionID: 4, localID: 43 },+ parentIndex: { guid: { sessionID: 4, localID: 42 }, position: '!' },+ type: 'FRAME',+ name: 'Header v2',+ size: { x: 200, y: 40 },+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ }+ ] as NodeChange[]++ const created = importClipboardNodes(nodeChanges, graph, page.id)+ expect(created).toHaveLength(2)++ // Pasted instance IS linked (positional + type, name-independent).+ const pastedInst = getNodeByType(graph, created, 'INSTANCE')+ const pastedComp = getNodeByType(graph, created, 'COMPONENT')+ if (!pastedInst || !pastedComp) throw new Error('pasted instance/component missing')+ expect(pastedInst.componentId).toBe(pastedComp.id)+ const pastedChild = graph.getChildren(pastedInst.id)[0]+ const pastedCompChild = graph.getChildren(pastedComp.id)[0]+ expect(pastedChild?.name).toBe('Header v2')+ expect(pastedChild?.componentId).toBe(pastedCompChild?.id)++ // Pre-existing instance is NOT re-linked by the same paste.+ expect(preExtra.componentId).toBeNull()+ expect(preInst.childIds[0]).toBe(preExtra.id)+ expect(preInst.childIds[1]).toBe(preSlot.id)+ expect(preSlot.componentId).toBeNull()+ })+})++function getNodeByType(+ graph: SceneGraph,+ created: string[],+ type: 'INSTANCE' | 'COMPONENT'+): ReturnType<SceneGraph['getNode']> {+ for (const id of created) {+ const node = graph.getNode(id)+ if (node?.type === type) return node+ }+ return undefined+}diff --git a/tests/engine/scene-graph/instance-sync-duplication.test.ts b/tests/engine/scene-graph/instance-sync-duplication.test.tsnew file mode 100644index 000000000..97684637d--- /dev/null+++ b/tests/engine/scene-graph/instance-sync-duplication.test.ts@@ -0,0 +1,559 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph, recordInstanceOverride } from '@open-pencil/scene-graph'++import { linkImportedInstanceChildren } from '#core/kiwi/fig/import-linkage'++describe('instance synchronization child deduplication', () => {+ test('syncInstances on instance with imported children without componentId does not duplicate children', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ // Component with 1 FRAME child+ const component = graph.createNode('COMPONENT', page.id, { name: 'Card' })+ const compChild = graph.createNode('FRAME', component.id, {+ name: 'Header',+ width: 200,+ height: 50+ })++ // Simulate an instance imported from .fig:+ // The instance exists, its child exists with name 'Header', type 'FRAME',+ // but its componentId is null/empty because it was imported from Figma.+ const instance = graph.createNode('INSTANCE', page.id, {+ name: 'Card Instance',+ componentId: component.id+ })+ const instChild = graph.createNode('FRAME', instance.id, {+ name: 'Header',+ width: 200,+ height: 50,+ componentId: null+ })++ expect(instance.childIds.length).toBe(1)+ expect(instance.childIds[0]).toBe(instChild.id)++ // Mutate the component child and synchronize+ graph.updateNode(compChild.id, { height: 60 })+ graph.syncInstances(component.id)++ // In unpatched code: instance.childIds.length becomes 2 because Header was re-cloned!+ expect(instance.childIds.length).toBe(1)+ expect(instance.childIds[0]).toBe(instChild.id)+ expect(instChild.height).toBe(60)+ })++ test('syncInstances handles nested imported subtrees without duplicating nested children', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ // Component hierarchy: Sidebar -> StatusFooter -> StatusRow+ const sidebar = graph.createNode('COMPONENT', page.id, {+ name: 'Sidebar',+ width: 240,+ height: 800+ })+ const statusFooter = graph.createNode('FRAME', sidebar.id, {+ name: 'Status Footer',+ width: 240,+ height: 40+ })+ const statusRow = graph.createNode('FRAME', statusFooter.id, {+ name: 'Status Row',+ width: 200,+ height: 24+ })++ // Instance hierarchy as imported from Figma (componentId is null on frames)+ const sidebarInst = graph.createNode('INSTANCE', page.id, {+ name: 'Sidebar Instance',+ componentId: sidebar.id+ })+ const statusFooterInst = graph.createNode('FRAME', sidebarInst.id, {+ name: 'Status Footer',+ width: 240,+ height: 40,+ componentId: null+ })+ const statusRowInst = graph.createNode('FRAME', statusFooterInst.id, {+ name: 'Status Row',+ width: 200,+ height: 24,+ componentId: null+ })++ expect(sidebarInst.childIds.length).toBe(1)+ expect(statusFooterInst.childIds.length).toBe(1)++ // Mutate statusRow inside the component+ graph.updateNode(statusRow.id, { height: 28, opacity: 0.8 })+ graph.syncInstances(sidebar.id)++ expect(sidebarInst.childIds.length).toBe(1)+ expect(sidebarInst.childIds[0]).toBe(statusFooterInst.id)+ expect(statusFooterInst.childIds.length).toBe(1)+ expect(statusFooterInst.childIds[0]).toBe(statusRowInst.id)+ expect(statusRowInst.height).toBe(28)+ expect(statusRowInst.opacity).toBe(0.8)+ })++ test('syncInstances preserves explicit instance overrides while updating non-overridden properties', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const buttonComp = graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const labelComp = graph.createNode('TEXT', buttonComp.id, {+ name: 'Label',+ text: 'Submit',+ fontSize: 14,+ width: 80,+ height: 20+ })++ const buttonInst = graph.createNode('INSTANCE', page.id, {+ name: 'Button Instance',+ componentId: buttonComp.id+ })+ const labelInst = graph.createNode('TEXT', buttonInst.id, {+ name: 'Label',+ text: 'Custom Text', // override+ fontSize: 14,+ width: 80,+ height: 20,+ componentId: null+ })++ // Record override on text+ recordInstanceOverride(graph, labelInst.id, ['text'])++ // Mutate fontSize and text on component+ graph.updateNode(labelComp.id, { fontSize: 16, text: 'Click Here' })+ graph.syncInstances(buttonComp.id)++ expect(buttonInst.childIds.length).toBe(1)+ expect(labelInst.text).toBe('Custom Text') // preserved override+ expect(labelInst.fontSize).toBe(16) // synced from component+ })++ test('syncInstances adds newly added component children while keeping existing ones', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const comp = graph.createNode('COMPONENT', page.id, { name: 'Menu' })+ const _item1 = graph.createNode('FRAME', comp.id, { name: 'Item 1' })++ const inst = graph.createNode('INSTANCE', page.id, {+ name: 'Menu Instance',+ componentId: comp.id+ })+ const instItem1 = graph.createNode('FRAME', inst.id, {+ name: 'Item 1',+ componentId: null+ })++ // Now add a second child to the component+ const _item2 = graph.createNode('FRAME', comp.id, { name: 'Item 2', height: 32 })+ graph.syncInstances(comp.id)++ expect(inst.childIds.length).toBe(2)+ expect(inst.childIds[0]).toBe(instItem1.id) // original child preserved+ const instItem2 = graph.getNode(inst.childIds[1])+ expect(instItem2?.name).toBe('Item 2')+ expect(instItem2?.height).toBe(32)+ })+})++describe('instance synchronization regressions from review triage', () => {+ // V1: matchFallbackChildren backward iteration inverts same-name/type siblings.+ test('duplicate same-name/type siblings preserve FIFO mapping during fallback sync', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const comp = graph.createNode('COMPONENT', page.id, { name: 'List', width: 200, height: 60 })+ graph.createNode('FRAME', comp.id, { name: 'Row', width: 100, height: 30 })+ graph.createNode('FRAME', comp.id, { name: 'Row', width: 200, height: 30 })++ const inst = graph.createNode('INSTANCE', page.id, {+ name: 'List Inst',+ componentId: comp.id,+ width: 200,+ height: 60+ })+ const iA = graph.createNode('FRAME', inst.id, {+ name: 'Row',+ width: 50,+ height: 30,+ componentId: null+ })+ const iB = graph.createNode('FRAME', inst.id, {+ name: 'Row',+ width: 60,+ height: 30,+ componentId: null+ })++ graph.syncInstances(comp.id)++ expect(iA.width).toBe(100)+ expect(iB.width).toBe(200)+ expect(inst.childIds[0]).toBe(iA.id)+ expect(inst.childIds[1]).toBe(iB.id)+ })++ test('duplicate same-name siblings preserve overrides on the correct child', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const comp = graph.createNode('COMPONENT', page.id, { name: 'Rows', width: 200, height: 60 })+ graph.createNode('TEXT', comp.id, {+ name: 'Label',+ text: 'A',+ fontSize: 14,+ width: 80,+ height: 20+ })+ graph.createNode('TEXT', comp.id, {+ name: 'Label',+ text: 'B',+ fontSize: 14,+ width: 80,+ height: 20+ })++ const inst = graph.createNode('INSTANCE', page.id, {+ name: 'Rows Inst',+ componentId: comp.id,+ width: 200,+ height: 60+ })+ const labelA = graph.createNode('TEXT', inst.id, {+ name: 'Label',+ text: 'override-A',+ fontSize: 14,+ width: 80,+ height: 20,+ componentId: null+ })+ const labelB = graph.createNode('TEXT', inst.id, {+ name: 'Label',+ text: 'override-B',+ fontSize: 14,+ width: 80,+ height: 20,+ componentId: null+ })++ recordInstanceOverride(graph, labelA.id, ['text'])++ const compLabels = comp.childIds+ .map((id) => graph.getNode(id))+ .filter((n): n is NonNullable<typeof n> => n !== undefined)+ graph.updateNode(compLabels[0].id, { text: 'A-changed' })+ graph.updateNode(compLabels[1].id, { text: 'B-changed' })++ graph.syncInstances(comp.id)++ expect(labelA.text).toBe('override-A')+ expect(labelB.text).toBe('B-changed')+ })++ // V2+V3: extra unmatched instance child is not co-opted by positional or type-only fallback.+ test('extra unmatched instance child is not co-opted or renamed by fallback matching', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const comp = graph.createNode('COMPONENT', page.id, { name: 'Menu', width: 200, height: 60 })+ graph.createNode('FRAME', comp.id, { name: 'Item 1', width: 100, height: 30 })++ const inst = graph.createNode('INSTANCE', page.id, {+ name: 'Menu Inst',+ componentId: comp.id,+ width: 200,+ height: 60+ })+ const instItem1 = graph.createNode('FRAME', inst.id, {+ name: 'Item 1',+ width: 100,+ height: 30,+ componentId: null+ })+ const extra = graph.createNode('FRAME', inst.id, {+ name: 'Badge',+ width: 20,+ height: 20,+ componentId: null+ })++ graph.createNode('FRAME', comp.id, { name: 'Item 2', width: 100, height: 32 })++ graph.syncInstances(comp.id)++ expect(extra.name).toBe('Badge')+ expect(extra.width).toBe(20)+ expect(extra.height).toBe(20)+ expect(inst.childIds.length).toBe(3)+ expect(inst.childIds[0]).toBe(instItem1.id)+ expect(inst.childIds).toContain(extra.id)+ })++ // Sort tie-break contract: mapped children sort in component order, unmapped extras+ // sort to the END (not the front). Locks the deliberate behavior change where the+ // comparator sends unmapped children (no componentId resolving to a comp child) to+ // the end instead of the front.+ test('unmapped extra children sort to the end after sync, mapped children keep component order', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const comp = graph.createNode('COMPONENT', page.id, { name: 'Menu', width: 200, height: 60 })+ graph.createNode('FRAME', comp.id, { name: 'Item 1', width: 100, height: 30 })+ const compItem2 = graph.createNode('FRAME', comp.id, { name: 'Item 2', width: 100, height: 32 })++ const inst = graph.createNode('INSTANCE', page.id, {+ name: 'Menu Inst',+ componentId: comp.id,+ width: 200,+ height: 60+ })+ const instItem1 = graph.createNode('FRAME', inst.id, {+ name: 'Item 1',+ width: 100,+ height: 30,+ componentId: null+ })+ const extra = graph.createNode('FRAME', inst.id, {+ name: 'Badge',+ width: 20,+ height: 20,+ componentId: null+ })++ graph.syncInstances(comp.id)++ expect(inst.childIds.length).toBe(3)+ // Mapped children in component child order first...+ expect(inst.childIds[0]).toBe(instItem1.id)+ const instItem2 = graph.getNode(inst.childIds[1])+ expect(instItem2?.name).toBe('Item 2')+ expect(instItem2?.componentId).toBe(compItem2.id)+ // ...unmapped extra LAST — not yanked to the front on every sync.+ expect(inst.childIds[2]).toBe(extra.id)+ })++ // V5: self-referential component does not cause unbounded recursion / OOM.+ test('self-referential component does not hang or OOM on syncInstances', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const comp = graph.createNode('COMPONENT', page.id, { name: 'Self', width: 100, height: 50 })+ graph.createNode('INSTANCE', comp.id, {+ name: 'Self Inst',+ componentId: comp.id,+ width: 100,+ height: 50+ })++ graph.syncInstances(comp.id)++ expect(graph.countDescendants(comp.id)).toBeLessThan(50)+ })++ test('syncInstances on component with instance whose componentId is an ancestor is bounded', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const outer = graph.createNode('COMPONENT', page.id, { name: 'Outer', width: 200, height: 100 })+ const inner = graph.createNode('COMPONENT', outer.id, { name: 'Inner', width: 100, height: 50 })+ graph.createNode('INSTANCE', inner.id, {+ name: 'Outer Inst',+ componentId: outer.id,+ width: 200,+ height: 100+ })++ graph.syncInstances(outer.id)+ graph.syncInstances(inner.id)++ expect(graph.countDescendants(outer.id)).toBeLessThan(100)+ })++ // V7: graph-scoped syncingComponents. GENUINE reentrancy test — unlike the old+ // two-sequential-calls version (which passed even with NO guard), this fires the+ // reentrancy guard from inside a sync via the node:created event (emitted when+ // syncChildren Pass 3 clones a missing component child), and proves a second graph+ // with the same componentId can sync while the first is mid-sync — the exact+ // property a module-global Set breaks.+ test('reentrant syncInstances is a no-op, and a second graph with the same component ID syncs mid-sync', () => {+ const graph1 = new SceneGraph()+ const page1 = graph1.getPages()[0]+ if (!page1) throw new Error('page1 missing')+ graph1.createNodeWithId('comp-x', 'COMPONENT', page1.id, { name: 'C', width: 100, height: 50 })+ // Component child so Pass 3 clones it into inst-x — the clone fires node:created+ // mid-sync, which is where the reentrancy is exercised from.+ graph1.createNodeWithId('comp-row', 'FRAME', 'comp-x', { name: 'Row', width: 100, height: 10 })+ graph1.createNodeWithId('inst-x', 'INSTANCE', page1.id, {+ name: 'I',+ componentId: 'comp-x',+ width: 100,+ height: 50+ })++ const graph2 = new SceneGraph()+ const page2 = graph2.getPages()[0]+ if (!page2) throw new Error('page2 missing')+ graph2.createNodeWithId('comp-x', 'COMPONENT', page2.id, { name: 'C', width: 80, height: 40 })+ graph2.createNodeWithId('inst-x', 'INSTANCE', page2.id, {+ name: 'I',+ componentId: 'comp-x',+ width: 100,+ height: 50+ })++ let firedDuringSync = 0+ let graph2SyncedDuringSync = false++ // Arm AFTER both graphs exist, so the handler only fires for nodes created+ // during graph1's sync (the Pass 3 clone).+ const unbind = graph1.onNodeEvents({+ created: () => {+ // Re-entrant sync of the SAME graph+component must be safe: the guard makes+ // it a no-op, and even a hypothetical non-guarded re-entry must stay+ // idempotent (the clone already carries componentId, so Pass 1 matches it+ // and nothing is re-cloned). Call it to prove neither path corrupts state.+ graph1.syncInstances('comp-x')++ // Cross-graph sync with the SAME componentId must proceed (WeakMap scoping).+ graph2.syncInstances('comp-x')+ firedDuringSync+++ if (graph2.getNode('inst-x')?.width === 80) graph2SyncedDuringSync = true+ }+ })++ try {+ graph1.syncInstances('comp-x')+ } finally {+ unbind()+ }++ // The handler fired at least once during the sync (reentrancy actually exercised —+ // this is what makes the test non-vacuous).+ expect(firedDuringSync).toBeGreaterThan(0)+ // The re-entrant graph1 sync left exactly one clone of comp-row (no corruption).+ expect(graph1.getNode('inst-x')?.childIds.length).toBe(1)+ // graph2's instance synced while graph1's sync was in progress — a module-global+ // Set would have blocked this ('comp-x' already marked in-flight). This is the+ // discriminating assertion: the old sequential-calls test passed even with a+ // module-global Set; this one does not.+ expect(graph2SyncedDuringSync).toBe(true)+ expect(graph2.getNode('inst-x')?.width).toBe(80)+ // The outer sync still completed correctly: inst1 synced its component's width.+ expect(graph1.getNode('inst-x')?.width).toBe(100)+ })++ // V4: import-linkage does not stamp sub-instance descendants with proxy componentIds.+ test('linkImportedInstanceChildren does not recurse across INSTANCE boundaries', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const compB = graph.createNode('COMPONENT', page.id, { name: 'B', width: 100, height: 50 })+ const compBChild = graph.createNode('FRAME', compB.id, { name: 'G', width: 80, height: 30 })++ const compA = graph.createNode('COMPONENT', page.id, { name: 'A', width: 200, height: 100 })+ const compA_F = graph.createNode('FRAME', compA.id, { name: 'F', width: 200, height: 100 })+ const compA_N = graph.createNode('INSTANCE', compA_F.id, {+ name: 'N',+ componentId: compB.id,+ width: 100,+ height: 50+ })+ const compA_N_Child = graph.createNode('FRAME', compA_N.id, {+ name: 'G',+ width: 80,+ height: 30,+ componentId: null+ })++ const instA = graph.createNode('INSTANCE', page.id, {+ name: 'A Inst',+ componentId: compA.id,+ width: 200,+ height: 100+ })+ const instA_F = graph.createNode('FRAME', instA.id, {+ name: 'F',+ width: 200,+ height: 100,+ componentId: null+ })+ const instA_N = graph.createNode('INSTANCE', instA_F.id, {+ name: 'N',+ componentId: compB.id,+ width: 100,+ height: 50+ })+ const instA_N_Child = graph.createNode('FRAME', instA_N.id, {+ name: 'G',+ width: 80,+ height: 30,+ componentId: null+ })++ linkImportedInstanceChildren(graph)++ expect(instA_N_Child.componentId).toBe(compBChild.id)+ expect(instA_N_Child.componentId).not.toBe(compA_N_Child.id)+ })++ test('syncInstances on sub-instance main component works after linkImportedInstanceChildren', () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Page')++ const compB = graph.createNode('COMPONENT', page.id, { name: 'B', width: 100, height: 50 })+ const compBChild = graph.createNode('FRAME', compB.id, { name: 'G', width: 80, height: 30 })++ const compA = graph.createNode('COMPONENT', page.id, { name: 'A', width: 200, height: 100 })+ const compA_F = graph.createNode('FRAME', compA.id, { name: 'F', width: 200, height: 100 })+ graph.createNode('INSTANCE', compA_F.id, {+ name: 'N',+ componentId: compB.id,+ width: 100,+ height: 50+ })++ const instA = graph.createNode('INSTANCE', page.id, {+ name: 'A Inst',+ componentId: compA.id,+ width: 200,+ height: 100+ })+ const instA_F = graph.createNode('FRAME', instA.id, {+ name: 'F',+ width: 200,+ height: 100,+ componentId: null+ })+ const instA_N = graph.createNode('INSTANCE', instA_F.id, {+ name: 'N',+ componentId: compB.id,+ width: 100,+ height: 50+ })+ const instA_N_Child = graph.createNode('FRAME', instA_N.id, {+ name: 'G',+ width: 80,+ height: 30,+ componentId: null+ })++ linkImportedInstanceChildren(graph)++ graph.updateNode(compBChild.id, { height: 40 })+ graph.syncInstances(compB.id)++ expect(instA_N_Child.height).toBe(40)+ })+})