LCOV - code coverage report
Current view: top level - src/platform/assets/composables/media - assetMappers.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 78.3 % 46 36
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { AssetItem } from '@/platform/assets/schemas/assetSchema'
       2              : import { getOutputSubfolder } from '@/platform/assets/utils/assetMetadataUtils'
       3              : import type { OutputAssetMetadata } from '@/platform/assets/schemas/assetMetadataSchema'
       4              : import { getOutputAssetMetadata } from '@/platform/assets/schemas/assetMetadataSchema'
       5              : import type { AssetContext } from '@/platform/assets/schemas/mediaAssetSchema'
       6              : import { getAssetType as getAssetSourceType } from '@/platform/assets/utils/assetTypeUtil'
       7              : import { getStoredOutputIdentity } from '@/platform/assets/utils/outputAssetUtil'
       8              : import { appendCloudResParam } from '@/platform/distribution/cloudPreviewUtil'
       9              : import { api } from '@/scripts/api'
      10              : import type { TaskItemImpl } from '@/stores/queueStore'
      11              : import type { AugmentedResultItem } from '@/utils/resultItem'
      12              : import { resultItemPreviewUrl, resultItemUrl } from '@/utils/resultItemUrl'
      13              : import {
      14              :   getMediaTypeFromFilename,
      15              :   isPreviewableMediaType
      16              : } from '@/utils/formatUtil'
      17              : 
      18              : /**
      19              :  * Extract asset type from tags array
      20              :  * @param tags The tags array from AssetItem
      21              :  * @returns The asset type ('input' or 'output')
      22              :  */
      23          409 : export function getAssetType(tags?: string[]): AssetContext['type'] {
      24              :   const tag = tags?.[0]
      25          409 :   if (tag === 'output') return 'output'
      26           22 :   return 'input'
      27              : }
      28              : 
      29              : /**
      30              :  * Maps a TaskItemImpl output to an AssetItem format
      31              :  * @param taskItem The task item containing execution data
      32              :  * @param output The output from the task
      33              :  * @param useDisplayName Whether to truncate the filename for display
      34              :  * @returns AssetItem formatted object
      35              :  */
      36         3724 : export function mapTaskOutputToAssetItem(
      37              :   taskItem: TaskItemImpl,
      38              :   output: AugmentedResultItem
      39              : ): AssetItem {
      40         3724 :   const metadata: OutputAssetMetadata = {
      41              :     jobId: taskItem.jobId,
      42              :     nodeId: output.nodeId,
      43              :     subfolder: output.subfolder,
      44              :     executionTimeInSeconds: taskItem.executionTimeInSeconds,
      45              :     format: output.format,
      46              :     create_time: taskItem.createTime
      47              :   }
      48              : 
      49         3724 :   const executionTime = taskItem.executionStartTimestamp
      50              :     ? new Date(taskItem.executionStartTimestamp).toISOString()
      51              :     : new Date().toISOString()
      52              : 
      53         3724 :   return {
      54              :     id: taskItem.jobId,
      55              :     name: output.filename,
      56              :     display_name: output.display_name,
      57              :     size: 0,
      58              :     created_at: executionTime,
      59              :     updated_at: executionTime,
      60              :     tags: ['output'],
      61              :     thumbnail_url: resultItemPreviewUrl(output),
      62              :     preview_url: resultItemUrl(output),
      63              :     user_metadata: metadata
      64              :   }
      65              : }
      66              : 
      67         2356 : const byCreatedAtAsc = (a: AssetItem, b: AssetItem): number =>
      68              :   new Date(a.created_at).getTime() - new Date(b.created_at).getTime() ||
      69              :   a.name.localeCompare(b.name)
      70              : 
      71         2356 : const byCreatedAtDesc = (a: AssetItem, b: AssetItem): number =>
      72              :   new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
      73          104 : function isTempOutput(asset: AssetItem): boolean {
      74          104 :   return asset.tags.includes('temp') || getAssetSourceType(asset) === 'temp'
      75              : }
      76              : 
      77         2356 : const NON_OUTPUT_TAGS = new Set(['input', 'models'])
      78              : 
      79              : /** Whether an asset added to a workflow lives in the temp root: its stored output identity, else temp evidence on a generated output. */
      80         1903 : export function isGeneratedTempOutput(asset: AssetItem): boolean {
      81         1903 :   const storedType = getStoredOutputIdentity(asset)?.type
      82         1903 :   if (storedType) return storedType === 'temp'
      83         1736 :   if (getAssetSourceType(asset) === 'input') return false
      84         1903 :   return (
      85              :     !asset.tags.some((tag) => NON_OUTPUT_TAGS.has(tag)) && isTempOutput(asset)
      86              :   )
      87              : }
      88              : 
      89         2356 : const byIsTemp = (a: AssetItem, b: AssetItem): number =>
      90              :   Number(isTempOutput(b)) - Number(isTempOutput(a))
      91              : 
      92            0 : function flatAssetToResultItem(asset: AssetItem): AugmentedResultItem {
      93            0 :   const metadata = getOutputAssetMetadata(asset.user_metadata)
      94            0 :   const url = asset.preview_url ?? ''
      95            0 :   return {
      96              :     assetId: asset.id,
      97              :     hash: asset.hash,
      98              :     display_name: asset.display_name ?? undefined,
      99              :     filename: asset.name,
     100              :     format: metadata?.format,
     101              :     mediaType: getMediaTypeFromFilename(asset.name),
     102              :     nodeId: metadata?.nodeId ?? '',
     103              :     subfolder: getOutputSubfolder(asset) ?? '',
     104              :     type: isTempOutput(asset) ? 'temp' : 'output',
     105              :     url,
     106              :     previewUrl: asset.thumbnail_url ?? url
     107              :   }
     108              : }
     109              : 
     110              : /**
     111              :  * Group flat per-file output assets into one asset per job, mirroring the
     112              :  * grouped shape produced from the history API: the group id is the job id and
     113              :  * user_metadata carries outputCount/allOutputs. Assets without output job
     114              :  * metadata pass through ungrouped.
     115              :  */
     116            8 : export function unflattenOutputAssets(
     117              :   flatAssets: readonly AssetItem[]
     118              : ): AssetItem[] {
     119            8 :   const assetsByJob = new Map<string, AssetItem[]>()
     120            8 :   const ungrouped: AssetItem[] = []
     121              : 
     122            8 :   for (const asset of flatAssets) {
     123           22 :     const { job_id } = asset
     124           22 :     if (!job_id) {
     125           22 :       ungrouped.push(asset)
     126           22 :       continue
     127              :     }
     128            0 :     const group = assetsByJob.get(job_id)
     129            0 :     if (group) group.push(asset)
     130            0 :     else assetsByJob.set(job_id, [asset])
     131              :   }
     132              : 
     133              :   const grouped = [...assetsByJob.entries()].map(([job_id, assets]) => {
     134            0 :     const ordered = [...assets].sort(byCreatedAtAsc)
     135            0 :     const representative =
     136              :       [...ordered]
     137              :         .sort(byIsTemp)
     138              :         .findLast((asset) =>
     139              :           isPreviewableMediaType(getMediaTypeFromFilename(asset.name))
     140              :         ) ?? ordered.at(-1)!
     141            0 :     return {
     142              :       ...representative,
     143              :       id: job_id,
     144              :       created_at: ordered.at(-1)!.created_at,
     145              :       user_metadata: {
     146              :         jobId: job_id,
     147              :         ...representative.user_metadata,
     148              :         subfolder: getOutputSubfolder(representative) ?? '',
     149              :         assetId: representative.id,
     150              :         outputCount: ordered.length,
     151              :         allOutputs: ordered.map(flatAssetToResultItem)
     152              :       }
     153              :     }
     154              :   })
     155              : 
     156            8 :   return [...grouped, ...ungrouped].sort(byCreatedAtDesc)
     157              : }
     158              : 
     159              : /**
     160              :  * Strips ComfyUI's trailing directory-type annotation (e.g. ` [input]`,
     161              :  * ` [output]`, `[temp]`) from a filename returned by the OSS internal
     162              :  * `/internal/files/{type}` endpoint. The annotation is part of the wire
     163              :  * format LoadImage-style widgets expect, but for the assets sidebar we
     164              :  * want the canonical on-disk filename so type detection / titles work.
     165              :  */
     166         5781 : function stripDirectoryAnnotation(filename: string): string {
     167         5781 :   return filename.replace(/\s*\[(?:input|output|temp)\]\s*$/i, '')
     168              : }
     169              : 
     170              : /**
     171              :  * Maps input directory file to AssetItem format
     172              :  * @param filename The filename
     173              :  * @param index File index for unique ID
     174              :  * @param directory The directory type
     175              :  * @returns AssetItem formatted object
     176              :  */
     177         5781 : export function mapInputFileToAssetItem(
     178              :   filename: string,
     179              :   index: number,
     180              :   directory: 'input' | 'output' = 'input'
     181              : ): AssetItem {
     182         5781 :   const cleanName = stripDirectoryAnnotation(filename)
     183         5781 :   const params = new URLSearchParams({ filename: cleanName, type: directory })
     184         5781 :   const preview_url = api.apiURL(`/view?${params}`)
     185         5781 :   appendCloudResParam(params, cleanName)
     186              : 
     187         5781 :   const created_at = new Date().toISOString()
     188         5781 :   return {
     189              :     id: `${directory}-${index}-${cleanName}`,
     190              :     name: cleanName,
     191              :     size: 0,
     192              :     created_at,
     193              :     updated_at: created_at,
     194              :     tags: [directory],
     195              :     thumbnail_url: api.apiURL(`/view?${params}`),
     196              :     preview_url
     197              :   }
     198              : }
        

Generated by: LCOV version 2.0-1