LCOV - code coverage report
Current view: top level - src/platform/workflow/management/stores - workflowStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 84.4 % 289 244
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { union } from 'es-toolkit/compat'
       2              : import { createEventHook, until, useAsyncState } from '@vueuse/core'
       3              : import { defineStore } from 'pinia'
       4              : import { computed, markRaw, ref, shallowRef, watch } from 'vue'
       5              : import type { Raw } from 'vue'
       6              : 
       7              : import { t } from '@/i18n'
       8              : import type {
       9              :   LGraph,
      10              :   LGraphNode,
      11              :   Subgraph
      12              : } from '@/lib/litegraph/src/litegraph'
      13              : import {
      14              :   areWorkflowIdsEquivalent,
      15              :   ensureWorkflowId,
      16              :   getLegacyWorkflowId
      17              : } from '@/platform/workflow/core/utils/workflowId'
      18              : import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema'
      19              : import { useSettingStore } from '@/platform/settings/settingStore'
      20              : import { useWorkflowDraftStoreV2 } from '@/platform/workflow/persistence/stores/workflowDraftStoreV2'
      21              : // oxlint-disable-next-line comfy/no-restricted-paths
      22              : import { useWorkflowThumbnail } from '@/renderer/core/thumbnail/useWorkflowThumbnail'
      23              : import { api } from '@/scripts/api'
      24              : import { useApp } from '@/scripts/appInstance'
      25              : import { ChangeTrackerAccess } from '@/scripts/changeTrackerAccess'
      26              : import { getDefaultWorkflow } from '@/platform/workflow/core/services/defaultWorkflowService'
      27              : import { useDialogService } from '@/services/dialogService'
      28              : import { useWidgetHistoryStore } from '@/stores/widgetHistoryStore'
      29              : import { reportError } from '@comfyorg/telemetry/reportError'
      30              : import type {
      31              :   NodeExecutionId,
      32              :   NodeLocatorId
      33              : } from '@comfyorg/graph-model/nodeIdentification'
      34              : import {
      35              :   createLeafNodeExecutionId,
      36              :   createNodeLocatorId,
      37              :   parseNodeExecutionId,
      38              :   parseNodeLocatorId,
      39              :   tryNormalizeNodeExecutionId
      40              : } from '@comfyorg/graph-model/nodeIdentification'
      41              : import { parseNodeId } from '@comfyorg/graph-model/nodeId'
      42              : import type { NodeId } from '@comfyorg/graph-model/nodeId'
      43              : import { generateUUID, getPathDetails } from '@/utils/formatUtil'
      44              : import { syncEntities } from '@/utils/syncUtil'
      45              : import { isSubgraph } from '@/utils/typeGuardUtil'
      46              : import {
      47              :   ComfyWorkflow,
      48              :   registerWorkflowRuntime,
      49              :   reportWorkflowStateAnomaly
      50              : } from './comfyWorkflow'
      51              : import type { LoadedComfyWorkflow } from './comfyWorkflow'
      52              : import type { WorkflowStore } from './workflowStoreTypes'
      53              : export { ComfyWorkflow, type LoadedComfyWorkflow }
      54              : 
      55         2356 : registerWorkflowRuntime({
      56              :   createChangeTracker: (workflow, initialState) =>
      57              :     new ChangeTrackerAccess(workflow, initialState),
      58              :   graphEqual: (a, b) => ChangeTrackerAccess.graphEqual(a, b),
      59              :   getDraft: (path) => useWorkflowDraftStoreV2().getDraft(path),
      60              :   removeDraft: (path) => useWorkflowDraftStoreV2().removeDraft(path),
      61              :   markDraftUsed: (path) => useWorkflowDraftStoreV2().markDraftUsed(path),
      62              :   isDraftPersistenceEnabled: () =>
      63              :     useSettingStore().get('Comfy.Workflow.Persist'),
      64              :   forgetNodeHistories: (rootGraphId) =>
      65              :     useWidgetHistoryStore().clearWorkflow(rootGraphId),
      66              :   async promptSave(workflow) {
      67           95 :     try {
      68           95 :       return await useDialogService().prompt({
      69              :         title: t(workflow.saveNamePrompt.title),
      70              :         message: t(workflow.saveNamePrompt.message),
      71              :         defaultValue: workflow.filename
      72              :       })
      73              :     } catch (error) {
      74            0 :       reportError(error, {
      75              :         surface: 'graph',
      76              :         errorType: 'error_loading_dialog_service_prompt_save'
      77              :       })
      78            0 :       return null
      79              :     }
      80              :   }
      81              : })
      82              : 
      83         2356 : export const useWorkflowStore = defineStore('workflow', () => {
      84              :   /**
      85              :    * History of tab activations. Most recent at the end.
      86              :    * Tracks the order in which tabs were activated to support "go to previous" behavior.
      87              :    * Lazily cleaned on access.
      88              :    */
      89         2355 :   const tabActivationHistory = ref<string[]>([])
      90         2355 :   const MAX_HISTORY_SIZE = 32
      91              : 
      92              :   /**
      93              :    * Detach the workflow from the store. lightweight helper function.
      94              :    * @param workflow The workflow to detach.
      95              :    * @returns The index of the workflow in the openWorkflowPaths array, or -1 if the workflow was not open.
      96              :    */
      97         2355 :   const detachWorkflow = (workflow: ComfyWorkflow) => {
      98          132 :     delete workflowLookup.value[workflow.path]
      99          132 :     const index = openWorkflowPaths.value.indexOf(workflow.path)
     100          132 :     if (index !== -1) {
     101          114 :       openWorkflowPaths.value = openWorkflowPaths.value.filter(
     102              :         (path) => path !== workflow.path
     103              :       )
     104              :     }
     105          132 :     return index
     106              :   }
     107              : 
     108              :   /**
     109              :    * Attach the workflow to the store. lightweight helper function.
     110              :    * @param workflow The workflow to attach.
     111              :    * @param openIndex The index to open the workflow at.
     112              :    */
     113         2355 :   const attachWorkflow = (workflow: ComfyWorkflow, openIndex: number = -1) => {
     114       262997 :     workflowLookup.value[workflow.path] = workflow
     115              : 
     116       262997 :     if (openIndex !== -1) {
     117          114 :       openWorkflowPaths.value.splice(openIndex, 0, workflow.path)
     118              :     }
     119              :   }
     120              : 
     121              :   /**
     122              :    * The active workflow currently being edited.
     123              :    */
     124         2355 :   const activeWorkflow = ref<LoadedComfyWorkflow | null>(null)
     125         2355 :   const isActive = (workflow: ComfyWorkflow) =>
     126              :     activeWorkflow.value?.path === workflow.path
     127              :   /**
     128              :    * All workflows.
     129              :    */
     130         2355 :   const workflowLookup = ref<Record<string, ComfyWorkflow>>({})
     131         2355 :   const workflows = computed<ComfyWorkflow[]>(() =>
     132              :     Object.values(workflowLookup.value)
     133              :   )
     134         2355 :   const getWorkflowByPath = (path: string): ComfyWorkflow | null =>
     135              :     workflowLookup.value[path] ?? null
     136              : 
     137              :   /**
     138              :    * The paths of the open workflows. It is setup as a ref to allow user
     139              :    * to reorder the workflows opened.
     140              :    */
     141         2355 :   const openWorkflowPaths = ref<string[]>([])
     142         2355 :   const openWorkflowPathSet = computed(() => new Set(openWorkflowPaths.value))
     143         2355 :   const openWorkflows = computed(() =>
     144              :     openWorkflowPaths.value
     145              :       .map(getWorkflowByPath)
     146              :       .filter((workflow) => workflow !== null)
     147              :   )
     148         2355 :   const reorderWorkflows = (from: number, to: number) => {
     149            3 :     const paths = openWorkflows.value.map((workflow) => workflow.path)
     150            3 :     const [movedTab] = paths.splice(from, 1)
     151            3 :     paths.splice(to, 0, movedTab)
     152            3 :     openWorkflowPaths.value = paths
     153              :   }
     154         2355 :   const isOpen = (workflow: ComfyWorkflow) =>
     155              :     openWorkflowPathSet.value.has(workflow.path)
     156              : 
     157              :   /**
     158              :    * Add paths to the list of open workflow paths without loading the files
     159              :    * or changing the active workflow.
     160              :    *
     161              :    * @param paths - The workflows to open, specified as:
     162              :    *   - `left`: Workflows to be added to the left.
     163              :    *   - `right`: Workflows to be added to the right.
     164              :    *
     165              :    * Invalid paths (non-strings or paths not found in `workflowLookup.value`)
     166              :    * will be ignored. Duplicate paths are automatically removed.
     167              :    */
     168         2355 :   const openWorkflowsInBackground = (paths: {
     169              :     left?: string[]
     170              :     right?: string[]
     171              :   }) => {
     172           55 :     const { left = [], right = [] } = paths
     173           55 :     if (!left.length && !right.length) return
     174              : 
     175           55 :     const isValidPath = (
     176              :       path: unknown
     177              :     ): path is keyof typeof workflowLookup.value =>
     178              :       typeof path === 'string' && path in workflowLookup.value
     179              : 
     180           55 :     openWorkflowPaths.value = union(
     181              :       left,
     182              :       openWorkflowPaths.value,
     183              :       right
     184              :     ).filter(isValidPath)
     185              :   }
     186              : 
     187              :   /**
     188              :    * Set the workflow as the active workflow.
     189              :    * @param workflow The workflow to open.
     190              :    */
     191         2355 :   const openWorkflow = async (
     192              :     workflow: ComfyWorkflow
     193              :   ): Promise<LoadedComfyWorkflow> => {
     194         3902 :     if (isActive(workflow)) {
     195          105 :       if (workflow.isLoaded) return workflow as LoadedComfyWorkflow
     196              :       // `isActive` matches by path, so a workflow can be "active" while this
     197              :       // instance never loaded (or has since unloaded) its change tracker.
     198              :       // Returning it as loaded would hand callers a null `initialState`.
     199            0 :       reportWorkflowStateAnomaly(
     200              :         'openWorkflow called on an active workflow that is not loaded',
     201              :         'workflowStore.openWorkflow',
     202              :         workflow,
     203              :         { isActive: true }
     204              :       )
     205              :     }
     206              : 
     207         3797 :     const addedTab = !openWorkflowPaths.value.includes(workflow.path)
     208         3815 :     if (addedTab) openWorkflowPaths.value.push(workflow.path)
     209         3902 :     const graphState = useApp().rootGraphOrUndefined?.state
     210         3902 :     const loadedWorkflow = await workflow.load().catch((error: unknown) => {
     211            1 :       if (addedTab) {
     212            0 :         openWorkflowPaths.value = openWorkflowPaths.value.filter(
     213              :           (path) => path !== workflow.path
     214              :         )
     215              :       }
     216            1 :       throw error
     217              :     })
     218         3902 :     if (graphState !== useApp().rootGraphOrUndefined?.state) {
     219            0 :       throw new DOMException('Workflow load was replaced', 'AbortError')
     220              :     }
     221         3796 :     activeWorkflow.value = loadedWorkflow
     222         3796 :     useApp().canvas.bg_tint = loadedWorkflow.tintCanvasBg
     223              : 
     224              :     // Track activation in history (move to end if already present)
     225         3796 :     const historyIndex = tabActivationHistory.value.indexOf(workflow.path)
     226         3902 :     if (historyIndex !== -1) {
     227           78 :       tabActivationHistory.value.splice(historyIndex, 1)
     228              :     }
     229         3796 :     tabActivationHistory.value.push(workflow.path)
     230              :     // Trim history if too large
     231         3902 :     if (tabActivationHistory.value.length > MAX_HISTORY_SIZE) {
     232            0 :       tabActivationHistory.value.shift()
     233              :     }
     234              : 
     235         3796 :     return loadedWorkflow
     236              :   }
     237              : 
     238         2355 :   const getUnconflictedPath = (basePath: string): string => {
     239         3709 :     const { directory, filename, suffix } = getPathDetails(basePath)
     240         3709 :     let counter = 2
     241         3709 :     let newPath = basePath
     242         3709 :     while (Object.hasOwn(workflowLookup.value, newPath)) {
     243          450 :       newPath = `${directory}/${filename} (${counter}).${suffix}`
     244          450 :       counter++
     245              :     }
     246         3709 :     return newPath
     247              :   }
     248         2355 :   const saveAs = (
     249              :     existingWorkflow: ComfyWorkflow,
     250              :     path: string
     251              :   ): ComfyWorkflow => {
     252              :     // Generate new id when saving existing workflow as a new file
     253            8 :     const id = generateUUID()
     254            8 :     const state = JSON.parse(
     255              :       JSON.stringify(existingWorkflow.activeState)
     256              :     ) as ComfyWorkflowJSON
     257            8 :     state.id = id
     258              : 
     259            8 :     const workflow: ComfyWorkflow =
     260              :       new (existingWorkflow.constructor as typeof ComfyWorkflow)({
     261              :         path,
     262              :         modified: Date.now(),
     263              :         size: -1
     264              :       })
     265            8 :     workflow.initialMode = existingWorkflow.initialMode
     266            8 :     workflow.originalContent = workflow.content = JSON.stringify(state)
     267            8 :     workflowLookup.value[workflow.path] = workflow
     268            8 :     return workflow
     269              :   }
     270              : 
     271              :   /**
     272              :    * Helper to create a new temporary workflow
     273              :    */
     274         2355 :   const createNewWorkflow = (
     275              :     path: string,
     276              :     workflowData?: ComfyWorkflowJSON
     277              :   ): ComfyWorkflow => {
     278         3709 :     const workflow = new ComfyWorkflow({
     279              :       path,
     280              :       modified: Date.now(),
     281              :       size: -1
     282              :     })
     283         3709 :     workflow.legacyId = getLegacyWorkflowId(workflowData?.id)
     284              : 
     285         3709 :     const initialWorkflowData = ensureWorkflowId(
     286              :       workflowData ?? getDefaultWorkflow()
     287              :     )
     288         3709 :     workflow.originalContent = workflow.content =
     289              :       JSON.stringify(initialWorkflowData)
     290              : 
     291         3709 :     workflowLookup.value[workflow.path] = workflow
     292         3709 :     return workflow
     293              :   }
     294              : 
     295              :   /**
     296              :    * Create a temporary workflow, attempting to reuse an existing workflow if conditions match
     297              :    */
     298         2355 :   const createTemporary = (path?: string, workflowData?: ComfyWorkflowJSON) => {
     299           78 :     const fullPath = getUnconflictedPath(
     300              :       ComfyWorkflow.basePath + (path ?? 'Unsaved Workflow.json')
     301              :     )
     302              : 
     303              :     // Try to reuse an existing loaded workflow with the same filename
     304              :     // that is not stored in the workflows directory
     305           78 :     if (path && workflowData) {
     306           78 :       const existingWorkflow = workflows.value.find(
     307              :         (w) => w.fullFilename === path
     308              :       )
     309           78 :       if (
     310              :         existingWorkflow?.changeTracker &&
     311              :         !existingWorkflow.directory.startsWith(
     312              :           ComfyWorkflow.basePath.slice(0, -1)
     313              :         ) &&
     314              :         areWorkflowIdsEquivalent(
     315              :           existingWorkflow.activeState?.id,
     316              :           workflowData.id,
     317              :           existingWorkflow.legacyId
     318              :         )
     319              :       ) {
     320            0 :         existingWorkflow.legacyId ??= getLegacyWorkflowId(workflowData.id)
     321            0 :         existingWorkflow.changeTracker.reset(
     322              :           ensureWorkflowId(workflowData, existingWorkflow.activeState?.id)
     323              :         )
     324            0 :         return existingWorkflow
     325              :       }
     326              :     }
     327              : 
     328           78 :     return createNewWorkflow(fullPath, workflowData)
     329              :   }
     330              : 
     331              :   /**
     332              :    * Create a new temporary workflow without attempting to reuse existing workflows
     333              :    */
     334         2355 :   const createNewTemporary = (
     335              :     path?: string,
     336              :     workflowData?: ComfyWorkflowJSON
     337              :   ): ComfyWorkflow => {
     338         3631 :     const fullPath = getUnconflictedPath(
     339              :       ComfyWorkflow.basePath + (path ?? 'Unsaved Workflow.json')
     340              :     )
     341         3631 :     return createNewWorkflow(fullPath, workflowData)
     342              :   }
     343              : 
     344          128 :   function forgetNodeHistories(workflow: ComfyWorkflow) {
     345          128 :     const rootGraphId = workflow.activeState?.id
     346          128 :     if (rootGraphId) useWidgetHistoryStore().clearWorkflow(rootGraphId)
     347              :   }
     348              : 
     349         2355 :   const closeWorkflow = async (workflow: ComfyWorkflow) => {
     350           32 :     openWorkflowPaths.value = openWorkflowPaths.value.filter(
     351              :       (path) => path !== workflow.path
     352              :     )
     353           32 :     useWorkflowDraftStoreV2().removeDraft(workflow.path)
     354           32 :     if (workflow.isTemporary) {
     355            7 :       forgetNodeHistories(workflow)
     356            7 :       clearThumbnail(workflow.key)
     357            7 :       delete workflowLookup.value[workflow.path]
     358              :     } else {
     359           25 :       workflow.unload()
     360              :       // Closing discards the in-memory edits and their draft. A modified mark
     361              :       // left behind keeps the workflow in `modifiedWorkflows`, where a later
     362              :       // bulk save (sign-out) would write the unloaded state, `null`, over
     363              :       // the stored file.
     364           25 :       workflow.isModified = false
     365              :     }
     366              :   }
     367              : 
     368              :   /**
     369              :    * Get the workflow at the given index shift from the active workflow.
     370              :    * @param shift The shift to the next workflow. Positive for next, negative for previous.
     371              :    * @returns The next workflow or null if the shift is out of bounds.
     372              :    */
     373         2355 :   const openedWorkflowIndexShift = (shift: number): ComfyWorkflow | null => {
     374            3 :     const index = openWorkflows.value.findIndex(
     375              :       (workflow) => workflow.path === activeWorkflow.value?.path
     376              :     )
     377              : 
     378            3 :     if (index !== -1) {
     379            3 :       const length = openWorkflows.value.length
     380            3 :       const nextIndex = (index + shift + length) % length
     381              :       const nextWorkflow = openWorkflows.value[nextIndex]
     382              :       return nextWorkflow
     383              :     }
     384            0 :     return null
     385              :   }
     386              : 
     387              :   /**
     388              :    * Get the most recently active workflow from history (excluding current).
     389              :    * Lazily cleans invalid paths from history.
     390              :    * @returns The most recent valid workflow or null if none found.
     391              :    */
     392         2355 :   const getMostRecentWorkflow = (): ComfyWorkflow | null => {
     393           22 :     const currentPath = activeWorkflow.value?.path
     394           22 :     const validPaths: string[] = []
     395              : 
     396              :     // Scan backwards through history
     397           22 :     for (let i = tabActivationHistory.value.length - 1; i >= 0; i--) {
     398           33 :       const path = tabActivationHistory.value[i]
     399              : 
     400              :       // Skip current workflow
     401           33 :       if (path === currentPath) continue
     402              : 
     403              :       // Check if workflow is still open
     404           22 :       if (openWorkflowPathSet.value.has(path)) {
     405           10 :         validPaths.unshift(path)
     406           10 :         const workflow = getWorkflowByPath(path)
     407              :         {
     408              :           // Lazy cleanup: keep only valid paths
     409           10 :           tabActivationHistory.value = validPaths
     410           10 :           return workflow
     411              :         }
     412              :       }
     413              :     }
     414              : 
     415              :     // Cleanup: no valid workflows found, clear history
     416           12 :     tabActivationHistory.value = []
     417           12 :     return null
     418              :   }
     419              : 
     420         2355 :   const persistedWorkflows = computed(() =>
     421              :     Array.from(workflows.value).filter(
     422              :       (workflow) =>
     423              :         workflow.isPersisted && !workflow.path.startsWith('subgraphs/')
     424              :     )
     425              :   )
     426              : 
     427         2355 :   const {
     428              :     isReady: isSyncReady,
     429              :     isLoading: isSyncLoading,
     430              :     execute: executeSyncWorkflows
     431              :   } = useAsyncState(
     432              :     async (dir: string = '') => {
     433         4860 :       await syncEntities(
     434              :         dir ? 'workflows/' + dir : 'workflows',
     435              :         workflowLookup.value,
     436              :         (file) =>
     437              :           new ComfyWorkflow({
     438              :             path: file.path,
     439              :             modified: file.modified,
     440              :             size: file.size
     441              :           }),
     442              :         (existingWorkflow, file) => {
     443         2056 :           const isActiveWorkflow =
     444              :             activeWorkflow.value?.path === existingWorkflow.path
     445              : 
     446         2056 :           if (!isActiveWorkflow && existingWorkflow.isModified) return
     447              : 
     448         2056 :           const nextLastModified = Math.max(
     449              :             existingWorkflow.lastModified,
     450              :             file.modified
     451              :           )
     452              : 
     453         2056 :           const isMetadataUnchanged =
     454              :             nextLastModified === existingWorkflow.lastModified &&
     455              :             file.size === existingWorkflow.size
     456              : 
     457         2056 :           if (!isMetadataUnchanged) {
     458            6 :             existingWorkflow.lastModified = nextLastModified
     459            6 :             existingWorkflow.size = file.size
     460              :           }
     461              : 
     462         2056 :           if (isActiveWorkflow) {
     463            4 :             return
     464              :           }
     465              : 
     466         2052 :           if (isMetadataUnchanged) {
     467         2046 :             return
     468              :           }
     469              : 
     470            6 :           existingWorkflow.unload()
     471              :         },
     472              :         /* exclude */ (workflow) => workflow.isTemporary,
     473              :         /* beforeDelete */ (workflow, path) => {
     474          156 :           if (isActive(workflow)) return false
     475          121 :           openWorkflowPaths.value = openWorkflowPaths.value.filter(
     476              :             (openPath) => openPath !== path
     477              :           )
     478          121 :           forgetNodeHistories(workflow)
     479          121 :           return true
     480              :         }
     481              :       )
     482              :     },
     483              :     undefined,
     484              :     { immediate: false }
     485              :   )
     486              : 
     487         4860 :   async function syncWorkflows(dir: string = '') {
     488         4860 :     return executeSyncWorkflows(0, dir)
     489              :   }
     490              : 
     491         7008 :   async function loadWorkflows(): Promise<void> {
     492         7008 :     if (isSyncReady.value) return
     493              : 
     494         7008 :     if (isSyncLoading.value) {
     495            0 :       await until(isSyncLoading).toBe(false)
     496            0 :       return
     497              :     }
     498              : 
     499         2355 :     await syncWorkflows()
     500              :   }
     501              : 
     502         2355 :   const bookmarkStore = useWorkflowBookmarkStore()
     503         2355 :   const bookmarkedWorkflows = computed(() =>
     504              :     workflows.value.filter((workflow) =>
     505              :       bookmarkStore.isBookmarked(workflow.path)
     506              :     )
     507              :   )
     508         2355 :   const modifiedWorkflows = computed(() =>
     509              :     workflows.value.filter((workflow) => workflow.isModified)
     510              :   )
     511              : 
     512              :   /** A filesystem operation is currently in progress (e.g. save, rename, delete) */
     513         2355 :   const isBusy = ref<boolean>(false)
     514         2355 :   const workflowRenamed = createEventHook<ComfyWorkflow>()
     515         2355 :   const userActivation = createEventHook<ComfyWorkflow>()
     516            0 :   function reportActivationError(error: unknown) {
     517            0 :     return reportError(error, {
     518              :       surface: 'graph',
     519              :       errorType: 'user_activation_listener_failure',
     520              :       level: 'warning'
     521              :     })
     522              :   }
     523         2355 :   const { moveWorkflowThumbnail, clearThumbnail } = useWorkflowThumbnail()
     524              : 
     525         2355 :   const renameWorkflow = async (workflow: ComfyWorkflow, newPath: string) => {
     526          100 :     isBusy.value = true
     527          100 :     try {
     528              :       // Capture all needed values upfront
     529          100 :       const oldPath = workflow.path
     530          100 :       const oldKey = workflow.key
     531          100 :       const wasBookmarked = bookmarkStore.isBookmarked(oldPath)
     532          100 :       const draftStore = useWorkflowDraftStoreV2()
     533              : 
     534          100 :       await workflow.rename(newPath)
     535          100 :       void workflowRenamed.trigger(workflow)
     536              : 
     537              :       // Synchronously swap old path for new path in lookup and open paths
     538              :       // to avoid a tab flicker caused by an async gap between detach/attach.
     539          100 :       delete workflowLookup.value[oldPath]
     540          100 :       workflowLookup.value[workflow.path] = workflow
     541          100 :       const openIndex = openWorkflowPaths.value.indexOf(oldPath)
     542          100 :       if (openIndex !== -1) {
     543          100 :         openWorkflowPaths.value.splice(openIndex, 1, workflow.path)
     544              :       }
     545              : 
     546          100 :       draftStore.moveDraft(oldPath, newPath, workflow.key)
     547              : 
     548              :       // Move thumbnail from old key to new key (using workflow keys, not full paths)
     549          100 :       const newKey = workflow.key
     550          100 :       moveWorkflowThumbnail(oldKey, newKey)
     551              :       // Update bookmarks
     552          100 :       if (wasBookmarked) {
     553            0 :         await bookmarkStore.setBookmarked(oldPath, false)
     554            0 :         await bookmarkStore.setBookmarked(newPath, true)
     555              :       }
     556              :     } finally {
     557          100 :       isBusy.value = false
     558              :     }
     559              :   }
     560              : 
     561         2355 :   const deleteWorkflow = async (workflow: ComfyWorkflow) => {
     562           18 :     isBusy.value = true
     563           18 :     try {
     564           18 :       await workflow.delete()
     565           18 :       useWorkflowDraftStoreV2().removeDraft(workflow.path)
     566           18 :       if (bookmarkStore.isBookmarked(workflow.path)) {
     567            0 :         await bookmarkStore.setBookmarked(workflow.path, false)
     568              :       }
     569              :       // Clear thumbnail when workflow is deleted
     570           18 :       clearThumbnail(workflow.key)
     571           18 :       detachWorkflow(workflow)
     572              :     } finally {
     573           18 :       isBusy.value = false
     574              :     }
     575              :   }
     576              : 
     577              :   /**
     578              :    * Save a workflow.
     579              :    * @param workflow The workflow to save.
     580              :    */
     581         2355 :   const saveWorkflow = async (workflow: ComfyWorkflow) => {
     582          116 :     isBusy.value = true
     583          116 :     try {
     584          116 :       await workflow.save()
     585              :       // Synchronously detach and re-attach to force refresh the tree objects
     586              :       // without an async gap that would cause the tab to disappear.
     587          114 :       const openIndex = detachWorkflow(workflow)
     588          114 :       attachWorkflow(workflow, openIndex)
     589              :     } finally {
     590          114 :       isBusy.value = false
     591              :     }
     592              :   }
     593              : 
     594         2355 :   const tabsRestored = ref(false)
     595         2355 :   const markTabsRestored = () => {
     596         4710 :     tabsRestored.value = true
     597              :   }
     598              : 
     599              :   /** @see WorkflowStore.isSubgraphActive */
     600         2355 :   const isSubgraphActive = ref(false)
     601              : 
     602              :   /** @see WorkflowStore.activeSubgraph */
     603         2355 :   const activeSubgraph = shallowRef<Raw<Subgraph>>()
     604              : 
     605              :   /** @see WorkflowStore.updateActiveGraph */
     606         2355 :   const updateActiveGraph = () => {
     607         4085 :     const canvas = useApp().canvasOrUndefined
     608         4085 :     if (!canvas) return
     609         4085 :     const subgraph = canvas.subgraph
     610         4085 :     activeSubgraph.value = subgraph ? markRaw(subgraph) : undefined
     611              : 
     612         4085 :     isSubgraphActive.value = isSubgraph(subgraph)
     613              :   }
     614              : 
     615         2355 :   const subgraphNodeIdToSubgraph = (id: string, graph: LGraph | Subgraph) => {
     616            0 :     const parsedNodeId = parseNodeId(id)
     617            0 :     if (!parsedNodeId) return
     618            0 :     const node = graph.getNodeById(parsedNodeId)
     619            0 :     if (node?.isSubgraphNode()) return node.subgraph
     620              :   }
     621              : 
     622         2355 :   const getSubgraphsFromInstanceIds = (
     623              :     currentGraph: LGraph | Subgraph,
     624              :     subgraphNodeIds: string[]
     625              :   ): Subgraph[] | undefined => {
     626            0 :     const currentPart = subgraphNodeIds.at(0)
     627            0 :     const remainingParts = subgraphNodeIds.slice(1)
     628            0 :     if (currentPart === undefined) return []
     629              : 
     630            0 :     const subgraph = subgraphNodeIdToSubgraph(currentPart, currentGraph)
     631            0 :     if (subgraph === undefined) return
     632              : 
     633            0 :     const childSubgraphs = getSubgraphsFromInstanceIds(subgraph, remainingParts)
     634            0 :     return childSubgraphs ? [subgraph, ...childSubgraphs] : undefined
     635              :   }
     636              : 
     637              :   //FIXME: use existing util function
     638         2355 :   const executionIdToCurrentId = (id: string): string | undefined => {
     639          227 :     const subgraph = activeSubgraph.value
     640              : 
     641              :     // Short-circuit: ID belongs to the parent workflow / no active subgraph
     642          227 :     if (!id.includes(':')) {
     643          200 :       return !subgraph ? id : undefined
     644           27 :     } else if (!subgraph) {
     645           27 :       return
     646              :     }
     647              : 
     648          227 :     const executionPath = parseNodeExecutionId(id)?.map(String)
     649          227 :     if (!executionPath) return
     650              : 
     651            0 :     const nodeId = executionPath.at(-1)
     652            0 :     if (nodeId === undefined) return
     653              : 
     654              :     const subgraphs = getSubgraphsFromInstanceIds(
     655              :       useApp().rootGraph,
     656              :       executionPath.slice(0, -1)
     657              :     )
     658          227 :     if (subgraphs?.at(-1) === subgraph) return nodeId
     659              :   }
     660              : 
     661         2355 :   watch(activeWorkflow, updateActiveGraph)
     662              : 
     663              :   /**
     664              :    * Convert a node ID to a NodeLocatorId
     665              :    * @param nodeId The local node ID
     666              :    * @param subgraph The subgraph containing the node (defaults to active subgraph)
     667              :    * @returns The NodeLocatorId
     668              :    */
     669         2355 :   const nodeIdToNodeLocatorId = (
     670              :     nodeId: NodeId,
     671              :     subgraph?: Subgraph
     672              :   ): NodeLocatorId => {
     673        73796 :     const targetSubgraph = subgraph ?? activeSubgraph.value
     674        73796 :     if (!targetSubgraph) {
     675        73135 :       return createNodeLocatorId(null, nodeId)
     676              :     }
     677              : 
     678          661 :     return createNodeLocatorId(targetSubgraph.id, nodeId)
     679              :   }
     680              :   /**
     681              :    * Convert a node to a NodeLocatorId
     682              :    * Does not assume the node resides in  the active graph
     683              :    * @param The actual node instance
     684              :    * @returns The NodeLocatorId (for root graph nodes, returns the node ID as-is)
     685              :    */
     686         2355 :   const nodeToNodeLocatorId = (node: LGraphNode): NodeLocatorId => {
     687       171330 :     if (isSubgraph(node.graph))
     688         4084 :       return createNodeLocatorId(node.graph.id, node.id)
     689       167246 :     return createNodeLocatorId(null, node.id)
     690              :   }
     691              : 
     692              :   /**
     693              :    * Extract the node ID from a NodeLocatorId
     694              :    * @param locatorId The NodeLocatorId
     695              :    * @returns The local node ID
     696              :    */
     697         2355 :   const nodeLocatorIdToNodeId = (locatorId: NodeLocatorId): NodeId | null =>
     698              :     parseNodeLocatorId(locatorId)?.localNodeId ?? null
     699              : 
     700              :   /**
     701              :    * Convert a NodeLocatorId to an execution ID for a specific context
     702              :    * @param locatorId The NodeLocatorId
     703              :    * @param targetSubgraph The subgraph context (defaults to active subgraph)
     704              :    * @returns The execution ID or null if the node is not accessible from the target context
     705              :    */
     706         2355 :   const nodeLocatorIdToNodeExecutionId = (
     707              :     locatorId: NodeLocatorId,
     708              :     targetSubgraph?: Subgraph
     709              :   ): NodeExecutionId | null => {
     710        41263 :     const parsed = parseNodeLocatorId(locatorId)
     711        41263 :     if (!parsed) return null
     712              : 
     713        41263 :     const { subgraphUuid, localNodeId } = parsed
     714              : 
     715              :     // If no subgraph UUID, this is a root graph node
     716        41263 :     if (!subgraphUuid) {
     717        40933 :       return createLeafNodeExecutionId(localNodeId)
     718              :     }
     719              : 
     720              :     // Find the path from root to the subgraph with this UUID
     721          330 :     const findSubgraphPath = (
     722              :       graph: LGraph | Subgraph,
     723              :       targetUuid: string,
     724              :       path: NodeId[] = []
     725              :     ): NodeId[] | null => {
     726          684 :       if (isSubgraph(graph) && graph.id === targetUuid) {
     727          330 :         return path
     728              :       }
     729              : 
     730          490 :       for (const node of graph._nodes) {
     731          806 :         if (node.isSubgraphNode()) {
     732          354 :           const result = findSubgraphPath(node.subgraph, targetUuid, [
     733              :             ...path,
     734              :             node.id
     735              :           ])
     736          354 :           if (result) return result
     737              :         }
     738              :       }
     739              : 
     740            0 :       return null
     741              :     }
     742              : 
     743          330 :     const path = findSubgraphPath(useApp().rootGraph, subgraphUuid)
     744         3754 :     if (!path) return null
     745              : 
     746              :     // If we have a target subgraph, check if the path goes through it
     747        41263 :     if (
     748              :       targetSubgraph &&
     749              :       !path.some((_, idx) => {
     750              :         const subgraphs = getSubgraphsFromInstanceIds(
     751              :           useApp().rootGraph,
     752              :           path.slice(0, idx + 1).map((id) => String(id))
     753              :         )
     754            0 :         return subgraphs?.at(-1) === targetSubgraph
     755              :       })
     756              :     ) {
     757            0 :       return null
     758              :     }
     759              : 
     760          330 :     return tryNormalizeNodeExecutionId([...path, localNodeId].join(':'))
     761              :   }
     762              : 
     763         2355 :   return {
     764              :     activeWorkflow,
     765              :     attachWorkflow,
     766              :     isActive,
     767              :     openWorkflows,
     768              :     openedWorkflowIndexShift,
     769              :     getMostRecentWorkflow,
     770              :     openWorkflow,
     771              :     openWorkflowsInBackground,
     772              :     isOpen,
     773              :     isBusy,
     774              :     closeWorkflow,
     775              :     createTemporary,
     776              :     createNewTemporary,
     777              :     renameWorkflow,
     778              :     onWorkflowRenamed: workflowRenamed.on,
     779              :     onUserActivation: (listener: (workflow: ComfyWorkflow) => unknown) =>
     780              :       userActivation.on(async (workflow) => {
     781            0 :         try {
     782            0 :           await listener(workflow)
     783              :         } catch (error) {
     784            0 :           reportActivationError(error)
     785              :         }
     786              :       }),
     787              :     reportUserActivation: (workflow: ComfyWorkflow) =>
     788              :       void userActivation.trigger(workflow),
     789              :     deleteWorkflow,
     790              :     saveAs,
     791              :     saveWorkflow,
     792              :     reorderWorkflows,
     793              : 
     794              :     workflows,
     795              :     bookmarkedWorkflows,
     796              :     persistedWorkflows,
     797              :     modifiedWorkflows,
     798              :     getWorkflowByPath,
     799              :     syncWorkflows,
     800              :     isSyncLoading,
     801              :     loadWorkflows,
     802              : 
     803              :     tabsRestored: computed(() => tabsRestored.value),
     804              :     markTabsRestored,
     805              :     isSubgraphActive,
     806              :     activeSubgraph,
     807              :     updateActiveGraph,
     808              :     executionIdToCurrentId,
     809              :     nodeIdToNodeLocatorId,
     810              :     nodeToNodeLocatorId,
     811              :     nodeLocatorIdToNodeId,
     812              :     nodeLocatorIdToNodeExecutionId
     813              :   }
     814              : }) satisfies () => WorkflowStore
     815              : 
     816         2356 : export const useWorkflowBookmarkStore = defineStore('workflowBookmark', () => {
     817         2355 :   const bookmarks = ref<Set<string>>(new Set())
     818              : 
     819         2355 :   const isBookmarked = (path: string) => bookmarks.value.has(path)
     820              : 
     821         2355 :   const loadBookmarks = async () => {
     822           89 :     const resp = await api.getUserData('workflows/.index.json')
     823           87 :     if (resp.status === 200) {
     824            0 :       const info = await resp.json()
     825            0 :       bookmarks.value = new Set(info?.favorites ?? [])
     826              :     }
     827              :   }
     828              : 
     829         2355 :   const saveBookmarks = async () => {
     830            0 :     await api.storeUserData('workflows/.index.json', {
     831              :       favorites: Array.from(bookmarks.value)
     832              :     })
     833              :   }
     834              : 
     835         2355 :   const setBookmarked = async (path: string, value: boolean) => {
     836            0 :     if (bookmarks.value.has(path) === value) return
     837            0 :     if (value) {
     838            0 :       bookmarks.value.add(path)
     839              :     } else {
     840            0 :       bookmarks.value.delete(path)
     841              :     }
     842            0 :     await saveBookmarks()
     843              :   }
     844              : 
     845         2355 :   const toggleBookmarked = async (path: string) => {
     846            0 :     await setBookmarked(path, !bookmarks.value.has(path))
     847              :   }
     848              : 
     849         2355 :   return {
     850              :     isBookmarked,
     851              :     loadBookmarks,
     852              :     saveBookmarks,
     853              :     setBookmarked,
     854              :     toggleBookmarked
     855              :   }
     856              : })
        

Generated by: LCOV version 2.0-1