From 24c6dc0caad3a8d46d0cf3b29643fdb79db62826 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 17 Nov 2026 04:24:29 +0000 Subject: [PATCH 1/6] refactor: share widget component lifecycle and persistence Amp-Thread-ID: https://ampcode.com/threads/T-a5212181-fb76-42ae-a8b1-af7cfb2f8978 --- ...red-component-lifecycle-and-persistence.md | 59 ++++++++ .../graph/nodeShell/nodeShellLifecycle.ts | 3 + src/lib/litegraph/src/LGraphNode.ts | 14 +- src/stores/clearNodeOwnedStoreState.ts | 2 + src/stores/widgetComponentStore.ts | 91 ++++++++++++ src/stores/widgetComponents.test.ts | 140 ++++++++++++++++++ src/stores/widgetComponents.ts | 62 ++++++++ src/stores/widgetFolderLockStore.ts | 13 ++ src/stores/widgetHeightStore.ts | 14 ++ src/stores/widgetValueStore.ts | 24 +-- 10 files changed, 408 insertions(+), 14 deletions(-) create mode 100644 docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md create mode 100644 src/stores/widgetComponentStore.ts create mode 100644 src/stores/widgetComponents.test.ts create mode 100644 src/stores/widgetComponents.ts create mode 100644 src/stores/widgetFolderLockStore.ts create mode 100644 src/stores/widgetHeightStore.ts diff --git a/docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md b/docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md new file mode 100644 index 00000000000..eae3b80d228 --- /dev/null +++ b/docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md @@ -0,0 +1,59 @@ +# 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. 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. diff --git a/src/core/graph/nodeShell/nodeShellLifecycle.ts b/src/core/graph/nodeShell/nodeShellLifecycle.ts index 0eecd8ae657..6e7d9b4ffb7 100644 --- a/src/core/graph/nodeShell/nodeShellLifecycle.ts +++ b/src/core/graph/nodeShell/nodeShellLifecycle.ts @@ -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' @@ -102,6 +103,7 @@ export function attachNodeToStores( ) } + useWidgetComponents().adoptNode(graph.rootGraph.id, node.id, node.properties) refuseAmbiguousNodeWidgets(node, (report) => reportWidgetRefusal(node, report) ) @@ -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' diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index 443d82eb995..2258732526e 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -1402,6 +1402,12 @@ export class LGraphNode clearWidgetRestorationSlots(this) useWidgetValueStore().clearNodeWidgetRestoration(graphId, this.id) } + if (this.graph?.getNodeById(this.id) === this) + useWidgetValueStore().adoptNodeComponents( + graphId, + this.id, + this.properties + ) } /** @@ -1412,7 +1418,6 @@ export class LGraphNode } serializeFromStoreState(state: NodeState): ISerialisedNode { - // create serialization object const o: ISerialisedNode = { id: serializeNodeId(state.id), type: state.type, @@ -1424,7 +1429,6 @@ export class LGraphNode showAdvanced: state.showAdvanced } - // special case for when there were errors if (this.constructor === LGraphNode && state.lastSerialization) return { ...LiteGraph.cloneObject(state.lastSerialization), @@ -1443,6 +1447,12 @@ export class LGraphNode o.title = state.title o.properties = LiteGraph.cloneObject(state.properties) + if (this.graph?.getNodeById(this.id) === this) + useWidgetValueStore().writeNodeComponents( + this.graph.rootGraph.id, + state.id, + o.properties + ) const { widgets } = this if (widgets?.length && this.serialize_widgets) diff --git a/src/stores/clearNodeOwnedStoreState.ts b/src/stores/clearNodeOwnedStoreState.ts index d0e7d07b83a..d9f6912b734 100644 --- a/src/stores/clearNodeOwnedStoreState.ts +++ b/src/stores/clearNodeOwnedStoreState.ts @@ -5,6 +5,7 @@ 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 @@ -12,6 +13,7 @@ export function clearNodeOwnedStoreState(node: LGraphNode): void { 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, diff --git a/src/stores/widgetComponentStore.ts b/src/stores/widgetComponentStore.ts new file mode 100644 index 00000000000..21030c7a8cb --- /dev/null +++ b/src/stores/widgetComponentStore.ts @@ -0,0 +1,91 @@ +import { isPlainObject } from 'es-toolkit' +import { defineStore } from 'pinia' +import { shallowReactive } from 'vue' +import type { z } from 'zod' + +import type { NodeId } from '@comfyorg/graph-model/nodeId' +import type { NodeProperty } from '@comfyorg/graph-model/nodeProperty' +import { parseWidgetId, widgetId } from '@comfyorg/graph-model/widgetId' +import type { WidgetId } from '@comfyorg/graph-model/widgetId' +import type { UUID } from '@/utils/uuid' + +export function defineWidgetComponentStore< + const Id extends string, + T extends object +>(definition: { + id: Id + wireKey: string + schema: z.ZodType + encode: (component: T) => NodeProperty +}) { + return defineStore(definition.id, () => { + const components = shallowReactive(new Map()) + + function get(id: WidgetId): Readonly | undefined { + return components.get(id) + } + + function set(id: WidgetId, component: T | undefined): void { + if (component === undefined) components.delete(id) + else components.set(id, structuredClone(component)) + } + + function move(previous: WidgetId, next: WidgetId): void { + const component = components.get(previous) + components.delete(previous) + components.delete(next) + if (component) components.set(next, component) + } + + function clearNode(graphId: UUID, nodeId: NodeId): void { + for (const id of components.keys()) { + const owner = parseWidgetId(id) + if ( + owner.graphId === graphId && + String(owner.nodeId) === String(nodeId) + ) + components.delete(id) + } + } + + function clearGraph(graphId: UUID): void { + for (const id of components.keys()) { + if (parseWidgetId(id).graphId === graphId) components.delete(id) + } + } + + function writeNode( + graphId: UUID, + nodeId: NodeId, + properties: Record + ): void { + const entries = [...components].flatMap(([id, component]) => { + const owner = parseWidgetId(id) + return owner.graphId === graphId && + String(owner.nodeId) === String(nodeId) + ? [[owner.name, definition.encode(component)] as const] + : [] + }) + if (entries.length) + properties[definition.wireKey] = Object.fromEntries(entries) + else delete properties[definition.wireKey] + } + + function adoptNode( + graphId: UUID, + nodeId: NodeId, + properties: Record + ): void { + const saved = properties[definition.wireKey] + delete properties[definition.wireKey] + clearNode(graphId, nodeId) + if (!isPlainObject(saved)) return + for (const [name, raw] of Object.entries(saved)) { + const parsed = definition.schema.safeParse(raw) + if (parsed.success) set(widgetId(graphId, nodeId, name), parsed.data) + } + } + + return { get, set, move, clearNode, clearGraph, writeNode, adoptNode } + }) +} diff --git a/src/stores/widgetComponents.test.ts b/src/stores/widgetComponents.test.ts new file mode 100644 index 00000000000..ebdca2e1d35 --- /dev/null +++ b/src/stores/widgetComponents.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from 'vitest' + +import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { NodeProperty } from '@comfyorg/graph-model/nodeProperty' +import { widgetId } from '@comfyorg/graph-model/widgetId' + +import { widgetComponentStores } from './widgetComponents' + +const samples = { + widgetFolderLock: { + wireKey: 'widget_folder_locks', + wire: ['MOSS', 'image'], + component: { directory: ['MOSS', 'image'] } + }, + widgetHeight: { + wireKey: 'widgetHeights', + wire: 137, + component: { height: 137 } + } +} satisfies Record< + ReturnType<(typeof widgetComponentStores)[number]>['$id'], + { wireKey: string; wire: NodeProperty; component: object } +> + +describe.for( + widgetComponentStores.map((useStore) => ({ name: useStore.$id, useStore })) +)('$name widget component contract', ({ name, useStore }) => { + const sample = samples[name] + + function configure(node: LGraphNode) { + node.configure({ + ...node.serialize(), + properties: { [sample.wireKey]: { model: sample.wire, broken: false } } + }) + } + + it('round-trips valid entries even while widgets are absent, and replaces a restored snapshot', () => { + const graph = new LGraph() + const node = new LGraphNode('component owner') + graph.add(node) + configure(node) + const id = widgetId(graph.id, node.id, 'model') + const store = useStore() + + expect(store.get(id)).toEqual(sample.component) + expect(node.properties).not.toHaveProperty(sample.wireKey) + expect(node.serialize().properties?.[sample.wireKey]).toEqual({ + model: sample.wire + }) + + node.configure({ ...node.serialize(), properties: {} }) + + expect(store.get(id)).toBeUndefined() + expect(node.serialize().properties).not.toHaveProperty(sample.wireKey) + }) + + it('moves components with a widget rename and deletes them with the widget', () => { + const graph = new LGraph() + const node = new LGraphNode('component owner') + const widget = node.addWidget('text', 'model', 'value', () => {}) + graph.add(node) + configure(node) + const original = widgetId(graph.id, node.id, 'model') + const renamed = widgetId(graph.id, node.id, 'renamed') + + widget.name = 'renamed' + + expect(useStore().get(original)).toBeUndefined() + expect(useStore().get(renamed)).toEqual(sample.component) + expect(node.serialize().properties?.[sample.wireKey]).toEqual({ + renamed: sample.wire + }) + + node.removeWidget(widget) + + expect(useStore().get(renamed)).toBeUndefined() + expect(node.serialize().properties).not.toHaveProperty(sample.wireKey) + }) + + it('preserves components across node removal and reattachment under a new identity', () => { + const graph = new LGraph() + const node = new LGraphNode('component owner') + graph.add(node) + configure(node) + const original = widgetId(graph.id, node.id, 'model') + + graph.remove(node) + + expect(useStore().get(original)).toBeUndefined() + expect(node.serialize().properties?.[sample.wireKey]).toEqual({ + model: sample.wire + }) + + const destination = new LGraph() + destination.add(node) + + expect(useStore().get(widgetId(destination.id, node.id, 'model'))).toEqual( + sample.component + ) + expect(useStore().get(original)).toBeUndefined() + expect(node.properties).not.toHaveProperty(sample.wireKey) + }) + + it('adopts copied components after node identity collision resolution', () => { + const graph = new LGraph() + const original = new LGraphNode('original') + graph.add(original) + configure(original) + const copy = new LGraphNode('copy') + copy.graph = graph + copy.configure(original.serialize()) + graph.add(copy) + + expect(copy.id).not.toBe(original.id) + expect(useStore().get(widgetId(graph.id, original.id, 'model'))).toEqual( + sample.component + ) + expect(useStore().get(widgetId(graph.id, copy.id, 'model'))).toEqual( + sample.component + ) + }) + + it('clears only the destroyed graph, including components without live widgets', () => { + const graph = new LGraph() + const otherGraph = new LGraph() + const node = new LGraphNode('owner') + const otherNode = new LGraphNode('other owner') + graph.add(node) + otherGraph.add(otherNode) + configure(node) + configure(otherNode) + + graph.clear() + + expect(useStore().get(widgetId(graph.id, node.id, 'model'))).toBeUndefined() + expect( + useStore().get(widgetId(otherGraph.id, otherNode.id, 'model')) + ).toEqual(sample.component) + }) +}) diff --git a/src/stores/widgetComponents.ts b/src/stores/widgetComponents.ts new file mode 100644 index 00000000000..9dc065533ae --- /dev/null +++ b/src/stores/widgetComponents.ts @@ -0,0 +1,62 @@ +import { useWidgetFolderLockStore } from './widgetFolderLockStore' +import { useWidgetHeightStore } from './widgetHeightStore' + +export const widgetComponentStores = [ + useWidgetFolderLockStore, + useWidgetHeightStore +] + +export function useWidgetComponents() { + const stores = widgetComponentStores.map((useStore) => useStore()) + + function adoptNode( + ...args: Parameters<(typeof stores)[number]['adoptNode']> + ) { + for (const store of stores) store.adoptNode(...args) + } + + function writeNode( + ...args: Parameters<(typeof stores)[number]['writeNode']> + ) { + for (const store of stores) store.writeNode(...args) + } + + function detachNode( + ...args: Parameters<(typeof stores)[number]['writeNode']> + ) { + const [graphId, nodeId, properties] = args + const saved = {} + writeNode(graphId, nodeId, saved) + Object.assign(properties, saved) + } + + function remove(id: Parameters<(typeof stores)[number]['set']>[0]) { + for (const store of stores) store.set(id, undefined) + } + + function move(...args: Parameters<(typeof stores)[number]['move']>) { + for (const store of stores) store.move(...args) + } + + function clearNode( + ...args: Parameters<(typeof stores)[number]['clearNode']> + ) { + for (const store of stores) store.clearNode(...args) + } + + function clearGraph( + ...args: Parameters<(typeof stores)[number]['clearGraph']> + ) { + for (const store of stores) store.clearGraph(...args) + } + + return { + adoptNode, + writeNode, + detachNode, + remove, + move, + clearNode, + clearGraph + } +} diff --git a/src/stores/widgetFolderLockStore.ts b/src/stores/widgetFolderLockStore.ts new file mode 100644 index 00000000000..755206281cc --- /dev/null +++ b/src/stores/widgetFolderLockStore.ts @@ -0,0 +1,13 @@ +import { z } from 'zod' + +import { defineWidgetComponentStore } from './widgetComponentStore' + +export const useWidgetFolderLockStore = defineWidgetComponentStore({ + id: 'widgetFolderLock', + wireKey: 'widget_folder_locks', + schema: z + .array(z.string().min(1)) + .min(1) + .transform((directory) => ({ directory })), + encode: ({ directory }) => [...directory] +}) diff --git a/src/stores/widgetHeightStore.ts b/src/stores/widgetHeightStore.ts new file mode 100644 index 00000000000..174bc4aa508 --- /dev/null +++ b/src/stores/widgetHeightStore.ts @@ -0,0 +1,14 @@ +import { z } from 'zod' + +import { defineWidgetComponentStore } from './widgetComponentStore' + +export const useWidgetHeightStore = defineWidgetComponentStore({ + id: 'widgetHeight', + wireKey: 'widgetHeights', + schema: z + .number() + .finite() + .positive() + .transform((height) => ({ height: Math.round(height) })), + encode: ({ height }) => Math.round(height) +}) diff --git a/src/stores/widgetValueStore.ts b/src/stores/widgetValueStore.ts index 4fb498e9a8e..b6804d44f3c 100644 --- a/src/stores/widgetValueStore.ts +++ b/src/stores/widgetValueStore.ts @@ -1,6 +1,8 @@ import { defineStore } from 'pinia' import { reactive, ref } from 'vue' +import { useWidgetComponents } from './widgetComponents' + import { isUuidShapedSubgraphId } from '@/schemas/subgraphIdSchema' import type { UUID } from '@/utils/uuid' import { parseNodeId } from '@comfyorg/graph-model/nodeId' @@ -296,12 +298,6 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { const { graphId, nodeId, name: storageName } = parseWidgetId(widgetId) const widgets = getGraphWidgets(graphId) const existing = widgets.get(widgetId) - // WidgetId is `graphId:nodeId:name`. A node replacement can reuse the same - // numeric nodeId, so a stale entry from the previous occupant may survive in - // the store under the same key. The type check distinguishes a live - // re-registration (same widget, keep its value) from a recycled key (new - // widget type at an old address, overwrite). Without it a text widget - // rendered as the prior int type until the next full reload (#13073, #13773). if (existing && existing.state.type === init.type) { Object.assign(existing.state, { ...init, @@ -318,6 +314,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { return existing.state } + if (existing) useWidgetComponents().remove(widgetId) const state: WidgetState = { ...init, nodeId, @@ -455,6 +452,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { const { graphId } = parseWidgetId(widgetId) removeNodeWidgetOrder(widgetId) + useWidgetComponents().remove(widgetId) return graphWidgets.value.get(graphId)?.delete(widgetId) ?? false } @@ -484,6 +482,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { widgets.delete(oldId) entity.state.name = name widgets.set(newId, entity) + useWidgetComponents().move(oldId, newId) if (index === -1) order.push(newId) else order.splice(index, 1, newId) @@ -556,17 +555,12 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { } } - /** - * Releases the widget ids tracked for a node, from the store's own record - * rather than the node's live widget list — the two diverge once a node drops - * widgets without unregistering them. `discardValues` also drops the widget - * states; retaining them lets a node that comes back keep what the user set. - */ function releaseNodeWidgets( graphId: UUID, localNodeId: NodeId, { discardValues }: { discardValues: boolean } ): void { + if (discardValues) useWidgetComponents().clearNode(graphId, localNodeId) const graphOrders = graphNodeWidgetOrders.value.get(graphId) if (!graphOrders) return @@ -582,6 +576,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { } function clearNode(graphId: UUID, nodeId: NodeId): void { + useWidgetComponents().clearNode(graphId, nodeId) graphWidgetRestorations.get(graphId)?.delete(nodeId) const widgets = graphWidgets.value.get(graphId) if (widgets) { @@ -598,12 +593,17 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { } function clearGraph(graphId: UUID): void { + useWidgetComponents().clearGraph(graphId) graphWidgets.value.delete(graphId) graphNodeWidgetOrders.value.delete(graphId) graphWidgetRestorations.delete(graphId) } + const components = useWidgetComponents() + return { + adoptNodeComponents: components.adoptNode, + writeNodeComponents: components.writeNode, registerWidget, setNodeWidgetRestoration, clearNodeWidgetRestoration, From 8a1f6bde360c65a2d834e5c3355610459219d57b Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 17 Nov 2026 04:31:21 +0000 Subject: [PATCH 2/6] fix: replace detached widget components on snapshot restore Amp-Thread-ID: https://ampcode.com/threads/T-a5212181-fb76-42ae-a8b1-af7cfb2f8978 --- src/lib/litegraph/src/LGraphNode.ts | 4 ++++ src/stores/widgetComponentStore.ts | 11 ++++++++++- src/stores/widgetComponents.test.ts | 15 +++++++++++++++ src/stores/widgetComponents.ts | 10 ++++++++++ src/stores/widgetValueStore.ts | 1 + 5 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index 2258732526e..07f54417dbf 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -1335,6 +1335,10 @@ export class LGraphNode ) const namedValues = restoration.named const graphId = this.graph?.rootGraph.id ?? zeroUuid + useWidgetValueStore().prepareNodeComponents( + this.properties, + info.properties ?? {} + ) try { useWidgetValueStore().setNodeWidgetRestoration( graphId, diff --git a/src/stores/widgetComponentStore.ts b/src/stores/widgetComponentStore.ts index 21030c7a8cb..548d39821fb 100644 --- a/src/stores/widgetComponentStore.ts +++ b/src/stores/widgetComponentStore.ts @@ -86,6 +86,15 @@ export function defineWidgetComponentStore< } } - return { get, set, move, clearNode, clearGraph, writeNode, adoptNode } + return { + wireKey: definition.wireKey, + get, + set, + move, + clearNode, + clearGraph, + writeNode, + adoptNode + } }) } diff --git a/src/stores/widgetComponents.test.ts b/src/stores/widgetComponents.test.ts index ebdca2e1d35..05a8104029f 100644 --- a/src/stores/widgetComponents.test.ts +++ b/src/stores/widgetComponents.test.ts @@ -101,6 +101,21 @@ describe.for( expect(node.properties).not.toHaveProperty(sample.wireKey) }) + it('does not resurrect detached components when an override is omitted from a restored snapshot', () => { + const graph = new LGraph() + const node = new LGraphNode('component owner') + graph.add(node) + const empty = node.serialize() + configure(node) + graph.remove(node) + + node.configure(empty) + graph.add(node) + + expect(useStore().get(widgetId(graph.id, node.id, 'model'))).toBeUndefined() + expect(node.serialize().properties).not.toHaveProperty(sample.wireKey) + }) + it('adopts copied components after node identity collision resolution', () => { const graph = new LGraph() const original = new LGraphNode('original') diff --git a/src/stores/widgetComponents.ts b/src/stores/widgetComponents.ts index 9dc065533ae..27ee8e509da 100644 --- a/src/stores/widgetComponents.ts +++ b/src/stores/widgetComponents.ts @@ -9,6 +9,15 @@ export const widgetComponentStores = [ export function useWidgetComponents() { const stores = widgetComponentStores.map((useStore) => useStore()) + function prepareNode( + properties: Parameters<(typeof stores)[number]['adoptNode']>[2], + incoming: Parameters<(typeof stores)[number]['adoptNode']>[2] + ) { + for (const { wireKey } of stores) { + if (!Object.hasOwn(incoming, wireKey)) delete properties[wireKey] + } + } + function adoptNode( ...args: Parameters<(typeof stores)[number]['adoptNode']> ) { @@ -51,6 +60,7 @@ export function useWidgetComponents() { } return { + prepareNode, adoptNode, writeNode, detachNode, diff --git a/src/stores/widgetValueStore.ts b/src/stores/widgetValueStore.ts index b6804d44f3c..fe7b03529e9 100644 --- a/src/stores/widgetValueStore.ts +++ b/src/stores/widgetValueStore.ts @@ -602,6 +602,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { const components = useWidgetComponents() return { + prepareNodeComponents: components.prepareNode, adoptNodeComponents: components.adoptNode, writeNodeComponents: components.writeNode, registerWidget, From 42e4c96cd1efebdfe02dc89f275cb43fde2fd380 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 17 Nov 2026 04:46:11 +0000 Subject: [PATCH 3/6] fix: preserve components through temporary widget absence --- ...red-component-lifecycle-and-persistence.md | 5 ++- src/core/graph/widgets/dynamicWidgets.ts | 13 +----- src/lib/litegraph/src/LGraphNode.ts | 11 ++--- .../useNodeReplacement.test.ts | 2 + src/stores/widgetComponents.test.ts | 44 ++++++++++++++++++- src/stores/widgetValueStore.ts | 11 ++++- 6 files changed, 65 insertions(+), 21 deletions(-) diff --git a/docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md b/docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md index eae3b80d228..771d61e28ef 100644 --- a/docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md +++ b/docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md @@ -35,8 +35,9 @@ 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. Invalid saved entries are ignored independently, preserving valid -siblings. +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 diff --git a/src/core/graph/widgets/dynamicWidgets.ts b/src/core/graph/widgets/dynamicWidgets.ts index 15b894cbea5..358246f0052 100644 --- a/src/core/graph/widgets/dynamicWidgets.ts +++ b/src/core/graph/widgets/dynamicWidgets.ts @@ -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 @@ -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) { @@ -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 @@ -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) { @@ -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 @@ -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) diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index 07f54417dbf..70a6e8b2e2c 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -1335,10 +1335,11 @@ export class LGraphNode ) const namedValues = restoration.named const graphId = this.graph?.rootGraph.id ?? zeroUuid - useWidgetValueStore().prepareNodeComponents( - this.properties, - info.properties ?? {} - ) + if (info.properties) + useWidgetValueStore().prepareNodeComponents( + this.properties, + info.properties + ) try { useWidgetValueStore().setNodeWidgetRestoration( graphId, @@ -1406,7 +1407,7 @@ export class LGraphNode clearWidgetRestorationSlots(this) useWidgetValueStore().clearNodeWidgetRestoration(graphId, this.id) } - if (this.graph?.getNodeById(this.id) === this) + if (info.properties && this.graph?.getNodeById(this.id) === this) useWidgetValueStore().adoptNodeComponents( graphId, this.id, diff --git a/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts b/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts index 61144092fcf..2fae152469e 100644 --- a/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts +++ b/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts @@ -163,6 +163,7 @@ function createPlaceholderNode( mode: 0, flags: {}, has_errors: true, + properties: {}, last_serialization: { id, type, @@ -207,6 +208,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: {} })), diff --git a/src/stores/widgetComponents.test.ts b/src/stores/widgetComponents.test.ts index 05a8104029f..352a82368b9 100644 --- a/src/stores/widgetComponents.test.ts +++ b/src/stores/widgetComponents.test.ts @@ -1,5 +1,6 @@ -import { describe, expect, it } from 'vitest' +import { assert, describe, expect, it } from 'vitest' +import { addDynamicCombo } from '@/core/graph/widgets/__fixtures__/dynamicInputHelpers' import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' import type { NodeProperty } from '@comfyorg/graph-model/nodeProperty' import { widgetId } from '@comfyorg/graph-model/widgetId' @@ -54,6 +55,47 @@ describe.for( expect(node.serialize().properties).not.toHaveProperty(sample.wireKey) }) + it('preserves components when configure omits properties', () => { + const graph = new LGraph() + const node = new LGraphNode('component owner') + graph.add(node) + configure(node) + const { properties, ...withoutProperties } = node.serialize() + expect(properties?.[sample.wireKey]).toEqual({ model: sample.wire }) + + node.configure(withoutProperties) + + expect(useStore().get(widgetId(graph.id, node.id, 'model'))).toEqual( + sample.component + ) + }) + + it('preserves components while a dynamic option temporarily removes its widgets', () => { + const graph = new LGraph() + const node = new LGraphNode('component owner') + graph.add(node) + addDynamicCombo(node, [['STRING'], ['IMAGE']]) + const selector = node.widgets?.[0] + const child = node.widgets?.[1] + assert(selector) + assert(child) + node.configure({ + ...node.serialize(), + properties: { [sample.wireKey]: { [child.name]: sample.wire } } + }) + + selector.value = '1' + selector.value = '0' + + expect(node.widgets?.[1]?.name).toBe(child.name) + expect(useStore().get(widgetId(graph.id, node.id, child.name))).toEqual( + sample.component + ) + expect(node.serialize().properties?.[sample.wireKey]).toEqual({ + [child.name]: sample.wire + }) + }) + it('moves components with a widget rename and deletes them with the widget', () => { const graph = new LGraph() const node = new LGraphNode('component owner') diff --git a/src/stores/widgetValueStore.ts b/src/stores/widgetValueStore.ts index fe7b03529e9..015e1e2f944 100644 --- a/src/stores/widgetValueStore.ts +++ b/src/stores/widgetValueStore.ts @@ -447,15 +447,21 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { return true } - function deleteWidget(widgetId: WidgetId): boolean { + function releaseWidget(widgetId: WidgetId): boolean { if (!isWidgetId(widgetId)) return false const { graphId } = parseWidgetId(widgetId) removeNodeWidgetOrder(widgetId) - useWidgetComponents().remove(widgetId) return graphWidgets.value.get(graphId)?.delete(widgetId) ?? false } + function deleteWidget(widgetId: WidgetId): boolean { + if (!isWidgetId(widgetId)) return false + + useWidgetComponents().remove(widgetId) + return releaseWidget(widgetId) + } + function renameWidget( oldId: WidgetId, newId: WidgetId @@ -618,6 +624,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { setLabel, setOptions, updateOptions, + releaseWidget, deleteWidget, renameWidget, getNodeWidgets, From 9c51eb57a89cc8a7eecdf0caedd1b72fcfc11207 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 17 Nov 2026 05:02:39 +0000 Subject: [PATCH 4/6] fix: serialize current components for missing nodes --- src/lib/litegraph/src/LGraphNode.ts | 19 +++++++------ src/stores/widgetComponents.test.ts | 43 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index 70a6e8b2e2c..eca9f1242b9 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -1434,11 +1434,20 @@ export class LGraphNode showAdvanced: state.showAdvanced } + o.properties = LiteGraph.cloneObject(state.properties) + if (this.graph?.getNodeById(this.id) === this) + useWidgetValueStore().writeNodeComponents( + 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) => @@ -1451,14 +1460,6 @@ export class LGraphNode if (state.title && state.title != this.constructor.title) o.title = state.title - o.properties = LiteGraph.cloneObject(state.properties) - if (this.graph?.getNodeById(this.id) === this) - useWidgetValueStore().writeNodeComponents( - this.graph.rootGraph.id, - state.id, - o.properties - ) - const { widgets } = this if (widgets?.length && this.serialize_widgets) Object.assign(o, serialiseWidgetValues(widgets)) diff --git a/src/stores/widgetComponents.test.ts b/src/stores/widgetComponents.test.ts index 352a82368b9..a4a593b39d8 100644 --- a/src/stores/widgetComponents.test.ts +++ b/src/stores/widgetComponents.test.ts @@ -2,6 +2,7 @@ import { assert, describe, expect, it } from 'vitest' import { addDynamicCombo } from '@/core/graph/widgets/__fixtures__/dynamicInputHelpers' import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import { LGraphEventMode } from '@comfyorg/graph-model/globalEnums' import type { NodeProperty } from '@comfyorg/graph-model/nodeProperty' import { widgetId } from '@comfyorg/graph-model/widgetId' @@ -55,6 +56,48 @@ describe.for( expect(node.serialize().properties).not.toHaveProperty(sample.wireKey) }) + it('does not restore cleared components from a missing-node serialization cache', () => { + const graph = new LGraph() + const node = new LGraphNode( + 'missing component owner', + 'MissingComponentOwner' + ) + graph.add(node) + const cached = { + ...node.serialize(), + properties: { + extensionData: 'keep', + [sample.wireKey]: { model: sample.wire } + } + } + node.last_serialization = cached + node.configure(cached) + node.configure({ + ...node.serialize(), + properties: { extensionData: 'keep' } + }) + node.pos = [31, 79] + node.mode = LGraphEventMode.BYPASS + + const saved = graph.serialize() + const serialized = saved.nodes[0] + assert(serialized) + + expect(serialized.properties).toEqual({ extensionData: 'keep' }) + expect(serialized.pos).toEqual([31, 79]) + expect(serialized.mode).toBe(LGraphEventMode.BYPASS) + expect(cached.properties[sample.wireKey]).toEqual({ model: sample.wire }) + + const restored = new LGraph() + restored.configure(saved) + const reloaded = restored.getNodeById(node.id) + assert(reloaded) + expect(reloaded.serialize().properties).toEqual({ extensionData: 'keep' }) + expect( + useStore().get(widgetId(restored.id, reloaded.id, 'model')) + ).toBeUndefined() + }) + it('preserves components when configure omits properties', () => { const graph = new LGraph() const node = new LGraphNode('component owner') From 2203b35923c3fc0ecf67f8973474e1f6b84b9055 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 17 Nov 2026 05:15:35 +0000 Subject: [PATCH 5/6] test: align legacy graph snapshot with current properties --- src/lib/litegraph/src/__snapshots__/LGraph.test.ts.snap | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/litegraph/src/__snapshots__/LGraph.test.ts.snap b/src/lib/litegraph/src/__snapshots__/LGraph.test.ts.snap index 836ad17563b..21cbf1ea0d6 100644 --- a/src/lib/litegraph/src/__snapshots__/LGraph.test.ts.snap +++ b/src/lib/litegraph/src/__snapshots__/LGraph.test.ts.snap @@ -34,6 +34,7 @@ exports[`LGraph > supports schema v0.4 graphs > oldSchemaGraph 1`] = ` 10, 10, ], + "properties": {}, }, ], "revision": 0, From b6c890f4d409c7205ab7426c88e86855ae6e89fb Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 17 Nov 2026 08:37:31 +0000 Subject: [PATCH 6/6] fix: preserve and scope widget components across lifecycle changes Amp-Thread-ID: https://ampcode.com/threads/T-a5212181-fb76-42ae-a8b1-af7cfb2f8978 --- src/lib/litegraph/src/LGraphNode.ts | 14 +- .../useNodeReplacement.test.ts | 45 ++++++ .../nodeReplacement/useNodeReplacement.ts | 4 + src/stores/widgetComponentStore.ts | 77 ++++++---- src/stores/widgetComponents.test.ts | 136 +++++++++++++++++- src/stores/widgetValueStore.ts | 18 +-- 6 files changed, 243 insertions(+), 51 deletions(-) diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index eca9f1242b9..aae1d5a1e85 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -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' @@ -1336,10 +1337,7 @@ export class LGraphNode const namedValues = restoration.named const graphId = this.graph?.rootGraph.id ?? zeroUuid if (info.properties) - useWidgetValueStore().prepareNodeComponents( - this.properties, - info.properties - ) + useWidgetComponents().prepareNode(this.properties, info.properties) try { useWidgetValueStore().setNodeWidgetRestoration( graphId, @@ -1408,11 +1406,7 @@ export class LGraphNode useWidgetValueStore().clearNodeWidgetRestoration(graphId, this.id) } if (info.properties && this.graph?.getNodeById(this.id) === this) - useWidgetValueStore().adoptNodeComponents( - graphId, - this.id, - this.properties - ) + useWidgetComponents().adoptNode(graphId, this.id, this.properties) } /** @@ -1436,7 +1430,7 @@ export class LGraphNode o.properties = LiteGraph.cloneObject(state.properties) if (this.graph?.getNodeById(this.id) === this) - useWidgetValueStore().writeNodeComponents( + useWidgetComponents().writeNode( this.graph.rootGraph.id, state.id, o.properties diff --git a/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts b/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts index 2fae152469e..d43ba84182f 100644 --- a/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts +++ b/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts @@ -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, @@ -360,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]) diff --git a/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.ts b/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.ts index a9e157d7748..9a3f1c3ec07 100644 --- a/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.ts +++ b/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.ts @@ -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' @@ -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) diff --git a/src/stores/widgetComponentStore.ts b/src/stores/widgetComponentStore.ts index 548d39821fb..75ed34d2236 100644 --- a/src/stores/widgetComponentStore.ts +++ b/src/stores/widgetComponentStore.ts @@ -5,7 +5,12 @@ import type { z } from 'zod' import type { NodeId } from '@comfyorg/graph-model/nodeId' import type { NodeProperty } from '@comfyorg/graph-model/nodeProperty' -import { parseWidgetId, widgetId } from '@comfyorg/graph-model/widgetId' +import { + isWidgetId, + isWidgetNameUnreadable, + parseWidgetId, + widgetId +} from '@comfyorg/graph-model/widgetId' import type { WidgetId } from '@comfyorg/graph-model/widgetId' import type { UUID } from '@/utils/uuid' @@ -19,39 +24,55 @@ export function defineWidgetComponentStore< encode: (component: T) => NodeProperty }) { return defineStore(definition.id, () => { - const components = shallowReactive(new Map()) + const components = shallowReactive( + new Map>>() + ) function get(id: WidgetId): Readonly | undefined { - return components.get(id) + const { graphId, nodeId } = parseWidgetId(id) + return components.get(graphId)?.get(String(nodeId))?.get(id) } function set(id: WidgetId, component: T | undefined): void { - if (component === undefined) components.delete(id) - else components.set(id, structuredClone(component)) + const { graphId, nodeId } = parseWidgetId(id) + const key = String(nodeId) + let nodes = components.get(graphId) + let widgets = nodes?.get(key) + if (component === undefined) { + widgets?.delete(id) + if (!widgets?.size) nodes?.delete(key) + if (!nodes?.size) components.delete(graphId) + return + } + if (!nodes) { + nodes = shallowReactive(new Map>()) + components.set(graphId, nodes) + } + if (!widgets) { + widgets = shallowReactive(new Map()) + nodes.set(key, widgets) + } + widgets.set(id, structuredClone(component)) } function move(previous: WidgetId, next: WidgetId): void { - const component = components.get(previous) - components.delete(previous) - components.delete(next) - if (component) components.set(next, component) + const { graphId, nodeId } = parseWidgetId(previous) + const component = components + .get(graphId) + ?.get(String(nodeId)) + ?.get(previous) + set(previous, undefined) + set(next, component) } function clearNode(graphId: UUID, nodeId: NodeId): void { - for (const id of components.keys()) { - const owner = parseWidgetId(id) - if ( - owner.graphId === graphId && - String(owner.nodeId) === String(nodeId) - ) - components.delete(id) - } + const nodes = components.get(graphId) + nodes?.delete(String(nodeId)) + if (!nodes?.size) components.delete(graphId) } function clearGraph(graphId: UUID): void { - for (const id of components.keys()) { - if (parseWidgetId(id).graphId === graphId) components.delete(id) - } + components.delete(graphId) } function writeNode( @@ -59,13 +80,11 @@ export function defineWidgetComponentStore< nodeId: NodeId, properties: Record ): void { - const entries = [...components].flatMap(([id, component]) => { - const owner = parseWidgetId(id) - return owner.graphId === graphId && - String(owner.nodeId) === String(nodeId) - ? [[owner.name, definition.encode(component)] as const] - : [] - }) + const widgets = components.get(graphId)?.get(String(nodeId)) + const entries = [...(widgets ?? [])].map(([id, component]) => [ + parseWidgetId(id).name, + definition.encode(component) + ]) if (entries.length) properties[definition.wireKey] = Object.fromEntries(entries) else delete properties[definition.wireKey] @@ -82,7 +101,9 @@ export function defineWidgetComponentStore< if (!isPlainObject(saved)) return for (const [name, raw] of Object.entries(saved)) { const parsed = definition.schema.safeParse(raw) - if (parsed.success) set(widgetId(graphId, nodeId, name), parsed.data) + if (!parsed.success || isWidgetNameUnreadable({ name })) continue + const id = widgetId(graphId, nodeId, name) + if (isWidgetId(id)) set(id, parsed.data) } } diff --git a/src/stores/widgetComponents.test.ts b/src/stores/widgetComponents.test.ts index a4a593b39d8..8c9caf73ff2 100644 --- a/src/stores/widgetComponents.test.ts +++ b/src/stores/widgetComponents.test.ts @@ -1,10 +1,14 @@ import { assert, describe, expect, it } from 'vitest' +import { computed } from 'vue' import { addDynamicCombo } from '@/core/graph/widgets/__fixtures__/dynamicInputHelpers' import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' import { LGraphEventMode } from '@comfyorg/graph-model/globalEnums' import type { NodeProperty } from '@comfyorg/graph-model/nodeProperty' import { widgetId } from '@comfyorg/graph-model/widgetId' +import { toNodeId } from '@comfyorg/graph-model/nodeId' +import { detachNodeFromStores } from '@/core/graph/nodeShell/nodeShellLifecycle' +import { useWidgetValueStore } from './widgetValueStore' import { widgetComponentStores } from './widgetComponents' @@ -56,6 +60,39 @@ describe.for( expect(node.serialize().properties).not.toHaveProperty(sample.wireKey) }) + it('ignores invalid saved widget names without losing valid siblings or poisoning other graphs', () => { + const graph = new LGraph() + const node = new LGraphNode('component owner') + node.configure({ + ...node.serialize(), + properties: { + [sample.wireKey]: { + '': sample.wire, + '\ud800': sample.wire, + 'model:日本語': sample.wire + } + } + }) + graph.add(node) + + expect(graph.nodes).toContain(node) + expect(node.serialize().properties?.[sample.wireKey]).toEqual({ + 'model:日本語': sample.wire + }) + + const other = new LGraph() + const sibling = new LGraphNode('other component owner') + other.add(sibling) + configure(sibling) + expect(sibling.serialize().properties?.[sample.wireKey]).toEqual({ + model: sample.wire + }) + graph.clear() + expect(useStore().get(widgetId(other.id, sibling.id, 'model'))).toEqual( + sample.component + ) + }) + it('does not restore cleared components from a missing-node serialization cache', () => { const graph = new LGraph() const node = new LGraphNode( @@ -220,7 +257,96 @@ describe.for( ) }) - it('clears only the destroyed graph, including components without live widgets', () => { + it('updates reactive consumers when a node gains, loses and restores components', () => { + const graph = new LGraph() + const node = new LGraphNode('owner') + graph.add(node) + const sibling = new LGraphNode('sibling') + graph.add(sibling) + configure(sibling) + const store = useStore() + const id = widgetId(graph.id, node.id, 'model') + const current = computed(() => store.get(id)) + expect(current.value).toBeUndefined() + + configure(node) + expect(current.value).toEqual(sample.component) + + node.configure({ ...node.serialize(), properties: {} }) + expect(current.value).toBeUndefined() + + configure(node) + expect(current.value).toEqual(sample.component) + + graph.clear() + expect(current.value).toBeUndefined() + }) + + it('preserves components for the same widget type but discards them when its id is recycled for another type', () => { + const graph = new LGraph() + const node = new LGraphNode('owner') + node.addWidget('text', 'model', 'value', () => {}) + graph.add(node) + configure(node) + const id = widgetId(graph.id, node.id, 'model') + const widgets = useWidgetValueStore() + + widgets.registerWidget(id, { type: 'text', value: 'next', options: {} }) + expect(useStore().get(id)).toEqual(sample.component) + + widgets.registerWidget(id, { type: 'number', value: 17, options: {} }) + + expect(node.serialize().properties).not.toHaveProperty(sample.wireKey) + }) + + it('discards node components even when no widget order is registered', () => { + const graph = new LGraph() + const node = new LGraphNode('owner') + const sibling = new LGraphNode('sibling') + graph.add(node) + graph.add(sibling) + configure(node) + configure(sibling) + + useWidgetValueStore().releaseNodeWidgets(graph.id, node.id, { + discardValues: true + }) + + expect(node.serialize().properties).not.toHaveProperty(sample.wireKey) + expect(sibling.serialize().properties?.[sample.wireKey]).toEqual({ + model: sample.wire + }) + }) + + it('copies component metadata before the shell discards its stores', () => { + const graph = new LGraph() + const node = new LGraphNode('owner') + graph.add(node) + configure(node) + + detachNodeFromStores(graph, node, 'discard-values') + + expect(node.properties[sample.wireKey]).toEqual({ model: sample.wire }) + expect(useStore().get(widgetId(graph.id, node.id, 'model'))).toBeUndefined() + }) + + it("does not serialize another node's components while a copy awaits identity resolution", () => { + const graph = new LGraph() + const original = new LGraphNode('owner') + graph.add(original) + configure(original) + const copy = new LGraphNode('copy') + copy.graph = graph + copy.id = original.id + copy.properties = { extensionData: 'keep' } + + expect(copy.serialize().properties).toEqual({ extensionData: 'keep' }) + expect(original.serialize().properties?.[sample.wireKey]).toEqual({ + model: sample.wire + }) + }) + + it('clears only the destroyed graph, including components without live widgets or nodes', () => { const graph = new LGraph() const otherGraph = new LGraph() const node = new LGraphNode('owner') @@ -229,10 +355,16 @@ describe.for( otherGraph.add(otherNode) configure(node) configure(otherNode) + const orphanId = toNodeId(791) + const graphId = graph.id + useStore().adoptNode(graphId, orphanId, { + [sample.wireKey]: { model: sample.wire } + }) graph.clear() - expect(useStore().get(widgetId(graph.id, node.id, 'model'))).toBeUndefined() + expect(useStore().get(widgetId(graphId, orphanId, 'model'))).toBeUndefined() + expect(useStore().get(widgetId(graphId, node.id, 'model'))).toBeUndefined() expect( useStore().get(widgetId(otherGraph.id, otherNode.id, 'model')) ).toEqual(sample.component) diff --git a/src/stores/widgetValueStore.ts b/src/stores/widgetValueStore.ts index 015e1e2f944..67c93372a2f 100644 --- a/src/stores/widgetValueStore.ts +++ b/src/stores/widgetValueStore.ts @@ -107,6 +107,7 @@ export function stripGraphPrefix(scopedId: SerializedNodeId): NodeId | null { } export const useWidgetValueStore = defineStore('widgetValue', () => { + const components = useWidgetComponents() const graphWidgets = ref(new Map>()) const graphNodeWidgetOrders = ref(new Map>()) const convertedRestoredValues = new Map() @@ -314,7 +315,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { return existing.state } - if (existing) useWidgetComponents().remove(widgetId) + if (existing) components.remove(widgetId) const state: WidgetState = { ...init, nodeId, @@ -458,7 +459,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { function deleteWidget(widgetId: WidgetId): boolean { if (!isWidgetId(widgetId)) return false - useWidgetComponents().remove(widgetId) + components.remove(widgetId) return releaseWidget(widgetId) } @@ -488,7 +489,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { widgets.delete(oldId) entity.state.name = name widgets.set(newId, entity) - useWidgetComponents().move(oldId, newId) + components.move(oldId, newId) if (index === -1) order.push(newId) else order.splice(index, 1, newId) @@ -566,7 +567,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { localNodeId: NodeId, { discardValues }: { discardValues: boolean } ): void { - if (discardValues) useWidgetComponents().clearNode(graphId, localNodeId) + if (discardValues) components.clearNode(graphId, localNodeId) const graphOrders = graphNodeWidgetOrders.value.get(graphId) if (!graphOrders) return @@ -582,7 +583,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { } function clearNode(graphId: UUID, nodeId: NodeId): void { - useWidgetComponents().clearNode(graphId, nodeId) + components.clearNode(graphId, nodeId) graphWidgetRestorations.get(graphId)?.delete(nodeId) const widgets = graphWidgets.value.get(graphId) if (widgets) { @@ -599,18 +600,13 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { } function clearGraph(graphId: UUID): void { - useWidgetComponents().clearGraph(graphId) + components.clearGraph(graphId) graphWidgets.value.delete(graphId) graphNodeWidgetOrders.value.delete(graphId) graphWidgetRestorations.delete(graphId) } - const components = useWidgetComponents() - return { - prepareNodeComponents: components.prepareNode, - adoptNodeComponents: components.adoptNode, - writeNodeComponents: components.writeNode, registerWidget, setNodeWidgetRestoration, clearNodeWidgetRestoration,