diff --git a/browser_tests/tests/subgraph/subgraphPromotedWidgetRewireDuplication.spec.ts b/browser_tests/tests/subgraph/subgraphPromotedWidgetRewireDuplication.spec.ts new file mode 100644 index 00000000000..83dbd6646cb --- /dev/null +++ b/browser_tests/tests/subgraph/subgraphPromotedWidgetRewireDuplication.spec.ts @@ -0,0 +1,229 @@ +import { expect } from '@playwright/test' + +import type { ComfyPage } from '@e2e/fixtures/ComfyPage' +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import type { NodeReference } from '@e2e/fixtures/utils/litegraphUtils' +import { toNodeId } from '@/types/nodeId' + +// Reported (Jo Zhang / Christian Byrne): when the in-app AI agent (or a +// manual drag) wires a new node into a subgraph's promoted "prompt" widget, +// the subgraph host's *other* promoted widgets (width/height/seed) render +// duplicated above the prompt box. A sibling symptom (PM-1253/PM-1254): the +// rewired widget itself disappears, and redo misplaces the wire. Undo always +// restores a correct single-widget display, because it fully reloads the +// node from a snapshot. +// +// Linear: PM-1328 (this bug), PM-1253 (parent), PM-1254 (sibling: int node -> +// width). +// +// Two candidate trigger paths are covered as separate scenarios, since they +// go through different code: +// - Interior rewire: rebinding the link feeding the interior node *behind* +// the promoted widget, from inside the subgraph +// (SubgraphInputNode._disconnectNodeInput -> SubgraphNode's +// 'input-disconnected' handler, src/lib/litegraph/src/subgraph/ +// SubgraphNode.ts:325-354 / SubgraphInputNode.ts:173-234). +// - External boundary wire: dragging a brand-new node directly onto the +// SubgraphNode's own exposed widget socket from the parent graph -- the +// literal action in the bug report ("wire a text node into the +// subgraph's prompt widget"). This does not go through +// SubgraphNode._setWidget/ensureWidgetRemoved at all (SubgraphNode has no +// onConnectInput/onConnectionsChange override), so it is a genuinely +// different code path from the interior-rewire case above. +// +// Undo-test note: a Vue slot drag-connect records its own undo snapshot on +// drop (useSlotLinkInteraction.ts captureCanvasState, #18117), so undo right +// after the wire action deterministically restores the pre-wire state. + +const KSAMPLER_ID = '3' +const EMPTY_LATENT_ID = '5' +const POSITIVE_CLIP_ID = '6' + +const PROMOTED_WIDGET_NAMES = ['text', 'seed', 'width', 'height'] as const + +/** Builds a subgraph with 4 promoted widgets from 3 different node types: + * 'text' (CLIPTextEncode, the promoted "prompt"), 'seed' (KSampler), and + * 'width'/'height' (EmptyLatentImage) -- the exact widget mix from the bug + * report. */ +async function buildBaselineSubgraph(comfyPage: ComfyPage): Promise { + await comfyPage.workflow.loadWorkflow('default') + + await comfyPage.page.keyboard.down('Control') + try { + for (const id of [KSAMPLER_ID, EMPTY_LATENT_ID, POSITIVE_CLIP_ID]) { + const node = await comfyPage.nodeOps.getNodeRefById(id) + await node.click('title') + } + } finally { + await comfyPage.page.keyboard.up('Control') + await comfyPage.nextFrame() + } + + const subgraphNodeId = await comfyPage.subgraph.convertSelectionToSubgraph() + + // 'seed' (name match) and every CLIPTextEncode widget (node-type match) + // are auto-promoted as "recommended" on conversion; width/height are not, + // so promote them explicitly to match the real-world reported workflow. + await comfyPage.vueNodes.enterSubgraph(subgraphNodeId) + const emptyLatent = comfyPage.vueNodes.getNodeLocator(EMPTY_LATENT_ID) + await comfyPage.subgraph.promoteWidget(emptyLatent, 'width') + await comfyPage.subgraph.promoteWidget(emptyLatent, 'height') + await comfyPage.subgraph.exitViaBreadcrumb() + + await expectSingleRenderedWidgetOfEach(comfyPage, subgraphNodeId) + return subgraphNodeId +} + +function widgetLocators(comfyPage: ComfyPage, subgraphNodeId: string) { + const node = comfyPage.vueNodes.getNodeLocator(subgraphNodeId) + return PROMOTED_WIDGET_NAMES.map( + (name) => [name, node.getByLabel(name, { exact: true })] as const + ) +} + +/** The bug's core, verifiable symptom: after any rewire behind one promoted + * widget, every promoted widget -- including the ones nothing touched -- + * must still render exactly once. */ +async function expectSingleRenderedWidgetOfEach( + comfyPage: ComfyPage, + subgraphNodeId: string +) { + for (const [name, locator] of widgetLocators(comfyPage, subgraphNodeId)) { + await expect( + locator, + `"${name}" widget should render exactly once` + ).toHaveCount(1) + } +} + +test.describe( + 'Subgraph promoted widget duplication on rewire (PM-1328 / PM-1253 / PM-1254)', + { tag: ['@subgraph', '@widget', '@vue-nodes'] }, + () => { + test.use({ initialSettings: { 'Comfy.Canvas.SelectionToolbox': true } }) + + test.describe('Interior rewire (rebinding the link behind the promoted widget)', () => { + test('keeps sibling promoted widgets rendered exactly once on the subgraph host', async ({ + comfyPage + }) => { + const subgraphNodeId = await buildBaselineSubgraph(comfyPage) + + await comfyPage.vueNodes.enterSubgraph(subgraphNodeId) + const [interiorClip] = await comfyPage.nodeOps.getNodeRefsByType( + 'CLIPTextEncode', + true + ) + await comfyPage.subgraph.rebindPromotedInput(interiorClip, 'text') + await comfyPage.subgraph.exitViaBreadcrumb() + + await expectSingleRenderedWidgetOfEach(comfyPage, subgraphNodeId) + }) + + test('undo restores exactly one of each promoted widget', async ({ + comfyPage + }) => { + const subgraphNodeId = await buildBaselineSubgraph(comfyPage) + + await comfyPage.vueNodes.enterSubgraph(subgraphNodeId) + const [interiorClip] = await comfyPage.nodeOps.getNodeRefsByType( + 'CLIPTextEncode', + true + ) + await comfyPage.subgraph.rebindPromotedInput(interiorClip, 'text') + await comfyPage.subgraph.exitViaBreadcrumb() + + await comfyPage.keyboard.undo() + await comfyPage.nextFrame() + + // Undo fully reloads the node from a snapshot (ChangeTracker -> + // app.loadGraphData -> SubgraphNode.configure), so this must pass + // even though the rewire itself (above) does not. + await expectSingleRenderedWidgetOfEach(comfyPage, subgraphNodeId) + }) + }) + + test.describe("External boundary wire (new node onto the host node's promoted widget socket)", () => { + test('keeps sibling promoted widgets rendered exactly once on the subgraph host', async ({ + comfyPage + }) => { + const subgraphNodeId = await buildBaselineSubgraph(comfyPage) + + const subgraphNodeRef: NodeReference = + await comfyPage.nodeOps.getNodeRefById(subgraphNodeId) + const textWidgetIndex = (await subgraphNodeRef.getWidgetByName('text')) + .index + + const source: NodeReference = await comfyPage.nodeOps.addNode( + 'PrimitiveNode', + {}, + { x: 100, y: 800 } + ) + await comfyPage.nextFrame() + + // The literal user/agent action from the bug report: drag a new + // node's output directly onto the SubgraphNode's own exposed + // "prompt" widget socket, from the parent graph -- not from inside + // the subgraph. + await source.connectWidget(0, subgraphNodeRef, textWidgetIndex) + await comfyPage.nextFrame() + + await expectSingleRenderedWidgetOfEach(comfyPage, subgraphNodeId) + }) + + test('undo keeps rendered promoted widgets consistent with the host model', async ({ + comfyPage + }) => { + const subgraphNodeId = await buildBaselineSubgraph(comfyPage) + + const subgraphNodeRef: NodeReference = + await comfyPage.nodeOps.getNodeRefById(subgraphNodeId) + const textWidgetIndex = (await subgraphNodeRef.getWidgetByName('text')) + .index + + const source: NodeReference = await comfyPage.nodeOps.addNode( + 'PrimitiveNode', + {}, + { x: 100, y: 800 } + ) + await comfyPage.nextFrame() + await source.connectWidget(0, subgraphNodeRef, textWidgetIndex) + await comfyPage.nextFrame() + + await comfyPage.keyboard.undo() + await comfyPage.nextFrame() + + // Which snapshot undo targets depends on change-tracker capture + // timing this test does not control (captures fire on window + // mouseup, before the click handlers that apply promotions), so + // assert render/model consistency instead of a fixed widget set: + // whatever state undo restored, the host's model must hold each + // promoted widget at most once and the grid must render exactly + // one row per model widget. Both reported symptoms -- duplicated + // rows and a disappeared widget -- violate this invariant. + const modelWidgetNames = await comfyPage.page.evaluate((id) => { + const node = window.app!.canvas.graph!.getNodeById(id) + return node + ? (node.widgets?.map((widget) => widget.name) ?? []) + : null + }, toNodeId(subgraphNodeId)) + + expect(modelWidgetNames, 'host node should survive undo').not.toBeNull() + expect( + new Set(modelWidgetNames).size, + 'model should hold no duplicate widgets' + ).toBe(modelWidgetNames!.length) + + for (const [name, locator] of widgetLocators( + comfyPage, + subgraphNodeId + )) { + const expected = modelWidgetNames!.includes(name) ? 1 : 0 + await expect( + locator, + `"${name}" should render ${expected === 1 ? 'exactly once' : 'not at all'}` + ).toHaveCount(expected) + } + }) + }) + } +) diff --git a/browser_tests/tests/subgraph/subgraphPromotion.spec.ts b/browser_tests/tests/subgraph/subgraphPromotion.spec.ts index 4c78efe4d57..e950e034297 100644 --- a/browser_tests/tests/subgraph/subgraphPromotion.spec.ts +++ b/browser_tests/tests/subgraph/subgraphPromotion.spec.ts @@ -212,7 +212,6 @@ test.describe( await comfyPage.subgraph.exitViaBreadcrumb() await comfyPage.vueNodes.waitForNodes() - test.fail() await expect(promotedTextarea).toHaveValue(hostValue) }) }) diff --git a/src/composables/graph/useErrorClearingHooks.test.ts b/src/composables/graph/useErrorClearingHooks.test.ts index 64581ebee9d..8715bcefce9 100644 --- a/src/composables/graph/useErrorClearingHooks.test.ts +++ b/src/composables/graph/useErrorClearingHooks.test.ts @@ -1156,7 +1156,7 @@ describe('onNodeRemoved clears missing asset errors by execution ID', () => { expect(scopeSpy).toHaveBeenCalledTimes(survivingNodes.length) }) - it('removes host-keyed missing media when its sole promoted consumer is deleted', () => { + it('removes host-keyed missing media when its sole promoted consumer is deleted', async () => { const { rootGraph, subgraph, @@ -1172,11 +1172,15 @@ describe('onNodeRemoved clears missing asset errors by execution ID', () => { expect(host.widgets).toHaveLength(1) subgraph.remove(sourceNodes[0]) + // Widget demotion is deferred by a microtask so a same-tick reconnect + // (a rewire) can cancel it; this genuine removal completes once it runs. + await Promise.resolve() + expect(host.widgets).toHaveLength(0) expect(mediaStore.missingMediaCandidates).toBeNull() }) - it('keeps promoted missing media until the last fanout consumer is deleted', () => { + it('keeps promoted missing media until the last fanout consumer is deleted', async () => { const { rootGraph, subgraph, @@ -1191,14 +1195,19 @@ describe('onNodeRemoved clears missing asset errors by execution ID', () => { mediaStore.setMissingMedia([candidate]) subgraph.remove(sourceNodes[0]) + await Promise.resolve() expect(host.widgets).toHaveLength(1) expect(mediaStore.missingMediaCandidates).toEqual([candidate]) subgraph.remove(sourceNodes[2]) + await Promise.resolve() expect(host.widgets).toHaveLength(1) expect(mediaStore.missingMediaCandidates).toEqual([candidate]) subgraph.remove(sourceNodes[1]) + // Widget demotion is deferred by a microtask so a same-tick reconnect + // (a rewire) can cancel it; this genuine removal completes once it runs. + await Promise.resolve() expect(host.widgets).toHaveLength(0) expect(mediaStore.missingMediaCandidates).toBeNull() }) diff --git a/src/core/graph/subgraph/promotionUtils.test.ts b/src/core/graph/subgraph/promotionUtils.test.ts index 16bafeb8283..0e895f69d35 100644 --- a/src/core/graph/subgraph/promotionUtils.test.ts +++ b/src/core/graph/subgraph/promotionUtils.test.ts @@ -805,7 +805,7 @@ describe('demoteWidget — axiomatic projection retraction', () => { return { host, interiorNode, interiorWidget } } - it('drops projection but keeps slot and external link when host slot is externally connected', () => { + it('drops projection but keeps slot and external link when host slot is externally connected', async () => { const { host, interiorNode, interiorWidget } = setupPromotedWidget() const hostInput = host.inputs[0] const source = new LGraphNode('External Source') @@ -819,6 +819,10 @@ describe('demoteWidget — axiomatic projection retraction', () => { demoteWidget(interiorNode, interiorWidget, [host]) + // Demotion is deferred by a microtask so a same-tick reconnect (a + // rewire) can cancel it; this genuine demote completes once it runs. + await Promise.resolve() + expect(host.subgraph.inputs).toHaveLength(1) expect(host.inputs[0]?.link).toBe(externalLink.id) expect(host.inputs[0]?._widget).toBeUndefined() diff --git a/src/lib/litegraph/src/interfaces.ts b/src/lib/litegraph/src/interfaces.ts index 8edc8a9ae8f..9ef0b638a92 100644 --- a/src/lib/litegraph/src/interfaces.ts +++ b/src/lib/litegraph/src/interfaces.ts @@ -379,6 +379,13 @@ export interface INodeInputSlot extends INodeSlot { * Internal use only; API is not finalised and may change at any time. */ _widget?: IBaseWidget + + /** + * Internal use only. Set while a promoted widget's demotion is deferred by + * a microtask, so a same-tick reconnect (a rewire) can cancel it instead + * of the widget being torn down and immediately rebuilt. + */ + _pendingDemotionToken?: symbol } export interface IWidgetInputSlot extends INodeInputSlot { diff --git a/src/lib/litegraph/src/subgraph/SubgraphNode.ts b/src/lib/litegraph/src/subgraph/SubgraphNode.ts index 08c2ab60449..fdd4f072c6a 100644 --- a/src/lib/litegraph/src/subgraph/SubgraphNode.ts +++ b/src/lib/litegraph/src/subgraph/SubgraphNode.ts @@ -311,6 +311,10 @@ export class SubgraphNode extends LGraphNode implements BaseLGraph { 'input-connected', (e) => { input.shape = this.getSlotShape(subgraphInput, e.detail.input) + // A reconnect landing before the deferred demotion below runs is a + // rewire, not a real disconnect: cancel the pending demotion so the + // widget is never torn down. + input._pendingDemotionToken = undefined if (!e.detail.widget || !e.detail.node) return this._setWidget( @@ -336,20 +340,33 @@ export class SubgraphNode extends LGraphNode implements BaseLGraph { return } - if (input._widget) this.ensureWidgetRemoved(input._widget) - if (input.widgetId) { - const id = input.widgetId - queueMicrotask(() => { - if (this.inputs.some((input) => input.widgetId === id)) return + // Defer the actual demotion by a microtask instead of clearing + // input.widgetId/.widget/._widget here: a rewire (this disconnect + // immediately followed by a reconnect of the same input, e.g. + // dragging a new source onto an already-promoted widget) would + // otherwise drop the widget from `this.widgets` for one tick, which + // is exactly the window the Vue widget grid can render from. The + // 'input-connected' listener above cancels this token on a + // same-tick reconnect. + const widget = input._widget + const id = input.widgetId + const token = Symbol() + input._pendingDemotionToken = token + queueMicrotask(() => { + if (input._pendingDemotionToken !== token) return + input._pendingDemotionToken = undefined + + if (widget) this.ensureWidgetRemoved(widget) + if (id && !this.inputs.some((i) => i.widgetId === id)) { useWidgetValueStore().deleteWidget(id) - }) - } + } - input.pos = undefined - input.widget = undefined - input.widgetId = undefined - input._widget = undefined - this.invalidatePromotedViews() + input.pos = undefined + input.widget = undefined + input.widgetId = undefined + input._widget = undefined + this.invalidatePromotedViews() + }) }, { signal } ) diff --git a/src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts b/src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts index e7ec541f848..5bacce033f8 100644 --- a/src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts +++ b/src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts @@ -2,16 +2,23 @@ import { fromAny } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { + ExportedSubgraphInstance, + INodeInputSlot, ISlotType, LGraphCanvas, Subgraph, TWidgetType } from '@/lib/litegraph/src/litegraph' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import type { WidgetValue } from '@/types/simplifiedWidget' +import { createPromotedMultilineWidget } from '@/renderer/extensions/vueNodes/widgets/utils/multilineTextarea' +import { useDomWidgetStore } from '@/stores/domWidgetStore' import { BaseWidget, + LegacyWidget, LGraphNode, - LiteGraph + LiteGraph, + SubgraphNode } from '@/lib/litegraph/src/litegraph' import { NumberWidget } from '@/lib/litegraph/src/widgets/NumberWidget' import { @@ -385,7 +392,7 @@ describe('SubgraphWidgetPromotion', () => { ) }) - it('should handle disconnection of promoted widget', () => { + it('should handle disconnection of promoted widget', async () => { const subgraph = createTestSubgraph({ inputs: [{ name: 'input', type: 'number' }] }) @@ -399,13 +406,19 @@ describe('SubgraphWidgetPromotion', () => { subgraph.inputNode.slots[0].disconnect() + // Demotion is deferred by a microtask so a same-tick reconnect (a + // rewire) can cancel it instead of dropping the widget for one tick; + // a genuine disconnect like this one still fully demotes once that + // microtask runs. + await Promise.resolve() + expect(subgraphNode.widgets).toHaveLength( promotedInputs(subgraphNode).length ) expect(promotedInputs(subgraphNode)).toHaveLength(0) }) - it('keeps the host widget promoted while another interior widget is still connected', () => { + it('keeps the host widget promoted while another interior widget is still connected', async () => { const subgraph = createTestSubgraph({ inputs: [{ name: 'value', type: 'number' }] }) @@ -449,6 +462,12 @@ describe('SubgraphWidgetPromotion', () => { second.disconnectInput(0, true) + // Demotion is deferred by a microtask (see the rewire-desync + // describe block below); this is a genuine disconnect with nothing + // left to re-resolve to, so it still fully demotes once that + // microtask runs. + await Promise.resolve() + expect(promotedInputs(subgraphNode)).toHaveLength(0) expect(subgraphNode.widgets).toHaveLength(0) }) @@ -1624,3 +1643,196 @@ describe('SubgraphWidgetPromotion', () => { }) }) }) + +// PM-1328 / PM-1253 / PM-1254: wiring a new source into the interior link +// behind one promoted widget (e.g. "prompt") was dropping/visually duplicating +// the *other*, unrelated promoted widgets (e.g. width/height/seed) on the +// same host node. Confirmed mechanism: SubgraphInputNode's +// 'input-disconnected' handler (SubgraphNode.ts) used to demote the widget +// synchronously while deferring the matching `widgetValueStore` cleanup to a +// `queueMicrotask`, leaving `hostNode.widgets.length` and the store's tracked +// id count for that node disagreeing for one tick -- exactly the window the +// Vue widget grid (useProcessedWidgets) reads from two different sources to +// render. The fix defers the demotion itself by a microtask, cancelled by a +// same-tick reconnect, so a rewire never drops the widget at all. +describe('Promoted widget rewire desync (PM-1328 / PM-1253 / PM-1254)', () => { + function makeInteriorNode(title: string, value: WidgetValue = 1) { + const node = new LGraphNode(title) + const input = node.addInput('value', 'number') + node.addOutput('out', 'number') + const widget: LegacyWidget = new LegacyWidget({ + name: 'widget', + type: 'number', + value, + y: 0, + options: {}, + node + }) + node.widgets = [widget] + input.widget = { name: widget.name } + return node + } + + it('keeps every promoted widget present while rewiring the interior link behind one of them', async () => { + const subgraph = createTestSubgraph({ + inputs: [ + { name: 'text', type: 'number' }, + { name: 'seed', type: 'number' }, + { name: 'width', type: 'number' }, + { name: 'height', type: 'number' } + ] + }) + + const textNode = makeInteriorNode('TextNode') + const seedNode = makeInteriorNode('SeedNode') + const widthNode = makeInteriorNode('WidthNode') + const heightNode = makeInteriorNode('HeightNode') + const replacementTextNode = makeInteriorNode('ReplacementTextNode', 2) + subgraph.add(textNode) + subgraph.add(seedNode) + subgraph.add(widthNode) + subgraph.add(heightNode) + subgraph.add(replacementTextNode) + + subgraph.inputNode.slots[0].connect(textNode.inputs[0], textNode) + subgraph.inputNode.slots[1].connect(seedNode.inputs[0], seedNode) + subgraph.inputNode.slots[2].connect(widthNode.inputs[0], widthNode) + subgraph.inputNode.slots[3].connect(heightNode.inputs[0], heightNode) + + const hostNode = createTestSubgraphNode(subgraph) + expect(hostNode.widgets).toHaveLength(4) + + // Rewire the interior link feeding the 'text' promoted widget onto a new + // source node, exactly as a user (or agent) dragging a new node onto + // that widget's socket does: the old link is removed before the new one + // lands. + textNode.disconnectInput(0, true) + + // The other, unrelated promoted widgets (seed/width/height) -- and the + // rewired one itself -- must never disappear mid-rewire. + expect(hostNode.widgets).toHaveLength(4) + + subgraph.inputNode.slots[0].connect( + replacementTextNode.inputs[0], + replacementTextNode + ) + await Promise.resolve() + + expect(hostNode.widgets).toHaveLength(4) + expect(promotedInputs(hostNode)).toHaveLength(4) + }) +}) + +// Speculative lead for PM-1328's duplication (not the confirmed disappear +// mechanism above): a promoted textarea's host widget is a DOMWidgetImpl +// living in useDomWidgetStore, materialized by createPromotedHostWidget +// (see multilineTextarea.ts, wired up the same way the app's real +// SubgraphNode subclass does in litegraphService.ts). Every other promoted +// widget is a plain store projection. The theory: if anything ever resolves +// a store-projected row for an input that already has a DOM host attached, +// the widget grid would render two rows for one input. `_projectPromotedWidget` +// guards this with `if (input._widget) return input._widget`, so this test +// exercises the guard across the real rebuild/rewire/configure sequence +// rather than asserting the guard exists in isolation. +describe('Promoted textarea dual-registration (PM-1328 duplication lead)', () => { + class DomHostSubgraphNode extends SubgraphNode { + protected override createPromotedHostWidget( + input: INodeInputSlot, + id: WidgetId, + sourceWidget: Readonly + ): IBaseWidget | undefined { + return createPromotedMultilineWidget({ + subgraphNode: this, + input, + widgetId: id, + sourceWidget + }) + } + } + + function createSettledDomHostSubgraphNode(subgraph: Subgraph): SubgraphNode { + const rootGraph = subgraph.rootGraph + const instanceData: ExportedSubgraphInstance = { + id: rootGraph.state.lastNodeId + 1, + type: subgraph.id, + pos: [100, 100], + size: [200, 100], + inputs: [], + outputs: [], + properties: {}, + flags: {}, + mode: 0, + order: 0 + } + const node = new DomHostSubgraphNode(rootGraph, subgraph, instanceData) + rootGraph.add(node) + return node + } + + function makeTextareaInteriorNode(title: string, value = 'hello') { + const node = new LGraphNode(title) + const input = node.addInput('value', 'STRING') + const widget = fromAny({ + name: 'widget', + type: 'customtext', + value, + options: {}, + element: document.createElement('textarea') + }) + node.widgets = [widget] + input.widget = { name: widget.name } + return node + } + + function textRowCount(hostNode: SubgraphNode): number { + return hostNode.widgets.filter((widget) => widget.name === 'text').length + } + + function domStoreEntryCount(hostNode: SubgraphNode): number { + return [...useDomWidgetStore().widgetStates.values()].filter( + (state) => state.widget.node === hostNode + ).length + } + + it('keeps exactly one widget row and one DOM registration per input across a rewire', () => { + const subgraph = createTestSubgraph({ + inputs: [{ name: 'text', type: 'STRING' }] + }) + const textNode = makeTextareaInteriorNode('TextNode') + subgraph.add(textNode) + + // Settle the host node in its graph *before* the interior link resolves + // the promoted widget, matching how the real app always adds a + // SubgraphNode before its subgraph's own construction-time links fire. + const hostNode = createSettledDomHostSubgraphNode(subgraph) + subgraph.inputNode.slots[0].connect(textNode.inputs[0], textNode) + + expect(textRowCount(hostNode)).toBe(1) + expect(domStoreEntryCount(hostNode)).toBe(1) + + textNode.disconnectInput(0, true) + expect(textRowCount(hostNode)).toBeLessThanOrEqual(1) + expect(domStoreEntryCount(hostNode)).toBeLessThanOrEqual(1) + + subgraph.inputNode.slots[0].connect(textNode.inputs[0], textNode) + expect(textRowCount(hostNode)).toBe(1) + expect(domStoreEntryCount(hostNode)).toBe(1) + }) + + it('keeps exactly one widget row and one DOM registration per input across a reconfigure', () => { + const subgraph = createTestSubgraph({ + inputs: [{ name: 'text', type: 'STRING' }] + }) + const textNode = makeTextareaInteriorNode('TextNode') + subgraph.add(textNode) + + const hostNode = createSettledDomHostSubgraphNode(subgraph) + subgraph.inputNode.slots[0].connect(textNode.inputs[0], textNode) + expect(textRowCount(hostNode)).toBe(1) + + hostNode.configure(hostNode.serialize()) + + expect(textRowCount(hostNode)).toBe(1) + expect(domStoreEntryCount(hostNode)).toBe(1) + }) +})