From 89c69cb947b5dbf582c289da72a527b145c8a1c0 Mon Sep 17 00:00:00 2001 From: "claude[bot]" <209825114+claude[bot]@users.noreply.github.com> Date: Tue, 22 Sep 2026 00:59:49 +0000 Subject: [PATCH] fix: keep hand-wired autogrow connections on their real slot after an agent slot sync (PM-1449) (#18279) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _Requested by **Christian Byrne** · [Slack thread](https://comfy-organization.slack.com/archives/C0BGH348Z0C/p1789985885071859)_ A hand-wired connection into an autogrow port could be serialized against the wrong input after an agent slot sync. `updateNodeSlots` replaced the store's slot arrays even though the live `LGraphNode` retained the original arrays, leaving serialization and the canvas with different slot layouts. - Preserve the registered input and output arrays and patch matching slot objects in place. - Match duplicate names occurrence by occurrence. Insert incoming-only slots before the next matching live slot while retaining existing-only slots and their order. - Treat `NodeInputSlot` and `NodeOutputSlot` connectivity as link-store-owned explicitly, without probing prototypes or reading deprecated `link`/`links` accessors. - Reduce CRDT slot records to supported serialized fields before they reach live slot objects. - Cover the PM-1449 serialization path, middle insertion, duplicate input/output names, external runtime fields, live output identity/reactivity, partial snapshots, and self-aliased live slots. The `updateNodeSlots` signature is unchanged. `LGraphNode` binds its slot arrays to the registered `NodeState` when it is constructed. Reassigning `state.inputs` or `state.outputs` later detached the store from the live node. Subsequent local autogrow and connection changes updated the canvas array, while `LGraph.serialize()` read the stale store array and associated positional topology with the wrong slot. The fix keeps the shared arrays stable. Existing slot objects also remain stable so Vue dependents continue to invalidate through the reactive object. Connectivity remains authoritative in `linkStore` for live slot classes and in the descriptor for plain store records. - #18021 addresses the same array-detachment root cause for queued execution. - #18101 covers a separate dynamic-widget slot-offset issue. - #18275 changes agent input reconciliation and may overlap when either PR rebases onto the other. - `pnpm vitest run src/stores/nodeDataStore.test.ts` — 29 passed. - `pnpm vitest run src/workbench/extensions/agent/crdt/graphMutations.test.ts` — 50 passed, 1 expected failure. - `pnpm vitest run src/workbench/extensions/agent src/stores/nodeDataStore.test.ts src/core/graph/widgets/dynamicWidgets.test.ts` — 123 files, 1,919 passed, 7 expected failures. - `pnpm typecheck` — passed. - Scoped ESLint, type-aware oxlint, and oxfmt checks — passed. - Commit hook checks and pre-push `knip --cache` — passed. Fixes PM-1449 (child of PM-1442). --------- Co-authored-by: Amp --- src/stores/nodeDataStore.test.ts | 412 +++++++++++++++++- src/stores/nodeDataStore.ts | 128 +++++- .../agent/crdt/graphMutations.test.ts | 33 ++ .../extensions/agent/crdt/graphMutations.ts | 90 +++- 4 files changed, 641 insertions(+), 22 deletions(-) diff --git a/src/stores/nodeDataStore.test.ts b/src/stores/nodeDataStore.test.ts index f9d256c6d36..bf8494b2ac7 100644 --- a/src/stores/nodeDataStore.test.ts +++ b/src/stores/nodeDataStore.test.ts @@ -1,13 +1,19 @@ import { createTestingPinia } from '@pinia/testing' import { setActivePinia } from 'pinia' -import { assert, beforeEach, describe, expect, it } from 'vitest' +import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import { computed } from 'vue' import { transferReplacementOwnership } from '@/core/graph/nodeShell/nodeShellState' -import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import { + LGraph, + LGraphNode, + NodeInputSlot, + NodeOutputSlot +} from '@/lib/litegraph/src/litegraph' import type { ISerialisedNode } from '@/lib/litegraph/src/types/serialisation' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' import type { GraphScope } from '@/types/graphScopeId' +import { toLinkId } from '@/types/linkId' import type { NodeState } from '@/types/nodeState' import { toNodeId } from '@/types/nodeId' import { @@ -20,6 +26,7 @@ import type { UUID } from '@/utils/uuid' import { useNodeDataStore } from './nodeDataStore' const rootA: UUID = 'root-a' +type NodeSlots = Pick function node(id: number, graphId: UUID = rootA): NodeState { return createNodeState({ id: toNodeId(id), graphId, title: `Node ${id}` }) @@ -196,6 +203,109 @@ describe('useNodeDataStore', () => { ).toBe(false) expect(registered.title).toBe('Renamed') }) + + it.for([ + { + slotKind: 'input', + existing: (): NodeSlots => ({ + inputs: [createMockNodeInputSlot({ name: 'a', link: toLinkId(1) })], + outputs: [] + }), + incoming: (): NodeSlots => ({ + inputs: [createMockNodeInputSlot({ name: 'a', link: toLinkId(2) })], + outputs: [] + }), + read: (state: NodeState) => state.inputs[0]?.link, + expected: toLinkId(2) + }, + { + slotKind: 'output', + existing: (): NodeSlots => ({ + inputs: [], + outputs: [createMockNodeOutputSlot({ name: 'a', links: [toLinkId(1)] })] + }), + incoming: (): NodeSlots => ({ + inputs: [], + outputs: [ + createMockNodeOutputSlot({ + name: 'a', + links: [toLinkId(2), toLinkId(3)] + }) + ] + }), + read: (state: NodeState) => state.outputs[0]?.links, + expected: [toLinkId(2), toLinkId(3)] + } + ])( + 'updates connectivity on matched plain $slotKind slots', + ({ existing, incoming, read, expected }) => { + const store = useNodeDataStore() + const scope = graphScope(rootA, rootA) + const registered = store.registerNode( + scope, + createNodeState({ id: toNodeId(1), graphId: rootA, ...existing() }) + ) + assert(registered) + + store.updateNodeSlots(scope, registered.id, incoming()) + + expect(read(registered)).toEqual(expected) + } + ) + + it.for([ + { + slotKind: 'input', + existing: (): NodeSlots => ({ + inputs: [ + createMockNodeInputSlot({ name: 'same', label: 'old-1' }), + createMockNodeInputSlot({ name: 'same', label: 'old-2' }) + ], + outputs: [] + }), + incoming: (): NodeSlots => ({ + inputs: [ + createMockNodeInputSlot({ name: 'same', label: 'new-1' }), + createMockNodeInputSlot({ name: 'same', label: 'new-2' }) + ], + outputs: [] + }), + read: (state: NodeState) => state.inputs.map(({ label }) => label) + }, + { + slotKind: 'output', + existing: (): NodeSlots => ({ + inputs: [], + outputs: [ + createMockNodeOutputSlot({ name: 'same', label: 'old-1' }), + createMockNodeOutputSlot({ name: 'same', label: 'old-2' }) + ] + }), + incoming: (): NodeSlots => ({ + inputs: [], + outputs: [ + createMockNodeOutputSlot({ name: 'same', label: 'new-1' }), + createMockNodeOutputSlot({ name: 'same', label: 'new-2' }) + ] + }), + read: (state: NodeState) => state.outputs.map(({ label }) => label) + } + ])( + 'updates duplicate $slotKind names by occurrence', + ({ existing, incoming, read }) => { + const store = useNodeDataStore() + const scope = graphScope(rootA, rootA) + const registered = store.registerNode( + scope, + createNodeState({ id: toNodeId(1), graphId: rootA, ...existing() }) + ) + assert(registered) + + store.updateNodeSlots(scope, registered.id, incoming()) + + expect(read(registered)).toEqual(['new-1', 'new-2']) + } + ) }) describe('nodeDataStore registration via LGraph', () => { @@ -301,6 +411,58 @@ describe('nodeDataStore registration via LGraph', () => { expect(state?.outputs.map((o) => o.name)).toEqual(['latent']) }) + it('keeps live slot edits visible after a remote slot sync', () => { + const graph = new LGraph() + const lgraphNode = new LGraphNode('test') + lgraphNode.addInput('old', 'INT') + lgraphNode.addOutput('old', 'INT') + graph.add(lgraphNode) + const state = registeredState(graph, lgraphNode) + assert.exists(state) + const inputNames = computed(() => state.inputs.map((input) => input.name)) + const outputNames = computed(() => + state.outputs.map((output) => output.name) + ) + expect(inputNames.value).toEqual(['old']) + expect(outputNames.value).toEqual(['old']) + + useNodeDataStore().updateNodeSlots( + graphScope(graph.rootGraph.id, graph.id), + lgraphNode.id, + { + inputs: [ + createMockNodeInputSlot({ + name: 'old', + type: 'IMAGE', + label: 'Remote input' + }) + ], + outputs: [ + createMockNodeOutputSlot({ + name: 'old', + type: 'IMAGE', + label: 'Remote output' + }) + ] + } + ) + lgraphNode.addInput('image_2', 'IMAGE') + lgraphNode.addOutput('mask', 'MASK') + + expect(inputNames.value).toEqual(['old', 'image_2']) + expect(outputNames.value).toEqual(['old', 'mask']) + expect(state.inputs[0]?.label).toBe('Remote input') + expect(state.outputs[0]?.label).toBe('Remote output') + expect(lgraphNode.inputs.map((input) => input.name)).toEqual([ + 'old', + 'image_2' + ]) + expect(lgraphNode.outputs.map((output) => output.name)).toEqual([ + 'old', + 'mask' + ]) + }) + it('reflects adds, reorders and removes without re-registration', () => { const graph = new LGraph() const lgraphNode = new LGraphNode('test') @@ -328,6 +490,209 @@ describe('nodeDataStore registration via LGraph', () => { expect(state?.inputs.map((i) => i.name)).toEqual(['third', 'first']) }) + it('serializes a hand-made link on its actual slot after an earlier agent slot sync (PM-1449)', () => { + const graph = new LGraph() + const source = new LGraphNode('source') + source.addOutput('out', 'IMAGE') + graph.add(source) + + const node = new LGraphNode('test') + node.addInput('videos.video0', 'IMAGE') + node.addInput('codec', 'COMBO') + graph.add(node) + const scope = graphScope(graph.id, graph.id) + + useNodeDataStore().updateNodeSlots(scope, node.id, { + inputs: [...node.inputs], + outputs: [...node.outputs] + }) + + node.addInput('videos.video1', 'IMAGE') + const grownInput = node.inputs.pop() + assert(grownInput) + node.inputs.splice(1, 0, grownInput) + source.connect(0, node, 1) + + const nodeJson = graph + .serialize() + .nodes.find((n) => String(n.id) === String(node.id)) + const names = nodeJson?.inputs?.map((i) => i.name) + + expect(names).toEqual(['videos.video0', 'videos.video1', 'codec']) + const linkedInput = nodeJson?.inputs?.find((i) => i.link !== null) + expect(linkedInput?.name).toBe('videos.video1') + }) + + it('never removes or reorders a live slot missing from an agent slot sync', () => { + const graph = new LGraph() + const source = new LGraphNode('source') + source.addOutput('out', 'IMAGE') + graph.add(source) + + const node = new LGraphNode('test') + node.addInput('a', 'IMAGE') + node.addInput('b', 'IMAGE') + node.addInput('c', 'IMAGE') + graph.add(node) + source.connect(0, node, 1) + expect(node.isInputConnected(1)).toBe(true) + + const liveInputs = node.inputs + const [liveA, , liveC] = liveInputs + const scope = graphScope(graph.id, graph.id) + useNodeDataStore().updateNodeSlots(scope, node.id, { + inputs: [ + { ...liveC, name: 'c', type: 'IMAGE' }, + { ...liveA, name: 'a', type: 'IMAGE' } + ], + outputs: [...node.outputs] + }) + + expect(registeredState(graph, node)?.inputs).toBe(liveInputs) + expect(node.inputs.map((i) => i.name)).toEqual(['a', 'b', 'c']) + expect(node.inputs[0]).toBe(liveA) + expect(node.inputs[2]).toBe(liveC) + expect(node.isInputConnected(1)).toBe(true) + }) + + it('inserts a new synced slot at its incoming topology index', () => { + const graph = new LGraph() + const source = new LGraphNode('source') + source.addOutput('out', 'IMAGE') + graph.add(source) + + const node = new LGraphNode('test') + node.addInput('a', 'IMAGE') + node.addInput('c', 'IMAGE') + graph.add(node) + source.connect(0, node, 1) + + useNodeDataStore().updateNodeSlots( + graphScope(graph.id, graph.id), + node.id, + { + inputs: [ + createMockNodeInputSlot({ name: 'a', type: 'IMAGE' }), + createMockNodeInputSlot({ name: 'b', type: 'IMAGE' }), + createMockNodeInputSlot({ name: 'c', type: 'IMAGE' }) + ], + outputs: [] + } + ) + + expect(node.inputs.map(({ name }) => name)).toEqual(['a', 'b', 'c']) + expect(node.isInputConnected(1)).toBe(true) + expect(node.isInputConnected(2)).toBe(false) + }) + + it('merges matched slot fields onto the existing object instead of replacing it', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + node.addInput('a', 'IMAGE') + graph.add(node) + const original = node.inputs[0] + + const scope = graphScope(graph.id, graph.id) + useNodeDataStore().updateNodeSlots(scope, node.id, { + inputs: [ + { + name: 'a', + type: 'IMAGE', + label: 'renamed', + boundingRect: [0, 0, 0, 0] + } + ], + outputs: [...node.outputs] + }) + + expect(node.inputs[0]).toBe(original) + expect(node.inputs[0].label).toBe('renamed') + }) + + it('preserves live output identity and reactivity during a partial sync', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + node.addOutput('a', 'IMAGE') + node.addOutput('local', 'IMAGE') + graph.add(node) + const store = useNodeDataStore() + const liveOutputs = node.outputs + const [original, local] = liveOutputs + const label = computed( + () => store.getNode(graph.id, node.id)?.outputs[0]?.label + ) + + store.updateNodeSlots(graphScope(graph.id, graph.id), node.id, { + inputs: [], + outputs: [ + createMockNodeOutputSlot({ + name: 'a', + type: 'IMAGE', + label: 'remote' + }) + ] + }) + + expect(node.outputs).toBe(liveOutputs) + expect(node.outputs[0]).toBe(original) + expect(node.outputs[1]).toBe(local) + expect(label.value).toBe('remote') + }) + + it('does not copy external fields into live slot internals', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + node.addInput('a', 'IMAGE') + graph.add(node) + const incoming = { + name: 'a', + type: 'IMAGE', + boundingRect: [0, 0, 0, 0] as const, + _node: new LGraphNode('payload') + } + + useNodeDataStore().updateNodeSlots( + graphScope(graph.id, graph.id), + node.id, + { + inputs: [incoming], + outputs: [] + } + ) + + const [liveInput] = node.inputs + assert(liveInput instanceof NodeInputSlot) + expect(liveInput.node).toBe(node) + }) + + it('keeps a cached computed over a merged slot field up to date', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + node.addInput('a', 'IMAGE') + graph.add(node) + const scope = graphScope(graph.id, graph.id) + const store = useNodeDataStore() + + const label = computed( + () => store.getNode(graph.id, node.id)?.inputs[0]?.label + ) + expect(label.value).toBeUndefined() + + store.updateNodeSlots(scope, node.id, { + inputs: [ + { + name: 'a', + type: 'IMAGE', + label: 'remote', + boundingRect: [0, 0, 0, 0] + } + ], + outputs: [...node.outputs] + }) + + expect(label.value).toBe('remote') + }) + it('moves registered state to a same-id replacement without changing store membership', () => { const graph = new LGraph() const original = new LGraphNode('original') @@ -381,6 +746,39 @@ describe('nodeDataStore registration via LGraph', () => { expect(replacement._graphScope).toBeUndefined() }) + it('never reads the deprecated link accessor merging a node’s own unchanged live slots into itself', () => { + const graph = new LGraph() + const source = new LGraphNode('source') + source.addOutput('out', 'IMAGE') + graph.add(source) + + const node = new LGraphNode('test') + node.addInput('in', 'IMAGE') + graph.add(node) + source.connect(0, node, 0) + expect(node.isInputConnected(0)).toBe(true) + expect(source.isOutputConnected(0)).toBe(true) + + const inputLinkGetter = vi.spyOn(NodeInputSlot.prototype, 'link', 'get') + const outputLinksGetter = vi.spyOn(NodeOutputSlot.prototype, 'links', 'get') + const scope = graphScope(graph.id, graph.id) + const store = useNodeDataStore() + + store.updateNodeSlots(scope, node.id, { + inputs: node.inputs, + outputs: [...node.outputs] + }) + store.updateNodeSlots(scope, source.id, { + inputs: [...source.inputs], + outputs: source.outputs + }) + + expect(inputLinkGetter).not.toHaveBeenCalled() + expect(outputLinksGetter).not.toHaveBeenCalled() + expect(node.isInputConnected(0)).toBe(true) + expect(source.isOutputConnected(0)).toBe(true) + }) + it('drops the registration when the node is removed', () => { const graph = new LGraph() const lgraphNode = new LGraphNode('test') @@ -390,4 +788,14 @@ describe('nodeDataStore registration via LGraph', () => { expect(registeredState(graph, lgraphNode)).toBeUndefined() }) + + it('does not crash the litegraph module graph on load', async () => { + vi.resetModules() + await import('@/lib/litegraph/src/LGraphGroup') + await import('@/stores/nodeDataStore') + const { SubgraphNode } = + await import('@/lib/litegraph/src/subgraph/SubgraphNode') + + expect(SubgraphNode).toBeTypeOf('function') + }) }) diff --git a/src/stores/nodeDataStore.ts b/src/stores/nodeDataStore.ts index 5d991493ca1..20c5c778d0a 100644 --- a/src/stores/nodeDataStore.ts +++ b/src/stores/nodeDataStore.ts @@ -1,6 +1,12 @@ import { defineStore } from 'pinia' import { reactive, toRaw } from 'vue' +import type { + INodeInputSlot, + INodeOutputSlot, + INodeSlot +} from '@/lib/litegraph/src/interfaces' +import { NodeInputSlot, NodeOutputSlot } from '@/lib/litegraph/src/litegraph' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' import type { GraphScope, @@ -12,6 +18,119 @@ import type { NodeId } from '@/types/nodeId' import type { RemoteMutationContext } from '@/types/graphMutationContext' import type { UUID } from '@/utils/uuid' +const SERIALISABLE_SLOT_FIELDS = [ + 'name', + 'localized_name', + 'label', + 'type', + 'dir', + 'removable', + 'shape', + 'color_off', + 'color_on', + 'locked', + 'nameLocked', + 'pos' +] as const satisfies readonly (keyof INodeSlot)[] + +function copyOwnFields( + target: T, + source: T, + fields: readonly (keyof T)[] +): void { + Object.assign( + target, + Object.fromEntries( + fields.flatMap((field) => + Object.hasOwn(source, field) ? [[field, source[field]]] : [] + ) + ) + ) +} + +function patchInputSlot( + target: INodeInputSlot, + incoming: INodeInputSlot +): void { + copyOwnFields(target, incoming, SERIALISABLE_SLOT_FIELDS) + copyOwnFields(target, incoming, ['widget']) + if ( + !(toRaw(target) instanceof NodeInputSlot) && + Object.hasOwn(incoming, 'link') + ) { + target.link = incoming.link + } +} + +function patchOutputSlot( + target: INodeOutputSlot, + incoming: INodeOutputSlot +): void { + copyOwnFields(target, incoming, SERIALISABLE_SLOT_FIELDS) + copyOwnFields(target, incoming, ['slot_index']) + if ( + !(toRaw(target) instanceof NodeOutputSlot) && + Object.hasOwn(incoming, 'links') + ) { + target.links = incoming.links + } +} + +function copyInputSlot(incoming: INodeInputSlot): INodeInputSlot { + const slot: INodeInputSlot = { + name: incoming.name, + type: incoming.type, + boundingRect: incoming.boundingRect + } + patchInputSlot(slot, incoming) + return slot +} + +function copyOutputSlot(incoming: INodeOutputSlot): INodeOutputSlot { + const slot: INodeOutputSlot = { + name: incoming.name, + type: incoming.type, + boundingRect: incoming.boundingRect + } + patchOutputSlot(slot, incoming) + return slot +} + +function mergeSlotsByName( + existing: Slot[], + incoming: readonly Slot[], + patch: (target: Slot, incoming: Slot) => void, + copy: (incoming: Slot) => Slot +): void { + const used = new Set() + const matches = incoming.map((incomingSlot) => { + const index = existing.findIndex( + (slot, candidate) => + !used.has(candidate) && slot.name === incomingSlot.name + ) + if (index === -1) return undefined + used.add(index) + return { index, slot: existing[index] } + }) + const insertions: number[] = [] + + for (const [incomingIndex, incomingSlot] of incoming.entries()) { + const match = matches[incomingIndex] + if (match) { + patch(match.slot, incomingSlot) + continue + } + + const anchor = + matches.slice(incomingIndex + 1).find((candidate) => candidate)?.index ?? + existing.length - insertions.length + const insertionIndex = + anchor + insertions.filter((prior) => prior <= anchor).length + existing.splice(insertionIndex, 0, copy(incomingSlot)) + insertions.push(anchor) + } +} + /** * One {@link NodeState} per node in a root-flat, owner-indexed bucket. * See docs/architecture/node-data-store.md. @@ -131,8 +250,13 @@ export const useNodeDataStore = defineStore('nodeData', () => { ): boolean { const state = roots.get(graphScope.rootGraphId)?.byId.get(nodeId) if (!state || state.graphId !== graphScope.owningGraphId) return false - state.inputs = slots.inputs - state.outputs = slots.outputs + mergeSlotsByName(state.inputs, slots.inputs, patchInputSlot, copyInputSlot) + mergeSlotsByName( + state.outputs, + slots.outputs, + patchOutputSlot, + copyOutputSlot + ) return true } diff --git a/src/workbench/extensions/agent/crdt/graphMutations.test.ts b/src/workbench/extensions/agent/crdt/graphMutations.test.ts index b4c71643f5e..1045fa44f0b 100644 --- a/src/workbench/extensions/agent/crdt/graphMutations.test.ts +++ b/src/workbench/extensions/agent/crdt/graphMutations.test.ts @@ -330,6 +330,39 @@ describe('graphMutations', () => { ) }) + it('keeps runtime-only fields out of prepared slots', () => { + const graph = mutations() + const payload = { + ...node(7), + inputs: [ + { + name: 'in', + type: 'IMAGE', + label: 'Input', + link: null, + _node: { corrupt: true } + } + ], + outputs: [ + { + name: 'out', + type: 'IMAGE', + label: 'Output', + links: [], + _data: { corrupt: true } + } + ] + } + + expect(graph.addNode(payload, context)).toBe(true) + + const state = useNodeDataStore().getNode(scope.rootGraphId, toNodeId(7)) + expect(state?.inputs[0]).toMatchObject({ name: 'in', label: 'Input' }) + expect(state?.outputs[0]).toMatchObject({ name: 'out', label: 'Output' }) + expect(state?.inputs[0]).not.toHaveProperty('_node') + expect(state?.outputs[0]).not.toHaveProperty('_data') + }) + it('repositions a template node placed far from an existing node', () => { const graph = mutations() graph.addNode({ ...node(1), pos: [0, 0] }, context) diff --git a/src/workbench/extensions/agent/crdt/graphMutations.ts b/src/workbench/extensions/agent/crdt/graphMutations.ts index abda33e70ba..445d0f7e21f 100644 --- a/src/workbench/extensions/agent/crdt/graphMutations.ts +++ b/src/workbench/extensions/agent/crdt/graphMutations.ts @@ -1,4 +1,9 @@ import { LiteGraph } from '@/lib/litegraph/src/litegraph' +import type { + INodeInputSlot, + INodeOutputSlot, + INodeSlot +} from '@/lib/litegraph/src/interfaces' import type { ISerialisableNodeInput, ISerialisableNodeOutput, @@ -220,6 +225,32 @@ function cloneRecord(value: unknown): Record { return isRecord(value) ? structuredClone(value) : {} } +const SERIALISABLE_SLOT_FIELDS = [ + 'name', + 'localized_name', + 'label', + 'type', + 'dir', + 'removable', + 'shape', + 'color_off', + 'color_on', + 'locked', + 'nameLocked', + 'pos' +] as const satisfies readonly (keyof INodeSlot)[] + +function serialisableSlotFields( + raw: Record, + additional: readonly string[] +): Record { + return Object.fromEntries( + [...SERIALISABLE_SLOT_FIELDS, ...additional].flatMap((field) => + Object.hasOwn(raw, field) ? [[field, structuredClone(raw[field])]] : [] + ) + ) +} + /** * A supplied input slot whose record has no `link` key carries no link * information (as opposed to `link: null`, which means unlinked). Such slots @@ -227,7 +258,7 @@ function cloneRecord(value: unknown): Record { * node has no slot there yet. */ function applySlotLink( - slot: Record, + slot: INodeInputSlot, index: number, existing?: NodeState['inputs'] ): void { @@ -245,7 +276,7 @@ function applySlotLink( * metadata instead of losing it to the thin payload. */ function preserveSlotDisplayMetadata( - slot: Record, + slot: INodeInputSlot, priorSlot?: NodeState['inputs'][number] ): void { if (!priorSlot || priorSlot.name !== slot.name) return @@ -258,14 +289,25 @@ function prepareInputSlot( raw: Record, index: number, existing?: NodeState['inputs'] -): NodeState['inputs'][number] { - const slot = structuredClone(raw) +): INodeInputSlot | undefined { + if ( + typeof raw.name !== 'string' || + (typeof raw.type !== 'string' && typeof raw.type !== 'number') + ) { + return undefined + } + const slot: INodeInputSlot = { + name: raw.name, + type: raw.type, + boundingRect: [0, 0, 0, 0] + } + Object.assign(slot, serialisableSlotFields(raw, ['widget'])) + if (raw.link === null || typeof raw.link === 'number') { + slot.link = raw.link === null ? null : toLinkId(raw.link) + } applySlotLink(slot, index, existing) preserveSlotDisplayMetadata(slot, existing?.[index]) - return { - ...slot, - boundingRect: [0, 0, 0, 0] - } as unknown as NodeState['inputs'][number] + return slot } function prepareInputSlots( @@ -273,22 +315,34 @@ function prepareInputSlots( existing?: NodeState['inputs'] ): NodeState['inputs'] { if (!Array.isArray(value)) return [] - return value - .filter(isRecord) - .map((raw, index) => prepareInputSlot(raw, index, existing)) + return value.flatMap((raw, index) => { + if (!isRecord(raw)) return [] + const slot = prepareInputSlot(raw, index, existing) + return slot ? [slot] : [] + }) } function prepareOutputSlots(value: unknown): NodeState['outputs'] { if (!Array.isArray(value)) return [] - return value.filter(isRecord).map((raw) => { - const slot = structuredClone(raw) - if (Array.isArray(slot.links)) { - slot.links = slot.links.map((id) => toLinkId(Number(id))) + return value.flatMap((raw) => { + if ( + !isRecord(raw) || + typeof raw.name !== 'string' || + (typeof raw.type !== 'string' && typeof raw.type !== 'number') + ) { + return [] } - return { - ...slot, + const slot: INodeOutputSlot = { + name: raw.name, + type: raw.type, boundingRect: [0, 0, 0, 0] - } as unknown as NodeState['outputs'][number] + } + Object.assign(slot, serialisableSlotFields(raw, ['slot_index', 'widget'])) + if (raw.links === null) slot.links = null + else if (Array.isArray(raw.links)) { + slot.links = raw.links.map((id) => toLinkId(Number(id))) + } + return [slot] }) }