Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions src/core/graph/widgets/dynamicGroupWidget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { useNodeDefStore } from '@/stores/nodeDefStore'
import type { ComfyNodeDef } from '@/schemas/nodeDefSchema'
import { graphToPrompt } from '@/utils/executionUtil'
import { isWidgetVisibleOnSurface } from '@/types/widgetVisibility'
import { renameWidget } from '@/utils/widgetUtil'

function setup(min = 0, max = 3) {
const graph = new LGraph()
Expand Down Expand Up @@ -354,6 +355,123 @@ describe('DynamicGroup widgets', () => {
}
)

function setupTwiceDeepPromotion() {
const { node, graph, widget } = setup()
graph.remove(node)
const outerSubgraph = createTestSubgraph({ rootGraph: graph })
const outerHost = createTestSubgraphNode(outerSubgraph)
graph.add(outerHost)
const innerSubgraph = createTestSubgraph({ rootGraph: graph })
const innerHost = createTestSubgraphNode(innerSubgraph, {
parentGraph: outerSubgraph
})
outerSubgraph.add(innerHost)
innerSubgraph.add(node)
widget('loras').value = 2
const strength = widget('loras.1.strength')
expect(
promoteValueWidgetViaSubgraphInput(innerHost, node, strength).ok
).toBe(true)
const innerPromoted = promotedInputWidget(innerHost.inputs[0])
if (!innerPromoted) throw new Error('Inner promotion failed')
expect(
promoteValueWidgetViaSubgraphInput(outerHost, innerHost, innerPromoted).ok
).toBe(true)
const outerInput = outerHost.inputs[0]
expect(promotedInputWidget(outerInput)?.label).toBe('LoRA #2 strength')
return { widget, innerHost, outerHost, outerSubgraph, outerInput }
}

it.for([
{ label: 'LoRA #2 strength', expected: 'LoRA #1 strength' },
{ label: 'My strength', expected: 'My strength' }
])(
'shows $expected through two boundaries after removing a row before the promoted field $label',
({ label, expected }) => {
const { widget, outerSubgraph, outerInput } = setupTwiceDeepPromotion()
outerSubgraph.renameInput(outerSubgraph.inputs[0], label)

widget('loras.0').callback?.(undefined)

expect(promotedInputWidget(outerInput)?.label).toBe(expected)
}
)

it.for([
{
name: 'generated labels',
innerLabel: 'LoRA #2 strength',
outerLabel: 'LoRA #2 strength',
expectedInner: 'LoRA #1 strength',
expectedOuter: 'LoRA #1 strength'
},
{
name: 'per-instance custom labels',
innerLabel: 'Inner strength',
outerLabel: 'Outer strength',
expectedInner: 'Inner strength',
expectedOuter: 'Outer strength'
}
])(
'preserves $name across multiple instances when rows are renumbered',
({ innerLabel, outerLabel, expectedInner, expectedOuter }) => {
const { widget, innerHost, outerHost, outerInput } =
setupTwiceDeepPromotion()
const rootGraph = innerHost.subgraph.rootGraph
const otherOuterSubgraph = createTestSubgraph({ rootGraph })
const otherOuterHost = createTestSubgraphNode(otherOuterSubgraph)
rootGraph.add(otherOuterHost)
const otherInnerHost = createTestSubgraphNode(innerHost.subgraph, {
parentGraph: otherOuterSubgraph
})
otherOuterSubgraph.add(otherInnerHost)
const otherInnerPromoted = promotedInputWidget(otherInnerHost.inputs[0])
assert.exists(otherInnerPromoted)
expect(
promoteValueWidgetViaSubgraphInput(
otherOuterHost,
otherInnerHost,
otherInnerPromoted
).ok
).toBe(true)
const otherOuterInput = otherOuterHost.inputs[0]
expect(promotedInputWidget(otherOuterInput)?.label).toBe(
'LoRA #2 strength'
)
const innerPromoted = promotedInputWidget(innerHost.inputs[0])
const outerPromoted = promotedInputWidget(outerInput)
assert.exists(innerPromoted)
assert.exists(outerPromoted)
renameWidget(innerPromoted, innerHost, innerLabel)
renameWidget(outerPromoted, outerHost, outerLabel)

widget('loras.0').callback?.(undefined)

expect(
[
innerHost.inputs[0],
otherInnerHost.inputs[0],
outerInput,
otherOuterInput
].map((input) => promotedInputWidget(input)?.label)
).toEqual([
expectedInner,
'LoRA #1 strength',
expectedOuter,
'LoRA #1 strength'
])
}
)

it('removes a field promoted through two boundaries when its row is removed', async () => {
const { widget, innerHost, outerInput } = setupTwiceDeepPromotion()

widget('loras.1').callback?.(undefined)

expect(innerHost.inputs[0].link).toBeNull()
await vi.waitFor(() => expect(promotedInputWidget(outerInput)).toBeNull())
})

it.for([
{ label: 'LoRA #2 strength', expected: 'LoRA 1행 strength' },
{ label: 'My strength', expected: 'My strength' }
Expand Down
115 changes: 88 additions & 27 deletions src/core/graph/widgets/dynamicGroupWidget.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { t } from '@/i18n'
import { SUBGRAPH_INPUT_ID } from '@/lib/litegraph/src/constants'
import type { LGraph, Subgraph } from '@/lib/litegraph/src/LGraph'
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
import type { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode'
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
import { VueOnlyWidget } from '@/lib/litegraph/src/widgets/VueOnlyWidget'
import {
captureInputLayout,
inputLink,
replaceNodeInputs
} from '@/lib/litegraph/src/node/slotLinks'
import {
Expand All @@ -18,6 +21,7 @@ import { useLitegraphService } from '@/services/litegraphService'
import { useNodeDefStore } from '@/stores/nodeDefStore'
import { useWidgetValueStore } from '@/stores/widgetValueStore'
import { deriveWidgetSurfaces } from '@/types/widgetVisibility'
import { mapUniqueNodes } from '@/utils/graphTraversalUtil'
import { isSubgraph } from '@/utils/typeGuardUtil'

export function dynamicGroupWidget(
Expand Down Expand Up @@ -120,14 +124,14 @@ export function dynamicGroupWidget(
}
}

function removeRow(index: number) {
function removeRow(index: number, hosts = createPromotionHostLookup()) {
if (!node.widgets) return false
const prefix = `${inputName}.${index}`
const removed = node.widgets.filter(
(widget) => widget.name === prefix || widget.name.startsWith(`${prefix}.`)
)
if (!removed.length) return false
if (!removeRowInputs(prefix)) return false
if (!removeRowInputs(prefix, hosts)) return false
for (const widget of removed.reverse()) {
if (node.widgets.includes(widget)) node.removeWidget(widget)
}
Expand All @@ -136,16 +140,22 @@ export function dynamicGroupWidget(
const row = Number(oldPrefix.slice(inputName.length + 1))
if (row <= index) continue
const newPrefix = `${inputName}.${row - 1}`
renameRow(oldPrefix, newPrefix)
renameRow(oldPrefix, newPrefix, hosts)
}
return true
}

function removeRowInputs(prefix: string) {
function removeRowInputs(prefix: string, hosts: PromotionHostLookup) {
const previous = captureInputLayout(node)
const inputs = previous.inputs.filter(
(input) => !input.name.startsWith(`${prefix}.`)
)
const promotedSlots = previous.inputs.flatMap((input) => {
const link = previous.links.get(input)
return !inputs.includes(input) && link?.origin_id === SUBGRAPH_INPUT_ID
? [link.origin_slot]
: []
})
const result = replaceNodeInputs(
node,
previous,
Expand All @@ -163,6 +173,8 @@ export function dynamicGroupWidget(
previous.inputs.forEach((input, slot) => {
if (!inputs.includes(input)) node.onInputRemoved?.(slot, input)
})
for (const slot of promotedSlots)
disconnectOrphanedPromotion(node.graph, slot, hosts)
return true
}

Expand All @@ -174,22 +186,10 @@ export function dynamicGroupWidget(
return `${row} ${fields[field][1]?.display_name ?? field}`
}

function renamePromotedInputLabel(
slot: number,
previous: string,
next: string
) {
const graph = node.graph
if (!graph || !isSubgraph(graph)) return
const link = node.getInputLink(slot)
if (link?.origin_id !== SUBGRAPH_INPUT_ID) return
const promoted = graph.inputs[link.origin_slot]
if (promoted.label === previous) graph.renameInput(promoted, next)
}

function renameRowLabels(
oldIndex: number,
newIndex: number,
hosts: PromotionHostLookup,
rowLabel?: string
) {
for (const field of Object.keys(fields)) {
Expand All @@ -204,11 +204,15 @@ export function dynamicGroupWidget(
if (!input) continue
if (input.label === previous) input.label = next
input.localized_name = next
renamePromotedInputLabel(slot, previous, next)
renamePromotedInputLabel(node, slot, previous, next, hosts)
}
}

function renameRow(oldPrefix: string, newPrefix: string) {
function renameRow(
oldPrefix: string,
newPrefix: string,
hosts: PromotionHostLookup
) {
const rowLabel = rows().find((row) => row.name === oldPrefix)?.label
for (const widget of node.widgets ?? []) {
if (widget.name === oldPrefix || widget.name.startsWith(`${oldPrefix}.`))
Expand All @@ -222,11 +226,12 @@ export function dynamicGroupWidget(
renameRowLabels(
Number(oldPrefix.slice(inputName.length + 1)),
Number(newPrefix.slice(inputName.length + 1)),
hosts,
rowLabel
)
}

function addRow(index: number) {
function addRow(index: number, hosts: PromotionHostLookup) {
const previousSize: [number, number] = [...node.size]
const start = node.widgets?.length ?? 0
const previous = captureInputLayout(node)
Expand All @@ -249,7 +254,7 @@ export function dynamicGroupWidget(
})
}
})
addRowFields(index)
addRowFields(index, hosts)
const addedInputs = node.inputs.splice(previous.inputs.length)
const inputs = [
...previous.inputs,
Expand Down Expand Up @@ -277,18 +282,22 @@ export function dynamicGroupWidget(
return true
}

function updateInputLabel(name: string, label: string) {
function updateInputLabel(
name: string,
label: string,
hosts: PromotionHostLookup
) {
const slot = node.findInputSlot(name)
if (slot === -1) return
const input = node.inputs[slot]
const previous = input.localized_name
if (!input.label || input.label === previous) input.label = label
input.localized_name = label
if (previous) renamePromotedInputLabel(slot, previous, label)
if (previous) renamePromotedInputLabel(node, slot, previous, label, hosts)
return input
}

function addRowFields(index: number) {
function addRowFields(index: number, hosts: PromotionHostLookup) {
for (const [fields, isOptional] of [
[template.required, false],
[template.optional, true]
Expand All @@ -302,7 +311,7 @@ export function dynamicGroupWidget(
transformInputSpecV1ToV2(spec, { name, isOptional })),
display_name: fieldLabel(index, field)
})
const input = updateInputLabel(name, fieldLabel(index, field))
const input = updateInputLabel(name, fieldLabel(index, field), hosts)
let auxiliaryIndex = 0
node.widgets?.slice(fieldStart).forEach((widget) => {
const options = widget.options
Expand Down Expand Up @@ -350,11 +359,12 @@ export function dynamicGroupWidget(
const requested = Math.max(0, Math.trunc(value))
validateSavedRowCount(value, requested)
const count = Math.max(min, requested)
const hosts = createPromotionHostLookup()
for (let index = rows().length - 1; index >= count; index--) {
if (!removeRow(index)) break
if (!removeRow(index, hosts)) break
}
while (rows().length < count) {
if (!addRow(rows().length)) break
if (!addRow(rows().length, hosts)) break
}
publish()
}
Expand All @@ -363,6 +373,57 @@ export function dynamicGroupWidget(
return { widget: controller }
}

type PromotionHostLookup = (subgraph: Subgraph) => SubgraphNode[]

function createPromotionHostLookup(): PromotionHostLookup {
let hosts: Map<Subgraph, SubgraphNode[]> | undefined
return (subgraph) => {
if (!hosts) {
hosts = new Map()
for (const host of mapUniqueNodes(subgraph.rootGraph, (node) =>
node.isSubgraphNode() ? node : undefined
)) {
const instances = hosts.get(host.subgraph) ?? []
instances.push(host)
hosts.set(host.subgraph, instances)
}
}
return hosts.get(subgraph) ?? []
}
}

function renamePromotedInputLabel(
node: LGraphNode,
slot: number,
previous: string,
next: string,
hosts: PromotionHostLookup
) {
const graph = node.graph
if (!isSubgraph(graph)) return
const link = inputLink(graph, node.id, slot)
if (link?.origin_id !== SUBGRAPH_INPUT_ID) return
const promoted = graph.inputs[link.origin_slot]
if (promoted.label !== previous) return
graph.renameInput(promoted, next)
for (const host of hosts(graph))
renamePromotedInputLabel(host, link.origin_slot, previous, next, hosts)
}

function disconnectOrphanedPromotion(
graph: LGraph | Subgraph | null,
slot: number,
hosts: PromotionHostLookup
) {
if (!isSubgraph(graph) || graph.inputs[slot]?.linkIds.length) return
for (const host of hosts(graph)) {
const link = host.graph && inputLink(host.graph, host.id, slot)
if (link?.origin_id !== SUBGRAPH_INPUT_ID) continue
host.disconnectInput(slot)
disconnectOrphanedPromotion(host.graph, link.origin_slot, hosts)
}
}

class DynamicGroupNoticeWidget extends VueOnlyWidget<IBaseWidget> {
protected get vueOnlyLabel(): string {
return this.label ?? this.name
Expand Down
Loading
Loading