diff --git a/src/lib/litegraph/src/LGraph.serialise.test.ts b/src/lib/litegraph/src/LGraph.serialise.test.ts index 5a386686686..e9be5bb1097 100644 --- a/src/lib/litegraph/src/LGraph.serialise.test.ts +++ b/src/lib/litegraph/src/LGraph.serialise.test.ts @@ -11,10 +11,19 @@ import { import type { ISerialisedGraph } from '@/lib/litegraph/src/litegraph' import { useLinkStore } from '@/stores/linkStore' import { graphScopeOf } from '@/types/graphScopeId' +import { toNodeId } from '@/types/nodeId' import { test } from './__fixtures__/testExtensions' -beforeEach(() => setActivePinia(createTestingPinia({ stubActions: false }))) +const mockReportError = vi.hoisted(() => vi.fn()) +vi.mock('@/platform/telemetry/reportError', () => ({ + reportError: mockReportError +})) + +beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + mockReportError.mockClear() +}) describe('LGraph Serialisation', () => { test('can (de)serialise node / group titles', ({ expect, minimalGraph }) => { @@ -76,6 +85,94 @@ describe('LGraph Serialisation', () => { expect(copiedLink).toMatchObject(expectedLink) }) + test('falls back to live adapters when a node is missing from the store', ({ + expect + }) => { + const graph = new LGraph() + const registered = new LGraphNode('Registered') + graph.add(registered) + const adapterOnly = new LGraphNode('Adapter only') + adapterOnly.id = toNodeId(99) + graph._nodes.push(adapterOnly) + + const serialized = graph.serialize() + + expect(serialized.nodes.map(({ title }) => title)).toEqual([ + 'Registered', + 'Adapter only' + ]) + expect(mockReportError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + message: 'Graph serialization state mismatch' + }), + { + errorType: 'graph_serialization_state_mismatch', + context: { + graphId: graph.id, + mismatch: `live node ${adapterOnly.id} has no stored state` + } + } + ) + }) + + test('serialises a node held twice in the live array only once', ({ + expect + }) => { + const graph = new LGraph() + const node = new LGraphNode('Doubled') + graph.add(node) + graph._nodes.push(node) + + const serialized = graph.serialize() + + expect(serialized.nodes.map(({ title }) => title)).toEqual(['Doubled']) + expect(mockReportError).not.toHaveBeenCalled() + }) + + test('serialises a duplicated live node once through the fallback', ({ + expect + }) => { + const graph = new LGraph() + const node = new LGraphNode('Doubled') + graph.add(node) + graph._nodes.push(node) + const adapterOnly = new LGraphNode('Adapter only') + adapterOnly.id = toNodeId(99) + graph._nodes.push(adapterOnly) + + const serialized = graph.serialize() + + expect(serialized.nodes.map(({ title }) => title)).toEqual([ + 'Doubled', + 'Adapter only' + ]) + expect(mockReportError).toHaveBeenCalledOnce() + }) + + test('serialises one entry per id when distinct live nodes share an id', ({ + expect + }) => { + const graph = new LGraph() + const registered = new LGraphNode('Registered') + graph.add(registered) + const impostor = new LGraphNode('Impostor') + impostor.id = registered.id + graph._nodes.push(impostor) + const adapterOnly = new LGraphNode('Adapter only') + adapterOnly.id = toNodeId(99) + graph._nodes.push(adapterOnly) + + const serialized = graph.serialize() + + const ids = serialized.nodes.map(({ id }) => id) + expect(new Set(ids).size).toBe(ids.length) + expect(ids).toHaveLength(2) + expect(new Set(ids)).toEqual( + new Set([registered.id, adapterOnly.id].map(Number)) + ) + expect(mockReportError).toHaveBeenCalledOnce() + }) + test('round trips namespaced node and graph extension payloads', ({ expect, minimalGraph diff --git a/src/lib/litegraph/src/LGraph.test.ts b/src/lib/litegraph/src/LGraph.test.ts index 66d7a1cb24b..739ab5c6b41 100644 --- a/src/lib/litegraph/src/LGraph.test.ts +++ b/src/lib/litegraph/src/LGraph.test.ts @@ -59,9 +59,15 @@ import { nodeIdSpaceExhausted } from './__fixtures__/nodeIdSpaceExhausted' import { uniqueSubgraphNodeIds } from './__fixtures__/uniqueSubgraphNodeIds' import { test } from './__fixtures__/testExtensions' +const mockReportError = vi.hoisted(() => vi.fn()) +vi.mock('@/platform/telemetry/reportError', () => ({ + reportError: mockReportError +})) + beforeEach(() => { setActivePinia(createTestingPinia({ stubActions: false })) LiteGraph.registerNodeType('dummy', DummyNode) + mockReportError.mockClear() }) afterEach(() => LiteGraph.unregisterNodeType('dummy')) @@ -750,13 +756,19 @@ describe('Store-driven serialization parity', () => { }) => { const graph = createGraph(new DummyNode()) graph._nodes = [] - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) expect(graph.asSerialisable().nodes).toEqual([]) - expect(error).toHaveBeenCalledWith( - expect.stringMatching( - /Cannot serialize graph .* from store: node .* has no live adapter; using live graph nodes/ - ) + expect(mockReportError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + message: 'Graph serialization state mismatch' + }), + { + errorType: 'graph_serialization_state_mismatch', + context: { + graphId: graph.id, + mismatch: expect.stringMatching(/stored node .* has no live adapter/) + } + } ) }) diff --git a/src/lib/litegraph/src/LGraph.ts b/src/lib/litegraph/src/LGraph.ts index c5181d2520e..eeb594b05ef 100644 --- a/src/lib/litegraph/src/LGraph.ts +++ b/src/lib/litegraph/src/LGraph.ts @@ -12,6 +12,7 @@ import { } from '@/core/graph/nodeShell/nodeShellLifecycle' import type { UUID } from '@/utils/uuid' import { createUuidv4, zeroUuid } from '@/utils/uuid' +import { reportError } from '@/platform/telemetry/reportError' import { attachGroupLayout, attachNodeLayout, @@ -381,14 +382,29 @@ function serialiseStoredNodes(owner: LGraph, sortNodes: boolean) { const adapter = adapters.get(state.id) return adapter ? [{ adapter, state }] : [] }) - if (serialisers.length !== ordered.length) { - const missing = ordered.find((state) => !adapters.has(state.id)) - console.error( - `Cannot serialize graph ${owner.id} from store: node ${missing?.id} has no live adapter; using live graph nodes` - ) + if ( + serialisers.length !== ordered.length || + ordered.length !== adapters.size + ) { + const liveNodes = [...adapters.values()] + const missingState = ordered.find((state) => !adapters.has(state.id)) + let missingAdapter: LGraphNode | undefined + if (missingState === undefined) { + const stateIds = new Set(ordered.map((state) => state.id)) + missingAdapter = liveNodes.find((adapter) => !stateIds.has(adapter.id)) + } + const mismatch = missingState + ? `stored node ${missingState.id} has no live adapter` + : missingAdapter + ? `live node ${missingAdapter.id} has no stored state` + : `${ordered.length} stored nodes do not match ${adapters.size} live nodes` + reportError(new Error('Graph serialization state mismatch'), { + errorType: 'graph_serialization_state_mismatch', + context: { graphId: owner.id, mismatch } + }) const nodes = sortNodes - ? [...owner._nodes].sort((a, b) => compareNodeIds(a.id, b.id)) - : owner._nodes + ? [...liveNodes].sort((a, b) => compareNodeIds(a.id, b.id)) + : liveNodes return nodes.map((node) => node.serialize()) } return serialisers.map(({ adapter, state }) => diff --git a/src/lib/litegraph/src/LLink.spreadCopy.test.ts b/src/lib/litegraph/src/LLink.spreadCopy.test.ts index fb4c13bd702..4300367bf69 100644 --- a/src/lib/litegraph/src/LLink.spreadCopy.test.ts +++ b/src/lib/litegraph/src/LLink.spreadCopy.test.ts @@ -52,15 +52,18 @@ describe('plain-object copies of LLink (uncovered)', () => { it('carries topology onto a spread copy of a link', () => { const { graph, link } = connectedPair(toRerouteId(7)) - const copy: Partial = { ...graph.links[link.id] } + const stored = graph.links[link.id] + stored.type = 'FLOAT' + stored.parentId = toRerouteId(8) + const copy: Partial = { ...stored } expect(copy.id).toBe(link.id) - expect(copy.type).toBe(link.type) + expect(copy.type).toBe('FLOAT') expect(copy.origin_id).toBe(link.origin_id) expect(copy.origin_slot).toBe(link.origin_slot) expect(copy.target_id).toBe(link.target_id) expect(copy.target_slot).toBe(link.target_slot) - expect(copy.parentId).toBe(link.parentId) + expect(copy.parentId).toBe(toRerouteId(8)) }) it('rewires Custom-Scripts consumers from copied links (#15594)', () => { diff --git a/src/lib/litegraph/src/linkDeduplication.remapReferences.test.ts b/src/lib/litegraph/src/linkDeduplication.remapReferences.test.ts new file mode 100644 index 00000000000..ed8cdf20440 --- /dev/null +++ b/src/lib/litegraph/src/linkDeduplication.remapReferences.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest' + +import { toLinkId } from '@/types/linkId' + +import { duplicateLinksRoot } from './__fixtures__/duplicateLinks' +import { remapLinkReferences } from './linkDeduplication' + +describe('remapLinkReferences', () => { + it('remaps every serialized reference kind to the surviving link', () => { + const data = { + ...structuredClone(duplicateLinksRoot), + inputs: [{ id: 'input', name: 'input', type: 'number', linkIds: [2] }], + outputs: [{ id: 'output', name: 'output', type: 'number', linkIds: [2] }], + reroutes: [{ id: 1, pos: [0, 0] as [number, number], linkIds: [2] }], + extra: { + linkExtensions: [{ id: toLinkId(2), parentId: undefined }] + } + } + const nodes = data.nodes + expect(nodes).toBeDefined() + if (!nodes) return + const targetInput = nodes[1].inputs?.[0] + expect(targetInput).toBeDefined() + if (!targetInput) return + targetInput.link = 2 + + remapLinkReferences( + data, + new Map([ + [2, 1], + [3, 1] + ]) + ) + + expect(nodes[1].inputs?.[0].link).toBe(1) + expect(nodes[0].outputs?.[0].links).toEqual([1]) + expect(data.inputs[0].linkIds).toEqual([1]) + expect(data.outputs[0].linkIds).toEqual([1]) + expect(data.reroutes[0].linkIds).toEqual([1]) + expect(data.extra.linkExtensions?.[0].id).toBe(1) + }) + + it('preserves a null input reference', () => { + const data = structuredClone(duplicateLinksRoot) + const input = data.nodes?.[0].inputs?.[0] + expect(input).toBeDefined() + if (!input) return + + remapLinkReferences(data, new Map([[2, 1]])) + + expect(input.link).toBeNull() + }) + + it('accepts omitted optional reference collections', () => { + const data = structuredClone(duplicateLinksRoot) + if (!data.nodes) return + data.nodes[0].inputs = undefined + data.nodes[0].outputs = undefined + + expect(() => remapLinkReferences(data, new Map([[2, 1]]))).not.toThrow() + }) + + it('preserves an unmapped link reference', () => { + const data = structuredClone(duplicateLinksRoot) + const output = data.nodes?.[0].outputs?.[0] + expect(output).toBeDefined() + if (!output) return + output.links = [99] + + remapLinkReferences(data, new Map([[2, 1]])) + + expect(output.links).toEqual([99]) + }) + + it('collapses duplicate aliases of the surviving link', () => { + const data = structuredClone(duplicateLinksRoot) + const output = data.nodes?.[0].outputs?.[0] + expect(output).toBeDefined() + if (!output) return + output.links = [2, 3] + + remapLinkReferences( + data, + new Map([ + [2, 1], + [3, 1] + ]) + ) + + expect(output.links).toEqual([1]) + }) +}) diff --git a/src/lib/litegraph/src/widgetValueNullContract.test.ts b/src/lib/litegraph/src/widgetValueNullContract.test.ts index 2e85977632d..2136df171a6 100644 --- a/src/lib/litegraph/src/widgetValueNullContract.test.ts +++ b/src/lib/litegraph/src/widgetValueNullContract.test.ts @@ -12,6 +12,7 @@ import { import type { TWidgetValue } from '@/lib/litegraph/src/litegraph' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' +import type { ISerialisedNode } from '@/lib/litegraph/src/types/serialisation' vi.mock('@/platform/telemetry', () => ({ useTelemetry: () => ({ @@ -27,6 +28,10 @@ vi.mock('@/platform/nodeReplacement/cnrIdUtil', () => ({ const NODE_TYPE = 'test/NullContractNode' const DEFAULT_VALUE = 'default' +const nullSlotTypeContract = [30, null, 12345] satisfies NonNullable< + ISerialisedNode['widgets_values'] +> + function registerNullContractNode(): void { class NullContractNode extends LGraphNode { constructor() { @@ -109,6 +114,23 @@ describe('widget value null contract', () => { }) describe('LGraphNode.configure (workflow read)', () => { + it('restores a typed null in the middle positional slot', () => { + LiteGraph.namedValuesRestore = false + const graph = new LGraph() + const node = new LGraphNode('Three widgets') + node.addWidget('number', 'first', 0, () => undefined) + node.addWidget('number', 'nullable', 0, () => undefined) + node.addWidget('number', 'third', 0, () => undefined) + graph.add(node) + + node.configure({ + ...node.serialize(), + widgets_values: nullSlotTypeContract + }) + + expect(node.widgets?.map(({ value }) => value)).toEqual([30, null, 12345]) + }) + it('restores a null widget value through the indexed path', () => { LiteGraph.namedValuesRestore = false const { graph } = makeGraphWithWidget(null) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index af86f19dba0..97b11a447c8 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -65,6 +65,20 @@ describe('widgetId', () => { const id = widgetId(graphId, toNodeId('node-7'), 'value') expect(id).toBe(`${graphId}:node-7:value`) }) + + it('percent-encodes separator-colliding node ids and names', () => { + const first = widgetId(graphId, toNodeId('node:7'), 'value') + const second = widgetId(graphId, toNodeId('node'), '7:value') + + expect(first).not.toBe(second) + expect(first).toContain('node%3A7:value') + expect(second).toContain('node:7%3Avalue') + expect(parseWidgetId(first)).toEqual({ + graphId, + nodeId: toNodeId('node:7'), + name: 'value' + }) + }) }) describe('parseWidgetId', () => { diff --git a/src/utils/litegraphUtil.test.ts b/src/utils/litegraphUtil.test.ts index 524dd79cde2..2b30782493f 100644 --- a/src/utils/litegraphUtil.test.ts +++ b/src/utils/litegraphUtil.test.ts @@ -224,6 +224,78 @@ describe('getWidgetIdForNode', () => { ]) }) + it('maps every widget when one duplicate cannot be renamed', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const node = fakeNode(42) + const first = { + name: 'shared', + type: 'number', + value: 1, + options: {}, + y: 0 + } + const frozen = Object.freeze({ + name: 'shared', + type: 'number', + value: 2, + options: {}, + y: 0 + }) + node.widgets = [first, frozen] + + const mapped = mapLiveWidgetsById(node) + expect([...mapped.keys()]).toEqual([ + widgetId(graphId, toNodeId(42), 'shared'), + widgetId(graphId, toNodeId(42), 'shared#1') + ]) + const [mappedFirst, mappedFrozen] = mapped.values() + expect(mappedFirst).toBe(first) + expect(mappedFrozen).toBe(frozen) + expect(node.widgets.map(({ name }) => name)).toEqual(['shared', 'shared']) + expect(warn).toHaveBeenCalledOnce() + warn.mockClear() + expect(getWidgetIdForNode(node, frozen)).toBe( + widgetId(graphId, toNodeId(42), 'shared#1') + ) + expect(warn).toHaveBeenCalledOnce() + }) + + it('maps repeated widget object references only once', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const node = fakeNode(42) + const first = { + name: 'shared', + type: 'number', + value: 1, + options: {}, + y: 0 + } + const frozen = Object.freeze({ + name: 'shared', + type: 'number', + value: 2, + options: {}, + y: 0 + }) + node.widgets = [first, first, frozen] + + const mapped = mapLiveWidgetsById(node) + + expect([...mapped.keys()]).toEqual([ + widgetId(graphId, toNodeId(42), 'shared'), + widgetId(graphId, toNodeId(42), 'shared#1') + ]) + const [mappedFirst, mappedFrozen] = mapped.values() + expect(mappedFirst).toBe(first) + expect(mappedFrozen).toBe(frozen) + expect(node.widgets.map(({ name }) => name)).toEqual([ + 'shared', + 'shared', + 'shared' + ]) + expect(warn).toHaveBeenCalledOnce() + }) + it('returns undefined when the node has no graph', () => { const node = fakeNode(1, { detached: true }) expect(getWidgetIdForNode(node, { name: 'x' })).toBeUndefined() diff --git a/src/utils/litegraphUtil.ts b/src/utils/litegraphUtil.ts index 5997d9f37e3..6a76eacc398 100644 --- a/src/utils/litegraphUtil.ts +++ b/src/utils/litegraphUtil.ts @@ -351,14 +351,29 @@ export function mapLiveWidgetsById( ): Map { const byId = new Map() const widgets = node.widgets ?? [] - if (!ensureUniqueWidgetNames(widgets)) return byId + const distinctWidgets = [...new Set(widgets)] + const namesAreUnique = ensureUniqueWidgetNames(distinctWidgets) const graphId = node.graph?.rootGraph.id const nodeId = parseNodeId(node.id) - for (const widget of widgets) { + const usedNames = new Set() + const reservedNames = new Set(distinctWidgets.map(({ name }) => name)) + for (const widget of distinctWidgets) { + let name = widget.name + if (!namesAreUnique && usedNames.has(name)) { + let suffix = 1 + while ( + usedNames.has(`${name}#${suffix}`) || + reservedNames.has(`${name}#${suffix}`) + ) { + suffix++ + } + name = `${name}#${suffix}` + } + usedNames.add(name) const id = widget.widgetId ?? (graphId && nodeId && nodeId !== UNASSIGNED_NODE_ID - ? widgetId(graphId, nodeId, widget.name) + ? widgetId(graphId, nodeId, name) : undefined) if (id) byId.set(id, widget) }