diff --git a/browser_tests/tests/groupNode.spec.ts b/browser_tests/tests/groupNode.spec.ts index 8b797839b97..b857db9ae4f 100644 --- a/browser_tests/tests/groupNode.spec.ts +++ b/browser_tests/tests/groupNode.spec.ts @@ -31,10 +31,11 @@ test.describe('Group node migration', { tag: '@node' }, () => { }) // QA found this broken on 2026-09-10 while running the 1.54 test plan: - // converting a v1.3.3 group node misaligns widget values by two positions, so - // denoise receives 'euler' and filename_prefix receives 'normal'. Saving then - // writes the wrong values back, silently corrupting the workflow. Pinned with - // test.fail() so the fix flips this to passing. + // converting a v1.3.3 group node misaligned widget values by two positions, so + // denoise received 'euler' and filename_prefix received 'normal'. Saving then + // wrote the wrong values back, silently corrupting the workflow. Fixed by + // pairing each widget to its originating inner node instead of matching by + // name alone (see findUnconsumedWidgetIndex in groupNode.ts). test('Preserves group node widget values through subgraph conversion', async ({ comfyPage }) => { @@ -51,10 +52,6 @@ test.describe('Group node migration', { tag: '@node' }, () => { ) ) - // Structure first, while a failure here is still unexpected. test.fail() - // below makes everything after it expected to fail, so a conversion that - // stopped producing these nodes at all would otherwise be swallowed by - // the known widget defect. const ksampler = interiorNodes.find((node) => node.type === 'KSampler') expect( ksampler, @@ -66,11 +63,9 @@ test.describe('Group node migration', { tag: '@node' }, () => { 'converted subgraph should contain a SaveImage' ).toBeDefined() - // Below is the known defect. groupNode.ts maps widgets by name through - // findIndex, and this fixture has two CLIPTextEncode nodes both exposing - // `text`, so values land two slots back. filename_prefix is on the wrong - // side of that same shift, which is why it stays below the marker. - test.fail() + // This fixture has two CLIPTextEncode nodes both exposing `text`, which + // used to make groupNode.ts's name-only widget lookup land two slots + // back (see PR #17464 for the pinned defect this now proves is fixed). expect(ksampler!.widgets).toMatchObject({ seed: 156680208700286, steps: 20, diff --git a/src/extensions/core/groupNode.test.ts b/src/extensions/core/groupNode.test.ts index 234514b6e65..889befd8c80 100644 --- a/src/extensions/core/groupNode.test.ts +++ b/src/extensions/core/groupNode.test.ts @@ -1,4 +1,6 @@ import { fromAny, fromPartial } from '@total-typescript/shoehorn' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { t } from '@/i18n' @@ -7,8 +9,12 @@ import type { LGraph } from '@/lib/litegraph/src/litegraph' import { LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' import type { ComfyNode } from '@/platform/workflow/validation/schemas/workflowSchema' import { useMissingNodesErrorStore } from '@/platform/nodeReplacement/missingNodesErrorStore' +import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import { app } from '@/scripts/app' +import { ComfyWidgets } from '@/scripts/widgets' +import { useLitegraphService } from '@/services/litegraphService' import { useNodeDefStore } from '@/stores/nodeDefStore' +import { useWidgetStore } from '@/stores/widgetStore' import type { MissingNodeType } from '@/types/comfy' @@ -16,8 +22,12 @@ import type { GroupNodeLink, GroupNodeWorkflowData } from './groupNode' vi.mock(import('@/scripts/app')) -const { GroupNodeConfig, GroupNodeHandler, replaceLegacySeparators } = - await import('./groupNode') +const { + GroupNodeConfig, + GroupNodeHandler, + findUnconsumedWidgetIndex, + replaceLegacySeparators +} = await import('./groupNode') const groupNodeExtension = vi .mocked(app.registerExtension) .mock.calls.find(([extension]) => extension.name === 'Comfy.GroupNode')?.[0] @@ -113,6 +123,60 @@ describe('GroupNodeConfig.getLinks', () => { }) }) +describe('findUnconsumedWidgetIndex', () => { + it('pairs same-named widgets to distinct originating nodes in request order', () => { + // Two inner nodes (e.g. two CLIPTextEncode nodes both exposing `text`) + // that end up sharing an outer widget name. A plain `findIndex` by name + // would resolve both to the first "text" widget, copying that node's + // value into both inner nodes. + const outerWidgets = [ + { name: 'text' }, + { name: 'text' }, + { name: 'denoise' } + ] + const consumed = new Set() + + const firstMatch = findUnconsumedWidgetIndex(outerWidgets, 'text', consumed) + expect(firstMatch).toBe(0) + consumed.add(firstMatch) + + const secondMatch = findUnconsumedWidgetIndex( + outerWidgets, + 'text', + consumed + ) + expect(secondMatch).toBe(1) + }) + + it('never re-matches an index already recorded as consumed, even for a genuine name collision', () => { + const outerWidgets = [{ name: 'text' }, { name: 'text' }, { name: 'text' }] + const consumed = new Set() + + const indices = [0, 1, 2].map(() => { + const index = findUnconsumedWidgetIndex(outerWidgets, 'text', consumed) + consumed.add(index) + return index + }) + + expect(indices).toEqual([0, 1, 2]) + + // A fourth request has nothing left to consume. + expect(findUnconsumedWidgetIndex(outerWidgets, 'text', consumed)).toBe(-1) + }) + + it('ignores consumed indices and matches by name otherwise', () => { + const outerWidgets = [{ name: 'denoise' }, { name: 'filename_prefix' }] + + expect( + findUnconsumedWidgetIndex(outerWidgets, 'filename_prefix', new Set()) + ).toBe(1) + expect( + findUnconsumedWidgetIndex(outerWidgets, 'denoise', new Set([0])) + ).toBe(-1) + expect(findUnconsumedWidgetIndex(undefined, 'denoise', new Set())).toBe(-1) + }) +}) + describe('GroupNodeConfig.processInputSlots', () => { it('maps exposed inputs by name instead of definition index', () => { const config = new GroupNodeConfig('group', { @@ -136,6 +200,54 @@ describe('GroupNodeConfig.processInputSlots', () => { expect(inputMap).toEqual({ model: 0, latent_image: 1 }) }) + + it('falls back to the positional slot index when the synthesized input name matches no real input name (e.g. Reroute)', () => { + // A Reroute's def is keyed by type (e.g. 'MODEL'), but its real slot is + // unnamed (`addInput('', '*')`), so the name lookup always misses. + const config = new GroupNodeConfig('group', { + nodes: [{ index: 0, type: 'Reroute' }], + links: [], + external: [] + }) + const inputMap: Record = {} + const link: GroupNodeLink = [null, 0, 0, 0, 0, 'MODEL'] + + config.processInputSlots( + { MODEL: ['MODEL', {}] }, + fromPartial({ index: 0, type: 'Reroute', inputs: [{ name: '' }] }), + ['MODEL'], + { 0: link }, + inputMap, + {} + ) + + // Recognized as internally linked via the positional fallback, so it's + // skipped rather than wrongly exposed as an external group input. + expect(inputMap).toEqual({}) + }) +}) + +describe('GroupNodeConfig.processWidgetInputs', () => { + it('keeps a forceInput combo as a slot, never a widget', () => { + const config = new GroupNodeConfig('group', { + nodes: [{ index: 0, type: 'KSampler' }], + links: [], + external: [] + }) + + const { slots, converted } = config.processWidgetInputs( + { + sampler_name: [['euler', 'ddim'], { forceInput: true }], + steps: ['INT', {}] + }, + { index: 0, type: 'KSampler' }, + ['sampler_name', 'steps'], + {} + ) + + expect(slots).toEqual(['sampler_name']) + expect(converted.size).toBe(0) + }) }) describe('GroupNodeConfig.processConvertedWidgets', () => { @@ -150,7 +262,6 @@ describe('GroupNodeConfig.processConvertedWidgets', () => { config.processConvertedWidgets( { seed: ['INT'], steps: ['INT'], cfg: ['FLOAT'] }, { index: 0, type: 'KSampler' }, - [], new Map([ [10, 'cfg'], [2, 'steps'], @@ -163,6 +274,32 @@ describe('GroupNodeConfig.processConvertedWidgets', () => { expect(inputMap).toEqual({ seed: 0, steps: 1, cfg: 2 }) }) + + it('resolves a converted widget link by its own serialized slot index, not its position among converted widgets', () => { + const config = new GroupNodeConfig('group', { + nodes: [{ index: 0, type: 'KSampler' }], + links: [], + external: [] + }) + const inputMap: Record = {} + const link: GroupNodeLink = [null, 0, 0, 0, 0, 'INT'] + + config.processConvertedWidgets( + { b: ['INT'] }, + { index: 0, type: 'KSampler' }, + // The converted widget's real slot index is 5 (the map key), which + // doesn't equal `slots.length + i` for any plausible `slots` this + // node could have had. + new Map([[5, 'b']]), + { 5: link }, + inputMap, + {} + ) + + // Recognized as internally linked by its real slot index, so it's + // skipped rather than wrongly exposed as an external group input. + expect(inputMap).toEqual({}) + }) }) describe('GroupNodeConfig.registerFromWorkflow', () => { @@ -473,3 +610,200 @@ describe('group node extension beforeConfigureGraph', () => { } }) }) + +describe('GroupNodeHandler.convertToNodes', () => { + function nodeDef( + def: Partial & { name: string } + ): ComfyNodeDef { + return fromPartial({ + display_name: def.name, + category: 'testing', + python_module: 'nodes', + description: '', + output: [], + output_name: [], + output_node: false, + input: { required: {} }, + ...def + }) + } + + // Real ComfyUI node defs for the inner nodes of + // browser_tests/assets/groupnodes/group_node_v1.3.3.json, trimmed to the + // inputs that matter for widget/slot classification. + const REAL_NODE_DEFS: Record = { + EmptyLatentImage: nodeDef({ + name: 'EmptyLatentImage', + input: { + required: { + width: ['INT', { default: 512 }], + height: ['INT', { default: 512 }], + batch_size: ['INT', { default: 1 }] + } + }, + output: ['LATENT'], + output_name: ['LATENT'] + }), + CheckpointLoaderSimple: nodeDef({ + name: 'CheckpointLoaderSimple', + input: { required: { ckpt_name: [['v1-5-pruned-emaonly.ckpt'], {}] } }, + output: ['MODEL', 'CLIP', 'VAE'], + output_name: ['MODEL', 'CLIP', 'VAE'] + }), + CLIPTextEncode: nodeDef({ + name: 'CLIPTextEncode', + input: { + required: { + text: ['STRING', { multiline: true }], + clip: ['CLIP', {}] + } + }, + output: ['CONDITIONING'], + output_name: ['CONDITIONING'] + }), + KSampler: nodeDef({ + name: 'KSampler', + input: { + required: { + model: ['MODEL', {}], + seed: ['INT', { default: 0 }], + steps: ['INT', { default: 20 }], + cfg: ['FLOAT', { default: 8.0 }], + sampler_name: [['euler', 'euler_ancestral', 'dpmpp_2m'], {}], + scheduler: [['normal', 'karras'], {}], + positive: ['CONDITIONING', {}], + negative: ['CONDITIONING', {}], + latent_image: ['LATENT', {}], + denoise: ['FLOAT', { default: 1.0 }] + } + }, + output: ['LATENT'], + output_name: ['LATENT'] + }), + VAEDecode: nodeDef({ + name: 'VAEDecode', + input: { + required: { samples: ['LATENT', {}], vae: ['VAE', {}] } + }, + output: ['IMAGE'], + output_name: ['IMAGE'] + }), + SaveImage: nodeDef({ + name: 'SaveImage', + input: { + required: { + images: ['IMAGE', {}], + filename_prefix: ['STRING', { default: 'ComfyUI' }] + } + } + }) + } + + async function registerRealNodeDefs() { + useWidgetStore().registerCustomWidgets(ComfyWidgets) + vi.mocked(app.registerNodeDef).mockImplementation(async (id, def) => { + await useLitegraphService().registerNodeDef(id, def) + }) + await groupNodeExtension!.addCustomNodeDefs?.(REAL_NODE_DEFS, app) + for (const [name, def] of Object.entries(REAL_NODE_DEFS)) { + await useLitegraphService().registerNodeDef(name, def) + } + } + + // QA found this broken on 2026-09-10 while running the 1.54 test plan (see + // the e2e regression test in browser_tests/tests/groupNode.spec.ts): a + // KSampler's combo widgets (sampler_name, scheduler) were misclassified as + // plain input slots, which then shifted every widget value after them by + // two positions on conversion, so denoise received sampler_name's value + // ('euler') and filename_prefix received scheduler's ('normal'). + it('preserves KSampler widget values through the real v1.3.3 fixture', async () => { + await registerRealNodeDefs() + + const fixture = JSON.parse( + readFileSync( + join( + process.cwd(), + 'browser_tests', + 'assets', + 'groupnodes', + 'group_node_v1.3.3.json' + ), + 'utf-8' + ) + ) + const groupNodeData: GroupNodeWorkflowData = + fixture.extra.groupNodes.group_node + + const config = new GroupNodeConfig('group_node', groupNodeData) + await config.registerType() + + // The app mock stubs out selectItems/selectNodes; make it behave like + // the real LGraphCanvas so deserialiseAndCreate's selection is visible + // to convertToNodes via app.canvas.selected_nodes. + Object.assign(app.canvas, { + selectNodes(nodes: { id: number | string }[]) { + app.canvas.selected_nodes = {} + for (const n of nodes) { + vi.mocked(app.canvas).selected_nodes[n.id] = fromAny(n) + } + } + }) + + const outerNodeInfo = fixture.nodes[0] + const outerNode = LiteGraph.createNode(outerNodeInfo.type) + if (!outerNode) throw new Error('Failed to create outer group node') + outerNode.configure(outerNodeInfo) + app.rootGraph.add(outerNode) + + // Every asserted value in this fixture (steps, cfg, sampler_name, + // scheduler, denoise, filename_prefix) happens to equal that widget's + // own node-def default, so the test can't tell a real copy from the + // value simply being left untouched. Overwrite the *live* outer widget + // values - as if the user had edited them on canvas after the group + // was created - to values that differ from both the node-def defaults + // and the fixture's original recorded values, so only a real copy can + // produce a match. + const setOuterWidget = (name: string, value: string | number) => { + const widget = outerNode.widgets?.find((w) => w.name === name) + if (!widget) throw new Error(`Outer widget '${name}' not found`) + widget.value = value + } + setOuterWidget('steps', 999) + setOuterWidget('cfg', 4.5) + setOuterWidget('text', 'edited_positive_prompt') + setOuterWidget('CLIPTextEncode text', 'edited_negative_prompt') + setOuterWidget('sampler_name', 'dpmpp_2m') + setOuterWidget('scheduler', 'karras') + setOuterWidget('denoise', 0.42) + setOuterWidget('filename_prefix', 'edited_prefix') + + const handler = GroupNodeHandler.getHandler(outerNode) + if (!handler) throw new Error('No GroupNodeHandler for outer node') + + const innerNodes = handler.convertToNodes() + const widgetValues = (node: (typeof innerNodes)[number] | undefined) => + Object.fromEntries((node?.widgets ?? []).map((w) => [w.name, w.value])) + + const ksampler = innerNodes.find((n) => n.comfyClass === 'KSampler') + const saveImage = innerNodes.find((n) => n.comfyClass === 'SaveImage') + + expect(innerNodes[2]?.widgets?.find((w) => w.name === 'text')?.value).toBe( + 'edited_positive_prompt' + ) + expect(innerNodes[3]?.widgets?.find((w) => w.name === 'text')?.value).toBe( + 'edited_negative_prompt' + ) + + expect(widgetValues(ksampler)).toMatchObject({ + seed: 156680208700286, + steps: 999, + cfg: 4.5, + sampler_name: 'dpmpp_2m', + scheduler: 'karras', + denoise: 0.42 + }) + expect(widgetValues(saveImage)).toMatchObject({ + filename_prefix: 'edited_prefix' + }) + }) +}) diff --git a/src/extensions/core/groupNode.ts b/src/extensions/core/groupNode.ts index 89fd86ac513..d0247e942d2 100644 --- a/src/extensions/core/groupNode.ts +++ b/src/extensions/core/groupNode.ts @@ -410,12 +410,29 @@ export class GroupNodeConfig { ] = {}) for (const inputName of inputNames) { const inputSpec = inputs[inputName] + // The type is either a string (e.g. 'INT') or, for a combo widget, an + // array of options (e.g. [['euler', 'ddim']]) — both are valid V1 + // input specs. Rejecting the array form here misclassified every combo + // widget as a plain input slot. const isValidSpec = Array.isArray(inputSpec) && inputSpec.length >= 1 && - typeof inputSpec[0] === 'string' + (typeof inputSpec[0] === 'string' || Array.isArray(inputSpec[0])) + // A `forceInput` spec is always a socket, even for a type (e.g. a + // combo) that would otherwise materialize as a widget — matches the + // rule `litegraphService.addInputSocket`/`addInputWidget` apply when + // actually building the node. + const specOptions = + Array.isArray(inputSpec) && + typeof inputSpec[1] === 'object' && + inputSpec[1] !== null + ? inputSpec[1] + : {} + const isForcedInput = + 'forceInput' in specOptions && specOptions.forceInput === true if ( isValidSpec && + !isForcedInput && useWidgetStore().inputIsWidget(inputSpec as InputSpec) ) { const convertedIndex = @@ -518,7 +535,21 @@ export class GroupNodeConfig { const nodeInputs: Record = (this.nodeInputs[nodeIdx] = {}) for (let i = 0; i < slots.length; i++) { const inputName = slots[i] - const link = linksTo[i] + // `linksTo` is keyed by this inner node's own original input-slot + // index, which rarely lines up with `i` (this input's position within + // the *filtered* `slots` list). Look the real slot index up by name so + // an internally-linked input isn't matched against a different slot's + // link (or missed/misread entirely) and either wrongly hidden or + // wrongly exposed on the group node. A synthesized def can key its + // input by type rather than by slot name (e.g. Reroute, whose actual + // slot name is always ''), so fall back to the old positional index + // when the name lookup misses. + const namedSlotIndex = node.inputs?.findIndex( + (inp) => inp.name === inputName + ) + const slotIndex = + namedSlotIndex != null && namedSlotIndex >= 0 ? namedSlotIndex : i + const link = linksTo[slotIndex] if (link) { this.checkPrimitiveConnection(link, inputName, inputs) // This input is linked so we can skip it @@ -546,20 +577,21 @@ export class GroupNodeConfig { processConvertedWidgets( inputs: Record, node: GroupNodeData, - slots: string[], converted: Map, linksTo: SlotLinks, inputMap: Record, seenInputs: Record ) { - // Add converted widgets sorted into their index order (ordered as they were converted) so link ids match up - const convertedSlots = [...converted.keys()] - .sort((a, b) => a - b) - .map((k) => converted.get(k)) - for (let i = 0; i < convertedSlots.length; i++) { - const inputName = convertedSlots[i] + // Process converted widgets sorted into their index order (ordered as + // they were converted) so link ids match up. `converted`'s keys are + // this node's real serialized input-slot indices (set by the + // `findIndex` in processWidgetInputs), so use that key - not this + // widget's position among converted widgets - to look its link up in + // `linksTo`, which is also keyed by real slot index. + const convertedEntries = [...converted.entries()].sort(([a], [b]) => a - b) + for (const [slotIndex, inputName] of convertedEntries) { if (!inputName) continue - const link = linksTo[slots.length + i] + const link = linksTo[slotIndex] if (link) { this.checkPrimitiveConnection( link, @@ -628,7 +660,6 @@ export class GroupNodeConfig { this.processConvertedWidgets( inputs, node, - slots, converted, linksTo, inputMap, @@ -782,6 +813,35 @@ export class GroupNodeConfig { } } +/** + * Finds the outer widget matching `name`, skipping any index already in + * `consumed`. + * + * Widget names inside a synthesized group-node type are meant to be unique + * (see {@link GroupNodeConfig.getInputConfig}'s de-duplication), so pairing + * by name alone is normally safe. But it is not *guaranteed* unique across + * every inner node/widget combination, and a plain `Array.findIndex` always + * resolves a shared name to the *first* matching widget — silently copying + * that node's value into every other inner node exposing a widget with the + * same final name. Consuming each match exactly once, in the same + * node-by-node order the inner nodes are unpacked, keeps every widget paired + * with the widget belonging to its own originating node even when two + * inner nodes end up sharing an outer widget name (e.g. two `CLIPTextEncode` + * nodes both exposing `text`). + */ +export function findUnconsumedWidgetIndex( + widgets: { name?: string }[] | undefined, + name: string, + consumed: Set +): number { + if (!widgets) return -1 + for (let i = 0; i < widgets.length; i++) { + if (consumed.has(i)) continue + if (widgets[i]?.name === name) return i + } + return -1 +} + /** * Migration-only adapter for deprecated group nodes. * @@ -828,6 +888,10 @@ export class GroupNodeHandler { // matches nodeData.nodes order. const selectedIds = Object.keys(app.canvas.selected_nodes) const newNodes: LGraphNode[] = [] + // Shared across every inner node processed below, in nodeData.nodes + // order, so a widget already paired to one inner node's value can + // never be matched again for another (see findUnconsumedWidgetIndex). + const consumedOuterWidgetIndices = new Set() for (let i = 0; i < selectedIds.length; i++) { const selectedId = parseNodeId(selectedIds[i]) const newNode = selectedId @@ -848,21 +912,30 @@ export class GroupNodeHandler { const newName = map[oldName] if (!newName) continue - const widgetIndex = - node.widgets?.findIndex((w) => w.name === newName) ?? -1 + const widgetIndex = findUnconsumedWidgetIndex( + node.widgets, + newName, + consumedOuterWidgetIndices + ) if (widgetIndex === -1) continue - // Populate the main and any linked widgets + // An index is only marked consumed once its value is actually + // copied, so a bail below (a missing inner widget, or fewer outer + // widgets than this PrimitiveNode has) can't permanently burn an + // index another inner node legitimately needs. if (innerNodeData.type === 'PrimitiveNode') { for (let j = 0; j < newNode.widgets.length; j++) { const srcWidget = node.widgets?.[widgetIndex + j] - if (srcWidget) newNode.widgets[j].value = srcWidget.value + if (!srcWidget) continue + consumedOuterWidgetIndices.add(widgetIndex + j) + newNode.widgets[j].value = srcWidget.value } } else { const outerWidget = node.widgets?.[widgetIndex] const newWidget = newNode.widgets.find((w) => w.name === oldName) if (!newWidget || !outerWidget) continue + consumedOuterWidgetIndices.add(widgetIndex) newWidget.value = outerWidget.value const linkedWidgets = outerWidget.linkedWidgets ?? [] for (let w = 0; w < linkedWidgets.length; w++) {