LCOV - code coverage report
Current view: top level - src/core/graph/subgraph/migration - proxyWidgetMigration.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 86.1 % 274 236
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { isEqual } from 'es-toolkit/compat'
       2              : 
       3              : import { promotedInputWidget } from '@/core/graph/subgraph/promotedInputWidget'
       4              : import type { PromotedWidgetSource } from '@/core/graph/subgraph/promotedWidgetTypes'
       5              : import {
       6              :   findHostInputForPromotion,
       7              :   getPromotableWidgets,
       8              :   isPreviewPseudoWidget
       9              : } from '@/core/graph/subgraph/promotionUtils'
      10              : import { resolveConcretePromotedWidget } from '@/core/graph/subgraph/resolveConcretePromotedWidget'
      11              : import { resolveSubgraphInputTarget } from '@/core/graph/subgraph/resolveSubgraphInputTarget'
      12              : import type { SerializedProxyWidgetTuple } from '@/core/schemas/promotionSchema'
      13              : import { parseProxyWidgets } from '@/core/schemas/promotionSchema'
      14              : import type {
      15              :   ProxyWidgetErrorQuarantineEntry,
      16              :   ProxyWidgetQuarantineReason
      17              : } from '@/core/schemas/proxyWidgetQuarantineSchema'
      18              : import { parseProxyWidgetErrorQuarantine } from '@/core/schemas/proxyWidgetQuarantineSchema'
      19              : import type { INodeInputSlot } from '@comfyorg/graph-model/slots'
      20              : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
      21              : import { nextUniqueName } from '@/lib/litegraph/src/strings'
      22              : import type { Subgraph } from '@/lib/litegraph/src/subgraph/Subgraph'
      23              : import type { SubgraphInput } from '@/lib/litegraph/src/subgraph/SubgraphInput'
      24              : import type { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode'
      25              : import type { IBaseWidget, TWidgetValue } from '@comfyorg/graph-model/widgets'
      26              : import { isWidgetValue } from '@comfyorg/graph-model/widgets'
      27              : import { useLinkStore } from '@/stores/linkStore'
      28              : import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId'
      29              : import {
      30              :   getPreviewExposureHostLocator,
      31              :   usePreviewExposureStore
      32              : } from '@/stores/previewExposureStore'
      33              : import { useWidgetValueStore } from '@/stores/widgetValueStore'
      34              : import type { LinkTopology } from '@comfyorg/graph-model/linkTopology'
      35              : import { toNodeId } from '@comfyorg/graph-model/nodeId'
      36              : import type { NodeId, SerializedNodeId } from '@comfyorg/graph-model/nodeId'
      37              : 
      38              : interface LegacyProxyEntrySource extends PromotedWidgetSource {
      39              :   disambiguatingSourceNodeId?: NodeId
      40              : }
      41              : 
      42         2356 : const LEGACY_PROXY_WIDGET_PREFIX_PATTERN = /^\s*(\d+)\s*:\s*(.+)$/
      43              : 
      44              : interface StrippedPrefix {
      45              :   sourceWidgetName: string
      46              :   deepestPrefixId?: NodeId
      47              : }
      48              : 
      49           94 : function stripLegacyPrefixes(sourceWidgetName: string): StrippedPrefix {
      50           94 :   let remaining = sourceWidgetName
      51           94 :   let deepestPrefixId: NodeId | undefined
      52           94 :   for (;;) {
      53          100 :     const match = LEGACY_PROXY_WIDGET_PREFIX_PATTERN.exec(remaining)
      54          100 :     if (!match) return { sourceWidgetName: remaining, deepestPrefixId }
      55            6 :     deepestPrefixId = toNodeId(match[1])
      56            6 :     remaining = match[2]
      57              :   }
      58              : }
      59              : 
      60          277 : function canResolveLegacyProxy(
      61              :   hostNode: SubgraphNode,
      62              :   sourceNodeId: SerializedNodeId,
      63              :   widgetName: string
      64              : ): boolean {
      65          277 :   return (
      66              :     resolveConcretePromotedWidget(hostNode, sourceNodeId, widgetName).status ===
      67              :     'resolved'
      68              :   )
      69              : }
      70              : 
      71          277 : export function normalizeLegacyProxyWidgetEntry(
      72              :   hostNode: SubgraphNode,
      73              :   sourceNodeId: SerializedNodeId,
      74              :   sourceWidgetName: string,
      75              :   disambiguatingSourceNodeId?: SerializedNodeId
      76              : ): LegacyProxyEntrySource {
      77          277 :   const normalizedSourceNodeId = toNodeId(sourceNodeId)
      78          277 :   const normalizedDisambiguatingSourceNodeId =
      79              :     disambiguatingSourceNodeId === undefined
      80              :       ? undefined
      81              :       : toNodeId(disambiguatingSourceNodeId)
      82              : 
      83          277 :   if (canResolveLegacyProxy(hostNode, sourceNodeId, sourceWidgetName)) {
      84          183 :     return {
      85              :       sourceNodeId: normalizedSourceNodeId,
      86              :       sourceWidgetName,
      87              :       ...(normalizedDisambiguatingSourceNodeId && {
      88              :         disambiguatingSourceNodeId: normalizedDisambiguatingSourceNodeId
      89              :       })
      90              :     }
      91              :   }
      92              : 
      93           94 :   const stripped = stripLegacyPrefixes(sourceWidgetName)
      94          277 :   const patchDisambiguatingSourceNodeId =
      95              :     stripped.deepestPrefixId ?? normalizedDisambiguatingSourceNodeId
      96              : 
      97          277 :   return {
      98              :     sourceNodeId: normalizedSourceNodeId,
      99              :     sourceWidgetName: stripped.sourceWidgetName,
     100              :     ...(patchDisambiguatingSourceNodeId && {
     101              :       disambiguatingSourceNodeId: patchDisambiguatingSourceNodeId
     102              :     })
     103              :   }
     104              : }
     105              : 
     106           56 : function resolveSourceWidget(
     107              :   sourceNode: LGraphNode,
     108              :   sourceWidgetName: string,
     109              :   disambiguatingSourceNodeId?: string
     110              : ): IBaseWidget | undefined {
     111           56 :   if (sourceNode.isSubgraphNode()) {
     112            8 :     const input = sourceNode.inputs.find((input) => {
     113           10 :       const target = resolveSubgraphInputTarget(sourceNode, input.name)
     114           10 :       if (disambiguatingSourceNodeId) {
     115           10 :         return (
     116              :           target?.widgetName === sourceWidgetName &&
     117              :           target.nodeId === disambiguatingSourceNodeId
     118              :         )
     119              :       }
     120            0 :       if (input.name === sourceWidgetName) return true
     121           10 :       return target?.widgetName === sourceWidgetName
     122              :     })
     123              :     // Store-backed projection for a promoted input on a nested subgraph node:
     124              :     // getSlotFromWidget locates the backing slot by widgetId.
     125            8 :     if (input?.widgetId) return promotedInputWidget(input) ?? undefined
     126              :   }
     127              : 
     128              :   const widgets = sourceNode.widgets
     129           56 :   return (
     130              :     widgets?.find((w) => w.name === sourceWidgetName) ??
     131              :     getPromotableWidgets(sourceNode).find((w) => w.name === sourceWidgetName)
     132              :   )
     133              : }
     134              : 
     135              : interface FlushArgs {
     136              :   hostNode: SubgraphNode
     137              :   hostWidgetValues?: readonly unknown[]
     138              : }
     139              : 
     140              : interface PrimitiveBypassTargetRef {
     141              :   targetNodeId: NodeId
     142              :   targetSlot: number
     143              : }
     144              : 
     145              : type Plan =
     146              :   | { kind: 'alreadyLinked'; subgraphInputName: string }
     147              :   | { kind: 'createSubgraphInput'; sourceWidgetName: string }
     148              :   | {
     149              :       kind: 'primitiveBypass'
     150              :       primitiveNodeId: NodeId
     151              :       sourceWidgetName: string
     152              :       targets: readonly PrimitiveBypassTargetRef[]
     153              :     }
     154              :   | { kind: 'previewExposure'; sourcePreviewName: string }
     155              :   | { kind: 'quarantine'; reason: ProxyWidgetQuarantineReason }
     156              : 
     157              : interface PendingEntry {
     158              :   originalEntry: SerializedProxyWidgetTuple
     159              :   normalized: LegacyProxyEntrySource
     160              :   hostValue: TWidgetValue | undefined
     161              :   isHole: boolean
     162              :   plan: Plan
     163              : }
     164              : 
     165         2356 : const PRIMITIVE_NODE_TYPE = 'PrimitiveNode'
     166         2356 : const QUARANTINE_PROPERTY = 'proxyWidgetErrorQuarantine'
     167         2356 : const QUARANTINE_VERSION = 1
     168         2356 : const PROXY_BYPASS_MARKER_PROPERTY = 'proxyBypassedToSubgraphInput'
     169              : 
     170          134 : export function flushProxyWidgetMigration(args: FlushArgs): void {
     171          134 :   const { hostNode, hostWidgetValues } = args
     172              : 
     173          134 :   const tuples = parseProxyWidgets(hostNode.properties.proxyWidgets)
     174          134 :   if (tuples.length === 0) return
     175              : 
     176          132 :   const normalizedEntries = tuples.map((originalEntry) => {
     177          277 :     const [sourceNodeId, sourceWidgetName, disambiguator] = originalEntry
     178          277 :     return {
     179              :       originalEntry,
     180              :       normalized: normalizeLegacyProxyWidgetEntry(
     181              :         hostNode,
     182              :         sourceNodeId,
     183              :         sourceWidgetName,
     184              :         disambiguator
     185              :       )
     186              :     }
     187              :   })
     188          132 :   const cohort = normalizedEntries.map((entry) => entry.normalized)
     189              : 
     190          132 :   const pending: PendingEntry[] = normalizedEntries.map((entry, index) => {
     191          277 :     const { value, isHole } = pickHostValue(hostWidgetValues, index)
     192          277 :     return {
     193              :       ...entry,
     194              :       hostValue: value,
     195              :       isHole,
     196              :       plan: classify(hostNode, entry.normalized, cohort)
     197              :     }
     198              :   })
     199              : 
     200          132 :   const previewStore = usePreviewExposureStore()
     201          132 :   const quarantineToAppend: ProxyWidgetErrorQuarantineEntry[] = []
     202          132 :   const primitiveCohorts = new Map<NodeId, PendingEntry[]>()
     203              : 
     204          132 :   for (const entry of pending) {
     205          277 :     switch (entry.plan.kind) {
     206              :       case 'primitiveBypass': {
     207            3 :         const c = primitiveCohorts.get(entry.plan.primitiveNodeId) ?? []
     208            3 :         c.push(entry)
     209            3 :         primitiveCohorts.set(entry.plan.primitiveNodeId, c)
     210            3 :         break
     211              :       }
     212              :       case 'alreadyLinked': {
     213          164 :         const r = repairAlreadyLinked(
     214              :           hostNode,
     215              :           entry,
     216              :           entry.plan.subgraphInputName
     217              :         )
     218          164 :         if (!r.ok) quarantineToAppend.push(quarantineFor(entry, r.reason))
     219          164 :         break
     220              :       }
     221              :       case 'createSubgraphInput': {
     222           23 :         const r = repairCreateSubgraphInput(
     223              :           hostNode,
     224              :           entry,
     225              :           entry.plan.sourceWidgetName
     226              :         )
     227           23 :         if (!r.ok) quarantineToAppend.push(quarantineFor(entry, r.reason))
     228           23 :         break
     229              :       }
     230              :       case 'previewExposure': {
     231           10 :         const r = migratePreview(hostNode, entry, previewStore, entry.plan)
     232           10 :         if (!r.ok) quarantineToAppend.push(quarantineFor(entry, r.reason))
     233           10 :         break
     234              :       }
     235              :       case 'quarantine':
     236           77 :         quarantineToAppend.push(quarantineFor(entry, entry.plan.reason))
     237              :         break
     238              :     }
     239              :   }
     240              : 
     241          132 :   for (const c of primitiveCohorts.values()) {
     242            3 :     const r = repairPrimitive(hostNode, c)
     243            3 :     if (!r.ok)
     244            0 :       for (const e of c) quarantineToAppend.push(quarantineFor(e, r.reason))
     245              :   }
     246              : 
     247          132 :   if (quarantineToAppend.length > 0) {
     248           77 :     appendQuarantine(hostNode, quarantineToAppend)
     249              :   }
     250              : 
     251          132 :   delete hostNode.properties.proxyWidgets
     252              : }
     253              : 
     254          277 : function pickHostValue(
     255              :   hostWidgetValues: readonly unknown[] | undefined,
     256              :   index: number
     257              : ): { value: TWidgetValue | undefined; isHole: boolean } {
     258          277 :   if (
     259              :     hostWidgetValues === undefined ||
     260              :     index < 0 ||
     261              :     index >= hostWidgetValues.length ||
     262              :     !Object.hasOwn(hostWidgetValues, index)
     263              :   ) {
     264          213 :     return { value: undefined, isHole: true }
     265              :   }
     266           64 :   const raw = hostWidgetValues[index]
     267           82 :   if (!isWidgetValue(raw)) return { value: undefined, isHole: true }
     268           64 :   return { value: raw, isHole: false }
     269              : }
     270              : 
     271            9 : function primitiveOutputTopologies(primitiveNode: LGraphNode): LinkTopology[] {
     272            9 :   if (!primitiveNode.graph) return []
     273            9 :   return [
     274              :     ...useLinkStore().getOutputSlotLinks(
     275              :       graphScopeOf(primitiveNode.graph),
     276              :       primitiveNode.id,
     277              :       0
     278              :     )
     279              :   ]
     280              : }
     281              : 
     282            3 : function collectTargetsStrict(
     283              :   hostNode: SubgraphNode,
     284              :   primitiveNode: LGraphNode
     285              : ): PrimitiveBypassTargetRef[] | undefined {
     286            3 :   const subgraph = hostNode.subgraph
     287            3 :   const targets: PrimitiveBypassTargetRef[] = []
     288            3 :   for (const topology of primitiveOutputTopologies(primitiveNode)) {
     289            3 :     if (!subgraph.links.get(topology.id)) return undefined
     290            3 :     targets.push({
     291              :       targetNodeId: topology.targetNodeId,
     292              :       targetSlot: topology.targetSlot
     293              :     })
     294              :   }
     295            3 :   return targets
     296              : }
     297              : 
     298            3 : function collectTargetsSkippingDangling(
     299              :   hostNode: SubgraphNode,
     300              :   primitiveNode: LGraphNode
     301              : ): PrimitiveBypassTargetRef[] {
     302            3 :   const subgraph = hostNode.subgraph
     303            3 :   return primitiveOutputTopologies(primitiveNode)
     304              :     .filter((topology) => subgraph.links.get(topology.id))
     305              :     .map((topology) => ({
     306              :       targetNodeId: topology.targetNodeId,
     307              :       targetSlot: topology.targetSlot
     308              :     }))
     309              : }
     310              : 
     311            3 : function cohortDuplicatesPrimitive(
     312              :   cohort: readonly LegacyProxyEntrySource[],
     313              :   primitiveNodeId: NodeId
     314              : ): boolean {
     315            3 :   return (
     316              :     cohort.filter((entry) => entry.sourceNodeId === primitiveNodeId).length >= 2
     317              :   )
     318              : }
     319              : 
     320          277 : function classify(
     321              :   hostNode: SubgraphNode,
     322              :   normalized: LegacyProxyEntrySource,
     323              :   cohort: readonly LegacyProxyEntrySource[]
     324              : ): Plan {
     325          277 :   const linkedInput = findHostInputForPromotion(
     326              :     hostNode,
     327              :     normalized.sourceNodeId,
     328              :     normalized.sourceWidgetName
     329              :   )
     330          277 :   if (linkedInput) {
     331          163 :     return { kind: 'alreadyLinked', subgraphInputName: linkedInput.name }
     332              :   }
     333              : 
     334          114 :   const sourceNode = hostNode.subgraph.getNodeById(normalized.sourceNodeId)
     335          136 :   if (!sourceNode) {
     336           77 :     return { kind: 'quarantine', reason: 'missingSourceNode' }
     337              :   }
     338              : 
     339           70 :   if (sourceNode.type === PRIMITIVE_NODE_TYPE) {
     340            4 :     const bypassedTo = sourceNode.properties[PROXY_BYPASS_MARKER_PROPERTY]
     341            4 :     if (typeof bypassedTo === 'string') {
     342            1 :       const existingInput = hostNode.inputs.find(
     343              :         (input) => input.name === bypassedTo
     344              :       )
     345            1 :       if (existingInput) {
     346            1 :         return { kind: 'alreadyLinked', subgraphInputName: existingInput.name }
     347              :       }
     348              :     }
     349              : 
     350            3 :     const targets = collectTargetsSkippingDangling(hostNode, sourceNode)
     351            3 :     const cohortDuplicated = cohortDuplicatesPrimitive(
     352              :       cohort,
     353              :       normalized.sourceNodeId
     354              :     )
     355            4 :     if (targets.length >= 1 || cohortDuplicated) {
     356            3 :       return {
     357              :         kind: 'primitiveBypass',
     358              :         primitiveNodeId: sourceNode.id,
     359              :         sourceWidgetName: normalized.sourceWidgetName,
     360              :         targets
     361              :       }
     362              :     }
     363            0 :     return { kind: 'quarantine', reason: 'unlinkedSourceWidget' }
     364              :   }
     365              : 
     366           33 :   const sourceWidget = resolveSourceWidget(
     367              :     sourceNode,
     368              :     normalized.sourceWidgetName,
     369              :     normalized.disambiguatingSourceNodeId
     370              :   )
     371           66 :   if (!sourceWidget) {
     372            0 :     return { kind: 'quarantine', reason: 'missingSourceWidget' }
     373              :   }
     374              : 
     375          277 :   if (
     376              :     normalized.sourceWidgetName.startsWith('$$') ||
     377              :     isPreviewPseudoWidget(sourceWidget)
     378              :   ) {
     379           10 :     return {
     380              :       kind: 'previewExposure',
     381              :       sourcePreviewName: normalized.sourceWidgetName
     382              :     }
     383              :   }
     384              : 
     385           23 :   return {
     386              :     kind: 'createSubgraphInput',
     387              :     sourceWidgetName: normalized.sourceWidgetName
     388              :   }
     389              : }
     390              : 
     391          185 : function applyHostValueToInput(
     392              :   input: INodeInputSlot,
     393              :   entry: PendingEntry
     394              : ): boolean {
     395          185 :   if (!input.widgetId || entry.isHole) return Boolean(input.widgetId)
     396            9 :   return useWidgetValueStore().restoreValue(input.widgetId, entry.hostValue)
     397              : }
     398              : 
     399           20 : function applyHostLabelToInput(
     400              :   input: INodeInputSlot,
     401              :   label: string | undefined
     402              : ): void {
     403           20 :   if (label === undefined) return
     404            2 :   input.label = label
     405            2 :   if (!input.widgetId) return
     406            2 :   const state = useWidgetValueStore().getWidget(input.widgetId)
     407            2 :   if (state) state.label = label
     408              : }
     409              : 
     410           23 : function addUniqueSubgraphInput(
     411              :   subgraph: Subgraph,
     412              :   baseName: string,
     413              :   type: string
     414              : ): SubgraphInput {
     415           23 :   const existingNames = subgraph.inputs.map((input) => input.name)
     416           23 :   const uniqueName = nextUniqueName(baseName, existingNames)
     417           23 :   return subgraph.addInput(uniqueName, type)
     418              : }
     419              : 
     420              : type Outcome<TOk, TReason = ProxyWidgetQuarantineReason> =
     421              :   | ({ ok: true } & TOk)
     422              :   | { ok: false; reason: TReason }
     423              : 
     424              : type RepairValueResult = Outcome<{ subgraphInputName: string }>
     425              : 
     426          164 : function repairAlreadyLinked(
     427              :   hostNode: SubgraphNode,
     428              :   entry: PendingEntry,
     429              :   subgraphInputName: string
     430              : ): RepairValueResult {
     431              :   // Resolve by name directly: source-id matching would miss for primitive
     432              :   // bypasses, where the view's `sourceNodeId` is the consumer, not the
     433              :   // primitive.
     434          164 :   const matches = hostNode.inputs.filter(
     435              :     (input) => input.name === subgraphInputName
     436              :   )
     437          164 :   if (matches.length === 0) {
     438            0 :     return { ok: false, reason: 'missingSubgraphInput' }
     439              :   }
     440          164 :   if (matches.length > 1) {
     441            0 :     return { ok: false, reason: 'ambiguousSubgraphInput' }
     442              :   }
     443          164 :   const hostInput = matches[0]
     444          164 :   if (!applyHostValueToInput(hostInput, entry)) {
     445            0 :     return { ok: false, reason: 'missingSubgraphInput' }
     446              :   }
     447          164 :   return { ok: true, subgraphInputName: hostInput.name }
     448              : }
     449              : 
     450           23 : function repairCreateSubgraphInput(
     451              :   hostNode: SubgraphNode,
     452              :   entry: PendingEntry,
     453              :   sourceWidgetName: string
     454              : ): RepairValueResult {
     455           23 :   const subgraph = hostNode.subgraph
     456           23 :   const sourceNode: LGraphNode | null = subgraph.getNodeById(
     457              :     entry.normalized.sourceNodeId
     458              :   )
     459           23 :   if (!sourceNode) {
     460            0 :     return { ok: false, reason: 'missingSourceNode' }
     461              :   }
     462              : 
     463           23 :   const sourceWidget = resolveSourceWidget(
     464              :     sourceNode,
     465              :     sourceWidgetName,
     466              :     entry.normalized.disambiguatingSourceNodeId
     467              :   )
     468           23 :   if (!sourceWidget) {
     469            0 :     return { ok: false, reason: 'missingSourceWidget' }
     470              :   }
     471              : 
     472           23 :   const slot: INodeInputSlot | undefined =
     473              :     sourceNode.getSlotFromWidget(sourceWidget)
     474           23 :   if (!slot) {
     475            3 :     console.warn(
     476              :       '[proxyWidgetMigration] source widget has no backing input slot; quarantining',
     477              :       {
     478              :         sourceNodeId: entry.normalized.sourceNodeId,
     479              :         sourceWidgetName
     480              :       }
     481              :     )
     482            3 :     return { ok: false, reason: 'missingSubgraphInput' }
     483              :   }
     484              : 
     485              :   // oxlint-disable-next-line typescript/no-unnecessary-condition -- legacy workflow slots may omit type at runtime
     486              :   const slotType = String(slot.type ?? '*')
     487           23 :   const newSubgraphInput = addUniqueSubgraphInput(
     488              :     subgraph,
     489              :     sourceWidgetName,
     490              :     slotType
     491              :   )
     492           23 :   if (slot.label !== undefined) newSubgraphInput.label = slot.label
     493              :   const link = newSubgraphInput.connect(slot, sourceNode)
     494           21 :   if (!link) {
     495            0 :     subgraph.removeInput(newSubgraphInput)
     496            0 :     return { ok: false, reason: 'missingSubgraphInput' }
     497              :   }
     498              : 
     499           20 :   const hostInput = hostNode.inputs.find(
     500              :     (input) => input.name === newSubgraphInput.name
     501              :   )
     502           20 :   if (hostInput) {
     503           20 :     applyHostLabelToInput(hostInput, slot.label)
     504           20 :     applyHostValueToInput(hostInput, entry)
     505              :   }
     506           20 :   return { ok: true, subgraphInputName: newSubgraphInput.name }
     507              : }
     508              : 
     509              : type RepairPrimitiveResult = Outcome<
     510              :   { subgraphInputName: string; reconnectCount: number },
     511              :   'primitiveBypassFailed'
     512              : >
     513              : 
     514         2356 : const PRIMITIVE_FAILED: RepairPrimitiveResult = {
     515              :   ok: false,
     516              :   reason: 'primitiveBypassFailed'
     517              : }
     518              : 
     519              : interface SnapshotLink extends PrimitiveBypassTargetRef {
     520              :   primitiveSlot: number
     521              : }
     522              : 
     523              : interface CohortValidationOk {
     524              :   ok: true
     525              :   primitiveNodeId: NodeId
     526              :   sourceWidgetName: string
     527              :   uniqueEntries: readonly PendingEntry[]
     528              : }
     529              : 
     530            0 : function failPrimitive(message: string, ctx?: unknown): RepairPrimitiveResult {
     531            0 :   console.warn(`[proxyWidgetMigration] ${message}`, ctx)
     532            0 :   return PRIMITIVE_FAILED
     533              : }
     534              : 
     535            3 : function userRenamedTitle(primitiveNode: LGraphNode): string | undefined {
     536            3 :   const title = primitiveNode.title
     537            3 :   return title && title !== PRIMITIVE_NODE_TYPE ? title : undefined
     538              : }
     539              : 
     540            3 : function validateCohort(
     541              :   cohort: readonly PendingEntry[]
     542              : ): CohortValidationOk | { ok: false } {
     543            3 :   const first = cohort.at(0)
     544            3 :   if (!first || first.plan.kind !== 'primitiveBypass') return { ok: false }
     545            3 :   const { primitiveNodeId, sourceWidgetName } = first.plan
     546            3 :   for (const entry of cohort) {
     547            3 :     if (
     548              :       entry.plan.kind !== 'primitiveBypass' ||
     549              :       entry.plan.primitiveNodeId !== primitiveNodeId ||
     550              :       entry.plan.sourceWidgetName !== sourceWidgetName
     551              :     ) {
     552            0 :       return { ok: false }
     553              :     }
     554              :   }
     555            3 :   const uniqueEntries: PendingEntry[] = []
     556            3 :   for (const entry of cohort) {
     557            3 :     if (!uniqueEntries.some((k) => isEqual(k.normalized, entry.normalized))) {
     558            3 :       uniqueEntries.push(entry)
     559              :     }
     560              :   }
     561            3 :   return { ok: true, primitiveNodeId, sourceWidgetName, uniqueEntries }
     562              : }
     563              : 
     564            0 : function rollback(
     565              :   hostNode: SubgraphNode,
     566              :   primitiveNode: LGraphNode,
     567              :   newSubgraphInput: SubgraphInput | undefined,
     568              :   snapshot: readonly SnapshotLink[]
     569              : ): void {
     570            0 :   if (newSubgraphInput) {
     571            0 :     try {
     572            0 :       hostNode.subgraph.removeInput(newSubgraphInput)
     573              :     } catch (e) {
     574            0 :       console.warn('[proxyWidgetMigration] rollback removeInput failed', e)
     575              :     }
     576              :   }
     577            0 :   for (const link of snapshot) {
     578            0 :     const targetNode = hostNode.subgraph.getNodeById(link.targetNodeId)
     579            0 :     if (!targetNode) continue
     580            0 :     primitiveNode.connect(link.primitiveSlot, targetNode, link.targetSlot)
     581              :   }
     582              : }
     583              : 
     584            3 : function repairPrimitive(
     585              :   hostNode: SubgraphNode,
     586              :   cohort: readonly PendingEntry[]
     587              : ): RepairPrimitiveResult {
     588            3 :   const validated = validateCohort(cohort)
     589            3 :   if (!validated.ok)
     590            0 :     return failPrimitive('cohort validation failed', { cohort })
     591              : 
     592            3 :   const subgraph = hostNode.subgraph
     593            3 :   const primitiveNode = subgraph.getNodeById(validated.primitiveNodeId)
     594            3 :   if (!primitiveNode) return failPrimitive('primitive node missing', validated)
     595            3 :   if (primitiveNode.type !== PRIMITIVE_NODE_TYPE) {
     596            0 :     return failPrimitive('node is not a PrimitiveNode', primitiveNode.type)
     597              :   }
     598              : 
     599            3 :   const targets = collectTargetsStrict(hostNode, primitiveNode)
     600            3 :   if (!targets?.length)
     601            0 :     return failPrimitive('no targets to reconnect', validated)
     602              : 
     603            3 :   const primitiveOutput = primitiveNode.outputs.at(0)
     604            3 :   if (!primitiveOutput) return failPrimitive('primitive has no output')
     605              :   // oxlint-disable-next-line typescript/no-unnecessary-condition -- legacy workflow slots may omit type at runtime
     606            3 :   const primitiveOutputType = String(primitiveOutput.type ?? '*')
     607              : 
     608            3 :   for (const target of targets) {
     609            3 :     const targetNode = subgraph.getNodeById(target.targetNodeId)
     610            3 :     if (!targetNode) return failPrimitive('target node missing', target)
     611            3 :     const targetSlot = targetNode.inputs.at(target.targetSlot)
     612            3 :     if (!targetSlot) return failPrimitive('target slot missing', target)
     613              :     // oxlint-disable-next-line typescript/no-unnecessary-condition -- legacy workflow slots may omit type at runtime
     614            3 :     const targetType = String(targetSlot.type ?? '*')
     615            3 :     if (
     616              :       targetType !== primitiveOutputType &&
     617              :       targetType !== '*' &&
     618              :       primitiveOutputType !== '*'
     619              :     ) {
     620            0 :       return failPrimitive('target slot type incompatible', {
     621              :         target,
     622              :         targetType,
     623              :         primitiveOutputType
     624              :       })
     625              :     }
     626              :   }
     627              : 
     628            3 :   const baseName = userRenamedTitle(primitiveNode) ?? validated.sourceWidgetName
     629            3 :   const snapshot: SnapshotLink[] = primitiveOutputTopologies(primitiveNode).map(
     630              :     (topology) => ({
     631              :       primitiveSlot: topology.originSlot,
     632              :       targetNodeId: topology.targetNodeId,
     633              :       targetSlot: topology.targetSlot
     634              :     })
     635              :   )
     636              : 
     637            3 :   let newSubgraphInput: SubgraphInput | undefined
     638            3 :   try {
     639            3 :     newSubgraphInput = addUniqueSubgraphInput(
     640              :       subgraph,
     641              :       baseName,
     642              :       primitiveOutputType
     643              :     )
     644              : 
     645            3 :     for (const snap of snapshot) {
     646            3 :       const targetNode = subgraph.getNodeById(snap.targetNodeId)
     647            3 :       if (!targetNode)
     648            0 :         throw new Error(
     649              :           `target node ${snap.targetNodeId} disappeared mid-mutation`
     650              :         )
     651            3 :       targetNode.disconnectInput(snap.targetSlot, false)
     652              :     }
     653              : 
     654            3 :     for (const target of targets) {
     655            3 :       const targetNode = subgraph.getNodeById(target.targetNodeId)
     656            3 :       if (!targetNode)
     657            0 :         throw new Error(`target node ${target.targetNodeId} disappeared`)
     658            3 :       const targetSlot = targetNode.inputs.at(target.targetSlot)
     659            3 :       if (!targetSlot)
     660            0 :         throw new Error(`target slot ${target.targetSlot} disappeared`)
     661              :       const link = newSubgraphInput.connect(targetSlot, targetNode)
     662            3 :       if (!link) {
     663            0 :         throw new Error('SubgraphInput.connect returned no link')
     664              :       }
     665              :     }
     666              :   } catch (e) {
     667            0 :     rollback(hostNode, primitiveNode, newSubgraphInput, snapshot)
     668            0 :     return failPrimitive('mutation failed; rolled back', { error: e })
     669              :   }
     670              : 
     671            3 :   const hostInput = hostNode.inputs.find(
     672              :     (input) => input.name === newSubgraphInput.name
     673              :   )
     674            3 :   if (hostInput) {
     675            3 :     const valueEntry = validated.uniqueEntries.find((e) => !e.isHole)
     676            3 :     if (valueEntry) {
     677            1 :       applyHostValueToInput(hostInput, valueEntry)
     678              :     } else {
     679            2 :       const primitiveValue = primitiveNode.widgets?.find(
     680              :         (w) => w.name === validated.sourceWidgetName
     681              :       )?.value
     682            2 :       if (primitiveValue !== undefined) {
     683            0 :         applyHostValueToInput(hostInput, {
     684              :           ...validated.uniqueEntries[0],
     685              :           hostValue: primitiveValue,
     686              :           isHole: false
     687              :         })
     688              :       }
     689              :     }
     690              :   }
     691              : 
     692            3 :   primitiveNode.properties[PROXY_BYPASS_MARKER_PROPERTY] = newSubgraphInput.name
     693              : 
     694            3 :   return {
     695              :     ok: true,
     696              :     subgraphInputName: newSubgraphInput.name,
     697              :     reconnectCount: targets.length
     698              :   }
     699              : }
     700              : 
     701              : type MigratePreviewResult = Outcome<
     702              :   { previewName: string },
     703              :   'missingSourceNode' | 'missingSourceWidget'
     704              : >
     705              : 
     706           10 : function migratePreview(
     707              :   hostNode: SubgraphNode,
     708              :   entry: PendingEntry,
     709              :   store: ReturnType<typeof usePreviewExposureStore>,
     710              :   plan: { kind: 'previewExposure'; sourcePreviewName: string }
     711              : ): MigratePreviewResult {
     712           10 :   const sourceNode = hostNode.subgraph.getNodeById(
     713              :     entry.normalized.sourceNodeId
     714              :   )
     715           10 :   if (!sourceNode) {
     716            0 :     return { ok: false, reason: 'missingSourceNode' }
     717              :   }
     718              : 
     719              :   const isCanonicalPseudo = plan.sourcePreviewName.startsWith('$$')
     720           10 :   if (!isCanonicalPseudo) {
     721              :     const widget = sourceNode.widgets?.find(
     722              :       (w) => w.name === plan.sourcePreviewName
     723              :     )
     724            0 :     if (!widget) {
     725            0 :       return { ok: false, reason: 'missingSourceWidget' }
     726              :     }
     727              :   }
     728              : 
     729           10 :   const hostNodeLocator = getPreviewExposureHostLocator(hostNode)
     730           10 :   if (!hostNodeLocator) return { ok: false, reason: 'missingSourceNode' }
     731           10 :   const existing = store
     732              :     .getExposures(hostNode.rootGraph.id, hostNodeLocator)
     733              :     .find(
     734              :       (exposure) =>
     735              :         exposure.sourceNodeId === entry.normalized.sourceNodeId &&
     736              :         exposure.sourcePreviewName === plan.sourcePreviewName
     737              :     )
     738           10 :   if (existing) return { ok: true, previewName: existing.name }
     739              : 
     740              :   const added = store.addExposure(hostNode.rootGraph.id, hostNodeLocator, {
     741              :     sourceNodeId: entry.normalized.sourceNodeId,
     742              :     sourcePreviewName: plan.sourcePreviewName
     743              :   })
     744              : 
     745           10 :   return { ok: true, previewName: added.name }
     746              : }
     747              : 
     748           80 : function quarantineFor(
     749              :   entry: PendingEntry,
     750              :   reason: ProxyWidgetQuarantineReason
     751              : ): ProxyWidgetErrorQuarantineEntry {
     752           80 :   return makeQuarantineEntry({
     753              :     originalEntry: entry.originalEntry,
     754              :     reason,
     755              :     hostValue: entry.isHole ? undefined : entry.hostValue
     756              :   })
     757              : }
     758              : 
     759           77 : export function appendQuarantine(
     760              :   hostNode: SubgraphNode,
     761              :   entries: readonly ProxyWidgetErrorQuarantineEntry[]
     762              : ): void {
     763           77 :   if (entries.length === 0) return
     764              : 
     765           77 :   for (const {
     766              :     originalEntry: [sourceNodeId, inputName],
     767              :     hostValue
     768              :   } of entries) {
     769           80 :     if (sourceNodeId !== '-1' || hostValue === undefined) continue
     770              : 
     771           54 :     const input = hostNode.inputs.find((input) => input.name === inputName)
     772           80 :     if (input?.widgetId)
     773           54 :       useWidgetValueStore().restoreValue(input.widgetId, hostValue)
     774              :   }
     775              : 
     776              :   const existing = parseProxyWidgetErrorQuarantine(
     777              :     hostNode.properties[QUARANTINE_PROPERTY]
     778              :   )
     779           77 :   const merged = [...existing]
     780           77 :   for (const candidate of entries) {
     781           80 :     if (
     782              :       !merged.some((e) => isEqual(e.originalEntry, candidate.originalEntry))
     783              :     ) {
     784           80 :       merged.push(candidate)
     785              :     }
     786              :   }
     787           77 :   if (merged.length === 0) delete hostNode.properties[QUARANTINE_PROPERTY]
     788           77 :   else hostNode.properties[QUARANTINE_PROPERTY] = merged
     789              : }
     790              : 
     791              : export function readHostQuarantine(
     792              :   hostNode: SubgraphNode
     793              : ): ProxyWidgetErrorQuarantineEntry[] {
     794              :   return parseProxyWidgetErrorQuarantine(
     795              :     hostNode.properties[QUARANTINE_PROPERTY]
     796              :   )
     797              : }
     798              : 
     799           80 : export function makeQuarantineEntry(args: {
     800              :   originalEntry: SerializedProxyWidgetTuple
     801              :   reason: ProxyWidgetQuarantineReason
     802              :   hostValue?: TWidgetValue
     803              : }): ProxyWidgetErrorQuarantineEntry {
     804           80 :   const entry: ProxyWidgetErrorQuarantineEntry = {
     805              :     originalEntry: args.originalEntry,
     806              :     reason: args.reason,
     807              :     attemptedAtVersion: QUARANTINE_VERSION
     808              :   }
     809           80 :   if (args.hostValue !== undefined) {
     810           55 :     entry.hostValue = args.hostValue
     811              :   }
     812           80 :   return entry
     813              : }
        

Generated by: LCOV version 2.0-1