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..771d61e28ef --- /dev/null +++ b/docs/adr/WIDGET-COMPONENTS-0058-shared-component-lifecycle-and-persistence.md @@ -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. 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/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 443d82eb995..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' @@ -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, @@ -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) } /** @@ -1412,7 +1417,6 @@ export class LGraphNode } serializeFromStoreState(state: NodeState): ISerialisedNode { - // create serialization object const o: ISerialisedNode = { id: serializeNodeId(state.id), type: state.type, @@ -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) => @@ -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)) 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, diff --git a/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts b/src/platform/workflowErrors/nodeReplacement/useNodeReplacement.test.ts index 61144092fcf..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, @@ -163,6 +165,7 @@ function createPlaceholderNode( mode: 0, flags: {}, has_errors: true, + properties: {}, last_serialization: { id, type, @@ -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: {} })), @@ -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]) 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/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..75ed34d2236 --- /dev/null +++ b/src/stores/widgetComponentStore.ts @@ -0,0 +1,121 @@ +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 { + isWidgetId, + isWidgetNameUnreadable, + 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 { + const { graphId, nodeId } = parseWidgetId(id) + return components.get(graphId)?.get(String(nodeId))?.get(id) + } + + function set(id: WidgetId, component: T | undefined): void { + 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 { 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 { + const nodes = components.get(graphId) + nodes?.delete(String(nodeId)) + if (!nodes?.size) components.delete(graphId) + } + + function clearGraph(graphId: UUID): void { + components.delete(graphId) + } + + function writeNode( + graphId: UUID, + nodeId: NodeId, + properties: Record + ): void { + 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] + } + + 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 || isWidgetNameUnreadable({ name })) continue + const id = widgetId(graphId, nodeId, name) + if (isWidgetId(id)) set(id, parsed.data) + } + } + + 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 new file mode 100644 index 00000000000..8c9caf73ff2 --- /dev/null +++ b/src/stores/widgetComponents.test.ts @@ -0,0 +1,372 @@ +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' + +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('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( + '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') + 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') + 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('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') + 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('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') + const otherNode = new LGraphNode('other owner') + graph.add(node) + 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(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/widgetComponents.ts b/src/stores/widgetComponents.ts new file mode 100644 index 00000000000..27ee8e509da --- /dev/null +++ b/src/stores/widgetComponents.ts @@ -0,0 +1,72 @@ +import { useWidgetFolderLockStore } from './widgetFolderLockStore' +import { useWidgetHeightStore } from './widgetHeightStore' + +export const widgetComponentStores = [ + useWidgetFolderLockStore, + useWidgetHeightStore +] + +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']> + ) { + 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 { + prepareNode, + 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..67c93372a2f 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' @@ -105,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() @@ -296,12 +299,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 +315,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { return existing.state } + if (existing) components.remove(widgetId) const state: WidgetState = { ...init, nodeId, @@ -450,7 +448,7 @@ 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) @@ -458,6 +456,13 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { return graphWidgets.value.get(graphId)?.delete(widgetId) ?? false } + function deleteWidget(widgetId: WidgetId): boolean { + if (!isWidgetId(widgetId)) return false + + components.remove(widgetId) + return releaseWidget(widgetId) + } + function renameWidget( oldId: WidgetId, newId: WidgetId @@ -484,6 +489,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { widgets.delete(oldId) entity.state.name = name widgets.set(newId, entity) + components.move(oldId, newId) if (index === -1) order.push(newId) else order.splice(index, 1, newId) @@ -556,17 +562,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) components.clearNode(graphId, localNodeId) const graphOrders = graphNodeWidgetOrders.value.get(graphId) if (!graphOrders) return @@ -582,6 +583,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { } function clearNode(graphId: UUID, nodeId: NodeId): void { + components.clearNode(graphId, nodeId) graphWidgetRestorations.get(graphId)?.delete(nodeId) const widgets = graphWidgets.value.get(graphId) if (widgets) { @@ -598,6 +600,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { } function clearGraph(graphId: UUID): void { + components.clearGraph(graphId) graphWidgets.value.delete(graphId) graphNodeWidgetOrders.value.delete(graphId) graphWidgetRestorations.delete(graphId) @@ -617,6 +620,7 @@ export const useWidgetValueStore = defineStore('widgetValue', () => { setLabel, setOptions, updateOptions, + releaseWidget, deleteWidget, renameWidget, getNodeWidgets,