LCOV - code coverage report
Current view: top level - src/platform/workflowErrors/nodeReplacement - useNodeReplacement.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 72.3 % 242 175
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import {
       2              :   canTransferReplacementOwnership,
       3              :   transferReplacementOwnership
       4              : } from '@/core/graph/nodeShell/nodeShellState'
       5              : import { growAutogrowInput } from '@/core/graph/widgets/dynamicWidgets'
       6              : import type { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph'
       7              : import { LiteGraph } from '@/lib/litegraph/src/litegraph'
       8              : import {
       9              :   inputLink,
      10              :   inputLinkId,
      11              :   outputLinks
      12              : } from '@/lib/litegraph/src/node/slotLinks'
      13              : import type { LLink } from '@/lib/litegraph/src/LLink'
      14              : import type { ISerialisedNode } from '@comfyorg/graph-model/serialisation'
      15              : import { NodeSlotType } from '@comfyorg/graph-model/globalEnums'
      16              : import type { TWidgetValue } from '@comfyorg/graph-model/widgets'
      17              : import { isNodeBindable } from '@/lib/litegraph/src/utils/type'
      18              : import { reportError } from '@comfyorg/telemetry/reportError'
      19              : import { t } from '@/i18n'
      20              : import { useMissingNodesErrorStore } from '@/platform/workflowErrors/nodeReplacement/missingNodesErrorStore'
      21              : import type {
      22              :   MissingNodeType,
      23              :   NodeReplacement
      24              : } from '@/platform/workflowErrors/nodeReplacement/types'
      25              : import { useToast } from '@/components/ui/toast/toastStore'
      26              : import {
      27              :   removePendingMissingNodeTypesByType,
      28              :   updatePendingWarnings
      29              : } from '@/platform/workflow/core/utils/pendingWarnings'
      30              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
      31              : import { app, sanitizeNodeName } from '@/scripts/app'
      32              : import { clearNodeOwnedStoreState } from '@/stores/clearNodeOwnedStoreState'
      33              : import type { EndpointPatch, EndpointUpdate } from '@/stores/linkStore'
      34              : import { useLinkStore } from '@/stores/linkStore'
      35              : import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId'
      36              : import type { LinkId } from '@comfyorg/graph-model/linkId'
      37              : import type { LinkTopology } from '@comfyorg/graph-model/linkTopology'
      38              : import { collectAllNodes } from '@/utils/graphTraversalUtil'
      39              : 
      40              : interface WidgetAssignment {
      41              :   name: string
      42              :   value: TWidgetValue
      43              : }
      44              : 
      45              : interface ReplacementGroup {
      46              :   type: string
      47              :   nodeTypes: MissingNodeType[]
      48              : }
      49              : 
      50              : /** Compares sanitized type strings to match placeholder → missing node type. */
      51           19 : function findMatchingType(
      52              :   node: LGraphNode,
      53              :   selectedTypes: MissingNodeType[]
      54              : ): Extract<MissingNodeType, { type: string }> | undefined {
      55           19 :   const nodeType = node.type
      56           19 :   for (const selected of selectedTypes) {
      57           26 :     if (typeof selected !== 'object' || !selected.isReplaceable) continue
      58           26 :     if (sanitizeNodeName(selected.type) === nodeType) return selected
      59              :   }
      60              :   return undefined
      61              : }
      62              : 
      63              : interface ReplacementTopologyPlan {
      64              :   error?: string
      65              :   updates: EndpointUpdate[]
      66              :   removals: {
      67              :     link: LLink
      68              :     topology: LinkTopology
      69              :     connection: Pick<
      70              :       ReturnType<LLink['resolve']>,
      71              :       'input' | 'inputNode' | 'output' | 'outputNode'
      72              :     >
      73              :   }[]
      74              : }
      75              : 
      76           19 : function planReplacementTopology(
      77              :   oldNode: LGraphNode,
      78              :   newNode: LGraphNode,
      79              :   replacement: NodeReplacement,
      80              :   graph: LGraph
      81              : ): ReplacementTopologyPlan {
      82           19 :   const linkStore = useLinkStore()
      83           19 :   const scope = graphScopeOf(graph)
      84           19 :   const oldNodeId = String(oldNode.id)
      85           19 :   const updates = new Map<LinkId, EndpointUpdate>()
      86           19 :   const addUpdate = (link: LLink, patch: EndpointPatch) => {
      87           14 :     const topology = linkStore.getTopology(scope.rootGraphId, link.id)
      88           14 :     if (!topology) return
      89           14 :     const existing = updates.get(link.id)
      90           14 :     updates.set(link.id, {
      91              :       topology,
      92              :       patch: { ...existing?.patch, ...patch }
      93              :     })
      94              :   }
      95              : 
      96           19 :   for (const inputMap of replacement.input_mapping ?? []) {
      97          127 :     if (!('old_id' in inputMap)) continue
      98          126 :     const oldSlot = oldNode.inputs.findIndex(
      99              :       (input) => input.name === inputMap.old_id
     100              :     )
     101          126 :     const newSlot = newNode.inputs.findIndex(
     102              :       (input) => input.name === inputMap.new_id
     103              :     )
     104          127 :     if (oldSlot === -1 || newSlot === -1) continue
     105           51 :     const linkId = inputLinkId(graph, oldNode.id, oldSlot)
     106          127 :     const link = linkId == null ? undefined : graph.links.get(linkId)
     107          127 :     if (link) addUpdate(link, { targetSlot: newSlot })
     108              :   }
     109              : 
     110           19 :   for (const outputMap of replacement.output_mapping ?? []) {
     111           16 :     if (!newNode.outputs[outputMap.new_idx]) continue
     112           16 :     for (const link of outputLinks(graph, oldNode.id, outputMap.old_idx)) {
     113           11 :       addUpdate(link, { originSlot: outputMap.new_idx })
     114              :     }
     115              :   }
     116              : 
     117           19 :   let error: string | undefined
     118           19 :   const removals = [...graph.links.values()].flatMap((link) => {
     119           27 :     if (
     120              :       link.origin_id === oldNodeId &&
     121              :       replacement.output_mapping == null &&
     122              :       !newNode.outputs[link.origin_slot]
     123              :     ) {
     124            0 :       error ??= `output slot ${link.origin_slot} cannot preserve link ${link.id}`
     125              :     }
     126           27 :     if (
     127              :       link.target_id === oldNodeId &&
     128              :       replacement.input_mapping == null &&
     129              :       !newNode.inputs[link.target_slot]
     130              :     ) {
     131            0 :       error ??= `input slot ${link.target_slot} cannot preserve link ${link.id}`
     132              :     }
     133           27 :     const update = updates.get(link.id)
     134           27 :     const removesOrigin =
     135              :       link.origin_id === oldNodeId &&
     136              :       replacement.output_mapping != null &&
     137              :       update?.patch.originSlot == null
     138           27 :     const removesTarget =
     139              :       link.target_id === oldNodeId &&
     140              :       replacement.input_mapping != null &&
     141              :       update?.patch.targetSlot == null
     142           27 :     if (!removesOrigin && !removesTarget) return []
     143            0 :     const topology = linkStore.getTopology(scope.rootGraphId, link.id)
     144           27 :     const outputNode = graph.getNodeById(link.origin_id) ?? undefined
     145           27 :     const inputNode = graph.getNodeById(link.target_id) ?? undefined
     146           27 :     return topology
     147              :       ? [
     148              :           {
     149              :             link,
     150              :             topology,
     151              :             connection: {
     152              :               inputNode,
     153              :               outputNode,
     154              :               input: inputNode?.inputs[link.target_slot],
     155              :               output: outputNode?.outputs[link.origin_slot]
     156              :             }
     157              :           }
     158              :         ]
     159              :       : []
     160              :   })
     161           19 :   return { error, updates: [...updates.values()], removals }
     162              : }
     163              : 
     164           19 : function savedWidgetValues(
     165              :   serialized: ISerialisedNode,
     166              :   replacement: NodeReplacement
     167              : ): Record<string, TWidgetValue> {
     168           19 :   if (serialized.widgets_values_named) return serialized.widgets_values_named
     169           19 :   const values = serialized.widgets_values ?? []
     170           19 :   const names =
     171              :     replacement.old_widget_ids ??
     172              :     soleMappedWidgetName(serialized, replacement, values.length)
     173           19 :   return Object.fromEntries(
     174              :     names.flatMap((name, idx) =>
     175              :       values[idx] === undefined ? [] : [[name, values[idx]]]
     176              :     )
     177              :   )
     178              : }
     179              : 
     180            2 : function soleMappedWidgetName(
     181              :   serialized: ISerialisedNode,
     182              :   replacement: NodeReplacement,
     183              :   valueCount: number
     184              : ): string[] {
     185            2 :   if (valueCount !== 1) return []
     186            2 :   const socketOnlyInputs = new Set(
     187              :     serialized.inputs?.flatMap((input) => (input.widget ? [] : [input.name]))
     188              :   )
     189            2 :   const widgetIds = (replacement.input_mapping ?? []).flatMap((inputMap) =>
     190              :     'old_id' in inputMap && !socketOnlyInputs.has(inputMap.old_id)
     191              :       ? [inputMap.old_id]
     192              :       : []
     193              :   )
     194            2 :   return widgetIds.length === 1 ? widgetIds : []
     195              : }
     196              : 
     197          410 : function mappingDepth(inputMap: { new_id: string }): number {
     198          410 :   return inputMap.new_id.split('.').length
     199              : }
     200              : 
     201           19 : function assignMappedInputs(
     202              :   newNode: LGraphNode,
     203              :   replacement: NodeReplacement,
     204              :   savedValues: Record<string, TWidgetValue>
     205              : ): WidgetAssignment[] {
     206           19 :   const assigned: WidgetAssignment[] = []
     207           72 :   function assign(name: string, value: unknown) {
     208           72 :     const widget = newNode.widgets?.find((w) => w.name === name)
     209           72 :     if (!widget) return
     210           72 :     try {
     211           72 :       widget.value = value as TWidgetValue
     212           72 :       assigned.push({ name, value: widget.value })
     213              :     } catch (error) {
     214            0 :       reportError(error, {
     215              :         surface: 'graph',
     216              :         errorType: 'failure_assigning_replacement_widget_value',
     217              :         tags: { node_type: replacement.new_node_id, widget_name: name }
     218              :       })
     219              :     }
     220              :   }
     221           19 :   const inputMaps = [...(replacement.input_mapping ?? [])].sort(
     222              :     (a, b) => mappingDepth(a) - mappingDepth(b)
     223              :   )
     224           19 :   for (const inputMap of inputMaps) {
     225          127 :     if ('set_value' in inputMap) {
     226            1 :       assign(inputMap.new_id, inputMap.set_value)
     227            1 :       continue
     228              :     }
     229          126 :     growAutogrowInput(newNode, inputMap.new_id)
     230          127 :     if (Object.hasOwn(savedValues, inputMap.old_id))
     231           71 :       assign(inputMap.new_id, savedValues[inputMap.old_id])
     232              :   }
     233           19 :   return assigned
     234              : }
     235              : 
     236              : /** Auto-generates identity mapping by name for same-structure replacements without backend mapping. */
     237            0 : function generateDefaultMapping(
     238              :   serialized: ISerialisedNode,
     239              :   newNode: LGraphNode
     240              : ): Pick<
     241              :   NodeReplacement,
     242              :   'input_mapping' | 'output_mapping' | 'old_widget_ids'
     243              : > {
     244            0 :   const oldInputNames = new Set(serialized.inputs?.map((i) => i.name) ?? [])
     245              : 
     246            0 :   const inputMapping: { old_id: string; new_id: string }[] = []
     247            0 :   for (const newInput of newNode.inputs) {
     248            0 :     if (oldInputNames.has(newInput.name)) {
     249            0 :       inputMapping.push({ old_id: newInput.name, new_id: newInput.name })
     250              :     }
     251              :   }
     252              : 
     253            0 :   const oldWidgetIds = (newNode.widgets ?? []).map((w) => w.name)
     254            0 :   for (const widget of newNode.widgets ?? []) {
     255            0 :     if (!oldInputNames.has(widget.name)) {
     256            0 :       inputMapping.push({ old_id: widget.name, new_id: widget.name })
     257              :     }
     258              :   }
     259              : 
     260            0 :   const outputMapping: { old_idx: number; new_idx: number }[] = []
     261            0 :   for (const [oldIdx, oldOutput] of (serialized.outputs ?? []).entries()) {
     262            0 :     const newIdx = newNode.outputs.findIndex((o) => o.name === oldOutput.name)
     263            0 :     if (newIdx !== -1) {
     264            0 :       outputMapping.push({ old_idx: oldIdx, new_idx: newIdx })
     265              :     }
     266              :   }
     267              : 
     268            0 :   return {
     269              :     input_mapping: inputMapping.length > 0 ? inputMapping : null,
     270              :     output_mapping: outputMapping.length > 0 ? outputMapping : null,
     271              :     old_widget_ids: oldWidgetIds.length > 0 ? oldWidgetIds : null
     272              :   }
     273              : }
     274              : 
     275           19 : function replaceWithMapping(
     276              :   node: LGraphNode,
     277              :   newNode: LGraphNode,
     278              :   replacement: NodeReplacement,
     279              :   nodeGraph: LGraph,
     280              :   idx: number
     281              : ): boolean {
     282           19 :   const order = node.order
     283           19 :   newNode.id = node.id
     284           19 :   newNode.order = order
     285           19 :   newNode.mode = node.mode
     286           19 :   newNode.flags = { ...node.flags }
     287              : 
     288           19 :   if (
     289              :     nodeGraph._nodes[idx] !== node ||
     290              :     nodeGraph._nodes_by_id[node.id] !== node ||
     291              :     !canTransferReplacementOwnership(node, newNode)
     292              :   ) {
     293            0 :     console.error(`Cannot replace node ${node.id}: ownership is invalid`)
     294            0 :     return false
     295              :   }
     296              : 
     297           19 :   const serialized = node.last_serialization ?? node.serialize()
     298           19 :   if (serialized.title != null) newNode.title = serialized.title
     299           19 :   if (serialized.properties) {
     300           19 :     newNode.properties = { ...newNode.properties, ...serialized.properties }
     301           19 :     if ('Node name for S&R' in newNode.properties) {
     302           19 :       newNode.properties['Node name for S&R'] = replacement.new_node_id
     303              :     }
     304              :   }
     305           19 :   const assignedWidgets = assignMappedInputs(
     306              :     newNode,
     307              :     replacement,
     308              :     savedWidgetValues(serialized, replacement)
     309              :   )
     310              : 
     311           19 :   const topologyPlan = planReplacementTopology(
     312              :     node,
     313              :     newNode,
     314              :     replacement,
     315              :     nodeGraph
     316              :   )
     317           19 :   newNode.has_errors = false
     318              : 
     319           19 :   if (topologyPlan.error) {
     320            0 :     console.error(`Cannot replace node ${node.id}: ${topologyPlan.error}`)
     321            0 :     return false
     322              :   }
     323              : 
     324           19 :   const linkStore = useLinkStore()
     325           19 :   const scope = graphScopeOf(nodeGraph)
     326           19 :   const removalTopologies = topologyPlan.removals.map(
     327              :     ({ topology }) => topology
     328              :   )
     329           19 :   const endpointError = linkStore.validateEndpointUpdates(
     330              :     scope,
     331              :     topologyPlan.updates,
     332              :     removalTopologies
     333              :   )
     334           19 :   if (endpointError) {
     335            0 :     console.error(`Cannot replace node ${node.id}: ${endpointError.message}`)
     336            0 :     return false
     337              :   }
     338              : 
     339           19 :   if (
     340              :     nodeGraph._nodes[idx] !== node ||
     341              :     nodeGraph._nodes_by_id[node.id] !== node ||
     342              :     !canTransferReplacementOwnership(node, newNode) ||
     343              :     !transferReplacementOwnership(node, newNode)
     344              :   ) {
     345            0 :     console.error(
     346              :       `Cannot replace node ${node.id}: ownership changed during removal`
     347              :     )
     348            0 :     return false
     349              :   }
     350              : 
     351           19 :   const topologyResult = linkStore.updateEndpoints(
     352              :     scope,
     353              :     topologyPlan.updates,
     354              :     removalTopologies
     355              :   )
     356           19 :   if (!topologyResult.ok) {
     357            0 :     transferReplacementOwnership(newNode, node)
     358            0 :     console.error(
     359              :       `Cannot replace node ${node.id}: ${topologyResult.error.message}`
     360              :     )
     361            0 :     return false
     362              :   }
     363              : 
     364           19 :   for (const { connection, link, topology } of topologyPlan.removals) {
     365            0 :     link.disconnect(nodeGraph)
     366            0 :     nodeGraph.incrementVersion()
     367            0 :     if (connection.inputNode && connection.input) {
     368            0 :       try {
     369            0 :         connection.inputNode.onConnectionsChange?.(
     370              :           NodeSlotType.INPUT,
     371              :           topology.targetSlot,
     372              :           false,
     373              :           link,
     374              :           connection.input
     375              :         )
     376              :       } catch (error) {
     377            0 :         console.error(`Failed to notify disconnected link ${link.id}`, error)
     378              :       }
     379              :     }
     380            0 :     if (connection.outputNode && connection.output) {
     381            0 :       try {
     382            0 :         connection.outputNode.onConnectionsChange?.(
     383              :           NodeSlotType.OUTPUT,
     384              :           topology.originSlot,
     385              :           false,
     386              :           link,
     387              :           connection.output
     388              :         )
     389              :       } catch (error) {
     390            0 :         console.error(`Failed to notify disconnected link ${link.id}`, error)
     391              :       }
     392              :     }
     393              :   }
     394              : 
     395           19 :   try {
     396           19 :     node.onRemoved?.()
     397              :   } catch (error) {
     398            0 :     console.error(`Failed to remove replaced node ${node.id}`, error)
     399              :   }
     400           19 :   clearNodeOwnedStoreState(node)
     401              : 
     402           19 :   nodeGraph._nodes[idx] = newNode
     403           19 :   newNode.graph = nodeGraph
     404           19 :   node.graph = null
     405           19 :   nodeGraph._nodes_by_id[newNode.id] = newNode
     406              : 
     407           19 :   for (const { name, value } of assignedWidgets) {
     408           72 :     const widget = newNode.widgets?.find((w) => w.name === name)
     409           72 :     if (!widget) continue
     410           72 :     try {
     411           72 :       if (widget.value !== value) widget.value = value
     412           72 :       widget.callback?.(value)
     413              :     } catch (error) {
     414            0 :       reportError(error, {
     415              :         surface: 'graph',
     416              :         errorType: 'failure_invoking_replacement_widget_callback',
     417              :         tags: { node_type: replacement.new_node_id, widget_name: name }
     418              :       })
     419              :     }
     420              :   }
     421           19 :   for (const widget of newNode.widgets ?? []) {
     422           96 :     if (!isNodeBindable(widget)) continue
     423           96 :     try {
     424           96 :       widget.setNodeId(newNode.id)
     425              :     } catch (error) {
     426            0 :       console.error(`Failed to bind replacement widget ${widget.name}`, error)
     427              :     }
     428              :   }
     429           19 :   const connectedInputs = newNode.inputs.flatMap((input, slot) => {
     430          139 :     const link = inputLink(nodeGraph, newNode.id, slot)
     431          139 :     return link ? [{ input, link }] : []
     432              :   })
     433           19 :   for (const { input, link } of connectedInputs) {
     434            3 :     try {
     435            3 :       newNode.onConnectionsChange?.(
     436              :         NodeSlotType.INPUT,
     437              :         newNode.inputs.indexOf(input),
     438              :         true,
     439              :         link,
     440              :         input
     441              :       )
     442              :     } catch (error) {
     443            0 :       reportError(error, {
     444              :         surface: 'graph',
     445              :         errorType: 'failure_notifying_replacement_input_connection',
     446              :         tags: { node_type: replacement.new_node_id, input_name: input.name }
     447              :       })
     448              :     }
     449              :   }
     450              : 
     451           19 :   try {
     452           19 :     nodeGraph.onNodeAdded?.(newNode)
     453              :   } catch (error) {
     454            0 :     console.error(`Failed to notify replacement node ${newNode.id}`, error)
     455              :   }
     456           19 :   try {
     457           19 :     nodeGraph.events.dispatch('node:added', { node: newNode })
     458              :   } catch (error) {
     459            0 :     console.error(`Failed to dispatch replacement node ${newNode.id}`, error)
     460              :   }
     461           19 :   return true
     462              : }
     463              : 
     464           13 : function removeReplacedMissingNodeTypes(types: string[]): void {
     465              :   // Remove from the rendered store directly rather than re-projecting the
     466              :   // cache into it: entries surfaced outside the load path (e.g. the
     467              :   // missing_node_type rescan) exist only in the store, and a projection from
     468              :   // a cache that never saw them would wipe them.
     469           13 :   useMissingNodesErrorStore().removeMissingNodesByType(types)
     470              : 
     471           13 :   const activeWorkflow = useWorkflowStore().activeWorkflow
     472           13 :   if (!activeWorkflow) return
     473              : 
     474           13 :   updatePendingWarnings(activeWorkflow, {
     475              :     missingNodeTypes: removePendingMissingNodeTypesByType(
     476              :       activeWorkflow.pendingWarnings?.missingNodeTypes,
     477              :       types
     478              :     )
     479              :   })
     480              : }
     481              : 
     482           89 : export function useNodeReplacement() {
     483           89 :   const toast = useToast()
     484              : 
     485           13 :   function replaceNodesInPlace(selectedTypes: MissingNodeType[]): string[] {
     486           13 :     const replacedTypes: string[] = []
     487           13 :     const failedTypes = new Set<string>()
     488           13 :     let replacementFailed: true | undefined
     489           13 :     let anyNodeReplaced = false
     490           13 :     const graph = app.rootGraph
     491           13 :     const recordReplacementFailure = (type: string) => {
     492            0 :       replacementFailed = true
     493            0 :       failedTypes.add(type)
     494            0 :       const replacedTypeIndex = replacedTypes.indexOf(type)
     495            0 :       if (replacedTypeIndex !== -1) {
     496            0 :         replacedTypes.splice(replacedTypeIndex, 1)
     497              :       }
     498              :     }
     499              : 
     500           13 :     const changeTracker =
     501              :       useWorkflowStore().activeWorkflow?.changeTracker ?? null
     502           13 :     changeTracker?.beforeChange()
     503              : 
     504              :     // Target types come from node_replacements fetched at workflow load time
     505              :     // and the missing nodes detected at that point — not from the current
     506              :     // registered_node_types. This ensures replacement still works even if
     507              :     // the user has since installed the missing node pack.
     508              :     // Also include sanitized variants so that when the fallback path reads
     509              :     // n.type (which app.ts may have already run through sanitizeNodeName),
     510              :     // we can still match against the original type stored in selectedTypes.
     511           13 :     const targetTypes = new Set([
     512              :       ...selectedTypes.map((t) => (typeof t === 'string' ? t : t.type)),
     513              :       ...selectedTypes.map((t) =>
     514              :         sanitizeNodeName(typeof t === 'string' ? t : t.type)
     515              :       )
     516              :     ])
     517              : 
     518           13 :     try {
     519           13 :       const placeholders = collectAllNodes(graph, (n) => {
     520           34 :         if (!n.last_serialization) return false
     521              :         // Prefer the original serialized type; fall back to the live type
     522              :         // for nodes whose serialization predates the type field.
     523              :         // n.type may have been sanitized by app.ts (HTML special chars stripped);
     524              :         // the sanitized variants in targetTypes ensure we still match correctly.
     525           34 :         const originalType = n.last_serialization.type || n.type
     526           34 :         return !!originalType && targetTypes.has(originalType)
     527              :       })
     528              : 
     529           13 :       for (const node of new Set(placeholders)) {
     530           19 :         const match = findMatchingType(node, selectedTypes)
     531           19 :         if (!match?.replacement) continue
     532              : 
     533           19 :         const replacement = match.replacement
     534           19 :         const nodeGraph = node.graph
     535           19 :         if (!nodeGraph) {
     536            0 :           recordReplacementFailure(match.type)
     537            0 :           continue
     538              :         }
     539              : 
     540           19 :         const idx = nodeGraph._nodes.indexOf(node)
     541           19 :         if (idx === -1) {
     542            0 :           recordReplacementFailure(match.type)
     543            0 :           continue
     544              :         }
     545              : 
     546           19 :         const newNode = LiteGraph.createNode(replacement.new_node_id)
     547           19 :         if (!newNode) {
     548            0 :           recordReplacementFailure(match.type)
     549            0 :           continue
     550              :         }
     551              : 
     552              :         const hasMapping =
     553              :           replacement.input_mapping != null ||
     554              :           replacement.output_mapping != null
     555              : 
     556              :         const effectiveReplacement = hasMapping
     557              :           ? replacement
     558              :           : {
     559              :               ...replacement,
     560              :               ...generateDefaultMapping(
     561              :                 node.last_serialization ?? node.serialize(),
     562              :                 newNode
     563              :               )
     564              :             }
     565              :         const replaced = replaceWithMapping(
     566              :           node,
     567              :           newNode,
     568              :           effectiveReplacement,
     569              :           nodeGraph,
     570              :           idx
     571              :         )
     572           19 :         if (!replaced) {
     573            0 :           recordReplacementFailure(match.type)
     574            0 :           continue
     575              :         }
     576           19 :         anyNodeReplaced = true
     577              : 
     578           19 :         if (
     579              :           !failedTypes.has(match.type) &&
     580              :           !replacedTypes.includes(match.type)
     581              :         ) {
     582           19 :           replacedTypes.push(match.type)
     583              :         }
     584              :       }
     585              : 
     586           13 :       if (anyNodeReplaced) {
     587           13 :         graph.updateExecutionOrder()
     588           13 :         graph.setDirtyCanvas(true, true)
     589              :       }
     590              : 
     591           13 :       if (replacedTypes.length > 0) {
     592           13 :         toast.success(t('g.success'), {
     593              :           description: t('nodeReplacement.replacedAllNodes', {
     594              :             count: replacedTypes.length
     595              :           }),
     596              :           duration: 3000
     597              :         })
     598              :       }
     599           13 :       if (replacementFailed) {
     600            0 :         toast.error(t('g.error'), {
     601              :           description: t('nodeReplacement.replaceFailed')
     602              :         })
     603              :       }
     604              :     } catch (error) {
     605            0 :       console.error('Failed to replace nodes:', error)
     606            0 :       if (anyNodeReplaced) {
     607            0 :         graph.updateExecutionOrder()
     608            0 :         graph.setDirtyCanvas(true, true)
     609              :       }
     610            0 :       toast.error(t('g.error'), {
     611              :         description: t('nodeReplacement.replaceFailed')
     612              :       })
     613            0 :       return replacedTypes
     614              :     } finally {
     615           13 :       changeTracker?.afterChange()
     616              :     }
     617              : 
     618           13 :     return replacedTypes
     619              :   }
     620              : 
     621              :   /**
     622              :    * Replaces all nodes in a single swap group and removes successfully
     623              :    * replaced types from pending warnings and rendered state.
     624              :    */
     625            8 :   function replaceGroup(group: ReplacementGroup): void {
     626            8 :     const replaced = replaceNodesInPlace(group.nodeTypes)
     627            8 :     if (replaced.length > 0) {
     628            8 :       removeReplacedMissingNodeTypes(replaced)
     629              :     }
     630              :   }
     631              : 
     632              :   /**
     633              :    * Replaces every available node across all swap groups and removes
     634              :    * the succeeded types from pending warnings and rendered state.
     635              :    */
     636            5 :   function replaceAllGroups(groups: ReplacementGroup[]): void {
     637              :     const allNodeTypes = groups.flatMap((g) => g.nodeTypes)
     638            5 :     const replaced = replaceNodesInPlace(allNodeTypes)
     639            5 :     if (replaced.length > 0) {
     640            5 :       removeReplacedMissingNodeTypes(replaced)
     641              :     }
     642              :   }
     643              : 
     644           89 :   return {
     645              :     replaceNodesInPlace,
     646              :     replaceGroup,
     647              :     replaceAllGroups
     648              :   }
     649              : }
        

Generated by: LCOV version 2.0-1