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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 98 additions & 1 deletion src/lib/litegraph/src/LGraph.serialise.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down Expand Up @@ -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
Expand Down
22 changes: 17 additions & 5 deletions src/lib/litegraph/src/LGraph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down Expand Up @@ -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/)
}
}
)
})

Expand Down
30 changes: 23 additions & 7 deletions src/lib/litegraph/src/LGraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 }) =>
Expand Down
9 changes: 6 additions & 3 deletions src/lib/litegraph/src/LLink.spreadCopy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<LLink> = { ...graph.links[link.id] }
const stored = graph.links[link.id]
stored.type = 'FLOAT'
stored.parentId = toRerouteId(8)
const copy: Partial<LLink> = { ...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)', () => {
Expand Down
92 changes: 92 additions & 0 deletions src/lib/litegraph/src/linkDeduplication.remapReferences.test.ts
Original file line number Diff line number Diff line change
@@ -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])
})
})
22 changes: 22 additions & 0 deletions src/lib/litegraph/src/widgetValueNullContract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: () => ({
Expand All @@ -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() {
Expand Down Expand Up @@ -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)
Expand Down
14 changes: 14 additions & 0 deletions src/types/widgetId.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Loading
Loading