Line data Source code
1 : /**
2 : * Installs per-node error-clearing callbacks (onConnectionsChange,
3 : * onWidgetChanged) on all current and future nodes in a graph.
4 : *
5 : * Decoupled from the Vue rendering lifecycle so that error auto-clearing
6 : * works in legacy canvas mode as well.
7 : */
8 : import { useChainCallback } from '@/composables/functional/useChainCallback'
9 : import { resolvePromotedWidgetSource } from '@/core/graph/subgraph/resolvePromotedWidgetSource'
10 : import { createPromotionErrorReconciler } from '@/core/graph/subgraph/createPromotionErrorReconciler'
11 : import type {
12 : NodeBeforeRemovedEvent,
13 : NodeLifecycleEvent
14 : } from '@comfyorg/graph-model/LGraphEventMap'
15 : import { LiteGraph, Subgraph } from '@/lib/litegraph/src/litegraph'
16 : import type { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph'
17 : import {
18 : LGraphEventMode,
19 : NodeSlotType
20 : } from '@comfyorg/graph-model/globalEnums'
21 : import type { LGraphTriggerEvent } from '@comfyorg/graph-model/graphTriggers'
22 : import { ChangeTracker } from '@/scripts/changeTracker'
23 : import { assetService } from '@/platform/assets/services/assetService'
24 : import type { MissingMediaCandidate } from '@/platform/workflowErrors/missingMedia/types'
25 : import type { MissingModelCandidate } from '@/platform/workflowErrors/missingModel/types'
26 : import {
27 : scanNodeModelCandidates,
28 : verifyAssetSupportedCandidates
29 : } from '@/platform/workflowErrors/missingModel/missingModelScan'
30 : import { useMissingModelStore } from '@/platform/workflowErrors/missingModel/missingModelStore'
31 : import { cloudReleaseModelOptions } from '@/platform/workflowErrors/missingModel/releaseModelOptions'
32 : import {
33 : isMissingMediaCandidateActive,
34 : isMissingMediaCandidateScopeActive,
35 : scanNodeMediaCandidates,
36 : verifyMediaCandidates
37 : } from '@/platform/workflowErrors/missingMedia/missingMediaScan'
38 : import { useMissingMediaStore } from '@/platform/workflowErrors/missingMedia/missingMediaStore'
39 : import { useMissingNodesErrorStore } from '@/platform/workflowErrors/nodeReplacement/missingNodesErrorStore'
40 : import { useNodeReplacementStore } from '@/platform/workflowErrors/nodeReplacement/nodeReplacementStore'
41 : import { getCnrIdFromNode } from '@/platform/workflowErrors/nodeReplacement/cnrIdUtil'
42 : import { app } from '@/scripts/app'
43 : import { useExecutionErrorStore } from '@/stores/executionErrorStore'
44 : import { toNodeId } from '@comfyorg/graph-model/nodeId'
45 : import type { NodeId } from '@comfyorg/graph-model/nodeId'
46 : import { useModelToNodeStore } from '@/stores/modelToNodeStore'
47 : import {
48 : collectAllNodes,
49 : getExecutionIdByNode,
50 : getExecutionIdForNodeInGraph,
51 : getNodeByExecutionId,
52 : isExecutionPathActive,
53 : isMissingCandidateActive
54 : } from '@/utils/graphTraversalUtil'
55 : import { getParentExecutionIds } from '@comfyorg/graph-model/nodeIdentification'
56 :
57 2355 : const hookedNodes = new WeakSet<LGraphNode>()
58 :
59 : type OriginalCallbacks = {
60 : onConnectionsChange: LGraphNode['onConnectionsChange']
61 : onWidgetChanged: LGraphNode['onWidgetChanged']
62 : }
63 :
64 2355 : const originalCallbacks = new WeakMap<LGraphNode, OriginalCallbacks>()
65 :
66 10088 : function getRemovedNodeExecutionId(graph: LGraph, nodeId: NodeId): string {
67 10088 : const rootGraph = app.rootGraphOrUndefined
68 10088 : if (!rootGraph) return String(nodeId)
69 :
70 10088 : return (
71 : getExecutionIdForNodeInGraph(rootGraph, graph, nodeId) ?? String(nodeId)
72 : )
73 : }
74 :
75 23250 : function installNodeHooks(node: LGraphNode): void {
76 23250 : if (hookedNodes.has(node)) return
77 23228 : hookedNodes.add(node)
78 :
79 23228 : originalCallbacks.set(node, {
80 : onConnectionsChange: node.onConnectionsChange,
81 : onWidgetChanged: node.onWidgetChanged
82 : })
83 :
84 23228 : node.onConnectionsChange = useChainCallback(
85 : node.onConnectionsChange,
86 : function (type, slotIndex: number | undefined, isConnected) {
87 107202 : if (type !== NodeSlotType.INPUT || slotIndex === undefined) return
88 81064 : const rootGraph = app.rootGraphOrUndefined
89 107202 : if (!rootGraph) return
90 107202 : const slotName = node.inputs.at(slotIndex)?.name
91 107202 : if (!slotName) return
92 81058 : const execId = getExecutionIdByNode(rootGraph, node)
93 107202 : if (!execId) return
94 83302 : if (isConnected) {
95 80715 : useExecutionErrorStore().clearSimpleNodeErrors(execId, slotName)
96 : }
97 81054 : queueMicrotask(() => {
98 81054 : if (!app.rootGraphOrUndefined || ChangeTracker.isLoadingGraph) return
99 1311 : dropOutOfScopeMissingMedia()
100 9242 : if (!isConnected) scanSingleNodeMedia(node)
101 : })
102 : }
103 : )
104 :
105 23228 : node.onWidgetChanged = useChainCallback(
106 : node.onWidgetChanged,
107 : function (name, newValue, _oldValue, widget) {
108 126 : const rootGraph = app.rootGraphOrUndefined
109 126 : if (!rootGraph) return
110 126 : const hostExecId = getExecutionIdByNode(rootGraph, node)
111 126 : if (!hostExecId) return
112 :
113 126 : const options = { min: widget.options.min, max: widget.options.max }
114 126 : const source = resolvePromotedWidgetSource(rootGraph, node, widget)
115 126 : if (source?.sourceExecutionId) {
116 2 : useExecutionErrorStore().clearWidgetRelatedErrors(
117 : source.sourceExecutionId,
118 : source.sourceWidgetName,
119 : source.sourceWidgetName,
120 : newValue,
121 : options
122 : )
123 : }
124 :
125 126 : useExecutionErrorStore().clearWidgetRelatedErrors(
126 : hostExecId,
127 : name,
128 : widget.name,
129 : newValue,
130 : options
131 : )
132 : }
133 : )
134 : }
135 :
136 11070 : function restoreNodeHooks(node: LGraphNode): void {
137 11070 : const originals = originalCallbacks.get(node)
138 11070 : if (!originals) return
139 11044 : node.onConnectionsChange = originals.onConnectionsChange
140 11044 : node.onWidgetChanged = originals.onWidgetChanged
141 11044 : originalCallbacks.delete(node)
142 11044 : hookedNodes.delete(node)
143 : }
144 :
145 23250 : function installNodeHooksRecursive(node: LGraphNode): void {
146 23250 : installNodeHooks(node)
147 23250 : if (node.isSubgraphNode()) {
148 555 : for (const innerNode of node.subgraph._nodes) {
149 1137 : installNodeHooksRecursive(innerNode)
150 : }
151 : }
152 : }
153 :
154 11070 : function restoreNodeHooksRecursive(node: LGraphNode): void {
155 11070 : restoreNodeHooks(node)
156 11070 : if (node.isSubgraphNode()) {
157 271 : for (const innerNode of node.subgraph._nodes) {
158 559 : restoreNodeHooksRecursive(innerNode)
159 : }
160 : }
161 : }
162 :
163 4125 : function isNodeInactive(mode: number): boolean {
164 4125 : return mode === LGraphEventMode.NEVER || mode === LGraphEventMode.BYPASS
165 : }
166 :
167 1377 : function scanNodeErrorTargets(
168 : node: LGraphNode,
169 : scanNode: (node: LGraphNode) => void
170 : ): void {
171 1377 : if (!app.rootGraphOrUndefined) return
172 :
173 1377 : if (node.isSubgraphNode()) {
174 618 : scanNode(node)
175 618 : for (const innerNode of collectAllNodes(node.subgraph)) {
176 2619 : if (isNodeInactive(innerNode.mode)) continue
177 2619 : scanNode(innerNode)
178 : }
179 618 : return
180 : }
181 :
182 759 : scanNode(node)
183 : }
184 :
185 4359 : function getActiveExecutionId(node: LGraphNode): string | null {
186 4359 : const rootGraph = app.rootGraphOrUndefined
187 4359 : if (!rootGraph) return null
188 : // Skip when any enclosing subgraph is muted/bypassed. Callers only
189 : // verify each node's own mode, so an active node added inside a
190 : // bypassed subgraph reaches this point without the ancestor check.
191 : // A null execId means the node has no current graph (e.g. detached
192 : // mid lifecycle) — also skip, since we cannot verify its scope.
193 4359 : const execId = getExecutionIdByNode(rootGraph, node)
194 4359 : if (!execId || !isExecutionPathActive(rootGraph, execId)) return null
195 4184 : return execId
196 : }
197 :
198 : /** Scan a single node and add confirmed missing model/media to stores.
199 : * For subgraph containers, also scans all active interior nodes. */
200 31 : function scanAndAddNodeErrors(node: LGraphNode): void {
201 31 : scanNodeErrorTargets(node, scanSingleNodeErrors)
202 : }
203 :
204 36 : function scanSingleNodeErrors(node: LGraphNode): void {
205 36 : scanSingleNodeModelsAndTypes(node)
206 36 : scanSingleNodeMedia(node)
207 : }
208 :
209 606 : function scanSingleNodeModelsAndTypes(
210 : node: LGraphNode,
211 : pendingVerifications?: Promise<void>[],
212 : signal?: AbortSignal
213 : ): void {
214 606 : const rootGraph = app.rootGraphOrUndefined
215 606 : if (!rootGraph) return
216 606 : const execId = getActiveExecutionId(node)
217 606 : if (!execId) return
218 :
219 606 : const modelCandidates = scanNodeModelCandidates(
220 : rootGraph,
221 : node,
222 : assetService.shouldUseWidgetAssetPicker,
223 : (nodeType) => useModelToNodeStore().getCategoryForNodeType(nodeType),
224 : cloudReleaseModelOptions()
225 : )
226 606 : const confirmedModels = modelCandidates.filter((c) => c.isMissing === true)
227 606 : if (confirmedModels.length) {
228 40 : useMissingModelStore().addMissingModels(confirmedModels)
229 : }
230 : // Cloud scans return isMissing: undefined for asset-browser-supported
231 : // widgets until async verification resolves. Without this, realtime
232 : // add/un-bypass paths would silently drop those candidates.
233 606 : const pendingModels = modelCandidates.filter((c) => c.isMissing === undefined)
234 606 : if (pendingModels.length) {
235 0 : const verification = verifyAndAddPendingModels(pendingModels, signal)
236 0 : if (pendingVerifications) pendingVerifications.push(verification)
237 : else void verification
238 : }
239 :
240 606 : if (node.isSubgraphNode()) return
241 :
242 606 : const originalType = node.last_serialization?.type ?? node.type
243 606 : if (!(originalType in LiteGraph.registered_node_types)) {
244 : const nodeReplacementStore = useNodeReplacementStore()
245 3 : const replacement = nodeReplacementStore.getReplacementFor(originalType)
246 3 : const store = useMissingNodesErrorStore()
247 3 : const existing = store.missingNodesError?.nodeTypes ?? []
248 3 : store.surfaceMissingNodes([
249 : ...existing,
250 : {
251 : type: originalType,
252 : nodeId: execId,
253 : cnrId: getCnrIdFromNode(node),
254 : isReplaceable: replacement !== null,
255 : replacement: replacement ?? undefined
256 : }
257 : ])
258 : }
259 : }
260 :
261 3753 : function scanSingleNodeMedia(
262 : node: LGraphNode,
263 : pendingVerifications?: Promise<void>[],
264 : signal?: AbortSignal
265 : ): void {
266 3753 : const rootGraph = app.rootGraphOrUndefined
267 3753 : if (!rootGraph) return
268 3753 : if (!getActiveExecutionId(node)) return
269 :
270 3578 : const mediaCandidates = scanNodeMediaCandidates(rootGraph, node)
271 3578 : const confirmedMedia = mediaCandidates.filter((c) => c.isMissing === true)
272 3729 : if (confirmedMedia.length) {
273 11 : useMissingMediaStore().addMissingMedia(confirmedMedia)
274 : }
275 : // Cloud media scans return pending for asset verification. OSS scans only
276 : // return pending for generated output media.
277 3578 : const pendingMedia = mediaCandidates.filter((c) => c.isMissing === undefined)
278 3729 : if (pendingMedia.length) {
279 3 : const verification = verifyAndAddPendingMedia(pendingMedia, signal)
280 3 : if (pendingVerifications) pendingVerifications.push(verification)
281 : else void verification
282 : }
283 : }
284 :
285 : /**
286 : * True when the candidate's node still exists in the current root graph
287 : * and is active. Filters out late verification results for nodes that
288 : * have been bypassed, deleted, or belong to a workflow that is no
289 : * longer current — any of which would reintroduce stale errors.
290 : */
291 0 : function isModelCandidateStillMissingAndActive(
292 : candidate: MissingModelCandidate
293 : ): boolean {
294 0 : const rootGraph = app.rootGraphOrUndefined
295 0 : if (!isMissingCandidateActive(rootGraph, candidate)) return false
296 0 : if (!rootGraph || candidate.nodeId == null) return true
297 :
298 0 : const node = getNodeByExecutionId(rootGraph, String(candidate.nodeId))
299 0 : const widget = node?.widgets?.find(
300 : (candidateWidget) => candidateWidget.name === candidate.widgetName
301 : )
302 0 : if (!node || !widget || widget.value !== candidate.name) return false
303 0 : if (node.getSlotFromWidget(widget)?.link != null) return false
304 0 : if (!node.isSubgraphNode()) return true
305 :
306 0 : return (
307 : resolvePromotedWidgetSource(rootGraph, node, widget)?.sourceExecutionId ===
308 : candidate.sourceExecutionId
309 : )
310 : }
311 :
312 3 : function hasSameNodeOwner(
313 : rootGraph: LGraph,
314 : candidate: { nodeId?: string | number | null },
315 : ownerAtScan: LGraphNode | null | undefined
316 : ): boolean {
317 3 : return (
318 : candidate.nodeId == null ||
319 : ownerAtScan === getNodeByExecutionId(rootGraph, String(candidate.nodeId))
320 : )
321 : }
322 :
323 0 : async function verifyAndAddPendingModels(
324 : pending: MissingModelCandidate[],
325 : signal?: AbortSignal
326 : ): Promise<void> {
327 : // Capture rootGraph at scan time so a late verification for workflow
328 : // A cannot leak into workflow B after a switch — execution IDs (esp.
329 : // root-level like "1") collide across workflows.
330 0 : const rootGraphAtScan = app.rootGraphOrUndefined
331 0 : const ownersAtScan = new Map(
332 : pending.map((candidate) => [
333 : candidate,
334 : candidate.nodeId == null || rootGraphAtScan === undefined
335 : ? null
336 : : getNodeByExecutionId(rootGraphAtScan, String(candidate.nodeId))
337 : ])
338 : )
339 0 : try {
340 0 : await verifyAssetSupportedCandidates(pending, signal)
341 0 : if (
342 : signal?.aborted ||
343 : !rootGraphAtScan ||
344 : app.rootGraphOrUndefined !== rootGraphAtScan
345 : )
346 0 : return
347 0 : const verified = pending.filter(
348 : (candidate) =>
349 : hasSameNodeOwner(
350 : rootGraphAtScan,
351 : candidate,
352 : ownersAtScan.get(candidate)
353 : ) && isModelCandidateStillMissingAndActive(candidate)
354 : )
355 0 : if (verified.length) useMissingModelStore().addMissingModels(verified)
356 : } catch (error: unknown) {
357 0 : console.warn('[useErrorClearingHooks] model verification failed:', error)
358 : }
359 : }
360 :
361 3 : async function verifyAndAddPendingMedia(
362 : pending: MissingMediaCandidate[],
363 : signal?: AbortSignal
364 : ): Promise<void> {
365 3 : const rootGraphAtScan = app.rootGraphOrUndefined
366 3 : const ownersAtScan = new Map(
367 : pending.map((candidate) => [
368 : candidate,
369 : rootGraphAtScan
370 : ? getNodeByExecutionId(rootGraphAtScan, String(candidate.nodeId))
371 : : null
372 : ])
373 : )
374 3 : try {
375 3 : await verifyMediaCandidates(pending, { signal })
376 3 : if (
377 : signal?.aborted ||
378 : !rootGraphAtScan ||
379 : app.rootGraphOrUndefined !== rootGraphAtScan
380 : )
381 0 : return
382 3 : const verified = pending.filter(
383 : (candidate) =>
384 : hasSameNodeOwner(
385 : rootGraphAtScan,
386 : candidate,
387 : ownersAtScan.get(candidate)
388 : ) && isMissingMediaCandidateActive(rootGraphAtScan, candidate)
389 : )
390 3 : if (verified.length) useMissingMediaStore().addMissingMedia(verified)
391 : } catch (error: unknown) {
392 0 : console.warn('[useErrorClearingHooks] media verification failed:', error)
393 : }
394 : }
395 :
396 872 : function scanAddedNode(
397 : rootGraph: LGraph,
398 : node: LGraphNode,
399 : scanNode: (node: LGraphNode) => void
400 : ): void {
401 872 : if (app.rootGraphOrUndefined !== rootGraph || ChangeTracker.isLoadingGraph)
402 0 : return
403 872 : if (isNodeInactive(node.mode)) return
404 868 : scanNodeErrorTargets(node, scanNode)
405 : }
406 :
407 436 : async function runAddedNodeScan(
408 : rootGraph: LGraph,
409 : node: LGraphNode,
410 : signal: AbortSignal
411 : ): Promise<void> {
412 436 : const pendingVerifications: Promise<void>[] = []
413 :
414 436 : try {
415 436 : await Promise.resolve()
416 436 : if (signalAborted(signal) || app.rootGraphOrUndefined !== rootGraph) return
417 436 : scanAddedNode(rootGraph, node, (target) =>
418 : scanSingleNodeModelsAndTypes(target, pendingVerifications, signal)
419 : )
420 :
421 : // Paste/drop handlers need another microtask to mark upload state before
422 : // media detection reads the widget value.
423 436 : await Promise.resolve()
424 436 : if (signalAborted(signal) || app.rootGraphOrUndefined !== rootGraph) return
425 436 : scanAddedNode(rootGraph, node, (target) =>
426 : scanSingleNodeMedia(target, pendingVerifications, signal)
427 : )
428 : } finally {
429 436 : await Promise.allSettled(pendingVerifications)
430 : }
431 : }
432 :
433 : interface PendingScanControl {
434 : cancel: () => void
435 : finish: () => void
436 : }
437 :
438 872 : function signalAborted(signal: AbortSignal): boolean {
439 872 : return signal.aborted
440 : }
441 :
442 21667 : function scheduleAddedNodeScan(
443 : node: LGraphNode,
444 : pendingScans: Map<LGraphNode, Set<PendingScanControl>>
445 : ): void {
446 21667 : const rootGraph = app.rootGraphOrUndefined
447 21667 : if (!rootGraph || ChangeTracker.isLoadingGraph) return
448 5740 : if (isNodeInactive(node.mode)) return
449 :
450 436 : const executionId = getExecutionIdByNode(rootGraph, node)
451 3519 : if (!executionId) return
452 :
453 436 : const finishPendingScan = useExecutionErrorStore().beginAddedNodeErrorScan(
454 : rootGraph,
455 : executionId
456 : )
457 436 : const abortController = new AbortController()
458 436 : const existingScans = pendingScans.get(node)
459 21667 : const scansForNode = existingScans ?? new Set<PendingScanControl>()
460 21667 : if (!existingScans) {
461 436 : pendingScans.set(node, scansForNode)
462 : }
463 :
464 436 : function finish() {
465 436 : finishPendingScan()
466 436 : scansForNode.delete(control)
467 436 : if (scansForNode.size === 0) pendingScans.delete(node)
468 : }
469 :
470 0 : function cancel() {
471 0 : abortController.abort()
472 0 : finish()
473 : }
474 :
475 436 : const control = { cancel, finish }
476 436 : scansForNode.add(control)
477 436 : void runAddedNodeScan(rootGraph, node, abortController.signal)
478 : .catch((error: unknown) => {
479 0 : console.warn('[useErrorClearingHooks] added-node scan failed:', error)
480 : })
481 : .finally(finish)
482 : }
483 :
484 99 : function handleNodeModeChange(
485 : localGraph: LGraph,
486 : nodeId: NodeId,
487 : oldMode: number,
488 : newMode: number
489 : ): void {
490 99 : const rootGraph = app.rootGraphOrUndefined
491 99 : if (!rootGraph) return
492 :
493 99 : const wasInactive = isNodeInactive(oldMode)
494 99 : const isNowInactive = isNodeInactive(newMode)
495 :
496 99 : if (wasInactive === isNowInactive) return
497 :
498 : // Find the node by local ID in the graph that fired the event,
499 : // then compute its execution ID relative to the root graph.
500 99 : const node = localGraph.getNodeById(nodeId)
501 99 : if (!node) return
502 :
503 99 : const execId = getExecutionIdByNode(rootGraph, node)
504 99 : if (!execId) return
505 :
506 99 : if (isNowInactive) {
507 68 : removeNodeErrors(node, execId)
508 68 : dropOutOfScopeMissingMedia()
509 : } else {
510 31 : scanAndAddNodeErrors(node)
511 31 : scanAncestorSubgraphHosts(execId)
512 31 : const executionErrorStore = useExecutionErrorStore()
513 31 : if (executionErrorStore.hasMissingError) {
514 21 : executionErrorStore.showErrorOverlay()
515 : }
516 : }
517 : }
518 :
519 31 : function scanAncestorSubgraphHosts(execId: string): void {
520 31 : const rootGraph = app.rootGraphOrUndefined
521 31 : if (!rootGraph) return
522 31 : for (const ancestorId of getParentExecutionIds(execId)) {
523 2 : if (!isExecutionPathActive(rootGraph, ancestorId)) continue
524 2 : const ancestor = getNodeByExecutionId(rootGraph, ancestorId)
525 2 : if (ancestor?.isSubgraphNode()) scanSingleNodeErrors(ancestor)
526 : }
527 : }
528 :
529 : /** Remove all missing asset errors for a node and, if it's a subgraph
530 : * container, for all interior nodes (prefix match on execution ID). */
531 10156 : function removeNodeErrors(node: LGraphNode, execId: string): void {
532 10156 : const modelStore = useMissingModelStore()
533 10156 : const mediaStore = useMissingMediaStore()
534 10156 : const nodesStore = useMissingNodesErrorStore()
535 :
536 10156 : modelStore.removeMissingModelsByNodeId(execId)
537 10156 : modelStore.removeMissingModelsBySourceScope(execId)
538 10156 : mediaStore.removeMissingMediaByNodeId(execId)
539 10156 : nodesStore.removeMissingNodesByNodeId(execId)
540 :
541 : // For subgraph containers, also remove errors from interior nodes.
542 : // The trailing colon in the prefix is load-bearing: it prevents sibling
543 : // IDs sharing a numeric prefix (e.g. "705" vs "70") from being matched.
544 10156 : if (node.isSubgraphNode()) {
545 88 : const prefix = `${execId}:`
546 88 : modelStore.removeMissingModelsByPrefix(prefix)
547 88 : mediaStore.removeMissingMediaByPrefix(prefix)
548 88 : nodesStore.removeMissingNodesByPrefix(prefix)
549 : }
550 : }
551 :
552 : /** Removes candidates whose widget is no longer the editable value owner. */
553 3501 : function dropOutOfScopeMissingMedia(): void {
554 3501 : const rootGraph = app.rootGraphOrUndefined
555 3501 : if (!rootGraph || ChangeTracker.isLoadingGraph) return
556 :
557 1779 : const mediaStore = useMissingMediaStore()
558 1779 : const candidates = mediaStore.missingMediaCandidates
559 1780 : if (!candidates) return
560 4 : const inScope = candidates.filter((candidate) =>
561 : isMissingMediaCandidateScopeActive(rootGraph, candidate)
562 : )
563 4 : if (inScope.length === candidates.length) return
564 0 : mediaStore.setMissingMedia(inScope)
565 : }
566 :
567 4924 : export function installErrorClearingHooks(graph: LGraph): () => void {
568 4924 : const pendingScans = new Map<LGraphNode, Set<PendingScanControl>>()
569 4924 : let disposed = false
570 4924 : let pendingOutOfScopeDrop = false
571 :
572 : /**
573 : * Coalesces `dropOutOfScopeMissingMedia` across a burst of removals, which
574 : * would otherwise re-walk every candidate's topology once per removed node.
575 : */
576 4924 : const scheduleDropOutOfScopeMissingMedia = (): void => {
577 10088 : if (pendingOutOfScopeDrop) return
578 1646 : pendingOutOfScopeDrop = true
579 1646 : queueMicrotask(() => {
580 1646 : pendingOutOfScopeDrop = false
581 1646 : if (disposed) return
582 1644 : dropOutOfScopeMissingMedia()
583 : })
584 : }
585 :
586 4924 : const promotionErrors = createPromotionErrorReconciler({
587 : dropOutOfScope: dropOutOfScopeMissingMedia,
588 : rescanHost: (subgraphNode) =>
589 : scanNodeErrorTargets(subgraphNode, scanSingleNodeMedia),
590 : removeHostWidgetCandidate: (subgraphNode, widgetName) => {
591 29 : const rootGraph = app.rootGraphOrUndefined
592 29 : if (!rootGraph) return
593 29 : const executionId = getExecutionIdByNode(rootGraph, subgraphNode)
594 29 : if (!executionId) return
595 29 : useMissingMediaStore().removeMissingMediaByWidget(executionId, widgetName)
596 : }
597 : })
598 :
599 4924 : if (graph instanceof Subgraph) promotionErrors.attach(graph)
600 4924 : for (const node of graph._nodes) {
601 446 : installNodeHooksRecursive(node)
602 446 : promotionErrors.attachNode(node)
603 : }
604 :
605 4924 : const onNodeAdded = ({ detail: { node } }: NodeLifecycleEvent) => {
606 21667 : if (disposed) return
607 21667 : installNodeHooksRecursive(node)
608 21667 : promotionErrors.attachNode(node)
609 21667 : scheduleAddedNodeScan(node, pendingScans)
610 : }
611 :
612 : // `node:before-removed` covers both single removals and graph.clear();
613 : // `node:removed` fires only from LGraph.remove.
614 4924 : const onNodeRemoved = ({ detail: { node } }: NodeBeforeRemovedEvent) => {
615 10088 : if (disposed) return
616 10088 : for (const scan of pendingScans.get(node) ?? []) scan.cancel()
617 : // Derive the execution ID from the graph the hook is installed on plus
618 : // node.id. For subgraph interior nodes this yields the full
619 : // "parentId:...:nodeId" path that matches how missing asset errors are
620 : // keyed; without this, removal falls back to the local ID and misses
621 : // subgraph entries.
622 : const execId = getRemovedNodeExecutionId(graph, node.id)
623 10088 : removeNodeErrors(node, execId)
624 10088 : scheduleDropOutOfScopeMissingMedia()
625 10088 : restoreNodeHooksRecursive(node)
626 10088 : promotionErrors.detachNode(node)
627 : }
628 :
629 4924 : graph.events.addEventListener('node:added', onNodeAdded)
630 4924 : graph.events.addEventListener('node:before-removed', onNodeRemoved)
631 :
632 4924 : const originalOnTrigger = graph.onTrigger
633 4924 : graph.onTrigger = (event: LGraphTriggerEvent) => {
634 20496 : if (disposed) {
635 0 : originalOnTrigger?.(event)
636 0 : return
637 : }
638 20496 : if (event.type === 'node:property:changed' && event.property === 'mode') {
639 99 : handleNodeModeChange(
640 : graph,
641 : toNodeId(event.nodeId),
642 : event.oldValue as number,
643 : event.newValue as number
644 : )
645 : }
646 20496 : originalOnTrigger?.(event)
647 : }
648 :
649 4924 : return () => {
650 2569 : if (disposed) return
651 2569 : disposed = true
652 2569 : for (const scans of pendingScans.values()) {
653 0 : for (const scan of scans) scan.finish()
654 : }
655 2569 : for (const node of graph._nodes) {
656 423 : restoreNodeHooksRecursive(node)
657 : }
658 2569 : graph.events.removeEventListener('node:added', onNodeAdded)
659 2569 : graph.events.removeEventListener('node:before-removed', onNodeRemoved)
660 2569 : graph.onTrigger = originalOnTrigger || undefined
661 2569 : promotionErrors.dispose()
662 : }
663 : }
|