LCOV - code coverage report
Current view: top level - src/renderer/extensions/linearMode - linearOutputStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 88.2 % 153 135
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { defineStore } from 'pinia'
       2              : import { computed, ref, shallowRef, watch } from 'vue'
       3              : 
       4              : import { useAppMode } from '@/composables/useAppMode'
       5              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
       6              : import { flattenNodeOutput } from '@/renderer/extensions/linearMode/flattenNodeOutput'
       7              : import type { InProgressItem } from '@/renderer/extensions/linearMode/linearModeTypes'
       8              : import type { AugmentedResultItem } from '@/utils/resultItem'
       9              : import type {
      10              :   ExecutedWsMessage,
      11              :   JobId
      12              : } from '@comfyorg/api-client/executionTypes'
      13              : import { api } from '@/scripts/api'
      14              : import { useAppModeStore } from '@/stores/appModeStore'
      15              : import { useExecutionStore } from '@/stores/executionStore'
      16              : import { useJobPreviewStore } from '@/stores/jobPreviewStore'
      17              : 
      18         2355 : export const useLinearOutputStore = defineStore('linearOutput', () => {
      19           79 :   const { isAppMode } = useAppMode()
      20           79 :   const appModeStore = useAppModeStore()
      21           79 :   const executionStore = useExecutionStore()
      22           79 :   const jobPreviewStore = useJobPreviewStore()
      23           79 :   const workflowStore = useWorkflowStore()
      24              : 
      25           79 :   const inProgressItems = ref<InProgressItem[]>([])
      26           79 :   const resolvedOutputsCache = new Map<string, AugmentedResultItem[]>()
      27           79 :   const selectedId = ref<string | null>(null)
      28           79 :   const isFollowing = ref(true)
      29           79 :   const trackedJobId = ref<JobId | null>(null)
      30           79 :   const pendingResolve = ref(new Set<JobId>())
      31           79 :   const executedNodeIds = new Set<string>()
      32              : 
      33           79 :   const activeWorkflowInProgressItems = computed(() => {
      34          134 :     const path = workflowStore.activeWorkflow?.path
      35          134 :     if (!path) return []
      36              :     const all = inProgressItems.value
      37          134 :     return all.filter(
      38              :       (i) => executionStore.jobIdToSessionWorkflowPath.get(i.jobId) === path
      39              :     )
      40              :   })
      41              : 
      42           79 :   let nextSeq = 0
      43              : 
      44          124 :   function makeItemId(jobId: JobId): string {
      45          124 :     return `job-${jobId}-${nextSeq++}`
      46              :   }
      47              : 
      48            2 :   function replaceItem(
      49              :     id: string,
      50              :     updater: (item: InProgressItem) => InProgressItem
      51              :   ) {
      52            2 :     inProgressItems.value = inProgressItems.value.map((i) =>
      53              :       i.id === id ? updater(i) : i
      54              :     )
      55              :   }
      56              : 
      57              :   // --- Actions ---
      58              : 
      59           79 :   const currentSkeletonId = shallowRef<string | null>(null)
      60              : 
      61           20 :   function onJobStart(jobId: JobId) {
      62           20 :     executedNodeIds.clear()
      63              : 
      64           20 :     const item: InProgressItem = {
      65              :       id: makeItemId(jobId),
      66              :       jobId,
      67              :       state: 'skeleton'
      68              :     }
      69           20 :     currentSkeletonId.value = item.id
      70           20 :     inProgressItems.value = [item, ...inProgressItems.value]
      71              : 
      72           20 :     trackedJobId.value = jobId
      73           20 :     autoSelect(`slot:${item.id}`, jobId)
      74              :   }
      75              : 
      76           79 :   let raf: number | null = null
      77            2 :   function onLatentPreview(jobId: JobId, url: string, nodeId?: string) {
      78            2 :     if (nodeId && executedNodeIds.has(nodeId)) return
      79              : 
      80              :     // Issue in Firefox where it doesnt seem to always re-render, wrapping in RAF fixes it
      81            2 :     if (raf) cancelAnimationFrame(raf)
      82            2 :     raf = requestAnimationFrame(() => {
      83            2 :       const existing = inProgressItems.value.find(
      84              :         (i) => i.id === currentSkeletonId.value && i.jobId === jobId
      85              :       )
      86              : 
      87            2 :       if (existing) {
      88            2 :         const wasEmpty = existing.state === 'skeleton'
      89            2 :         replaceItem(existing.id, (i) => ({
      90              :           ...i,
      91              :           state: 'latent',
      92              :           latentPreviewUrl: url
      93              :         }))
      94            2 :         if (wasEmpty) autoSelect(`slot:${existing.id}`, jobId)
      95            2 :         return
      96              :       }
      97              : 
      98              :       // Only create on-demand for the tracked job
      99            0 :       if (jobId !== trackedJobId.value) return
     100              : 
     101            0 :       const item: InProgressItem = {
     102              :         id: makeItemId(jobId),
     103              :         jobId,
     104              :         state: 'latent',
     105              :         latentPreviewUrl: url
     106              :       }
     107            0 :       currentSkeletonId.value = item.id
     108            0 :       inProgressItems.value = [item, ...inProgressItems.value]
     109            0 :       autoSelect(`slot:${item.id}`, jobId)
     110              :     })
     111              :   }
     112              : 
     113           21 :   function onNodeExecuted(jobId: JobId, detail: ExecutedWsMessage) {
     114           21 :     const nodeId = String(detail.display_node || detail.node)
     115           21 :     executedNodeIds.add(nodeId)
     116           21 :     if (raf) {
     117            1 :       cancelAnimationFrame(raf)
     118            1 :       raf = null
     119              :     }
     120           21 :     const newOutputs = flattenNodeOutput([nodeId, detail.output])
     121           21 :     if (newOutputs.length === 0) return
     122              : 
     123              :     // Skip output items for nodes not flagged as output nodes
     124           14 :     const outputNodeIds = appModeStore.selectedOutputs
     125           21 :     if (
     126              :       outputNodeIds.length > 0 &&
     127              :       !outputNodeIds.some((id) => String(id) === nodeId)
     128              :     )
     129            1 :       return
     130              : 
     131           13 :     const skeletonItem = inProgressItems.value.find(
     132              :       (i) => i.id === currentSkeletonId.value && i.jobId === jobId
     133              :     )
     134              : 
     135           13 :     if (skeletonItem) {
     136           10 :       const imageItem: InProgressItem = {
     137              :         ...skeletonItem,
     138              :         state: 'image',
     139              :         output: newOutputs[0],
     140              :         latentPreviewUrl: undefined
     141              :       }
     142           10 :       autoSelect(`slot:${imageItem.id}`, jobId)
     143              : 
     144           10 :       const extras: InProgressItem[] = newOutputs.slice(1).map((o) => ({
     145              :         id: makeItemId(jobId),
     146              :         jobId,
     147              :         state: 'image' as const,
     148              :         output: o
     149              :       }))
     150              : 
     151           10 :       const idx = inProgressItems.value.indexOf(skeletonItem)
     152           10 :       const arr = [...inProgressItems.value]
     153           10 :       arr.splice(idx, 1, imageItem, ...extras)
     154           10 :       currentSkeletonId.value = null
     155           10 :       inProgressItems.value = arr
     156           10 :       return
     157              :     }
     158              : 
     159              :     // No skeleton — create image items directly (only for tracked job)
     160            6 :     if (jobId !== trackedJobId.value) return
     161              : 
     162            3 :     const newItems: InProgressItem[] = newOutputs.map((o) => ({
     163              :       id: makeItemId(jobId),
     164              :       jobId,
     165              :       state: 'image' as const,
     166              :       output: o
     167              :     }))
     168            3 :     autoSelect(`slot:${newItems[0].id}`, jobId)
     169            3 :     inProgressItems.value = [...newItems, ...inProgressItems.value]
     170              :   }
     171              : 
     172            5 :   function onJobComplete(jobId: JobId) {
     173              :     // On any job complete, remove all pending resolve items.
     174            5 :     if (pendingResolve.value.size > 0) {
     175            0 :       for (const oldJobId of pendingResolve.value) {
     176            0 :         removeJobItems(oldJobId)
     177              :       }
     178            0 :       pendingResolve.value = new Set()
     179              :     }
     180              : 
     181            5 :     if (raf) {
     182            0 :       cancelAnimationFrame(raf)
     183            0 :       raf = null
     184              :     }
     185            5 :     currentSkeletonId.value = null
     186            5 :     if (trackedJobId.value === jobId) {
     187            5 :       trackedJobId.value = null
     188              :     }
     189              : 
     190              :     const hasImages = inProgressItems.value.some(
     191              :       (i) => i.jobId === jobId && i.state === 'image'
     192              :     )
     193              : 
     194            5 :     if (hasImages) {
     195              :       // Remove non-image items (skeletons, latents), keep images for absorption
     196            2 :       inProgressItems.value = inProgressItems.value.filter(
     197              :         (i) => i.jobId !== jobId || i.state === 'image'
     198              :       )
     199            2 :       pendingResolve.value = new Set([...pendingResolve.value, jobId])
     200              :     } else {
     201            3 :       removeJobItems(jobId)
     202              :     }
     203              :   }
     204              : 
     205            5 :   function removeJobItems(jobId: JobId) {
     206            5 :     const removed = inProgressItems.value.filter((i) => i.jobId === jobId)
     207            5 :     inProgressItems.value = inProgressItems.value.filter(
     208              :       (i) => i.jobId !== jobId
     209              :     )
     210              : 
     211            5 :     if (
     212              :       selectedId.value &&
     213              :       removed.some((i) => `slot:${i.id}` === selectedId.value)
     214              :     ) {
     215            5 :       selectedId.value = null
     216              :     }
     217              :   }
     218              : 
     219            2 :   function resolveIfReady(jobId: JobId, historyLoaded: boolean) {
     220            2 :     if (!pendingResolve.value.has(jobId)) return
     221            2 :     if (!historyLoaded) return
     222              : 
     223            2 :     const next = new Set(pendingResolve.value)
     224            2 :     next.delete(jobId)
     225            2 :     pendingResolve.value = next
     226              : 
     227            2 :     removeJobItems(jobId)
     228              :   }
     229              : 
     230            2 :   function select(id: string | null) {
     231            2 :     selectedId.value = id
     232            2 :     isFollowing.value = false
     233              :   }
     234              : 
     235           84 :   function selectAsLatest(id: string | null) {
     236           84 :     selectedId.value = id
     237           84 :     isFollowing.value = true
     238              :   }
     239              : 
     240           55 :   function isJobForActiveWorkflow(jobId: JobId): boolean {
     241           55 :     return (
     242              :       executionStore.jobIdToSessionWorkflowPath.get(jobId) ===
     243              :       workflowStore.activeWorkflow?.path
     244              :     )
     245              :   }
     246              : 
     247           35 :   function autoSelect(slotId: string, jobId: JobId) {
     248              :     // Only auto-select if the job belongs to the active workflow
     249           35 :     if (!isJobForActiveWorkflow(jobId)) return
     250              : 
     251              :     const sel = selectedId.value
     252           35 :     if (!sel || isFollowing.value) {
     253           34 :       selectedId.value = slotId
     254           34 :       isFollowing.value = true
     255           34 :       return
     256              :     }
     257              :     // User is browsing history — don't yank
     258              :   }
     259              : 
     260              :   // --- Event bindings (only active in app mode) ---
     261              : 
     262           21 :   function handleExecuted({ detail }: CustomEvent<ExecutedWsMessage>) {
     263           21 :     const jobId = detail.prompt_id
     264           21 :     if (jobId !== executionStore.activeJobId) return
     265           21 :     onNodeExecuted(jobId, detail)
     266              :   }
     267              : 
     268              :   // Watch both activeJobId and the path mapping together. The path mapping
     269              :   // may arrive after activeJobId due to a race between WebSocket
     270              :   // (execution_start) and the HTTP response (queuePrompt > storeJob).
     271              :   // Watching both ensures onJobStart fires once the mapping is available.
     272           79 :   watch(
     273              :     [
     274              :       () => executionStore.activeJobId,
     275              :       () => executionStore.jobIdToSessionWorkflowPath
     276              :     ],
     277              :     ([jobId], [oldJobId]) => {
     278           47 :       if (!isAppMode.value) return
     279           47 :       if (oldJobId && oldJobId !== jobId) {
     280            5 :         onJobComplete(oldJobId)
     281              :       }
     282              :       // Guard with trackedJobId to avoid double-starting when the
     283              :       // path mapping arrives after activeJobId was already set.
     284           47 :       if (
     285              :         jobId &&
     286              :         trackedJobId.value !== jobId &&
     287              :         isJobForActiveWorkflow(jobId)
     288              :       ) {
     289           20 :         onJobStart(jobId)
     290              :       }
     291              :     }
     292              :   )
     293              : 
     294           79 :   watch(
     295              :     () => jobPreviewStore.nodePreviewsByPromptId,
     296              :     (previews) => {
     297            3 :       if (!isAppMode.value) return
     298            3 :       const jobId = executionStore.activeJobId
     299            3 :       if (!jobId) return
     300            3 :       const preview = Object.hasOwn(previews, jobId)
     301              :         ? previews[jobId]
     302              :         : undefined
     303            3 :       if (preview) onLatentPreview(jobId, preview.url, preview.nodeId)
     304              :     },
     305              :     { deep: true }
     306              :   )
     307              : 
     308           89 :   function reconcileOnEnter() {
     309              :     // Complete any tracked job that finished while we were away.
     310              :     // The activeJobId watcher couldn't fire onJobComplete because
     311              :     // isAppMode was false at the time.
     312           89 :     if (
     313              :       trackedJobId.value &&
     314              :       trackedJobId.value !== executionStore.activeJobId
     315              :     ) {
     316            0 :       onJobComplete(trackedJobId.value)
     317              :     }
     318              :     // Start tracking the current job only if it belongs to this
     319              :     // workflow — otherwise we'd adopt another tab's job.
     320           89 :     if (
     321              :       executionStore.activeJobId &&
     322              :       trackedJobId.value !== executionStore.activeJobId &&
     323              :       isJobForActiveWorkflow(executionStore.activeJobId)
     324              :     ) {
     325            0 :       onJobStart(executionStore.activeJobId)
     326              :     }
     327              : 
     328              :     // Clear stale selection from another workflow's job.
     329           89 :     if (
     330              :       selectedId.value?.startsWith('slot:') &&
     331              :       trackedJobId.value &&
     332              :       !isJobForActiveWorkflow(trackedJobId.value)
     333              :     ) {
     334            0 :       selectedId.value = null
     335            0 :       isFollowing.value = true
     336              :     }
     337              : 
     338              :     // Re-apply the latest latent preview that may have arrived while
     339              :     // away, but only for a job belonging to the active workflow.
     340           89 :     const jobId = trackedJobId.value
     341           89 :     if (jobId && isJobForActiveWorkflow(jobId)) {
     342            0 :       const previews = jobPreviewStore.nodePreviewsByPromptId
     343            0 :       const preview = Object.hasOwn(previews, jobId)
     344              :         ? previews[jobId]
     345              :         : undefined
     346            0 :       if (preview) onLatentPreview(jobId, preview.url, preview.nodeId)
     347              :     }
     348              :   }
     349              : 
     350           19 :   function cleanupOnLeave() {
     351              :     // If the tracked job already finished (no longer the active job),
     352              :     // complete it now to clean up skeletons/latents. If it's still
     353              :     // running, preserve all items for tab switching.
     354           19 :     if (
     355              :       trackedJobId.value &&
     356              :       trackedJobId.value !== executionStore.activeJobId
     357              :     ) {
     358            0 :       onJobComplete(trackedJobId.value)
     359              :     }
     360              :   }
     361              : 
     362           79 :   watch(
     363              :     isAppMode,
     364              :     (active, wasActive) => {
     365          108 :       if (active) {
     366           89 :         api.addEventListener('executed', handleExecuted)
     367           89 :         reconcileOnEnter()
     368           19 :       } else if (wasActive) {
     369           19 :         api.removeEventListener('executed', handleExecuted)
     370           19 :         cleanupOnLeave()
     371              :       }
     372              :     },
     373              :     { immediate: true }
     374              :   )
     375              : 
     376           79 :   return {
     377              :     activeWorkflowInProgressItems,
     378              :     resolvedOutputsCache,
     379              :     selectedId,
     380              :     pendingResolve,
     381              :     select,
     382              :     selectAsLatest,
     383              :     resolveIfReady,
     384              :     inProgressItems,
     385              :     onJobStart,
     386              :     onLatentPreview,
     387              :     onNodeExecuted,
     388              :     onJobComplete
     389              :   }
     390              : })
        

Generated by: LCOV version 2.0-1