LCOV - code coverage report
Current view: top level - src/stores - assetExportStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 28.3 % 120 34
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { useIntervalFn } from '@vueuse/core'
       2              : import { defineStore } from 'pinia'
       3              : import { computed, ref, watch } from 'vue'
       4              : 
       5              : import { assetService } from '@/platform/assets/services/assetService'
       6              : import { useToast } from '@/components/ui/toast/toastStore'
       7              : import type { TaskResponse, TaskStatus } from '@comfyorg/api-client/taskSchema'
       8              : import type { TaskId, TaskResult } from '@/platform/tasks/services/taskService'
       9              : import {
      10              :   TaskNotFoundError,
      11              :   taskService
      12              : } from '@/platform/tasks/services/taskService'
      13              : import type { AssetExportWsMessage } from '@comfyorg/api-client/executionTypes'
      14              : import { api } from '@/scripts/api'
      15              : import { t } from '@/i18n'
      16              : 
      17              : export interface AssetExport {
      18              :   taskId: TaskId
      19              :   exportName: string
      20              :   assetsTotal: number
      21              :   assetsAttempted: number
      22              :   assetsFailed: number
      23              :   bytesTotal: number
      24              :   bytesProcessed: number
      25              :   progress: number
      26              :   status: TaskStatus
      27              :   error?: string
      28              :   downloadError?: string
      29              :   lastUpdate: number
      30              :   downloadTriggered: boolean
      31              : }
      32              : 
      33         2355 : const STALE_THRESHOLD_MS = 10_000
      34         2355 : const POLL_INTERVAL_MS = 10_000
      35         2355 : const MAX_TASK_NOT_FOUND_ATTEMPTS = 2
      36              : 
      37              : /**
      38              :  * `DELETE /tasks/{id}` is task-type agnostic, so an export can be cancelled
      39              :  * server-side even though this store offers no cancel control. Treating
      40              :  * `cancelled` as finished is what lets such an export leave `activeExports`,
      41              :  * stop being polled, and be cleared by `clearFinishedExports`.
      42              :  */
      43         2355 : const finishedExportStatuses = new Set<TaskStatus>([
      44              :   'completed',
      45              :   'failed',
      46              :   'cancelled'
      47              : ])
      48         2355 : const wireExportStatuses = new Set<string>([
      49              :   'created',
      50              :   'running',
      51              :   ...finishedExportStatuses
      52              : ])
      53              : 
      54            0 : function stringValue(value: unknown, fallback: string): string {
      55            0 :   return typeof value === 'string' ? value : fallback
      56              : }
      57              : 
      58            0 : function numberValue(value: unknown, fallback: number): number {
      59            0 :   return typeof value === 'number' ? value : fallback
      60              : }
      61              : 
      62            1 : function shouldIgnoreExportUpdate(
      63              :   existing: AssetExport | undefined,
      64              :   data: AssetExportWsMessage
      65              : ): boolean {
      66            1 :   const ignoresCompleted =
      67              :     existing?.status === 'completed' &&
      68              :     !(
      69              :       data.status === 'completed' &&
      70              :       !existing.exportName &&
      71              :       data.export_name !== undefined
      72              :     )
      73            1 :   const ignoresFailed =
      74              :     existing?.status === 'failed' && existing.downloadTriggered
      75            1 :   const ignoresCancelled =
      76              :     existing?.status === 'cancelled' && data.status !== 'completed'
      77            1 :   return ignoresCompleted || ignoresFailed || ignoresCancelled
      78              : }
      79              : 
      80            1 : function settleUnknownExportStatus(
      81              :   existing: AssetExport | undefined,
      82              :   data: AssetExportWsMessage
      83              : ): boolean {
      84            1 :   if (wireExportStatuses.has(data.status)) return false
      85            0 :   if (existing) {
      86            0 :     existing.status = 'failed'
      87            0 :     existing.error = data.error || `Unknown task status: ${data.status}`
      88            0 :     existing.lastUpdate = Date.now()
      89              :   }
      90            0 :   return true
      91              : }
      92              : 
      93            0 : function resolveExportDownloadUrl(
      94              :   url: string
      95              : ): { ok: true; value: URL } | { ok: false; error: string } {
      96            0 :   const trimmedUrl = url.trim()
      97            0 :   if (
      98              :     !trimmedUrl ||
      99              :     trimmedUrl.startsWith('//') ||
     100              :     trimmedUrl.startsWith('\\') ||
     101              :     trimmedUrl.startsWith('/\\')
     102              :   ) {
     103            0 :     return { ok: false, error: t('exportToast.unsupportedDownloadUrl') }
     104              :   }
     105            0 :   const resolvedUrl = trimmedUrl.startsWith('/')
     106              :     ? api.apiURL(trimmedUrl)
     107              :     : trimmedUrl
     108            0 :   let parsedUrl: URL
     109            0 :   try {
     110            0 :     parsedUrl = new URL(resolvedUrl, document.baseURI)
     111              :   } catch {
     112            0 :     return { ok: false, error: t('exportToast.unsupportedDownloadUrl') }
     113              :   }
     114            0 :   if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
     115            0 :     return { ok: false, error: t('exportToast.unsupportedDownloadUrl') }
     116              :   }
     117            0 :   return { ok: true, value: parsedUrl }
     118              : }
     119              : 
     120         2355 : export const useAssetExportStore = defineStore('assetExport', () => {
     121         2355 :   const exports = ref<Map<TaskId, AssetExport>>(new Map())
     122         2355 :   const pollingTaskIds = new Set<TaskId>()
     123         2355 :   const taskNotFoundAttempts = new Map<TaskId, number>()
     124              : 
     125         2355 :   const exportList = computed(() => Array.from(exports.value.values()))
     126         2355 :   const activeExports = computed(() =>
     127              :     exportList.value.filter(
     128              :       (e) => e.status === 'created' || e.status === 'running'
     129              :     )
     130              :   )
     131         2355 :   const finishedExports = computed(() =>
     132              :     exportList.value.filter((e) => finishedExportStatuses.has(e.status))
     133              :   )
     134         2355 :   const hasActiveExports = computed(() => activeExports.value.length > 0)
     135         2355 :   const hasExports = computed(() => exports.value.size > 0)
     136              : 
     137            0 :   function trackExport(taskId: TaskId) {
     138            0 :     if (exports.value.has(taskId)) return
     139              : 
     140            0 :     exports.value.set(taskId, {
     141              :       taskId,
     142              :       exportName: '',
     143              :       assetsTotal: 0,
     144              :       assetsAttempted: 0,
     145              :       assetsFailed: 0,
     146              :       bytesTotal: 0,
     147              :       bytesProcessed: 0,
     148              :       progress: 0,
     149              :       status: 'created',
     150              :       lastUpdate: Date.now(),
     151              :       downloadTriggered: false
     152              :     })
     153              :   }
     154              : 
     155            0 :   async function triggerDownload(exp: AssetExport, force = false) {
     156            0 :     if (!force && (exp.downloadTriggered || !exp.exportName)) return
     157            0 :     exp.downloadTriggered = true
     158              : 
     159            0 :     try {
     160            0 :       exp.downloadError = undefined
     161            0 :       const { url } = await assetService.getExportDownloadUrl(exp.exportName)
     162            0 :       const resolvedUrl = resolveExportDownloadUrl(url)
     163            0 :       if (!resolvedUrl.ok) {
     164            0 :         exp.downloadError = resolvedUrl.error
     165            0 :         exp.downloadTriggered = false
     166            0 :         useToast().error(
     167              :           t('exportToast.downloadFailed', { name: exp.exportName }),
     168              :           { description: resolvedUrl.error }
     169              :         )
     170            0 :         return
     171              :       }
     172            0 :       const link = document.createElement('a')
     173            0 :       link.href = resolvedUrl.value.href
     174            0 :       link.download = exp.exportName
     175            0 :       link.style.display = 'none'
     176            0 :       link.target = '_blank'
     177            0 :       link.rel = 'noopener noreferrer'
     178            0 :       document.body.appendChild(link)
     179            0 :       link.click()
     180            0 :       document.body.removeChild(link)
     181              :     } catch (error) {
     182            0 :       const message = error instanceof Error ? error.message : String(error)
     183            0 :       exp.downloadError = message
     184            0 :       exp.downloadTriggered = false
     185              : 
     186            0 :       useToast().error(
     187              :         t('exportToast.downloadFailed', {
     188              :           name: exp.exportName
     189              :         }),
     190              :         { description: message }
     191              :       )
     192              :     }
     193              :   }
     194              : 
     195            1 :   function handleAssetExport(data: AssetExportWsMessage) {
     196            1 :     const existing = exports.value.get(data.task_id)
     197              : 
     198              :     // Completion is authoritative even when fetching the signed URL failed;
     199              :     // late progress/cancellation frames must not revive polling or erase the
     200              :     // retryable download error.
     201              :     // A cancelled export is only superseded by an authoritative completion;
     202              :     // a stale progress message must not revive it and resume polling.
     203            1 :     if (shouldIgnoreExportUpdate(existing, data)) return
     204            1 :     if (settleUnknownExportStatus(existing, data)) return
     205              : 
     206            1 :     const exp: AssetExport = {
     207              :       taskId: data.task_id,
     208              :       exportName: data.export_name ?? existing?.exportName ?? '',
     209              :       assetsTotal: data.assets_total,
     210              :       assetsAttempted: data.assets_attempted,
     211              :       assetsFailed: data.assets_failed,
     212              :       bytesTotal: data.bytes_total,
     213              :       bytesProcessed: data.bytes_processed,
     214              :       progress: data.progress,
     215              :       status: data.status,
     216              :       error: data.error,
     217              :       lastUpdate: Date.now(),
     218              :       downloadTriggered: existing?.downloadTriggered ?? false
     219              :     }
     220              : 
     221            1 :     exports.value.set(data.task_id, exp)
     222              : 
     223            1 :     if (data.status === 'completed') {
     224            0 :       void triggerDownload(exp)
     225              :     }
     226              :   }
     227              : 
     228            0 :   async function pollStaleExports() {
     229            0 :     const now = Date.now()
     230            0 :     const staleExports = activeExports.value.filter(
     231              :       (e) => now - e.lastUpdate >= STALE_THRESHOLD_MS
     232              :     )
     233              : 
     234            0 :     if (staleExports.length === 0) return
     235              : 
     236            0 :     function handleMissingExportTask(exp: AssetExport) {
     237            0 :       const attempts = (taskNotFoundAttempts.get(exp.taskId) ?? 0) + 1
     238            0 :       taskNotFoundAttempts.set(exp.taskId, attempts)
     239            0 :       if (attempts < MAX_TASK_NOT_FOUND_ATTEMPTS) {
     240            0 :         exp.lastUpdate = Date.now()
     241            0 :         return
     242              :       }
     243            0 :       taskNotFoundAttempts.delete(exp.taskId)
     244            0 :       handleAssetExport({
     245              :         task_id: exp.taskId,
     246              :         export_name: exp.exportName,
     247              :         assets_total: exp.assetsTotal,
     248              :         assets_attempted: exp.assetsAttempted,
     249              :         assets_failed: exp.assetsFailed,
     250              :         bytes_total: exp.bytesTotal,
     251              :         bytes_processed: exp.bytesProcessed,
     252              :         progress: exp.progress,
     253              :         status: 'failed',
     254              :         error: t('progressToast.taskUnavailable')
     255              :       })
     256              :     }
     257              : 
     258            0 :     function applyFinishedExport(
     259              :       exp: AssetExport,
     260              :       result: Extract<TaskResult<TaskResponse>, { ok: true }>
     261              :     ) {
     262            0 :       const task = result.value
     263            0 :       if (!finishedExportStatuses.has(task.status)) return
     264            0 :       const taskResult = task.result ?? {}
     265            0 :       handleAssetExport({
     266              :         task_id: exp.taskId,
     267              :         export_name: stringValue(taskResult.export_name, exp.exportName),
     268              :         assets_total: numberValue(taskResult.assets_total, exp.assetsTotal),
     269              :         assets_attempted: numberValue(
     270              :           taskResult.assets_attempted,
     271              :           exp.assetsAttempted
     272              :         ),
     273              :         assets_failed: numberValue(taskResult.assets_failed, exp.assetsFailed),
     274              :         bytes_total: exp.bytesTotal,
     275              :         bytes_processed: exp.bytesTotal,
     276              :         progress: task.status === 'completed' ? 1 : exp.progress,
     277              :         status: task.status,
     278              :         error: task.error_message ?? stringValue(taskResult.error, '')
     279              :       })
     280              :     }
     281              : 
     282            0 :     async function pollSingleExport(exp: AssetExport) {
     283            0 :       if (pollingTaskIds.has(exp.taskId)) return
     284            0 :       pollingTaskIds.add(exp.taskId)
     285            0 :       try {
     286            0 :         const result = await taskService.getTask(exp.taskId)
     287              :         // Without this identity guard, a poll that resolves after the user
     288              :         // dismissed the toast re-inserts the export with `downloadTriggered`
     289              :         // false, which resurrects it and downloads the archive a second time.
     290            0 :         if (exports.value.get(exp.taskId) !== exp) return
     291            0 :         if (!result.ok) {
     292            0 :           if (result.error instanceof TaskNotFoundError) {
     293            0 :             handleMissingExportTask(exp)
     294              :           } else {
     295            0 :             taskNotFoundAttempts.delete(exp.taskId)
     296              :           }
     297            0 :           return
     298              :         }
     299            0 :         taskNotFoundAttempts.delete(exp.taskId)
     300            0 :         applyFinishedExport(exp, result)
     301              :       } finally {
     302            0 :         pollingTaskIds.delete(exp.taskId)
     303              :       }
     304              :     }
     305              : 
     306            0 :     await Promise.all(staleExports.map(pollSingleExport))
     307              :   }
     308              : 
     309         2355 :   const { pause, resume } = useIntervalFn(
     310              :     () => void pollStaleExports(),
     311              :     POLL_INTERVAL_MS,
     312              :     { immediate: false }
     313              :   )
     314              : 
     315         2355 :   watch(
     316              :     hasActiveExports,
     317              :     (hasActive) => {
     318         2356 :       if (hasActive) resume()
     319         2355 :       else pause()
     320              :     },
     321              :     { immediate: true }
     322              :   )
     323              : 
     324         2355 :   api.addEventListener('asset_export', (e) => handleAssetExport(e.detail))
     325              : 
     326            0 :   function clearFinishedExports() {
     327            0 :     for (const exp of finishedExports.value) {
     328            0 :       taskNotFoundAttempts.delete(exp.taskId)
     329            0 :       exports.value.delete(exp.taskId)
     330              :     }
     331              :   }
     332              : 
     333         2355 :   return {
     334              :     activeExports,
     335              :     finishedExports,
     336              :     hasActiveExports,
     337              :     hasExports,
     338              :     exportList,
     339              :     trackExport,
     340              :     triggerDownload,
     341              :     clearFinishedExports
     342              :   }
     343              : })
        

Generated by: LCOV version 2.0-1