From 8453d95155f6d44092fb095980d6eafa1fcf171e Mon Sep 17 00:00:00 2001 From: "claude[bot]" <209825114+claude[bot]@users.noreply.github.com> Date: Wed, 30 Sep 2026 21:56:10 -0700 Subject: [PATCH] fix: keep promoted subgraph widgets present across a rewire (#18074) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _Requested by **Jo Zhang, Christian Byrne** · [Slack thread](https://comfy-organization.slack.com/archives/C0BGH348Z0C/p1789707519592879?thread_ts=1789707519.592879&cid=C0BGH348Z0C)_ A subgraph node shows several "promoted" widgets from the nodes hidden inside it (like width, height, seed). When you rewire the connection behind just one of those widgets, the others could flicker, duplicate, or vanish for a moment, and the wired-in widget itself could disappear. This PR fixes that and adds tests at both levels: unit tests prove the mechanism, and the browser-level repro tests — which this PR's own CI confirmed now pass with the fix — are kept as plain regression tests. - Fixes #14495 This started as a REPRO-ONLY PR for a reported bug: wiring a new node into a subgraph's promoted "prompt" widget makes the subgraph's *other* promoted widgets render duplicated, and a closely related report has the rewired widget itself disappear with redo misplacing the wire. Investigation traced a confirmed mechanism for the disappearing half at the data-model layer (see Summary). Once that mechanism was nailed down precisely enough to fix without guessing, and a second, more contained duplication theory was checked and refuted, it became worth landing the fix and the validating tests in the same PR rather than leaving a fully-diagnosed, small, well-scoped bug unfixed. - **Authored by:** interactive session, Claude Code - **Verified:** `pnpm exec vitest run src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts` — 51 passed, 0 failed (was 50 passed / 1 expected fail before the fix; that case now passes for real and was flipped from `it.fails` to `it`). `pnpm exec vitest run src/lib/litegraph/src/subgraph/ src/renderer/extensions/vueNodes/widgets/utils/multilineTextarea.promoted.test.ts src/stores/widgetValueStore.test.ts src/stores/domWidgetStore.test.ts` — 413 passed, 0 failed. `pnpm typecheck`, `pnpm lint`, `pnpm knip` — clean. E2E confirmation came from this PR's own CI (see Summary). Re-verified after the 2026-10-01 rebase onto main: same scoped suites green, typecheck/lint/knip clean. - **Deviations:** none remaining. The previous push deliberately left the e2e `test.fail()` cases unflipped pending CI evidence; that evidence has now arrived (see "E2E confirmation" below) and they are flipped to plain `test()` in this push, exactly per the plan recorded in the earlier Test plan. - **Type:** fix + test — a small, contained timing fix plus the tests that prove it, validate/refute an alternate duplication theory, and lock in the browser-level symptom as regression coverage - **Slots into:** a subgraph promoted-widget-promotion bug investigation; no project or epic, ad-hoc follow-up to that investigation - **Not in scope:** `createPromotedMultilineWidget`'s visibility/suppression path — that's PR #18085's territory (a sibling investigation into the same widget family) Rewiring the interior link behind a promoted widget (e.g. dragging a new node onto an already-promoted widget's socket) removes the old link before the new one lands. `SubgraphInputNode`'s `'input-disconnected'` handler used to demote the widget **synchronously** — clearing `input.widgetId`/`.widget`/`._widget` immediately — while deferring the matching `widgetValueStore` cleanup to a `queueMicrotask`. For one tick, `hostNode.widgets.length` (synchronous) and the store's tracked id count for that node (deferred) disagreed. The Vue widget grid (`useProcessedWidgets`/`computeProcessedWidgets`) reads its render *order* from the store and its liveness *filter* from `hostNode.widgets` — i.e. from both sides of that exact disagreement. The fix defers the demotion itself by a microtask (mirroring the already-deferred store cleanup), tracked with a per-input cancellation token. The `'input-connected'` listener clears that token on a same-tick reconnect, so a rewire never drops the widget from `hostNode.widgets` at all. A genuine disconnect with no reconnect still fully demotes once the microtask runs — nothing about final-state behavior changes, only the timing of an in-between state that used to be observable. **Deliberate timing-change note** (per this repo's own ecosystem-impact rule for changes touching `node.widgets` access): this changes when a disconnect becomes observable on `hostNode.widgets` — previously synchronous, now one microtask tick later for a genuine disconnect. Two existing tests in `SubgraphWidgetPromotion.test.ts` asserted this synchronously with no `await`; both were updated to `await Promise.resolve()` after the disconnecting call, with a comment explaining why. No public API shape or callback signature changed — only internal timing. - `SubgraphWidgetPromotion.test.ts`, "keeps every promoted widget present while rewiring the interior link behind one of them" (previously `it.fails`, now a plain `it`): builds a host with 4 promoted widgets from 4 different interior nodes, rewires the link behind one of them onto a *new* interior node mid-test, and asserts `hostNode.widgets.length` stays at 4 throughout — including immediately after the disconnect step, before the reconnect lands. - `SubgraphWidgetPromotion.test.ts`, "Promoted textarea dual-registration (PM-1328 duplication lead)": tests a second, independently-raised theory for the duplication symptom — that a promoted textarea's DOM-hosted widget (a `DOMWidgetImpl` living in `useDomWidgetStore`, materialized by `createPromotedHostWidget`) and a store-projected row could both end up registered for the same input, which would duplicate a row in the widget grid. Built a minimal `SubgraphNode` subclass wired the same way the app's real subclass is, exercised it across a rewire and a `configure()` reconfigure. **Both pass as-is — the theory is refuted.** `_projectPromotedWidget`'s `if (input._widget) return input._widget` guard is unconditional across every call site and there's no observable window where `input.widgetId` is set while `input._widget` isn't. Kept as regression coverage. [35419314544](https://github.com/Comfy-Org/ComfyUI_frontend/actions/runs/35419314544)) CI on the previous head answered the open question the `test.fail()` repros were posted to ask — the fix **does** resolve the browser-level symptom end-to-end: - Both `subgraphPromotedWidgetRewireDuplication.spec.ts` repro scenarios (interior rewire and external boundary wire) were reported "Expected to fail, but passed" on every run and retry (video job + shard 12, 4/4 retries). Flipped to plain `test()` regression tests, and retitled to describe the behavior they now guarantee. - `subgraphPromotion.spec.ts` "Promoted STRING widget edit survives a rebind of the interior link" — a *pre-existing* `test.fail()` for #14495 — also passed on all 4 shard-12 attempts. Flipped to plain `test()`; hence "Fixes #14495" above. - The external-boundary undo test went through two CI-informed revisions after the rebase: which snapshot undo targets depends on change-tracker capture timing the test cannot control (captures fire on window mouseup, before the click handlers that apply promotions, so the entry pushed by the slot drop — #18117 — can lag the built baseline by one action), and an attempt to pin the snapshot with an extra canvas click timed out in CI. The test now asserts the invariant both reported symptoms violate instead of a fixed widget set: whatever state undo restores, the host's model holds no duplicate widgets and the grid renders exactly one row per model widget, none otherwise. - [x] Watch this PR's `playwright-video-new-tests` CI check: the `test.fail()` cases were reported as unexpectedly passed (run 35419314544) - [x] Flip those cases (and the pre-existing #14495 one) to plain `test()` - [x] Make the external-boundary undo test deterministic (it now asserts render/model consistency after undo instead of assuming which snapshot undo targets) - [ ] CI green on the rebased head (the "Check for AI agent co-author trailers" check was removed from main in #19393; the first commit still carries trailers, and rewording it remains a maintainer call since it rewrites shared history) 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01U6aDANuoAYDtxd9WiCk44Q --------- (cherry picked from commit 9ee67cb17b0780eb611ae359e1659a38a8ed984d) ## Backport adaptation (core/1.54) The fix itself (`SubgraphNode.ts`, `interfaces.ts`) cherry-picked clean and is byte-identical to upstream. Only two test files conflicted, both because the cherry-pick's context included neighbouring code that is not on this branch: - `useErrorClearingHooks.test.ts` — the conflict hunk also carried an unrelated test, "retires an absorbed promoted media error when its host is deleted", which main gained from a different, unbackported PR. Dropped that test and applied only this PR's change to the test that does exist here: make "keeps promoted missing media until the last fanout consumer is deleted" async and await the deferred demotion. - `SubgraphWidgetPromotion.test.ts` — import-only conflict. Accepted the three new imports (`WidgetValue`, `createPromotedMultilineWidget`, `useDomWidgetStore`) required by the new PM-1328 describe block; verified all three modules and symbols exist on this branch. The new block also uses `LegacyWidget`, which main imports from the litegraph barrel in a neighbouring non-conflicting import hunk, so this branch's version of that hunk won and left it out; the test failed with `ReferenceError: LegacyWidget is not defined` until it was added to the barrel import. `LegacyWidget` already exists and is exported from the barrel on this branch. No backport-only compatibility shim was needed and no public API shape or callback signature changed. The deliberate timing change this PR documents (a genuine disconnect becomes observable on `hostNode.widgets` one microtask later) is carried as-is. --- ...aphPromotedWidgetRewireDuplication.spec.ts | 229 ++++++++++++++++++ .../tests/subgraph/subgraphPromotion.spec.ts | 1 - .../graph/useErrorClearingHooks.test.ts | 13 +- .../graph/subgraph/promotionUtils.test.ts | 6 +- src/lib/litegraph/src/interfaces.ts | 7 + .../litegraph/src/subgraph/SubgraphNode.ts | 41 +++- .../subgraph/SubgraphWidgetPromotion.test.ts | 218 ++++++++++++++++- 7 files changed, 496 insertions(+), 19 deletions(-) create mode 100644 browser_tests/tests/subgraph/subgraphPromotedWidgetRewireDuplication.spec.ts 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) + }) +})