Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# ADR-WIDGET-COMPONENTS-0058: Widget components share lifecycle and persistence

Date: 2026-11-17

## Status

Accepted

## Context

Folder scopes and user-sized heights are durable data attached to widget
identity. Separate implementations of rename, removal, and workflow persistence
produced different ownership rules. Future widget components need to inherit
these rules rather than reproduce them.

## Decision

Keep dedicated, typed component stores keyed by canonical `WidgetId`. Components
are plain data. A shared store primitive owns sparse storage, identity migration,
scoped cleanup, and the translation between runtime components and workflow
metadata. Each durable component supplies its wire key, schema, and encoder.

Register each component store with one widget-component lifecycle system. Widget
and node lifecycle paths invoke that system, never individual component stores.
A shared contract suite exercises every registered component through real node
and widget operations. Adding a registration requires a persistence example for
that suite.

A rename moves components with the widget entity. Explicit widget destruction
removes them. Renderer absence, a temporarily missing widget, and a preview that
has not appeared yet do not destroy the entity. An independently promoted widget
owns its own components even when it shares a source value.

Node removal clears live components after copying them into detached workflow
metadata. Attachment restores them after identity collision resolution. Copies
therefore acquire components under their destination identities. Snapshot restore
replaces previous components, including clearing overrides omitted from the
snapshot's properties. Configuring a node without properties leaves its existing
components unchanged. Invalid saved entries are ignored independently, preserving
valid siblings.

Existing workflow property names and value representations remain compatible.
Extension configure callbacks see the incoming metadata before the frontend
adopts it. These components are not layout operations, derived renderer geometry,
or backend execution options.

## Alternatives considered

- Matching hand-written stores by convention leaves lifecycle drift possible.
- A central entity registry would replace the dedicated-store architecture
without solving a requirement these components introduce.
- Keeping preferences under a name after rename associates old data with a
different future widget. Components follow the entity instead.

## Consequences

Component-specific systems retain their own behavior, such as folder filtering
and height allocation. Storage and persistence behavior changes in one shared
implementation. Feature stores do not introduce custom node or widget lifecycle
hooks.
3 changes: 3 additions & 0 deletions src/core/graph/nodeShell/nodeShellLifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { getWidgetIds } from '@/lib/litegraph/src/utils/widget'
import { reportError } from '@comfyorg/telemetry/reportError'
import { usePreviewExposureStore } from '@/stores/previewExposureStore'
import { useWidgetValueStore } from '@/stores/widgetValueStore'
import { useWidgetComponents } from '@/stores/widgetComponents'
import type { RefusedWidget } from '@comfyorg/graph-model/widgetId'

import { registerNodeState, unregisterNodeState } from './nodeShellState'
Expand Down Expand Up @@ -102,6 +103,7 @@ export function attachNodeToStores(
)
}

useWidgetComponents().adoptNode(graph.rootGraph.id, node.id, node.properties)
refuseAmbiguousNodeWidgets(node, (report) =>
reportWidgetRefusal(node, report)
)
Expand Down Expand Up @@ -145,6 +147,7 @@ export function detachNodeFromStores(
mode: WidgetDetachMode = 'keep-values'
): void {
const rootGraphId = graph.rootGraph.id
useWidgetComponents().detachNode(rootGraphId, node.id, node.properties)
unregisterNodeState(node)
useWidgetValueStore().releaseNodeWidgets(rootGraphId, node.id, {
discardValues: mode === 'discard-values'
Expand Down
13 changes: 2 additions & 11 deletions src/core/graph/widgets/dynamicWidgets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function dynamicComboWidget(
widgetName?: string
) {
const { addNodeInput } = useLitegraphServiceAccess()
const { deleteWidget } = useWidgetValueStore()
const { releaseWidget } = useWidgetValueStore()
const parseResult = zDynamicComboInputSpec.safeParse(untypedInputData)
if (!parseResult.success) throw new Error('invalid DynamicCombo spec')
const inputData = parseResult.data
Expand Down Expand Up @@ -183,7 +183,7 @@ function dynamicComboWidget(
})
removedWidgetValues.set(removedOption, optionValues)
widget.onRemove?.()
if (widget.widgetId) deleteWidget(widget.widgetId)
if (widget.widgetId) releaseWidget(widget.widgetId)
}

if (!newSpec) {
Expand Down Expand Up @@ -226,7 +226,6 @@ function dynamicComboWidget(
addedWidgets.length === 0 &&
node.inputs.length !== startingInputLength
)
//input is inputOnly, but lacks an insertion point
throw new Error('Failed to find input socket for ' + widget.name)
const result = commitMutatedInputs(node, previous, inputLinks)
if (!result.ok) return
Expand All @@ -243,7 +242,6 @@ function dynamicComboWidget(
? addedInput
: node.inputs.splice(existingInput, 1)[0]
})
//assume existing inputs are in correct order
node.inputs.splice(inputInsertionPoint, 0, ...addedInputs)

for (const input of removedInputs) {
Expand All @@ -253,8 +251,6 @@ function dynamicComboWidget(
}
const result = commitMutatedInputs(node, previous, inputLinks)
if (!result.ok) return
//A callback can grow the group it lands on, shifting every input after
//it, so the slot captured before the batch is stale for later entries.
for (const { input, link } of result.replacements) {
const slot = node.inputs.indexOf(input)
if (slot === -1) continue
Expand All @@ -267,15 +263,10 @@ function dynamicComboWidget(
node.arrange()
node.graph.setDirtyCanvas(true, true)
}
//Refit height on the callback channel: interaction fires it after the value
//setter, while configure (load, clone, paste) only fires the setter and must
//keep the serialised height.
widget.callback = useChainCallback(widget.callback, () => {
node.size = [node.size[0], node.computeSize([...node.size])[1]]
node.graph?.setDirtyCanvas(true, true)
})
//A little hacky, but onConfigure won't work.
//It fires too late and is overly disruptive
let widgetValue = widget.value
const getState = () => {
const graphId = resolveNodeRootGraphId(node)
Expand Down
20 changes: 15 additions & 5 deletions src/lib/litegraph/src/LGraphNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import type { ComfyNodeDef } from '@comfyorg/object-info-parser'
import type { DOMWidget, DOMWidgetOptions } from '@/types/domWidget'
import { useExecutionOrderStore } from '@/stores/executionOrderStore'
import { useWidgetValueStore } from '@/stores/widgetValueStore'
import { useWidgetComponents } from '@/stores/widgetComponents'
import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId'
import { toLinkId } from '@comfyorg/graph-model/linkId'
import type { GraphScope } from '@comfyorg/graph-model/graphScopeId'
Expand Down Expand Up @@ -1335,6 +1336,8 @@ export class LGraphNode
)
const namedValues = restoration.named
const graphId = this.graph?.rootGraph.id ?? zeroUuid
if (info.properties)
useWidgetComponents().prepareNode(this.properties, info.properties)
try {
useWidgetValueStore().setNodeWidgetRestoration(
graphId,
Expand Down Expand Up @@ -1402,6 +1405,8 @@ export class LGraphNode
clearWidgetRestorationSlots(this)
useWidgetValueStore().clearNodeWidgetRestoration(graphId, this.id)
}
if (info.properties && this.graph?.getNodeById(this.id) === this)
useWidgetComponents().adoptNode(graphId, this.id, this.properties)
}

/**
Expand All @@ -1412,7 +1417,6 @@ export class LGraphNode
}

serializeFromStoreState(state: NodeState): ISerialisedNode {
// create serialization object
const o: ISerialisedNode = {
id: serializeNodeId(state.id),
type: state.type,
Expand All @@ -1424,12 +1428,20 @@ export class LGraphNode
showAdvanced: state.showAdvanced
}

// special case for when there were errors
o.properties = LiteGraph.cloneObject(state.properties)
if (this.graph?.getNodeById(this.id) === this)
useWidgetComponents().writeNode(
this.graph.rootGraph.id,
state.id,
o.properties
)

if (this.constructor === LGraphNode && state.lastSerialization)
return {
...LiteGraph.cloneObject(state.lastSerialization),
mode: o.mode,
pos: o.pos
pos: o.pos,
properties: o.properties
}

o.inputs = state.inputs.map((input, i) =>
Expand All @@ -1442,8 +1454,6 @@ export class LGraphNode
if (state.title && state.title != this.constructor.title)
o.title = state.title

o.properties = LiteGraph.cloneObject(state.properties)

const { widgets } = this
if (widgets?.length && this.serialize_widgets)
Object.assign(o, serialiseWidgetValues(widgets))
Expand Down
1 change: 1 addition & 0 deletions src/lib/litegraph/src/__snapshots__/LGraph.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ exports[`LGraph > supports schema v0.4 graphs > oldSchemaGraph 1`] = `
10,
10,
],
"properties": {},
},
],
"revision": 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import { NodeSlotType } from '@comfyorg/graph-model/globalEnums'
import { useLinkStore } from '@/stores/linkStore'
import { usePreviewExposureStore } from '@/stores/previewExposureStore'
import { useWidgetValueStore } from '@/stores/widgetValueStore'
import { useWidgetFolderLockStore } from '@/stores/widgetFolderLockStore'
import { useWidgetHeightStore } from '@/stores/widgetHeightStore'
import {
graphScopeOf,
toOwningGraphId,
Expand Down Expand Up @@ -163,6 +165,7 @@ function createPlaceholderNode(
mode: 0,
flags: {},
has_errors: true,
properties: {},
last_serialization: {
id,
type,
Expand Down Expand Up @@ -207,6 +210,7 @@ function createNewNode(
mode: 0,
flags: {},
has_errors: false,
properties: {},
inputs: inputs.map((i) => ({ ...i, type: 'IMAGE' })),
outputs: outputs.map((o) => ({ ...o, type: 'IMAGE' })),
widgets: widgets.map((w) => ({ ...w, type: 'combo', options: {} })),
Expand Down Expand Up @@ -358,6 +362,49 @@ describe('useNodeReplacement', () => {
})
})

it('preserves live components instead of stale cached overrides during replacement', () => {
const graph = createReplacementGraph()
const placeholder = addSlottedNode(graph, 'MissingNode')
placeholder.configure({
...placeholder.serialize(),
properties: {
widget_folder_locks: { model: ['old'] },
widgetHeights: { notes: 101, keep: 137 }
}
})
markPlaceholder(placeholder)
const modelId = widgetId(graph.id, placeholder.id, 'model')
const notesId = widgetId(graph.id, placeholder.id, 'notes')
useWidgetFolderLockStore().set(modelId, { directory: ['live'] })
useWidgetHeightStore().set(notesId, undefined)
const newNode = createSlottedNode('Replacement')
newNode.addWidget('combo', 'model', 'live/a.safetensors', () => {}, {
values: ['live/a.safetensors']
})
vi.mocked(LiteGraph.createNode).mockReturnValue(newNode)

const result = useNodeReplacement().replaceNodesInPlace([
makeMissingNodeType('MissingNode', {
old_node_id: 'MissingNode',
new_node_id: 'Replacement',
old_widget_ids: null,
input_mapping: null,
output_mapping: null
})
])

expect(result).toEqual(['MissingNode'])
expect(graph.nodes).toContain(newNode)
expect(useWidgetFolderLockStore().get(modelId)).toEqual({
directory: ['live']
})
expect(useWidgetHeightStore().get(notesId)).toBeUndefined()
expect(newNode.serialize().properties).toEqual({
widget_folder_locks: { model: ['live'] },
widgetHeights: { keep: 137 }
})
})

it('clears stale node-owned records before binding the replacement', () => {
const placeholder = createPlaceholderNode(1, 'MissingNode')
const graph = createMockGraph([placeholder])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
import { app, sanitizeNodeName } from '@/scripts/app'
import { clearNodeOwnedStoreState } from '@/stores/clearNodeOwnedStoreState'
import { useWidgetComponents } from '@/stores/widgetComponents'
import type { EndpointPatch, EndpointUpdate } from '@/stores/linkStore'
import { useLinkStore } from '@/stores/linkStore'
import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId'
Expand Down Expand Up @@ -397,12 +398,15 @@ function replaceWithMapping(
} catch (error) {
console.error(`Failed to remove replaced node ${node.id}`, error)
}
const components = useWidgetComponents()
components.writeNode(scope.rootGraphId, node.id, newNode.properties)
clearNodeOwnedStoreState(node)

nodeGraph._nodes[idx] = newNode
newNode.graph = nodeGraph
node.graph = null
nodeGraph._nodes_by_id[newNode.id] = newNode
components.adoptNode(scope.rootGraphId, newNode.id, newNode.properties)

for (const { name, value } of assignedWidgets) {
const widget = newNode.widgets?.find((w) => w.name === name)
Expand Down
2 changes: 2 additions & 0 deletions src/stores/clearNodeOwnedStoreState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import { parseNodeId } from '@comfyorg/graph-model/nodeId'

import { usePreviewExposureStore } from './previewExposureStore'
import { useWidgetValueStore } from './widgetValueStore'
import { useWidgetComponents } from './widgetComponents'

export function clearNodeOwnedStoreState(node: LGraphNode): void {
const graph = node.graph
if (!graph) return

const rootGraphId = graph.isRootGraph ? graph.id : graph.rootGraph.id
const nodeId = parseNodeId(node.id) ?? node.id
useWidgetComponents().detachNode(rootGraphId, nodeId, node.properties)
useWidgetValueStore().clearNode(rootGraphId, nodeId)
usePreviewExposureStore().clearHost(
rootGraphId,
Expand Down
Loading
Loading