Line data Source code
1 : import QuickLRU from '@alloc/quick-lru'
2 : import { useRouteHash } from '@vueuse/router'
3 : import { defineStore } from 'pinia'
4 : import { computed, ref, shallowRef, watch } from 'vue'
5 : import {
6 : NavigationFailureType,
7 : isNavigationFailure,
8 : useRouter
9 : } from 'vue-router'
10 :
11 : import type { PanZoom as DragAndScaleState } from '@comfyorg/shared-frontend-utils/geometry'
12 : import type { LGraph, Subgraph } from '@/lib/litegraph/src/litegraph'
13 : import type { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore'
14 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
15 : import { reportError } from '@comfyorg/telemetry/reportError'
16 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
17 : import { useCanvasScheduler } from '@/renderer/core/canvas/useCanvasScheduler'
18 : import { isUuidShapedSubgraphId } from '@/schemas/subgraphIdSchema'
19 : import { useApp } from '@/scripts/appInstance'
20 : import type { ComfyApp } from '@/types/comfy'
21 : import { useLitegraphServiceAccess } from '@/core/graph/litegraphServiceAccess'
22 : import { findSubgraphPathById } from '@/utils/graphTraversalUtil'
23 : import { isNonNullish, isSubgraph } from '@/utils/typeGuardUtil'
24 :
25 : interface WorkflowServiceAccess {
26 : openWorkflow(
27 : workflow: ComfyWorkflow,
28 : options: { navigationIntentId?: number; initiator?: 'user' }
29 : ): Promise<boolean>
30 : }
31 :
32 2356 : let useWorkflowService: () => WorkflowServiceAccess
33 :
34 : /** Called by `workflowService` when it loads; it imports this store. */
35 2356 : export function provideWorkflowService(
36 : useService: () => WorkflowServiceAccess
37 : ): void {
38 2356 : useWorkflowService = useService
39 : }
40 :
41 : export const VIEWPORT_CACHE_MAX_SIZE = 32
42 :
43 : /**
44 : * Stores the current subgraph navigation state; a stack representing subgraph
45 : * navigation history from the root graph to the subgraph that is currently
46 : * open.
47 : */
48 2356 : export const useSubgraphNavigationStore = defineStore(
49 : 'subgraphNavigation',
50 : () => {
51 2355 : const workflowStore = useWorkflowStore()
52 2355 : const canvasStore = useCanvasStore()
53 2355 : const canvasScheduler = useCanvasScheduler()
54 2355 : const router = useRouter()
55 2355 : const routeHash = useRouteHash()
56 :
57 : /** The currently opened subgraph. */
58 2355 : const activeSubgraph = shallowRef<Subgraph>()
59 :
60 : /** The stack of subgraph IDs from the root graph to the currently opened subgraph. */
61 2355 : const idStack = ref<string[]>([])
62 :
63 : /** LRU cache for viewport states. Key: `workflowPath:graphId` */
64 2355 : const viewportCache = new QuickLRU<string, DragAndScaleState>({
65 : maxSize: VIEWPORT_CACHE_MAX_SIZE
66 : })
67 :
68 : /** Get the ID of the root graph for the currently active workflow. */
69 2355 : const getCurrentRootGraphId = () => {
70 1811 : return canvasStore.canvas?.graph?.rootGraph.id ?? 'root'
71 : }
72 :
73 : /**
74 : * Set by saveCurrentViewport() (called from beforeLoadNewGraph) to
75 : * prevent onNavigated from re-saving a stale viewport during the
76 : * workflow switch transition. Uses setTimeout instead of rAF so the
77 : * flag resets even when the tab is backgrounded.
78 : */
79 2355 : let isWorkflowSwitching = false
80 : // ── Helpers ──────────────────────────────────────────────────────
81 :
82 : /** Build a workflow-scoped cache key. */
83 1968 : function buildCacheKey(
84 : graphId: string,
85 : workflowRef?: { path?: string } | null
86 : ): string {
87 : const wf = workflowRef ?? workflowStore.activeWorkflow
88 : const prefix = wf?.path ?? ''
89 1968 : return `${prefix}:${graphId}`
90 : }
91 :
92 : /** ID of the graph currently shown on the canvas. */
93 2003 : function getActiveGraphId(): string {
94 2003 : return canvasStore.canvas?.subgraph?.id ?? getCurrentRootGraphId()
95 : }
96 :
97 : // ── Navigation stack ─────────────────────────────────────────────
98 :
99 : /**
100 : * A stack representing subgraph navigation history from the root graph to
101 : * the current opened subgraph.
102 : */
103 2355 : const navigationStack = computed(() =>
104 : idStack.value
105 : .map((id) => useApp().rootGraph.subgraphs.get(id))
106 : .filter(isNonNullish)
107 : )
108 :
109 : /**
110 : * Restore the navigation stack from a list of subgraph IDs.
111 : * @see exportState
112 : */
113 2355 : const restoreState = (subgraphIds: string[]) => {
114 184 : idStack.value.length = 0
115 184 : for (const id of subgraphIds) idStack.value.push(id)
116 : }
117 :
118 : /**
119 : * Export the navigation stack as a list of subgraph IDs.
120 : * @see restoreState
121 : */
122 2355 : const exportState = () => [...idStack.value]
123 :
124 : // ── Viewport save / restore ──────────────────────────────────────
125 :
126 : /** Get the current viewport state, or null if the canvas is not available. */
127 2355 : const getCurrentViewport = (): DragAndScaleState | null => {
128 1752 : const canvas = canvasStore.canvas
129 1752 : if (!canvas) return null
130 1752 : return {
131 : scale: canvas.ds.state.scale,
132 : offset: [...canvas.ds.state.offset]
133 : }
134 : }
135 :
136 : /** Save the current viewport state for a graph. */
137 1752 : function saveViewport(graphId: string, workflowRef?: object | null): void {
138 1752 : const viewport = getCurrentViewport()
139 1752 : if (!viewport) return
140 1752 : viewportCache.set(buildCacheKey(graphId, workflowRef), viewport)
141 : }
142 :
143 : /** Apply a viewport state to the canvas. */
144 96 : function applyViewport(viewport: DragAndScaleState): void {
145 96 : const canvas = canvasStore.canvas
146 96 : if (!canvas) return
147 96 : canvas.ds.scale = viewport.scale
148 96 : canvas.ds.offset[0] = viewport.offset[0]
149 96 : canvas.ds.offset[1] = viewport.offset[1]
150 96 : canvas.setDirty(true, true)
151 : }
152 :
153 216 : function restoreViewport(graphId: string): void {
154 216 : const canvas = canvasStore.canvas
155 216 : if (!canvas) return
156 :
157 216 : if (getActiveGraphId() === graphId)
158 216 : canvasScheduler.cancel('subgraph-navigation-fit')
159 :
160 216 : const expectedKey = buildCacheKey(graphId)
161 216 : const viewport = viewportCache.get(expectedKey)
162 216 : if (viewport) {
163 96 : applyViewport(viewport)
164 96 : return
165 : }
166 :
167 : // First visit — fit to content so subgraph nodes are visible
168 120 : canvasScheduler.schedule({
169 : key: 'subgraph-navigation-fit',
170 : isCurrent: () => getActiveGraphId() === graphId,
171 : run: () => {
172 119 : if (!canvas.graph?.nodes.length) return
173 119 : useLitegraphServiceAccess().fitView()
174 : }
175 : })
176 : }
177 :
178 : // ── Navigation handler ───────────────────────────────────────────
179 :
180 216 : function onNavigated(
181 : subgraph: Subgraph | undefined,
182 : prevSubgraph: Subgraph | undefined
183 : ): void {
184 : // During a workflow switch, beforeLoadNewGraph already saved the
185 : // outgoing viewport — skip the save here to avoid caching stale
186 : // canvas state from the transition.
187 216 : if (!isWorkflowSwitching) {
188 204 : if (prevSubgraph) {
189 81 : saveViewport(prevSubgraph.id)
190 123 : } else if (subgraph) {
191 123 : saveViewport(getCurrentRootGraphId())
192 : }
193 : }
194 :
195 : const isInRootGraph = !subgraph
196 216 : if (isInRootGraph) {
197 74 : idStack.value.length = 0
198 74 : restoreViewport(getCurrentRootGraphId())
199 74 : return
200 : }
201 :
202 142 : const path = findSubgraphPathById(subgraph.rootGraph, subgraph.id)
203 : const isInReachableSubgraph = !!path
204 216 : if (isInReachableSubgraph) {
205 136 : idStack.value = [...path]
206 : } else {
207 6 : idStack.value = [subgraph.id]
208 : }
209 :
210 142 : restoreViewport(subgraph.id)
211 : }
212 :
213 : // ── Watchers ─────────────────────────────────────────────────────
214 :
215 : // Sync flush ensures we capture the outgoing viewport before any other
216 : // watchers or DOM updates from the same state change mutate the canvas.
217 2355 : watch(
218 : () => workflowStore.activeSubgraph,
219 : (newValue, oldValue) => {
220 216 : onNavigated(newValue, oldValue)
221 : },
222 : { flush: 'sync' }
223 : )
224 :
225 : // Counter so nested/overlapping async navigations don't release
226 : // suppression early; gates both the canvasStore.currentGraph watcher
227 : // (updateHash) and the routeHash watcher to prevent re-entrant
228 : // navigateToHash calls during router.replace().
229 2355 : let blockNavDepth = 0
230 2355 : let initialLoad = true
231 2355 : let hashUpdateTail: Promise<void> = Promise.resolve()
232 : type GraphNavigationIntent = {
233 : id: number
234 : hash: string
235 : source: 'graph' | 'route' | 'restore'
236 : }
237 : type NavigationIntent =
238 : | GraphNavigationIntent
239 : | { id: number; source: 'workflow' }
240 2355 : const routeWriteStateKey = 'comfySubgraphNavigationWrite'
241 2355 : const pendingRouteWrites = new Map<number, string>()
242 : // D14: the reset-suppression flag dies with shared-graph loading at
243 : // ECS per-document scoping; the intent ids guard the router and survive.
244 2355 : let deferredNavigationIntent: GraphNavigationIntent | undefined
245 2355 : let latestNavigationIntent: NavigationIntent | undefined
246 2355 : let navigationIntentId = 0
247 2355 : let routeWriteId = 0
248 2355 : let blockedRouteHash: string | undefined
249 2355 : let pendingWorkflowResetGraph: ComfyApp['rootGraph'] | undefined
250 :
251 1667 : function createNavigationIntent(
252 : hash: string,
253 : source: GraphNavigationIntent['source']
254 : ): GraphNavigationIntent {
255 1667 : const intent = { id: ++navigationIntentId, hash, source }
256 1667 : latestNavigationIntent = intent
257 1667 : return intent
258 : }
259 :
260 185 : function beginWorkflowNavigation(): number {
261 185 : const intent = { id: ++navigationIntentId, source: 'workflow' as const }
262 185 : latestNavigationIntent = intent
263 185 : return intent.id
264 : }
265 :
266 : /**
267 : * Releases a workflow-load intent whose load FAILED: while it stays the
268 : * newest intent it suppresses the surviving graph's hash forever, so
269 : * clear it and republish the live graph.
270 : */
271 2 : function endWorkflowNavigation(navigationId: number): void {
272 2 : if (
273 : latestNavigationIntent?.source !== 'workflow' ||
274 : latestNavigationIntent.id !== navigationId
275 : ) {
276 0 : return
277 : }
278 2 : latestNavigationIntent = undefined
279 2 : void updateHash('graph')
280 : }
281 :
282 4 : async function withNavBlocked<T>(
283 : op: () => Promise<T>,
284 : blockedHash: string
285 : ): Promise<T> {
286 4 : const previousBlockedRouteHash = blockedRouteHash
287 4 : blockedRouteHash = blockedHash
288 4 : blockNavDepth++
289 4 : try {
290 4 : return await op()
291 : } finally {
292 4 : blockNavDepth--
293 4 : blockedRouteHash = previousBlockedRouteHash
294 : }
295 : }
296 :
297 2 : function ensureCanvasOnRoot() {
298 2 : const root = useApp().rootGraphOrUndefined
299 2 : const canvas = canvasStore.canvas
300 2 : if (!root || !canvas) return
301 2 : if (canvas.graph?.id !== root.id) canvas.setGraph(root)
302 : }
303 :
304 2 : async function redirectToRoot(reason: string, navigationId: number) {
305 2 : if (navigationId !== navigationIntentId) return
306 : const root = useApp().rootGraph
307 2 : const rootHash = '#' + root.id
308 2 : console.warn(`[subgraphNavigation] ${reason}; redirecting to root graph`)
309 2 : try {
310 2 : await withNavBlocked(() => writeRouteHash(rootHash, true), rootHash)
311 : } finally {
312 2 : if (navigationId === navigationIntentId) ensureCanvasOnRoot()
313 : }
314 : }
315 :
316 48 : async function navigateToHash(
317 : newHash: string,
318 : navigationId: number,
319 : initiator?: 'user'
320 : ) {
321 48 : const root = useApp().rootGraph
322 48 : const locatorId = newHash.slice(1) || root.id
323 48 : const canvas = canvasStore.getCanvas()
324 :
325 : const isRoot = locatorId === root.id
326 48 : const targetGraph = isRoot
327 : ? root
328 : : isUuidShapedSubgraphId(locatorId)
329 : ? root.subgraphs.get(locatorId)
330 : : undefined
331 48 : if (targetGraph) {
332 46 : if (canvas.graph?.id === targetGraph.id) return
333 2 : return withNavBlocked(async () => {
334 2 : canvas.setGraph(targetGraph)
335 : }, newHash)
336 : }
337 :
338 : //Search all open workflows
339 2 : for (const workflow of workflowStore.openWorkflows) {
340 2 : const { activeState } = workflow
341 2 : if (!activeState) continue
342 2 : const subgraphs = activeState.definitions?.subgraphs ?? []
343 2 : for (const graph of [activeState, ...subgraphs]) {
344 2 : if (graph.id !== locatorId) continue
345 : // This will trigger a navigation, which can break forward history.
346 : // After openWorkflow resolves, app.rootGraph has been swapped, so we
347 : // intentionally re-read app.rootGraph below instead of using the
348 : // `root` captured at function entry.
349 0 : try {
350 0 : await withNavBlocked(
351 : () =>
352 : useWorkflowService().openWorkflow(workflow, {
353 : navigationIntentId: navigationId,
354 : initiator
355 : }),
356 : newHash
357 : )
358 : } catch (err) {
359 0 : if (navigationId !== navigationIntentId) return
360 0 : reportError(err, {
361 : surface: 'graph',
362 : errorType: 'workflow_navigation_failure',
363 : level: 'warning',
364 : context: { stage: 'recovery' }
365 : })
366 0 : return redirectToRoot('workflow load failed', navigationId)
367 : }
368 0 : if (navigationId !== navigationIntentId) return
369 2 : const loadedGraph =
370 : useApp().rootGraph.id === locatorId
371 : ? useApp().rootGraph
372 : : useApp().rootGraph.subgraphs.get(locatorId)
373 2 : if (!loadedGraph) {
374 0 : return redirectToRoot(
375 : 'subgraph not found after workflow load',
376 : navigationId
377 : )
378 : }
379 2 : if (canvas.graph?.id === loadedGraph.id) return
380 0 : return withNavBlocked(async () => {
381 0 : canvas.setGraph(loadedGraph)
382 : }, newHash)
383 : }
384 : }
385 :
386 2 : await redirectToRoot(`subgraph not found: ${locatorId}`, navigationId)
387 : }
388 :
389 1624 : async function safeRouterCall(op: () => Promise<unknown>, label: string) {
390 1624 : try {
391 1624 : return !isNavigationFailure(await op())
392 : } catch (err) {
393 0 : if (
394 : !isNavigationFailure(err, NavigationFailureType.duplicated) &&
395 : !isNavigationFailure(err, NavigationFailureType.cancelled)
396 : ) {
397 0 : console.warn(`[subgraphNavigation] ${label} rejected`, err)
398 : }
399 0 : return false
400 : }
401 : }
402 :
403 1624 : async function writeRouteHash(hash: string, replace: boolean) {
404 1624 : const writeId = ++routeWriteId
405 1624 : pendingRouteWrites.set(writeId, hash)
406 1624 : const target = {
407 : hash,
408 : state: { [routeWriteStateKey]: writeId }
409 : }
410 1624 : try {
411 1624 : return await safeRouterCall(
412 : () => (replace ? router.replace(target) : router.push(target)),
413 : replace ? 'router.replace' : 'router.push'
414 : )
415 : } finally {
416 1624 : pendingRouteWrites.delete(writeId)
417 : }
418 : }
419 :
420 1619 : async function syncGraphHash(intent: GraphNavigationIntent) {
421 1619 : if (intent.id !== navigationIntentId) return false
422 1619 : if (!routeHash.value) {
423 : const rootHash = '#' + useApp().rootGraph.id
424 1187 : if (!(await writeRouteHash(rootHash, true))) return false
425 1186 : if (intent.id !== navigationIntentId) return false
426 : }
427 1619 : const currentId = routeHash.value?.slice(1)
428 1619 : if (intent.hash.slice(1) === currentId) return true
429 :
430 435 : return writeRouteHash(intent.hash, false)
431 : }
432 :
433 1619 : function queueGraphHash(intent: GraphNavigationIntent): Promise<boolean> {
434 1619 : const result = hashUpdateTail.then(() => syncGraphHash(intent))
435 1619 : hashUpdateTail = result.then(
436 : () => undefined,
437 : () => undefined
438 : )
439 1619 : return result
440 : }
441 :
442 48 : async function applyNavigationIntent(intent: GraphNavigationIntent) {
443 48 : await navigateToHash(
444 : intent.hash,
445 : intent.id,
446 : intent.source === 'route' ? 'user' : undefined
447 : )
448 48 : if (blockNavDepth > 0) return
449 :
450 48 : const deferredIntent = deferredNavigationIntent
451 48 : if (deferredIntent?.id === navigationIntentId) {
452 0 : deferredNavigationIntent = undefined
453 0 : return applyNavigationIntent(deferredIntent)
454 : }
455 :
456 48 : if (intent.source === 'graph' && intent.id === navigationIntentId) {
457 0 : await queueGraphHash(intent)
458 : }
459 : }
460 :
461 5 : async function navigateToGraph(targetGraph: LGraph): Promise<boolean> {
462 5 : const canvas = canvasStore.canvas
463 5 : const targetId = targetGraph.id
464 5 : const belongsToCurrentWorkflow =
465 : targetGraph === useApp().rootGraph ||
466 : (targetGraph.rootGraph === useApp().rootGraph &&
467 : useApp().rootGraph.subgraphs.get(targetId) === targetGraph)
468 :
469 5 : if (!canvas?.graph || !targetId || !belongsToCurrentWorkflow) return false
470 5 : if (canvas.graph === targetGraph) return true
471 :
472 0 : const previousGraph = canvas.graph
473 0 : const intent = createNavigationIntent('#' + targetId, 'graph')
474 0 : await withNavBlocked(
475 : async () => canvas.setGraph(targetGraph),
476 : intent.hash
477 : )
478 0 : if (intent.id !== navigationIntentId) return false
479 :
480 0 : const hashWritten = await queueGraphHash(intent)
481 5 : if (
482 : !hashWritten &&
483 : intent.id === navigationIntentId &&
484 : canvas.graph === targetGraph
485 : ) {
486 0 : await withNavBlocked(
487 : async () => canvas.setGraph(previousGraph),
488 : '#' + previousGraph.id
489 : )
490 : }
491 5 : return (
492 : hashWritten &&
493 : intent.id === navigationIntentId &&
494 : canvas.graph === targetGraph
495 : )
496 : }
497 :
498 4105 : async function updateHash(
499 : source: 'graph' | 'workflow-load' = 'graph',
500 : workflowNavigationId?: number,
501 : currentGraph?: LGraph | null
502 : ): Promise<void> {
503 4105 : const graph = currentGraph ?? canvasStore.getCanvas().graph
504 4105 : if (source === 'workflow-load') {
505 3887 : pendingWorkflowResetGraph = undefined
506 3887 : if (
507 : blockNavDepth > 0 &&
508 : workflowNavigationId === navigationIntentId &&
509 : latestNavigationIntent?.source === 'workflow' &&
510 : graph?.id
511 : ) {
512 0 : deferredNavigationIntent = {
513 : id: workflowNavigationId,
514 : hash: '#' + graph.id,
515 : source: 'graph'
516 : }
517 0 : return Promise.resolve()
518 : }
519 3887 : if (blockNavDepth > 0) return Promise.resolve()
520 3887 : if (workflowNavigationId !== undefined) {
521 183 : if (workflowNavigationId !== navigationIntentId) {
522 11 : const latestIntent = latestNavigationIntent
523 11 : return latestIntent && latestIntent.source !== 'workflow'
524 : ? applyNavigationIntent(latestIntent)
525 : : Promise.resolve()
526 : }
527 : }
528 : }
529 4105 : if (graph === pendingWorkflowResetGraph) {
530 2 : pendingWorkflowResetGraph = undefined
531 2 : return Promise.resolve()
532 : }
533 :
534 4105 : const newId = graph?.id ?? ''
535 4105 : if (initialLoad) {
536 2355 : initialLoad = false
537 2355 : if (!routeHash.value) return Promise.resolve()
538 46 : return applyNavigationIntent(
539 : createNavigationIntent(routeHash.value, 'restore')
540 : ).then(() => {
541 46 : const activeGraph = canvasStore.getCanvas().graph
542 46 : if (isSubgraph(activeGraph)) {
543 2 : workflowStore.activeSubgraph = activeGraph
544 : }
545 : })
546 : }
547 :
548 2950 : if (!newId) return Promise.resolve()
549 1737 : const newHash = '#' + newId
550 2948 : if (newHash === routeHash.value) return Promise.resolve()
551 4105 : if (blockNavDepth > 0 && newHash === blockedRouteHash) {
552 0 : return Promise.resolve()
553 : }
554 :
555 1619 : const intent = createNavigationIntent(newHash, 'graph')
556 2946 : if (blockNavDepth > 0) {
557 0 : deferredNavigationIntent = intent
558 0 : return Promise.resolve()
559 : }
560 :
561 1619 : await queueGraphHash(intent)
562 : }
563 2355 : watch(
564 : () => canvasStore.currentGraph,
565 : (graph) => void updateHash('graph', undefined, graph),
566 : { flush: 'sync' }
567 : )
568 2355 : watch(
569 : routeHash,
570 : (newHash) => {
571 1625 : initialLoad = false
572 1625 : const hash = String(newHash)
573 1625 : const stateWriteId = router.options.history.state[routeWriteStateKey]
574 1625 : if (
575 : typeof stateWriteId === 'number' &&
576 : pendingRouteWrites.get(stateWriteId) === hash
577 : ) {
578 1623 : pendingRouteWrites.delete(stateWriteId)
579 1623 : return
580 : }
581 2 : const intent = createNavigationIntent(hash, 'route')
582 192 : if (blockNavDepth > 0) {
583 0 : deferredNavigationIntent = intent
584 0 : return
585 : }
586 2 : void applyNavigationIntent(intent)
587 : },
588 : { flush: 'sync' }
589 : )
590 :
591 : /** Save the current viewport for the active graph/workflow. Called by
592 : * workflowService.beforeLoadNewGraph() before the canvas is overwritten. */
593 1548 : function saveCurrentViewport(suppressWorkflowReset = true): void {
594 1548 : saveViewport(getActiveGraphId())
595 1548 : const graph = canvasStore.getCanvas().graph
596 1548 : pendingWorkflowResetGraph =
597 : suppressWorkflowReset && graph !== useApp().rootGraph
598 : ? useApp().rootGraph
599 : : undefined
600 1548 : isWorkflowSwitching = true
601 1548 : setTimeout(() => {
602 1548 : isWorkflowSwitching = false
603 : }, 0)
604 : }
605 :
606 2355 : return {
607 : activeSubgraph,
608 : navigationStack,
609 : restoreState,
610 : exportState,
611 : saveViewport,
612 : restoreViewport,
613 : saveCurrentViewport,
614 : beginWorkflowNavigation,
615 : endWorkflowNavigation,
616 : navigateToGraph,
617 : updateHash,
618 : /** @internal Exposed for test assertions only. */
619 : viewportCache
620 : }
621 : }
622 : )
|