From ddbd84d9bdccc2e75020b26e87d4da00018e2193 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 3 Sep 2026 10:45:21 -0700 Subject: [PATCH] fix: normalize nested subgraph definition ids and cover node-shell input rehydration (#16546) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recursive subgraph-definition id normalization plus coverage for node-shell input rehydration and the brush-cursor rect read. Rebased onto current `main`; the node-replacement half was dropped because it landed separately.
Full context for agent readers Addresses part of #15973. ## Included 1. **Input-slot rehydration must not narrow to the `LGraphNode` constructor path** — `createNodeShellState` (the sole `NodeState` builder) returned a plain `shallowReactive` array for `inputs`; only `LGraphNode`'s constructor wrapped it with `createInputSlotView`, so a `NodeState` built any other way silently lost rehydration. The wrap now lives in `createNodeShellState` itself, injected as a parameter (`InputSlotViewFactory`) rather than statically imported: a static import there re-enters the litegraph module cycle at a point where `LGraphNode` is not yet defined (`TypeError: Class extends value undefined` in `SubgraphNode.ts`). Regression test constructs `NodeState` via `createNodeShellState` directly. 2. **Fixes #16010** — restores the deleted "read the container rect once per position, not once per axis" coverage for `BrushCursor`, adapted to the `useElementBounding()` implementation. Also characterizes a remaining gap: `useElementBounding()`'s observers do not see an ancestor moved via a transform on a non-target ancestor; only the next cursor move re-syncs via this component's `watch(cursorPoint, update)`. Coverage only; wiring an explicit recompute to dialog movement is separate follow-up work. 3. **Fixes #16012** — `normalizeSubgraphDefinitionIds` only normalized ids in the top-level `subgraphs` array and never descended into a definition's own nested `definitions.subgraphs` (structurally valid per `ExportedSubgraph extends SerialisableGraph`, never produced by our serializer, so this matters for external tools and older exports). Nested definitions are now recursively flattened into the returned list (clearing the redundant nested field) before the existing id-normalization and reference-rewrite pass. Tests cover one level, multi-level, empty, and sibling nesting. ## Dropped during rebase (already on `main`) - The per-node missing-node-warning tracking (#16011) was superseded by [#16464](https://github.com/Comfy-Org/ComfyUI_frontend/pull/16464), which fixed the same defect per type. Keeping both would have shipped two overlapping designs for one bug, so those commits were removed rather than reconciled. - The "documented identity break" test and JSDoc for `getInputSlotPos` were removed: [#16510](https://github.com/Comfy-Org/ComfyUI_frontend/pull/16510) made a retained plain-object reference resolvable, so the documented break no longer exists. `main`'s test for the fixed behavior is kept as-is. - #16009 was fixed by #16458; #16013 was fixed by #16512. Nothing duplicated here. ## Testing Focused `vitest` on the touched files and the `subgraph/` directory (399 tests), `vue-tsc --noEmit`, `oxlint` (type-aware) and `oxfmt --check` on the touched files — all clean on the rebased head. The recursive-normalization tests fail against the pre-fix code.
--- src/components/maskeditor/BrushCursor.test.ts | 31 ++++ .../graph/nodeShell/nodeShellState.test.ts | 48 +++++- src/core/graph/nodeShell/nodeShellState.ts | 24 ++- src/lib/litegraph/src/LGraphNode.ts | 10 +- .../src/node/slotDescriptorView.test.ts | 2 +- .../subgraph/subgraphDeduplication.test.ts | 142 +++++++++++++++++- .../src/subgraph/subgraphDeduplication.ts | 33 +++- 7 files changed, 280 insertions(+), 10 deletions(-) diff --git a/src/components/maskeditor/BrushCursor.test.ts b/src/components/maskeditor/BrushCursor.test.ts index 0e83312da7d..f47326c41a5 100644 --- a/src/components/maskeditor/BrushCursor.test.ts +++ b/src/components/maskeditor/BrushCursor.test.ts @@ -156,6 +156,37 @@ describe('BrushCursor', () => { expect(getBoundingClientRect).toHaveBeenCalledTimes(2) }) + it('should read the container rect once per position, not once per axis', async () => { + const container = document.createElement('div') + const readRect = vi + .spyOn(container, 'getBoundingClientRect') + .mockReturnValue(DOMRect.fromRect({ x: 30, y: 60 })) + + renderCursor(container) + await waitFor(() => { + expect(styleOf(getBrushEl())).toContain('left: 50px') + }) + + // left and top are both derived from the same underlying rect; reading + // it once per rendered position (rather than once per axis) is what + // keeps a mousemove down to a single forced layout. + expect( + readRect, + 'left and top come from the same rect; reading it twice is two forced layouts per mousemove' + ).toHaveBeenCalledTimes(1) + + mockStore.cursorPoint = { x: 101, y: 51 } + + await waitFor(() => { + expect(styleOf(getBrushEl())).toContain('left: 51px') + }) + + // A moved cursor must re-read the rect exactly once more, not once per + // axis: this is the same guarantee restated for the useElementBounding + // implementation that replaced the hand-rolled rect read. + expect(readRect).toHaveBeenCalledTimes(2) + }) + it('updates when the container moves under a stationary cursor', async () => { const container = document.createElement('div') vi.spyOn(container, 'getBoundingClientRect') diff --git a/src/core/graph/nodeShell/nodeShellState.test.ts b/src/core/graph/nodeShell/nodeShellState.test.ts index f88351f595c..36b557d4fa7 100644 --- a/src/core/graph/nodeShell/nodeShellState.test.ts +++ b/src/core/graph/nodeShell/nodeShellState.test.ts @@ -5,6 +5,8 @@ import { toRaw } from 'vue' import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' import type { Subgraph } from '@/lib/litegraph/src/litegraph' +import { NodeInputSlot } from '@/lib/litegraph/src/node/NodeInputSlot' +import { createInputSlotView } from '@/lib/litegraph/src/node/slotDescriptorView' import { createTestSubgraph } from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphHelpers' import { useNodeDataStore } from '@/stores/nodeDataStore' import { graphScopeOf } from '@/types/graphScopeId' @@ -35,7 +37,14 @@ describe('node shell state', () => { } it('starts unregistered and unowned', () => { - const state = createNodeShellState('Node', 'some/type', undefined) + const node = new LGraphNode('Node') + const state = createNodeShellState( + node, + createInputSlotView, + 'Node', + 'some/type', + undefined + ) expect(state.id).toBe(UNASSIGNED_NODE_ID) expect(state.graphId).toBe(zeroUuid) @@ -43,12 +52,39 @@ describe('node shell state', () => { }) it('falls back to a placeholder title and an empty type', () => { - const state = createNodeShellState('', undefined, undefined) + const node = new LGraphNode('Node') + const state = createNodeShellState( + node, + createInputSlotView, + '', + undefined, + undefined + ) expect(state.title).toBe('Unnamed') expect(state.type).toBe('') }) + it('rehydrates plain input-slot writes for any NodeState producer, not just the LGraphNode constructor', () => { + const node = new LGraphNode('Node') + const state = createNodeShellState( + node, + createInputSlotView, + 'Node', + 'some/type', + undefined + ) + + state.inputs.push({ + name: 'in', + type: 'INT', + link: null, + boundingRect: new Float64Array(4) + }) + + expect(state.inputs[0]).toBeInstanceOf(NodeInputSlot) + }) + it('buckets by root graph and partitions by owning graph', () => { const { subgraph, node } = addNodeToSubgraph() const rootId = subgraph.rootGraph.id @@ -112,7 +148,13 @@ describe('node registration invariants', () => { const graph = new LGraph() const node = new LGraphNode('Node') graph.add(node) - node._state = createNodeShellState('Node', 'test', undefined) + node._state = createNodeShellState( + node, + createInputSlotView, + 'Node', + 'test', + undefined + ) expect(() => unregisterNodeState(node)).toThrow(/identity drift/) expect(node._graphScope).toBeUndefined() diff --git a/src/core/graph/nodeShell/nodeShellState.ts b/src/core/graph/nodeShell/nodeShellState.ts index cf64ced83a1..455be7bca67 100644 --- a/src/core/graph/nodeShell/nodeShellState.ts +++ b/src/core/graph/nodeShell/nodeShellState.ts @@ -20,11 +20,33 @@ import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' import type { TitleMode } from '@/lib/litegraph/src/types/globalEnums' import type { NodeState } from '@/types/nodeState' +/** + * Wraps a node's `inputs` array with a rehydration view — e.g. + * {@link createInputSlotView} — that upgrades plain input-slot writes into + * class instances. Injected by the caller (rather than imported directly) + * to keep this module out of the litegraph value-import graph: `LGraphNode` + * sits in a cycle with the slot/subgraph modules that back that view, and a + * static import here resolves at a point in that cycle where `LGraphNode` + * isn't defined yet. + */ +export type InputSlotViewFactory = ( + node: LGraphNode, + inputs: INodeInputSlot[] +) => INodeInputSlot[] + /** * Builds the shell state a node carries from construction until it adopts the * {@link useNodeDataStore} proxy in {@link registerNodeState}. + * + * `inputs` is wrapped by `createInputSlotView` here — the one place that + * builds a node's slot arrays — so every `NodeState` producer, not just + * {@link LGraphNode}'s constructor, gets plain input-slot writes rehydrated + * into `NodeInputSlot` instances. Callers pass their own view factory (see + * {@link InputSlotViewFactory}) to avoid a static import cycle. */ export function createNodeShellState( + node: LGraphNode, + createInputSlotView: InputSlotViewFactory, title: string, type: string | undefined, titleMode: TitleMode | undefined @@ -33,7 +55,7 @@ export function createNodeShellState( flags: {}, graphId: zeroUuid, id: UNASSIGNED_NODE_ID, - inputs: shallowReactive([]), + inputs: createInputSlotView(node, shallowReactive([])), mode: LGraphEventMode.ALWAYS, outputs: shallowReactive([]), properties: {}, diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index 07026c41fef..cd8d4347f88 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -1006,8 +1006,14 @@ export class LGraphNode constructor(title: string, type?: string) { initializeWidgetsView(this) - this._state = createNodeShellState(title, type, this.title_mode) - this._inputs = createInputSlotView(this, this._state.inputs) + this._state = createNodeShellState( + this, + createInputSlotView, + title, + type, + this.title_mode + ) + this._inputs = this._state.inputs this._outputs = this._state.outputs for (const property of [ 'inputs', diff --git a/src/lib/litegraph/src/node/slotDescriptorView.test.ts b/src/lib/litegraph/src/node/slotDescriptorView.test.ts index d55743ab492..dc9a66ccace 100644 --- a/src/lib/litegraph/src/node/slotDescriptorView.test.ts +++ b/src/lib/litegraph/src/node/slotDescriptorView.test.ts @@ -55,7 +55,7 @@ describe('slot identity', () => { node.inputs = [input] - expect(node._state.inputs).not.toBe(node.inputs) + expect(node._state.inputs).toBe(node.inputs) expect(node.inputs[0]).toBeInstanceOf(NodeInputSlot) expect(node._state.inputs[0]).toBe(node.inputs[0]) }) diff --git a/src/lib/litegraph/src/subgraph/subgraphDeduplication.test.ts b/src/lib/litegraph/src/subgraph/subgraphDeduplication.test.ts index eeebacb5e64..c8a019376e1 100644 --- a/src/lib/litegraph/src/subgraph/subgraphDeduplication.test.ts +++ b/src/lib/litegraph/src/subgraph/subgraphDeduplication.test.ts @@ -21,11 +21,19 @@ import { deduplicateSubgraphLinkIds, deduplicateSubgraphNodeIds, deduplicateSubgraphRerouteIds, + normalizeSubgraphDefinitionIds, normalizeSubgraphDefinitions, topologicalSortSubgraphs } from './subgraphDeduplication' -function makeSubgraph(id: string, nodeTypes: string[] = []): ExportedSubgraph { +type NestedExportedSubgraph = ExportedSubgraph & { + definitions?: { subgraphs?: NestedExportedSubgraph[] } +} + +function makeSubgraph( + id: string, + nodeTypes: string[] = [] +): NestedExportedSubgraph { return { id, name: id, @@ -49,6 +57,138 @@ function makeSubgraph(id: string, nodeTypes: string[] = []): ExportedSubgraph { } as ExportedSubgraph } +function findSubgraph( + subgraphs: NestedExportedSubgraph[], + name: string +): NestedExportedSubgraph { + const subgraph = subgraphs.find((candidate) => candidate.name === name) + if (!subgraph) throw new Error(`Missing subgraph fixture: ${name}`) + return subgraph +} + +describe('normalizeSubgraphDefinitionIds', () => { + it('normalizes a legacy id at the top level and rewrites its references', () => { + const legacy = makeSubgraph('legacy-id') + const parent = makeSubgraph('parent', ['legacy-id']) + + const result = normalizeSubgraphDefinitionIds([legacy, parent]) + const normalizedId = result.subgraphs[0].id + + expect(result.subgraphs).toHaveLength(2) + expect(isUuidShapedSubgraphId(normalizedId)).toBe(true) + expect(result.subgraphs[1].nodes![0].type).toBe(normalizedId) + }) + + it('recursively normalizes a subgraph-within-subgraph definition and hoists it to the flat result', () => { + // Regression for #16012: a nested subgraph definition (embedded in a + // parent subgraph's own `definitions.subgraphs`, e.g. from an external + // tool or older export) must be normalized and surfaced, not skipped + // because normalization only looked at the top-level array. + const nestedChild = makeSubgraph('legacy-nested-id') + const parent = makeSubgraph('parent', ['legacy-nested-id']) + parent.definitions = { subgraphs: [nestedChild] } + const root = makeSubgraph('root', ['parent']) + + const result = normalizeSubgraphDefinitionIds([parent, root]) + + // Both the parent and the previously-nested child are present in the + // flat result. + expect(result.subgraphs).toHaveLength(3) + const normalizedParent = findSubgraph(result.subgraphs, 'parent') + const normalizedChild = findSubgraph(result.subgraphs, 'legacy-nested-id') + + // The nested child's legacy id was normalized to a fresh UUID. + expect(isUuidShapedSubgraphId(normalizedChild.id)).toBe(true) + expect(normalizedChild.id).not.toBe('legacy-nested-id') + + // The parent's node referencing the nested child by its old id now + // references the normalized UUID. + expect(normalizedParent.nodes).toHaveLength(1) + expect(normalizedParent.nodes?.[0]?.type).toBe(normalizedChild.id) + + // The now-redundant nested list is cleared: callers read the flat + // top-level result, not each definition's own nested subgraphs. + expect(normalizedParent.definitions?.subgraphs).toBeUndefined() + }) + + it('normalizes multiple levels of subgraph-within-subgraph nesting', () => { + const grandchild = makeSubgraph('legacy-grandchild') + const child = makeSubgraph('legacy-child', ['legacy-grandchild']) + child.definitions = { subgraphs: [grandchild] } + const parent = makeSubgraph('parent', ['legacy-child']) + parent.definitions = { subgraphs: [child] } + + const result = normalizeSubgraphDefinitionIds([parent]) + + expect(result.subgraphs).toHaveLength(3) + const normalizedChild = findSubgraph(result.subgraphs, 'legacy-child') + const normalizedGrandchild = findSubgraph( + result.subgraphs, + 'legacy-grandchild' + ) + const normalizedParent = findSubgraph(result.subgraphs, 'parent') + + expect(isUuidShapedSubgraphId(normalizedChild.id)).toBe(true) + expect(isUuidShapedSubgraphId(normalizedGrandchild.id)).toBe(true) + expect(normalizedParent.nodes).toHaveLength(1) + expect(normalizedParent.nodes?.[0]?.type).toBe(normalizedChild.id) + expect(normalizedChild.nodes).toHaveLength(1) + expect(normalizedChild.nodes?.[0]?.type).toBe(normalizedGrandchild.id) + }) + + it('handles an explicit empty definitions.subgraphs list without error', () => { + const parent = makeSubgraph('parent') + parent.definitions = { subgraphs: [] } + + const result = normalizeSubgraphDefinitionIds([parent]) + + expect(result.subgraphs).toHaveLength(1) + expect(result.subgraphs[0].name).toBe('parent') + }) + + it('preserves every sibling when a definition nests multiple subgraphs', () => { + const siblingA = makeSubgraph('legacy-sibling-a') + const siblingB = makeSubgraph('legacy-sibling-b') + const siblingC = makeSubgraph('legacy-sibling-c') + const parent = makeSubgraph('parent', [ + 'legacy-sibling-a', + 'legacy-sibling-b', + 'legacy-sibling-c' + ]) + parent.definitions = { + subgraphs: [siblingA, siblingB, siblingC] + } + + const result = normalizeSubgraphDefinitionIds([parent]) + + // Parent plus all three nested siblings survive flattening. + expect(result.subgraphs).toHaveLength(4) + const names = result.subgraphs.map((sg) => sg.name) + expect(names).toEqual( + expect.arrayContaining([ + 'parent', + 'legacy-sibling-a', + 'legacy-sibling-b', + 'legacy-sibling-c' + ]) + ) + + // Each sibling got its own normalized id and the parent's three nodes + // reference all three, not just the first. + const normalizedParent = findSubgraph(result.subgraphs, 'parent') + const siblingIds = [ + 'legacy-sibling-a', + 'legacy-sibling-b', + 'legacy-sibling-c' + ].map((name) => findSubgraph(result.subgraphs, name).id) + expect(new Set(siblingIds).size).toBe(3) + expect(siblingIds).not.toContain('legacy-sibling-a') + expect(siblingIds).not.toContain('legacy-sibling-b') + expect(siblingIds).not.toContain('legacy-sibling-c') + expect(normalizedParent.nodes?.map((node) => node.type)).toEqual(siblingIds) + }) +}) + describe('topologicalSortSubgraphs', () => { it('returns original order when there are no dependencies', () => { const a = makeSubgraph('a') diff --git a/src/lib/litegraph/src/subgraph/subgraphDeduplication.ts b/src/lib/litegraph/src/subgraph/subgraphDeduplication.ts index 49793a7ed1a..a8e07d78d84 100644 --- a/src/lib/litegraph/src/subgraph/subgraphDeduplication.ts +++ b/src/lib/litegraph/src/subgraph/subgraphDeduplication.ts @@ -77,14 +77,43 @@ export function normalizeSubgraphDefinitions( return { subgraphs: clonedSubgraphs, rootNodes: clonedRootNodes } } +interface NestedSubgraphDefinitions { + definitions?: { subgraphs?: Subgraph[] } +} + +/** + * Flattens every subgraph definition reachable from `subgraphs` into one + * array, descending into each definition's own nested + * `definitions.subgraphs` (a subgraph-within-subgraph definition) at any + * depth. Each definition's own nested list is cleared once its contents are + * hoisted, since callers operate on the returned flat list. + */ +function flattenSubgraphDefinitions< + Subgraph extends NestedSubgraphDefinitions +>(subgraphs: Subgraph[]): Subgraph[] { + const flattened: Subgraph[] = [] + for (const subgraph of subgraphs) { + flattened.push(subgraph) + const nested = subgraph.definitions?.subgraphs + if (nested?.length) { + flattened.push(...flattenSubgraphDefinitions(nested)) + subgraph.definitions!.subgraphs = undefined + } + } + return flattened +} + export function normalizeSubgraphDefinitionIds< - Subgraph extends { id: string; nodes?: { type: string }[] }, + Subgraph extends NestedSubgraphDefinitions & { + id: string + nodes?: { type: string }[] + }, Node extends { type: string } >( subgraphs: Subgraph[], rootNodes?: Node[] ): DeduplicationResult { - const clonedSubgraphs = structuredClone(subgraphs) + const clonedSubgraphs = flattenSubgraphDefinitions(structuredClone(subgraphs)) const clonedRootNodes = rootNodes ? structuredClone(rootNodes) : undefined const ids = new Set(clonedSubgraphs.map(({ id }) => id)) const remapped = new Map()