From e7dcbbd3d7256cc3a9eda3697f40eae81883908c Mon Sep 17 00:00:00 2001 From: "claude[bot]" <209825114+claude[bot]@users.noreply.github.com> Date: Wed, 23 Sep 2026 03:03:37 +0000 Subject: [PATCH] fix: keep released subgraph definitions consistent across convert-to-subgraph (#18040) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _Requested via [Slack thread](https://comfy-organization.slack.com/archives/C09KFK2ABB8/p1788424987450979?thread_ts=1788424987.450979&cid=C09KFK2ABB8)_ ## ELI5 Converting a selection to a subgraph is like packing a box into a bigger box. If the small box was the only one of its kind, the code threw away its packing list the moment it left the shelf, then put the box in the bigger box anyway. Every later save found a box with no list and raised an alarm. Now the packing list survives the move, because the box is being re-shelved, not discarded. ## Motivation `graph_serialization_state_mismatch` is currently the most frequent error type from `serialiseStoredNodes` in production. Datadog RUM shows nearly all of those events as "live node N has no stored state" with a subgraph `graphId`, in sessions that used Convert Selection to Subgraph, Unpack, or New Subgraph. The report fires on every save until reload, and the serialized definition for that subgraph falls back to live-node serialization, so the node store and the saved workflow disagree for the rest of the session. Fixing the trigger in the conversion path removes the dominant source of the alert. ## Provenance - **Authored by:** interactive session - **Verified:** `pnpm vitest run src/lib/litegraph/src/subgraph/SubgraphConversion.nestedDefinitions.test.ts`: 1 failed on the test-only commit ("live node 1 has no stored state"), 1 passed with the fix; `pnpm vitest run src/lib/litegraph/src/subgraph/`: 19 files, 356 passed; `pnpm vitest run src/lib/litegraph/src/LGraph` plus every test file referencing `releaseSubgraphs`, `convertToSubgraph`, `unpackSubgraph`, `findReleasableSubgraphs` or `detachAllNodesFromStores`: 46 files, 648 passed, 7 expected fail, 5 skipped; `pnpm typecheck` (via the pre-commit hook on both commits): clean; `eslint` and `oxlint --type-aware` on the two changed files: 0 errors; `oxfmt --check`: clean; `pnpm knip`: clean - **Deviations:** unknown ## Reviewer context - **Type:** bug fix, litegraph subgraph lifecycle - **Slots into:** no project or epic; ad-hoc production error fix - **Not in scope:** the general hazard that a registered subgraph node type keeps a closure over a released `Subgraph` instance and `LGraph.add()` re-inserts it into `rootGraph.subgraphs` without node state. This PR removes the trigger seen in production; hardening `releaseSubgraphs` / `add()` against resurrection is a follow-up. ## Summary - Convert-to-subgraph no longer releases the subgraph definitions referenced by the nodes it is about to re-create inside the new subgraph. - Adds a regression test that fails on `main` with the production mismatch report and passes with the fix. **Before:** convert nodes A and B into subgraph S1 (host node H1). Then select H1 plus another node and convert that into S2. Serializing the root graph reports `Graph serialization state mismatch` with `mismatch: "live node A has no stored state"` and `graphId: S1`, on every save until reload. **After:** the same sequence serializes cleanly. S1 stays a valid definition, nested inside S2, with all of its nodes stored. **Mechanism:** 1. `_convertToSubgraphImpl` removes the selected nodes with `this.remove(node)` before configuring the new subgraph from the serialized selection. 2. `removeNode` sees that H1 is a `SubgraphNode` and calls `releaseSubgraphs(findReleasableSubgraphs(...))`. H1 was S1's only instance, so S1 is released: its node store records are deleted and it is dropped from `rootGraph.subgraphs`, but the `Subgraph` instance keeps its `_nodes`. 3. The registered node type for S1 is a class whose constructor closes over that same `Subgraph` instance, so `LiteGraph.createNode(S1.id)` inside S2's configure returns a host pointing at the released instance. 4. `LGraph.add()` walks nested subgraph nodes and re-inserts S1 into `rootGraph.subgraphs`. S1 now has live nodes and zero stored state, and `serialiseStoredNodes` reports the mismatch on every serialize. **Fix choice:** option (a), skip the release for nodes that the conversion is moving. Every node removed in that loop is re-created inside the new subgraph from the same serialized data, so the set of definitions in use is identical before and after the operation and nothing should be released. This is a three-line change behind a new `GraphRemoveOptions.preserveSubgraphDefinitions` flag, used only by `_convertToSubgraphImpl`. The alternative (tearing down released instances fully and teaching `add()` to re-attach or refuse them) touches the release and add paths for every caller and is a broader behavioral change; unregistering the node type is not viable because the nested host inside the new subgraph is created through that type. ## Changes - **What**: `GraphRemoveOptions.preserveSubgraphDefinitions`; `removeNode` skips `releaseSubgraphs` when it is set; `_convertToSubgraphImpl` passes it when removing the moved nodes. New test `src/lib/litegraph/src/subgraph/SubgraphConversion.nestedDefinitions.test.ts`. If `createSubgraph` throws after the originals are removed, `_convertToSubgraphImpl` releases the removed nodes' definitions that no live node still references (`findOrphanedSubgraphs` in `subgraphUtils.ts`) and rethrows, so a failed conversion leaves no orphaned definitions registered. ## Red / green The first commit adds only the failing test (CI should be red on it), the second commit adds the fix (CI should be green). Unpack was checked and is not affected by this trigger: it materializes the inner nodes into the parent before removing the host, so the definitions are still live when the host is released. ## Review Focus - `findReleasableSubgraphs` is still called for every other removal path (delete, undo, unpack), so nothing else changes behavior. - If a moved node's type cannot be re-created inside the new subgraph, its definition stays registered but unused; `findUsedSubgraphIds` already excludes unused definitions from serialization. ## Test plan - [ ] CI red on the test-only commit, green on the fix commit - [ ] Convert nodes to a subgraph, then convert a selection containing that subgraph's host into another subgraph, save: no `graph_serialization_state_mismatch` in the console or RUM - [ ] Unpack the outer subgraph afterwards and save again: still clean 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01TsajsCwfDusee9F9rPWNb7 --- _Generated by [Claude Code](https://claude.ai/code/session_01TsajsCwfDusee9F9rPWNb7)_ --------- Co-authored-by: Christian Byrne Co-authored-by: glary-bot --- .../fixtures/helpers/SubgraphHelper.ts | 68 ++++++ .../subgraphWrapNestedDefinition.spec.ts | 101 ++++++++ src/lib/litegraph/src/LGraph.ts | 16 +- ...bgraphConversion.nestedDefinitions.test.ts | 222 ++++++++++++++++++ .../litegraph/src/subgraph/subgraphUtils.ts | 13 + .../subgraphConversionLayout.test.ts | 66 ++++++ 6 files changed, 483 insertions(+), 3 deletions(-) create mode 100644 browser_tests/tests/subgraph/subgraphWrapNestedDefinition.spec.ts create mode 100644 src/lib/litegraph/src/subgraph/SubgraphConversion.nestedDefinitions.test.ts create mode 100644 src/renderer/core/layout/operations/subgraphConversionLayout.test.ts diff --git a/browser_tests/fixtures/helpers/SubgraphHelper.ts b/browser_tests/fixtures/helpers/SubgraphHelper.ts index dce472a3634..24500f57863 100644 --- a/browser_tests/fixtures/helpers/SubgraphHelper.ts +++ b/browser_tests/fixtures/helpers/SubgraphHelper.ts @@ -18,6 +18,14 @@ import { SubgraphSlotReference } from '@e2e/fixtures/utils/litegraphUtils' import { getAllHostPromotedWidgets } from '@e2e/fixtures/utils/promotedWidgets' import type { PromotedWidgetEntry } from '@e2e/fixtures/utils/promotedWidgets' +interface SubgraphDefinitionRow { + name: string + nodes: number + links: number +} + +type SubgraphDefinitionInventory = SubgraphDefinitionRow[] + export class SubgraphHelper { public readonly editor: SubgraphEditor @@ -586,6 +594,66 @@ export class SubgraphHelper { return id } + /** Descends `levels` times, requiring exactly one subgraph node at each level. */ + async descendSubgraphs(levels: number): Promise { + for (let level = 0; level < levels; level++) { + await expect.poll(() => this.countSubgraphNodes()).toBe(1) + const parentGraphId = await this.getActiveGraphId() + await this.enterSubgraphWithFallback(await this.findSubgraphNodeId()) + await expect.poll(() => this.getActiveGraphId()).not.toBe(parentGraphId) + } + } + + /** Number of subgraph host nodes in the graph currently shown on the canvas. */ + async countSubgraphNodes(): Promise { + return this.page.evaluate( + () => + window.app!.canvas.graph!.nodes.filter((node) => node.isSubgraphNode()) + .length + ) + } + + /** + * Interior node and link counts of every subgraph definition, one row per + * definition sorted by name, then node count, then link count. Definitions + * sharing a name stay as separate rows, because `Convert to Subgraph` names + * every new definition 'New Subgraph'. + */ + async getDefinitionInventory(): Promise { + return this.page.evaluate(() => + [...window.app!.rootGraph.subgraphs.values()] + .map((definition) => ({ + name: definition.name, + nodes: definition.nodes.length, + links: definition.links.size + })) + .sort( + (a, b) => + a.name.localeCompare(b.name) || + a.nodes - b.nodes || + a.links - b.links + ) + ) + } + + /** Same inventory, read back from a serialized workflow rather than live state. */ + async getSerializedDefinitionInventory(): Promise { + return this.page.evaluate(() => + (window.app!.rootGraph.asSerialisable().definitions?.subgraphs ?? []) + .map((definition) => ({ + name: definition.name, + nodes: definition.nodes?.length ?? 0, + links: definition.links?.length ?? 0 + })) + .sort( + (a, b) => + a.name.localeCompare(b.name) || + a.nodes - b.nodes || + a.links - b.links + ) + ) + } + async getBoundaryLinkSnapshot() { return this.page.evaluate(() => { const graph = window.app!.graph diff --git a/browser_tests/tests/subgraph/subgraphWrapNestedDefinition.spec.ts b/browser_tests/tests/subgraph/subgraphWrapNestedDefinition.spec.ts new file mode 100644 index 00000000000..d7751370185 --- /dev/null +++ b/browser_tests/tests/subgraph/subgraphWrapNestedDefinition.spec.ts @@ -0,0 +1,101 @@ +import { expect } from '@playwright/test' + +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' + +test.use({ initialSettings: { 'Comfy.UseNewMenu': 'Disabled' } }) + +test.describe( + 'Wrapping a subgraph host that owns nested definitions', + { tag: ['@subgraph', '@slow'] }, + () => { + const WRAPPED_SELECTION = ['subgraph 2', 'VAE Decode', 'Save Image'] + + const NESTED_DEFINITIONS_INTACT = [ + { name: 'subgraph 2', nodes: 3, links: 7 }, + { name: 'subgraph 3', nodes: 3, links: 6 } + ] + + // The wrapper's 4th link is the boundary link feeding Save Image's + // filename_prefix widget, which conversion promotes to a wrapper input. + const NESTED_DEFINITIONS_AFTER_WRAP = [ + { name: 'New Subgraph', nodes: 3, links: 4 }, + ...NESTED_DEFINITIONS_INTACT + ] + + test.beforeEach(async ({ comfyPage }) => { + await comfyPage.workflow.loadWorkflow('subgraphs/nested-subgraph') + }) + + test('keeps the wrapped and nested definitions populated', async ({ + comfyPage + }) => { + await expect + .poll(() => comfyPage.subgraph.getDefinitionInventory()) + .toEqual(NESTED_DEFINITIONS_INTACT) + + await test.step('Wrap the subgraph host together with its siblings', async () => { + await comfyPage.nodeOps.selectNodes(WRAPPED_SELECTION) + expect( + [...(await comfyPage.nodeOps.getSelectedNodeIds())].sort(), + 'all three nodes must be selected, or the conversion under test is not the one being asserted' + ).toEqual(['10', '8', '9']) + + const host = await comfyPage.nodeOps.getNodeRefById('10') + await host.convertToSubgraph() + }) + + await expect + .poll(() => comfyPage.subgraph.getDefinitionInventory()) + .toEqual(NESTED_DEFINITIONS_AFTER_WRAP) + }) + + test('keeps the nested definitions populated in the saved workflow', async ({ + comfyPage + }) => { + await test.step('Wrap the subgraph host together with its siblings', async () => { + await comfyPage.nodeOps.selectNodes(WRAPPED_SELECTION) + const host = await comfyPage.nodeOps.getNodeRefById('10') + await host.convertToSubgraph() + }) + + await comfyPage.subgraph.serializeAndReload() + + await expect + .poll(() => comfyPage.subgraph.getSerializedDefinitionInventory()) + .toEqual(NESTED_DEFINITIONS_AFTER_WRAP) + }) + + test( + 'still renders the nested interior after wrapping', + { tag: ['@vue-nodes'] }, + async ({ comfyPage }) => { + await test.step('Wrap the subgraph host together with its siblings', async () => { + await comfyPage.nodeOps.selectNodes(WRAPPED_SELECTION) + const host = await comfyPage.nodeOps.getNodeRefById('10') + await host.convertToSubgraph() + }) + + await test.step('Descend through the wrapper into the deepest nested subgraph', async () => { + await comfyPage.subgraph.descendSubgraphs(3) + }) + + await test.step('Assert the deepest interior still renders its three nodes', async () => { + await expect(comfyPage.vueNodes.nodes).toHaveCount(3) + await expect( + comfyPage.vueNodes.getNodeByTitle('Load Checkpoint') + ).toBeVisible() + await expect( + comfyPage.vueNodes.getNodeByTitle('Empty Latent Image') + ).toBeVisible() + await expect( + comfyPage.vueNodes.getNodeByTitle('CLIP Text Encode (Prompt)') + ).toBeVisible() + await comfyPage.attachScreenshot( + 'nested-subgraph-interior-after-wrap', + { runInCI: true } + ) + }) + } + ) + } +) diff --git a/src/lib/litegraph/src/LGraph.ts b/src/lib/litegraph/src/LGraph.ts index a633f0bc68b..0258d9e2bb5 100644 --- a/src/lib/litegraph/src/LGraph.ts +++ b/src/lib/litegraph/src/LGraph.ts @@ -140,6 +140,7 @@ import { import type { UnpackedTargetInput } from './subgraph/unpackSubgraph' import { findUnresolvableSubgraphLink, + findOrphanedSubgraphs, findReleasableSubgraphs, findUsedSubgraphIds, getBoundaryLinks, @@ -234,6 +235,8 @@ export interface GraphRemoveOptions { * Same-id replacement state is left intact. */ preserveCanonicalState?: boolean + /** Keep the subgraph definitions the node references; the caller re-creates the node elsewhere in the same root graph. */ + preserveSubgraphDefinitions?: boolean } export interface LGraphExtra extends Dictionary { @@ -1495,7 +1498,7 @@ export class LGraph } } - if (node.isSubgraphNode()) { + if (node.isSubgraphNode() && !options.preserveSubgraphDefinitions) { this.releaseSubgraphs(findReleasableSubgraphs(this.rootGraph, node)) } @@ -2216,11 +2219,18 @@ export class LGraph resolved.inputNode ) - for (const node of nodes) this.remove(node) + for (const node of nodes) + this.remove(node, { preserveSubgraphDefinitions: true }) for (const reroute of reroutes) this.removeReroute(reroute.id) for (const group of groups) this.remove(group) - const subgraph = this.createSubgraph(data) + let subgraph: Subgraph + try { + subgraph = this.createSubgraph(data) + } catch (error) { + this.releaseSubgraphs(findOrphanedSubgraphs(this.rootGraph, nodes)) + throw error + } for (const node of subgraph.nodes) node.onGraphConfigured?.() for (const node of subgraph.nodes) node.onAfterGraphConfigured?.() diff --git a/src/lib/litegraph/src/subgraph/SubgraphConversion.nestedDefinitions.test.ts b/src/lib/litegraph/src/subgraph/SubgraphConversion.nestedDefinitions.test.ts new file mode 100644 index 00000000000..3692c7f7790 --- /dev/null +++ b/src/lib/litegraph/src/subgraph/SubgraphConversion.nestedDefinitions.test.ts @@ -0,0 +1,222 @@ +import { + assert, + beforeEach, + describe, + expect, + it, + onTestFinished, + vi +} from 'vitest' + +import type { + LGraph, + Positionable, + Subgraph, + SubgraphNode +} from '@/lib/litegraph/src/litegraph' +import { LiteGraph } from '@/lib/litegraph/src/litegraph' +import { createTestNode } from '@/lib/litegraph/src/__fixtures__/nodeHelpers' +import { reportError } from '@/platform/telemetry/reportError' + +import { + createTestRootGraph, + enableSubgraphNodeCreation, + resetSubgraphFixtureState +} from './__fixtures__/subgraphHelpers' + +vi.mock(import('@/platform/telemetry/reportError'), () => ({ + reportError: vi.fn() +})) + +beforeEach(() => { + resetSubgraphFixtureState() +}) + +interface DefinitionHealth { + nodes: number + links: number + serialisedNodes: number + serialisedLinks: number + reportedErrors: number +} + +function captureHealth( + rootGraph: LGraph, + definition: Subgraph +): DefinitionHealth { + const serialised = rootGraph + .asSerialisable() + .definitions?.subgraphs?.find(({ id }) => id === definition.id) + + return { + nodes: definition.nodes.length, + links: definition.links.size, + serialisedNodes: serialised?.nodes?.length ?? 0, + serialisedLinks: serialised?.links?.length ?? 0, + reportedErrors: vi.mocked(reportError).mock.calls.length + } +} + +function buildSubgraphWithTwoLinkedInteriorNodes(parent: LGraph): { + subgraph: Subgraph + node: SubgraphNode +} { + const origin = createTestNode(parent, [], ['number']) + const target = createTestNode(parent, ['number']) + origin.connect(0, target, 0) + return parent.convertToSubgraph(new Set([origin, target])) +} + +describe('Convert to Subgraph with a nested subgraph host in the selection', () => { + it('keeps the nested definition serialisable after its only host moves into the new subgraph', () => { + const rootGraph = createTestRootGraph() + onTestFinished(enableSubgraphNodeCreation(rootGraph)) + + const origin = createTestNode(rootGraph, [], ['number']) + const target = createTestNode(rootGraph, ['number']) + origin.connect(0, target, 0) + const { subgraph: inner, node: innerHost } = rootGraph.convertToSubgraph( + new Set([origin, target]) + ) + const sibling = createTestNode(rootGraph) + + const { subgraph: outer } = rootGraph.convertToSubgraph( + new Set([innerHost, sibling]) + ) + + const serialized = rootGraph.serialize() + + expect(reportError).not.toHaveBeenCalled() + const definitions = new Map( + (serialized.definitions?.subgraphs ?? []).map((s) => [s.id, s]) + ) + const innerDefinition = definitions.get(inner.id) + const outerDefinition = definitions.get(outer.id) + assert(innerDefinition?.nodes) + assert(outerDefinition?.nodes) + expect(innerDefinition.nodes.map((node) => node.type).sort()).toEqual( + [origin.type, target.type].sort() + ) + expect(outerDefinition.nodes.map((node) => node.type)).toContain(inner.id) + }) + + it.for([ + { + shape: 'host selected on its own', + wrap: (rootGraph: LGraph, host: SubgraphNode) => { + rootGraph.convertToSubgraph(new Set([host])) + } + }, + { + shape: 'host selected alongside a plain sibling', + wrap: (rootGraph: LGraph, host: SubgraphNode) => { + const sibling = createTestNode(rootGraph) + rootGraph.convertToSubgraph(new Set([host, sibling])) + } + }, + { + shape: 'host wrapped twice in a row', + wrap: (rootGraph: LGraph, host: SubgraphNode) => { + const { node: wrapper } = rootGraph.convertToSubgraph( + new Set([host]) + ) + rootGraph.convertToSubgraph(new Set([wrapper])) + } + }, + { + shape: 'host wrapped from inside the subgraph that owns it', + wrap: (rootGraph: LGraph, host: SubgraphNode) => { + const { subgraph: middle } = rootGraph.convertToSubgraph( + new Set([host]) + ) + const relocatedHost = middle.nodes.find((node) => node.isSubgraphNode()) + assert(relocatedHost) + middle.convertToSubgraph(new Set([relocatedHost])) + } + } + ])( + 'keeps the wrapped definition intact when the $shape', + ({ wrap }, { expect }) => { + const rootGraph = createTestRootGraph() + onTestFinished(enableSubgraphNodeCreation(rootGraph)) + const { subgraph: inner, node: innerHost } = + buildSubgraphWithTwoLinkedInteriorNodes(rootGraph) + + wrap(rootGraph, innerHost) + + expect(captureHealth(rootGraph, inner)).toEqual({ + nodes: 2, + links: 1, + serialisedNodes: 2, + serialisedLinks: 1, + reportedErrors: 0 + }) + } + ) + + it('keeps every level of a three-deep nest intact when the outermost host is wrapped', () => { + const rootGraph = createTestRootGraph() + onTestFinished(enableSubgraphNodeCreation(rootGraph)) + + const { subgraph: leaf, node: leafHost } = + buildSubgraphWithTwoLinkedInteriorNodes(rootGraph) + const middleOrigin = createTestNode(rootGraph, [], ['number']) + const middleTarget = createTestNode(rootGraph, ['number']) + middleOrigin.connect(0, middleTarget, 0) + const { subgraph: middle, node: middleHost } = rootGraph.convertToSubgraph( + new Set([leafHost, middleOrigin, middleTarget]) + ) + + rootGraph.convertToSubgraph( + new Set([middleHost, createTestNode(rootGraph)]) + ) + + expect({ + leaf: captureHealth(rootGraph, leaf), + middle: captureHealth(rootGraph, middle) + }).toEqual({ + leaf: { + nodes: 2, + links: 1, + serialisedNodes: 2, + serialisedLinks: 1, + reportedErrors: 0 + }, + middle: { + nodes: 3, + links: 1, + serialisedNodes: 3, + serialisedLinks: 1, + reportedErrors: 0 + } + }) + }) +}) + +describe('Convert to Subgraph failing after the originals are removed', () => { + it('releases only the definitions no live node still references', () => { + const rootGraph = createTestRootGraph() + onTestFinished(enableSubgraphNodeCreation(rootGraph)) + const { subgraph: orphaned, node: orphanedHost } = + buildSubgraphWithTwoLinkedInteriorNodes(rootGraph) + const { subgraph: shared, node: sharedHost } = + buildSubgraphWithTwoLinkedInteriorNodes(rootGraph) + const survivingSharedHost = LiteGraph.createNode(shared.id) + assert(survivingSharedHost) + rootGraph.add(survivingSharedHost) + vi.spyOn(rootGraph, 'createSubgraph').mockImplementationOnce(() => { + throw new Error('boom') + }) + + expect(() => + rootGraph.convertToSubgraph( + new Set([orphanedHost, sharedHost]) + ) + ).toThrow('boom') + + expect({ + orphaned: rootGraph.subgraphs.has(orphaned.id), + shared: rootGraph.subgraphs.has(shared.id) + }).toEqual({ orphaned: false, shared: true }) + }) +}) diff --git a/src/lib/litegraph/src/subgraph/subgraphUtils.ts b/src/lib/litegraph/src/subgraph/subgraphUtils.ts index 7a199e75bad..4de9b1bad6f 100644 --- a/src/lib/litegraph/src/subgraph/subgraphUtils.ts +++ b/src/lib/litegraph/src/subgraph/subgraphUtils.ts @@ -564,6 +564,19 @@ export function findReleasableSubgraphs( return removedSubtree.filter((subgraph) => !liveIds.has(subgraph.id)) } +export function findOrphanedSubgraphs( + rootGraph: LGraph, + removedNodes: Iterable +): Subgraph[] { + const orphaned = new Map() + for (const node of removedNodes) { + if (!node.isSubgraphNode()) continue + for (const subgraph of findReleasableSubgraphs(rootGraph, node)) + orphaned.set(subgraph.id, subgraph) + } + return [...orphaned.values()] +} + function reorderInPlace(arr: unknown[], indices: readonly number[]): void { arr.splice(0, arr.length, ...indices.flatMap((i) => arr[i] ?? [])) } diff --git a/src/renderer/core/layout/operations/subgraphConversionLayout.test.ts b/src/renderer/core/layout/operations/subgraphConversionLayout.test.ts new file mode 100644 index 00000000000..aaa8a86dff3 --- /dev/null +++ b/src/renderer/core/layout/operations/subgraphConversionLayout.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it, onTestFinished } from 'vitest' + +import type { + LGraph, + Positionable, + Subgraph +} from '@/lib/litegraph/src/litegraph' +import { createTestNode } from '@/lib/litegraph/src/__fixtures__/nodeHelpers' +import { + createTestRootGraph, + enableSubgraphNodeCreation, + resetSubgraphFixtureState +} from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphHelpers' +import { layoutStore } from '@/renderer/core/layout/store/layoutStore' + +import { setNodePosition } from './graphLayoutAttachment' + +beforeEach(() => { + resetSubgraphFixtureState() + layoutStore.resetForTests() +}) + +function interiorGeometry( + rootGraph: LGraph, + definition: Subgraph +): Record { + return Object.fromEntries( + definition.nodes.map((node) => [ + String(node.id), + layoutStore.getNodeLayout(rootGraph.id, node.id)?.position ?? null + ]) + ) +} + +describe('Convert to Subgraph and the layout records of a nested definition', () => { + it('leaves each interior node at its own distinct position', () => { + const rootGraph = createTestRootGraph() + onTestFinished(enableSubgraphNodeCreation(rootGraph)) + + const origin = createTestNode(rootGraph, [], ['number']) + const target = createTestNode(rootGraph, ['number']) + origin.connect(0, target, 0) + setNodePosition(origin, [110, 220]) + setNodePosition(target, [330, 440]) + + const { subgraph: inner, node: innerHost } = rootGraph.convertToSubgraph( + new Set([origin, target]) + ) + const before = interiorGeometry(rootGraph, inner) + + rootGraph.convertToSubgraph( + new Set([innerHost, createTestNode(rootGraph)]) + ) + + expect({ before, after: interiorGeometry(rootGraph, inner) }).toEqual({ + before: { + [origin.id]: { x: 110, y: 220 }, + [target.id]: { x: 330, y: 440 } + }, + after: { + [origin.id]: { x: 110, y: 220 }, + [target.id]: { x: 330, y: 440 } + } + }) + }) +})