LCOV - code coverage report
Current view: top level - src/platform/assets/composables - useMediaAssetActions.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 48.9 % 307 150
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { compact, uniqBy } from 'es-toolkit'
       2              : import { useToast } from '@/components/ui/toast/toastStore'
       3              : import { inject } from 'vue'
       4              : import { useI18n } from 'vue-i18n'
       5              : 
       6              : import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
       7              : import { useFeatureFlags } from '@/composables/useFeatureFlags'
       8              : import { isCloud } from '@/platform/distribution/types'
       9              : import { isGeneratedTempOutput } from '@/platform/assets/composables/media/assetMappers'
      10              : import { withNodeAddSource } from '@/platform/telemetry/nodeAdded/nodeAddSource'
      11              : import { reportError } from '@comfyorg/telemetry/reportError'
      12              : import { useWorkflowActionsService } from '@/platform/workflow/core/services/workflowActionsService'
      13              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
      14              : import {
      15              :   extractApiPromptFromAsset,
      16              :   extractWorkflowFromAsset
      17              : } from '@/platform/workflow/utils/workflowExtractionUtil'
      18              : import { api } from '@/scripts/api'
      19              : import { app } from '@/scripts/app'
      20              : import { useDialogService } from '@/services/dialogService'
      21              : import { isGraphLoadFailurePresented } from '@/services/graphLoadFailure'
      22              : import type { WorkflowOpenResult } from '@/platform/workflow/core/services/workflowActionsService'
      23              : import { useLitegraphService } from '@/services/litegraphService'
      24              : import { useNodeDefStore } from '@/stores/nodeDefStore'
      25              : import { getOutputAssetMetadata } from '@/platform/assets/schemas/assetMetadataSchema'
      26              : import { useAssetsStore } from '@/stores/assetsStore'
      27              : import { useNodeOutputStore } from '@/stores/nodeOutputStore'
      28              : import {
      29              :   getAssetDisplayName,
      30              :   getAssetStoredFilename,
      31              :   getOutputSubfolder
      32              : } from '@/platform/assets/utils/assetMetadataUtils'
      33              : import { getAssetType } from '@/platform/assets/utils/assetTypeUtil'
      34              : import { getAssetFileUrl } from '@/platform/assets/utils/assetUrlUtil'
      35              : import { clearDeletedAssetWidgetValues } from '@/platform/assets/utils/clearDeletedAssetWidgetValues'
      36              : import { clearNodePreviewCacheForValues } from '@/platform/assets/utils/clearNodePreviewCacheForValues'
      37              : import { markDeletedAssetsAsMissingMedia } from '@/platform/assets/utils/markDeletedAssetsAsMissingMedia'
      38              : import { getTotalAssetOutputCount } from '@/platform/assets/utils/outputAssetCountUtil'
      39              : import {
      40              :   getStoredOutputIdentity,
      41              :   resolveOutputAssetItems
      42              : } from '@/platform/assets/utils/outputAssetUtil'
      43              : import { createAnnotatedPath } from '@/utils/createAnnotatedPath'
      44              : import { detectNodeTypeFromFilename } from '@/utils/loaderNodeUtil'
      45              : import { isResultItemType } from '@/utils/typeGuardUtil'
      46              : 
      47              : import type { AssetId, AssetItem } from '@/platform/assets/schemas/assetSchema'
      48              : import { MediaAssetKey } from '@/platform/assets/schemas/mediaAssetSchema'
      49              : import { assetService } from '@/platform/assets/services/assetService'
      50              : import { useAssetDownload } from './useAssetDownload'
      51              : import { useAssetZipExport } from './useAssetZipExport'
      52              : import type { AssetDownload } from './useAssetDownload'
      53              : 
      54         2355 : const EXCLUDED_TAGS = new Set(['models', 'input', 'output'])
      55              : 
      56            5 : function createAssetWidgetPath(asset: AssetItem): string {
      57            5 :   const assetType = isGeneratedTempOutput(asset)
      58              :     ? 'temp'
      59              :     : getAssetType(asset, 'input')
      60              : 
      61            5 :   return createAnnotatedPath({
      62              :     filename: getAssetStoredFilename(
      63              :       asset,
      64              :       asset.hash ?? getStoredOutputIdentity(asset)?.hash
      65              :     ),
      66              :     subfolder: getOutputSubfolder(asset) ?? '',
      67              :     type: isResultItemType(assetType) ? assetType : undefined
      68              :   })
      69              : }
      70              : 
      71            0 : function widgetValueVariants(
      72              :   name: string | undefined,
      73              :   type: string | undefined,
      74              :   subfolder?: string,
      75              :   hash?: string
      76              : ): string[] {
      77            0 :   const rootFolder = isResultItemType(type) ? type : undefined
      78            0 :   return compact([name, hash]).map((filename) =>
      79              :     createAnnotatedPath(filename, { rootFolder, subfolder })
      80              :   )
      81              : }
      82              : 
      83          380 : export function useMediaAssetActions() {
      84          380 :   const { t } = useI18n()
      85          380 :   const toast = useToast()
      86          380 :   const assetsStore = useAssetsStore()
      87          380 :   const dialogService = useDialogService()
      88          380 :   const mediaContext = inject(MediaAssetKey, null)
      89          380 :   const { copyToClipboard } = useCopyToClipboard()
      90          380 :   const { flags } = useFeatureFlags()
      91          380 :   const workflowActions = useWorkflowActionsService()
      92          380 :   const litegraphService = useLitegraphService()
      93          380 :   const nodeDefStore = useNodeDefStore()
      94          380 :   const { downloadFiles } = useAssetDownload()
      95          380 :   const { startZipExport } = useAssetZipExport()
      96              : 
      97              :   /**
      98              :    * Download one or more assets.
      99              :    * When the assets system is enabled, creates a ZIP export via the
     100              :    * backend when called with 2+ assets or with any asset whose job has
     101              :    * `outputCount > 1`.
     102              :    * Otherwise downloads each file directly, expanding grouped assets
     103              :    * (`outputCount > 1`) into their individual outputs.
     104              :    * With no argument, uses the asset from `MediaAssetKey` context.
     105              :    */
     106          380 :   const downloadAssets = (assets?: AssetItem[]) => {
     107            0 :     const targetAssets =
     108              :       assets ?? (mediaContext?.asset.value ? [mediaContext.asset.value] : [])
     109            0 :     if (targetAssets.length === 0) return
     110              : 
     111            0 :     const hasMultiOutputJobs = targetAssets.some((a) => {
     112            0 :       const count = getOutputAssetMetadata(a.user_metadata)?.outputCount
     113            0 :       return typeof count === 'number' && count > 1
     114              :     })
     115              : 
     116            0 :     if (
     117              :       flags.assetsEnabled &&
     118              :       (targetAssets.length > 1 || hasMultiOutputJobs)
     119              :     ) {
     120            0 :       void downloadAssetsAsZip(targetAssets)
     121            0 :       return
     122              :     }
     123              : 
     124            0 :     if (hasMultiOutputJobs) {
     125            0 :       void downloadAssetsIndividually(targetAssets)
     126            0 :       return
     127              :     }
     128              : 
     129            0 :     void downloadFiles(targetAssets.map(createAssetDownload))
     130              :   }
     131              : 
     132            0 :   function createAssetDownload(asset: AssetItem): AssetDownload {
     133              :     const url = getAssetFileUrl(asset)
     134              :     const filename = getAssetDisplayName(asset)
     135            0 :     if (!isCloud) return { mode: 'direct', url, filename }
     136              : 
     137              :     // Required: a bare fetch sends no Authorization header and authenticates by
     138              :     // session cookie, which resolves to the personal workspace — an asset owned
     139              :     // by any other workspace then reads as missing.
     140              :     return {
     141              :       mode: 'fetch',
     142              :       url,
     143              :       filename,
     144              :       fetch: (route) => api.fetchApi(route)
     145              :     }
     146              :   }
     147              : 
     148            0 :   async function expandAssetForDownload(
     149              :     asset: AssetItem
     150              :   ): Promise<AssetItem[]> {
     151            0 :     const metadata = getOutputAssetMetadata(asset.user_metadata)
     152            0 :     if (
     153              :       !metadata ||
     154              :       typeof metadata.outputCount !== 'number' ||
     155              :       metadata.outputCount <= 1
     156              :     ) {
     157            0 :       return [asset]
     158              :     }
     159              : 
     160            0 :     try {
     161            0 :       const resolved = await resolveOutputAssetItems(metadata, {
     162              :         createdAt: asset.created_at
     163              :       })
     164            0 :       return resolved.length > 0 ? resolved : [asset]
     165              :     } catch (error) {
     166            0 :       console.error('Failed to expand grouped asset for download:', error)
     167            0 :       return [asset]
     168              :     }
     169              :   }
     170              : 
     171            0 :   async function downloadAssetsIndividually(assets: AssetItem[]) {
     172            0 :     const expanded = await Promise.all(assets.map(expandAssetForDownload))
     173            0 :     const seenAssetIds = new Set<string>()
     174            0 :     const filesToDownload = expanded.flat().filter((asset) => {
     175            0 :       if (seenAssetIds.has(asset.id)) return false
     176            0 :       seenAssetIds.add(asset.id)
     177            0 :       return true
     178              :     })
     179              : 
     180            0 :     await downloadFiles(filesToDownload.map(createAssetDownload))
     181              :   }
     182              : 
     183            0 :   async function downloadAssetsAsZip(assets: AssetItem[]) {
     184            0 :     const jobIds: string[] = []
     185            0 :     const assetIds: string[] = []
     186            0 :     const namesByJobId = new Map<string, Set<string>>()
     187            0 :     const wholeJobIds = new Set<string>()
     188              : 
     189            0 :     for (const asset of assets) {
     190            0 :       const assetType = getAssetType(asset)
     191            0 :       const metadata = getOutputAssetMetadata(asset.user_metadata)
     192            0 :       const jobId = metadata?.jobId
     193            0 :       if (jobId && (assetType === 'output' || assetType === 'temp')) {
     194            0 :         if (!jobIds.includes(jobId)) {
     195            0 :           jobIds.push(jobId)
     196              :         }
     197              :         // When outputCount is set, the asset is a job-level selection
     198              :         // from the gallery and the user wants all outputs for that job.
     199            0 :         if (metadata.outputCount != null) {
     200            0 :           wholeJobIds.add(jobId)
     201            0 :         } else if (asset.name) {
     202            0 :           const names = namesByJobId.get(jobId) ?? new Set<string>()
     203            0 :           names.add(asset.name)
     204            0 :           namesByJobId.set(jobId, names)
     205              :         }
     206              :       } else {
     207            0 :         assetIds.push(asset.id)
     208              :       }
     209              :     }
     210              : 
     211              :     // A job-level selection outranks any name filter a sibling child of the
     212              :     // same job contributed, whichever order they were selected in.
     213            0 :     const jobAssetNameFilters = Object.fromEntries(
     214              :       [...namesByJobId]
     215              :         .filter(([jobId]) => !wholeJobIds.has(jobId))
     216              :         .map(([jobId, names]): [string, string[]] => [jobId, [...names]])
     217              :     )
     218              : 
     219              :     const spansMultipleJobs = jobIds.length > 1
     220            0 :     const namingStrategy = spansMultipleJobs ? 'group_by_job_time' : 'preserve'
     221              : 
     222            0 :     await startZipExport(
     223              :       {
     224              :         ...(jobIds.length > 0 ? { job_ids: jobIds } : {}),
     225              :         ...(assetIds.length > 0 ? { asset_ids: assetIds } : {}),
     226              :         ...(Object.keys(jobAssetNameFilters).length > 0
     227              :           ? { job_asset_name_filters: jobAssetNameFilters }
     228              :           : {}),
     229              :         naming_strategy: namingStrategy,
     230              :         include_previews: true
     231              :       },
     232              :       getTotalAssetOutputCount(assets)
     233              :     )
     234              :   }
     235              : 
     236          380 :   const copyJobId = async (asset?: AssetItem) => {
     237            0 :     const targetAsset = asset ?? mediaContext?.asset.value
     238            0 :     if (!targetAsset) return
     239              : 
     240              :     const metadata = getOutputAssetMetadata(targetAsset.user_metadata)
     241            0 :     const jobId =
     242              :       metadata?.jobId ||
     243              :       (getAssetType(targetAsset) === 'output' ? targetAsset.id : undefined)
     244              : 
     245            0 :     if (!jobId) {
     246            0 :       toast.warning(t('g.warning'), {
     247              :         description: t('mediaAsset.noJobIdFound'),
     248              :         duration: 2000
     249              :       })
     250            0 :       return
     251              :     }
     252              : 
     253            0 :     await copyToClipboard(jobId)
     254              :   }
     255              : 
     256              :   /**
     257              :    * Add a loader node to the current workflow for this asset
     258              :    * Uses shared utility to detect appropriate node type based on file extension
     259              :    */
     260          380 :   const addWorkflow = async (asset?: AssetItem) => {
     261            3 :     const targetAsset = asset ?? mediaContext?.asset.value
     262            3 :     if (!targetAsset) return
     263              : 
     264              :     // Detect node type using shared utility
     265            3 :     const { nodeType, widgetName } = detectNodeTypeFromFilename(
     266              :       targetAsset.name
     267              :     )
     268              : 
     269            3 :     if (!nodeType || !widgetName) {
     270            0 :       toast.warning(t('g.warning'), {
     271              :         description: t('mediaAsset.unsupportedFileType'),
     272              :         duration: 2000
     273              :       })
     274            0 :       return
     275              :     }
     276              : 
     277            3 :     const nodeDef = nodeDefStore.nodeDefsByName[nodeType]
     278              : 
     279            3 :     const node = withNodeAddSource('programmatic', () =>
     280              :       litegraphService.addNodeOnGraph(nodeDef, {
     281              :         pos: litegraphService.getCanvasCenter()
     282              :       })
     283              :     )
     284              : 
     285            3 :     if (!node) {
     286            0 :       toast.error(t('g.error'), {
     287              :         description: t('mediaAsset.failedToCreateNode')
     288              :       })
     289            0 :       return
     290              :     }
     291              : 
     292            3 :     const annotated = createAssetWidgetPath(targetAsset)
     293              : 
     294            3 :     const widget = node.widgets?.find((w) => w.name === widgetName)
     295            3 :     if (widget) {
     296            3 :       widget.value = annotated
     297            3 :       widget.callback?.(annotated)
     298              :     }
     299            3 :     node.graph?.setDirtyCanvas(true, true)
     300              : 
     301            3 :     toast.success(t('g.success'), {
     302              :       description: t('mediaAsset.nodeAddedToWorkflow', { nodeType }),
     303              :       duration: 2000
     304              :     })
     305              :   }
     306              : 
     307              :   /**
     308              :    * Open the asset's stored API-format graph as a new workflow, the way the
     309              :    * canvas already does when an API-format JSON file is dropped onto it.
     310              :    *
     311              :    * Layout is invented and groups/reroutes cannot survive API format, so the
     312              :    * result is reopenable rather than faithful. It is only handed to the editor
     313              :    * — nothing is written back to the job or the asset.
     314              :    */
     315          380 :   const openApiPromptAsWorkflow = async (
     316              :     asset: AssetItem,
     317              :     filename: string
     318              :   ): Promise<WorkflowOpenResult> => {
     319            1 :     try {
     320            1 :       const apiPrompt = await extractApiPromptFromAsset(asset)
     321            1 :       if (!app.isApiJson(apiPrompt)) return { success: false }
     322              : 
     323            1 :       await app.loadApiJson(apiPrompt, filename)
     324            1 :       return { success: true }
     325              :     } catch (error) {
     326            0 :       console.error('Failed to open API graph as workflow:', error)
     327            0 :       reportError(error, {
     328              :         surface: 'assets',
     329              :         errorType: 'asset_api_prompt_open_failure'
     330              :       })
     331            0 :       return {
     332              :         success: false,
     333              :         error: error instanceof Error ? error.message : undefined,
     334              :         errorPresentation: isGraphLoadFailurePresented(error)
     335              :           ? 'handled'
     336              :           : undefined
     337              :       }
     338              :     }
     339              :   }
     340              : 
     341              :   /**
     342              :    * Open an asset's workflow in a new tab, falling back to the stored API
     343              :    * graph for assets whose job embeds no workflow (API submissions)
     344              :    */
     345          380 :   const isAlreadyPresented = (result: WorkflowOpenResult) =>
     346              :     result.errorPresentation === 'handled'
     347              : 
     348          380 :   const openAssetWorkflow = async (asset: AssetItem) => {
     349            1 :     const { workflow, filename } = await extractWorkflowFromAsset(asset)
     350              : 
     351            1 :     return workflow
     352              :       ? await workflowActions.openWorkflowAction(workflow, filename)
     353              :       : await openApiPromptAsWorkflow(asset, filename)
     354              :   }
     355              : 
     356              :   /**
     357              :    * Open the workflow from this asset in a new tab
     358              :    * Uses shared workflow extraction and action service
     359              :    */
     360          380 :   const openWorkflow = async (asset?: AssetItem) => {
     361            1 :     const targetAsset = asset ?? mediaContext?.asset.value
     362            1 :     if (!targetAsset) return
     363              : 
     364            1 :     const result = await openAssetWorkflow(targetAsset)
     365              : 
     366            1 :     if (result.success) {
     367            1 :       toast.success(t('g.success'), {
     368              :         description: t('mediaAsset.workflowOpenedInNewTab'),
     369              :         duration: 2000
     370              :       })
     371            1 :       return
     372              :     }
     373              : 
     374            0 :     if (isAlreadyPresented(result)) return
     375              : 
     376            1 :     toast.warning(t('g.warning'), {
     377              :       description: result.error || t('mediaAsset.noWorkflowDataFound'),
     378              :       duration: 2000
     379              :     })
     380              :   }
     381              : 
     382              :   /**
     383              :    * Export the workflow from this asset as a JSON file
     384              :    * Uses shared workflow extraction and action service
     385              :    */
     386          380 :   const exportWorkflow = async (asset?: AssetItem) => {
     387            3 :     const targetAsset = asset ?? mediaContext?.asset.value
     388            3 :     if (!targetAsset) return
     389              : 
     390              :     // Extract workflow using shared utility
     391            3 :     const { workflow, filename } = await extractWorkflowFromAsset(targetAsset)
     392              : 
     393              :     // Use shared action service
     394            3 :     const result = await workflowActions.exportWorkflowAction(
     395              :       workflow,
     396              :       filename
     397              :     )
     398              : 
     399            3 :     if (result.cancelled) return
     400              : 
     401            2 :     if (!result.success) {
     402            1 :       const kind = result.error?.includes('No workflow') ? 'warning' : 'error'
     403            1 :       toast[kind](t(`g.${kind}`), {
     404              :         description: result.error || t('mediaAsset.failedToExportWorkflow'),
     405              :         duration: 3000
     406              :       })
     407              :     } else {
     408            1 :       toast.success(t('g.success'), {
     409              :         description: t('mediaAsset.workflowExportedSuccessfully'),
     410              :         duration: 2000
     411              :       })
     412              :     }
     413              :   }
     414              : 
     415              :   /**
     416              :    * Add multiple assets to the current workflow
     417              :    * Creates loader nodes for each asset
     418              :    */
     419          380 :   const addMultipleToWorkflow = async (assets: AssetItem[]) => {
     420            1 :     const NODE_OFFSET = 50
     421            1 :     let nodeIndex = 0
     422            1 :     let succeeded = 0
     423            1 :     let failed = 0
     424              : 
     425            1 :     for (const asset of assets) {
     426            2 :       const { nodeType, widgetName } = detectNodeTypeFromFilename(asset.name)
     427              : 
     428            2 :       if (!nodeType || !widgetName) {
     429            0 :         failed++
     430            0 :         continue
     431              :       }
     432              : 
     433            2 :       const nodeDef = nodeDefStore.nodeDefsByName[nodeType]
     434              : 
     435            2 :       const center = litegraphService.getCanvasCenter()
     436            2 :       const node = withNodeAddSource('programmatic', () =>
     437              :         litegraphService.addNodeOnGraph(nodeDef, {
     438              :           pos: [
     439              :             center[0] + nodeIndex * NODE_OFFSET,
     440              :             center[1] + nodeIndex * NODE_OFFSET
     441              :           ]
     442              :         })
     443              :       )
     444              : 
     445            2 :       if (!node) {
     446            0 :         failed++
     447            0 :         continue
     448              :       }
     449              : 
     450            2 :       const annotated = createAssetWidgetPath(asset)
     451              : 
     452            2 :       const widget = node.widgets?.find((w) => w.name === widgetName)
     453            2 :       if (widget) {
     454            2 :         widget.value = annotated
     455            2 :         widget.callback?.(annotated)
     456              :       }
     457            2 :       node.graph?.setDirtyCanvas(true, true)
     458            2 :       succeeded++
     459            2 :       nodeIndex++
     460              :     }
     461              : 
     462            1 :     if (failed === 0) {
     463            1 :       toast.success(t('g.success'), {
     464              :         description: t('mediaAsset.selection.nodesAddedToWorkflow', {
     465              :           count: succeeded
     466              :         }),
     467              :         duration: 2000
     468              :       })
     469            0 :     } else if (succeeded === 0) {
     470            0 :       toast.error(t('g.error'), {
     471              :         description: t('mediaAsset.selection.failedToAddNodes')
     472              :       })
     473              :     } else {
     474            0 :       toast.warning(t('g.warning'), {
     475              :         description: t('mediaAsset.selection.partialAddNodesSuccess', {
     476              :           succeeded,
     477              :           failed
     478              :         }),
     479              :         duration: 3000
     480              :       })
     481              :     }
     482              :   }
     483              : 
     484              :   /**
     485              :    * Open workflows from multiple assets in new tabs
     486              :    */
     487          380 :   const openMultipleWorkflows = async (assets: AssetItem[]) => {
     488            0 :     let succeeded = 0
     489            0 :     let failed = 0
     490            0 :     let alreadyPresented = 0
     491              : 
     492            0 :     for (const asset of assets) {
     493            0 :       try {
     494            0 :         const result = await openAssetWorkflow(asset)
     495              : 
     496            0 :         if (result.success) {
     497            0 :           succeeded++
     498              :         } else {
     499            0 :           failed++
     500            0 :           if (isAlreadyPresented(result)) alreadyPresented++
     501              :         }
     502              :       } catch {
     503            0 :         failed++
     504              :       }
     505              :     }
     506              : 
     507            0 :     if (failed === 0) {
     508            0 :       toast.success(t('g.success'), {
     509              :         description: t('mediaAsset.selection.workflowsOpened', {
     510              :           count: succeeded
     511              :         }),
     512              :         duration: 2000
     513              :       })
     514            0 :     } else if (succeeded === 0) {
     515              :       const everyFailureAlreadyPresented = alreadyPresented === failed
     516            0 :       if (!everyFailureAlreadyPresented)
     517            0 :         toast.warning(t('g.warning'), {
     518              :           description: t('mediaAsset.selection.noWorkflowsFound'),
     519              :           duration: 3000
     520              :         })
     521              :     } else {
     522            0 :       toast.warning(t('g.warning'), {
     523              :         description: t('mediaAsset.selection.partialWorkflowsOpened', {
     524              :           succeeded,
     525              :           failed
     526              :         }),
     527              :         duration: 3000
     528              :       })
     529              :     }
     530              :   }
     531              : 
     532              :   /**
     533              :    * Export workflows from multiple assets as JSON files
     534              :    */
     535          380 :   const exportMultipleWorkflows = async (assets: AssetItem[]) => {
     536            0 :     let succeeded = 0
     537            0 :     let failed = 0
     538              : 
     539            0 :     for (const asset of assets) {
     540            0 :       try {
     541            0 :         const { workflow, filename } = await extractWorkflowFromAsset(asset)
     542            0 :         const result = await workflowActions.exportWorkflowAction(
     543              :           workflow,
     544              :           filename
     545              :         )
     546              : 
     547            0 :         if (result.success) {
     548            0 :           succeeded++
     549            0 :         } else if (!result.cancelled) {
     550            0 :           failed++
     551              :         }
     552              :       } catch {
     553            0 :         failed++
     554              :       }
     555              :     }
     556              : 
     557              :     // All cancelled
     558            0 :     if (succeeded === 0 && failed === 0) return
     559              : 
     560            0 :     if (failed === 0) {
     561            0 :       toast.success(t('g.success'), {
     562              :         description: t('mediaAsset.selection.workflowsExported', {
     563              :           count: succeeded
     564              :         }),
     565              :         duration: 2000
     566              :       })
     567            0 :     } else if (succeeded === 0) {
     568            0 :       toast.warning(t('g.warning'), {
     569              :         description: t('mediaAsset.selection.noWorkflowsToExport'),
     570              :         duration: 3000
     571              :       })
     572              :     } else {
     573            0 :       toast.warning(t('g.warning'), {
     574              :         description: t('mediaAsset.selection.partialWorkflowsExported', {
     575              :           succeeded,
     576              :           failed
     577              :         }),
     578              :         duration: 3000
     579              :       })
     580              :     }
     581              :   }
     582              : 
     583            4 :   async function deleteAssets(input: AssetItem[] | AssetItem) {
     584            4 :     const assets = Array.isArray(input) ? input : [input]
     585              :     interface BaseDeleteOperation {
     586              :       kind: string
     587              :       dependents?: DeleteOperation[]
     588              :       markDeletionId?: AssetId
     589              :       name?: string
     590              :     }
     591              :     interface AssetDeletion extends BaseDeleteOperation {
     592              :       kind: 'asset'
     593              :       variants: string[]
     594              :       id: AssetId
     595              :       tags?: string[]
     596              :     }
     597              :     interface JobDeletion extends BaseDeleteOperation {
     598              :       kind: 'job'
     599              :       id: string
     600              :     }
     601              :     type DeleteOperation = AssetDeletion | JobDeletion
     602              : 
     603            0 :     function getAssetDeletions(asset: AssetItem): AssetDeletion[] {
     604            0 :       const markDeletionId = asset.id
     605              :       const metadata = getOutputAssetMetadata(asset.user_metadata)
     606            0 :       const childAssets: AssetDeletion[] = (metadata?.allOutputs ?? []).flatMap(
     607              :         (output) => {
     608            0 :           if (!output.assetId) return []
     609              : 
     610            0 :           const variants = widgetValueVariants(
     611              :             output.filename,
     612              :             output.type,
     613              :             output.subfolder,
     614              :             output.hash
     615              :           )
     616            0 :           return {
     617              :             kind: 'asset',
     618              :             markDeletionId,
     619              :             name: output.display_name || output.filename,
     620              :             id: output.assetId,
     621              :             tags: asset.tags,
     622              :             variants
     623              :           }
     624              :         }
     625              :       )
     626            0 :       if (childAssets.length > 0) return childAssets
     627              : 
     628            0 :       const stored = getStoredOutputIdentity(asset)
     629            0 :       const variants = widgetValueVariants(
     630              :         asset.name,
     631              :         isGeneratedTempOutput(asset)
     632              :           ? 'temp'
     633              :           : (stored?.type ?? getAssetType(asset, 'input')),
     634              :         getOutputSubfolder(asset),
     635              :         asset.hash ?? stored?.hash
     636              :       )
     637            0 :       return [
     638              :         {
     639              :           kind: 'asset',
     640              :           id: asset.id,
     641              :           markDeletionId,
     642              :           name: getAssetDisplayName(asset),
     643              :           tags: asset.tags,
     644              :           variants
     645              :         }
     646              :       ]
     647              :     }
     648              : 
     649            4 :     async function getDeletionPlan(): Promise<DeleteOperation[] | null> {
     650            4 :       if (!flags.assetsEnabled) {
     651            4 :         const operations: JobDeletion[] = assets.flatMap((asset) => {
     652            4 :           const markDeletionId = asset.id
     653            4 :           const { jobId } = getOutputAssetMetadata(asset.user_metadata) ?? {}
     654            4 :           if (!jobId) return []
     655              : 
     656              :           const name = getAssetDisplayName(asset)
     657            4 :           return [{ kind: 'job', id: jobId, name, markDeletionId }]
     658              :         })
     659            4 :         return uniqBy(operations, (op) => op.id)
     660              :       }
     661            0 :       const operations: DeleteOperation[] = []
     662            0 :       for (const asset of assets) {
     663            0 :         const metadata = getOutputAssetMetadata(asset.user_metadata)
     664            0 :         if (metadata?.jobId !== asset.id || metadata.assetId) {
     665            0 :           operations.push(...getAssetDeletions(asset))
     666            0 :           continue
     667              :         }
     668            0 :         const jobAssets = await api.getJobAssets(metadata.jobId)
     669            0 :         if (!jobAssets.complete) return null
     670            0 :         const records = await Promise.all(
     671              :           jobAssets.assets.map(({ id }) => assetService.getAssetDetails(id))
     672              :         )
     673            0 :         operations.push({
     674              :           kind: 'job',
     675              :           id: metadata.jobId,
     676              :           markDeletionId: asset.id,
     677              :           name: getAssetDisplayName(asset),
     678              :           dependents: records.flatMap(getAssetDeletions)
     679              :         })
     680              :       }
     681            0 :       return operations
     682              :     }
     683              : 
     684            4 :     function getNames(operation: DeleteOperation): string[] {
     685            4 :       return [
     686              :         ...(operation.name ? [operation.name] : []),
     687              :         ...(operation.dependents ? operation.dependents.flatMap(getNames) : [])
     688              :       ]
     689              :     }
     690           16 :     function getOperationCount(
     691              :       kind: string,
     692              :       operation: DeleteOperation[]
     693              :     ): number {
     694           16 :       return operation.reduce((tally, op) => {
     695            8 :         const selfCount = op.kind === kind ? 1 : 0
     696            8 :         const dependents = getOperationCount(kind, op.dependents ?? [])
     697            8 :         return tally + selfCount + dependents
     698              :       }, 0)
     699              :     }
     700              : 
     701            4 :     const deletedVariants = new Set<string>()
     702            4 :     const invalidatedModelTags = new Set<string>()
     703              : 
     704            4 :     let deletedAssetCount = 0
     705            0 :     async function deleteAsset(operation: AssetDeletion) {
     706            0 :       await assetService.deleteAsset(operation.id)
     707            0 :       deletedAssetCount++
     708            0 :       for (const variant of operation.variants) deletedVariants.add(variant)
     709            0 :       for (const tag of operation.tags ?? []) {
     710            0 :         if (!EXCLUDED_TAGS.has(tag) && assetsStore.hasCategory(tag))
     711            0 :           invalidatedModelTags.add(tag)
     712              :       }
     713            0 :       void assetsStore.inputAssets.invalidate([operation.id])
     714              :     }
     715            4 :     let deletedJobCount = 0
     716            2 :     async function deleteJob(operation: JobDeletion) {
     717            2 :       const deleted = await api.deleteItem('history', operation.id)
     718            2 :       if (deleted) deletedJobCount++
     719            2 :       return deleted
     720              :     }
     721            2 :     async function performDelete(
     722              :       operation: DeleteOperation
     723              :     ): Promise<unknown[]> {
     724            2 :       if (operation.markDeletionId)
     725            2 :         assetsStore.setAssetDeleting(operation.markDeletionId, true)
     726            2 :       try {
     727            2 :         if (operation.dependents) {
     728            0 :           const failedDependents = (
     729              :             await Promise.all(operation.dependents.map(performDelete))
     730              :           ).flat()
     731            0 :           if (failedDependents.length) return failedDependents
     732              :         }
     733              : 
     734            2 :         try {
     735            2 :           if (operation.kind === 'asset') await deleteAsset(operation)
     736            2 :           else if (!(await deleteJob(operation))) return [operation]
     737              :         } catch (err) {
     738            0 :           return [err]
     739              :         }
     740              :       } finally {
     741            2 :         if (operation.markDeletionId)
     742            2 :           assetsStore.setAssetDeleting(operation.markDeletionId, false)
     743              :       }
     744              : 
     745            2 :       return []
     746              :     }
     747              : 
     748            4 :     let deletionPlan: DeleteOperation[] | null
     749            4 :     try {
     750            4 :       deletionPlan = await getDeletionPlan()
     751              :     } catch (error) {
     752            0 :       reportError(error, {
     753              :         errorType: 'failure_resolving_asset_deletion',
     754              :         surface: 'assets'
     755              :       })
     756            0 :       toast.error(t('mediaAsset.assetDelete.error'))
     757            0 :       return false
     758              :     }
     759            4 :     if (!deletionPlan) {
     760            0 :       toast.error(t('mediaAsset.assetDelete.error'))
     761            0 :       return false
     762              :     }
     763            4 :     if (!deletionPlan.length) return false
     764              : 
     765            4 :     const plannedAssetCount = getOperationCount('asset', deletionPlan)
     766            4 :     const plannedJobCount = getOperationCount('job', deletionPlan)
     767              :     const deleteConfirmed = await dialogService.confirm({
     768              :       title: t('mediaAsset.deleteItems'),
     769              :       type: 'delete',
     770              :       message: !plannedAssetCount
     771              :         ? t('mediaAsset.deleteHistoryOnly')
     772              :         : flags.assetDeletionEnabled
     773              :           ? t('mediaAsset.deletePermanent')
     774              :           : t('mediaAsset.deleteTombstone'),
     775              :       itemList: deletionPlan.flatMap(getNames)
     776              :     })
     777            4 :     if (!deleteConfirmed) return false
     778              : 
     779            2 :     const failedDeletions = (
     780              :       await Promise.all(deletionPlan.map(performDelete))
     781              :     ).flat()
     782              : 
     783            2 :     const rootGraph = app.rootGraph
     784            2 :     if (deletedVariants.size) {
     785            0 :       const nodeOutputStore = useNodeOutputStore()
     786            0 :       markDeletedAssetsAsMissingMedia(rootGraph, deletedVariants)
     787            0 :       clearNodePreviewCacheForValues(rootGraph, deletedVariants, (node) =>
     788              :         nodeOutputStore.removeNodeOutputsForNode(node)
     789              :       )
     790            0 :       clearDeletedAssetWidgetValues(rootGraph, deletedVariants)
     791            0 :       useWorkflowStore().activeWorkflow?.changeTracker.captureCanvasState()
     792              :     }
     793              : 
     794            2 :     for (const category of invalidatedModelTags)
     795            0 :       assetsStore.invalidateModelsForCategory(category)
     796              : 
     797            2 :     if (!flags.assetsEnabled) {
     798            2 :       const hasOutputAssets = assets.some((a) => {
     799            2 :         const type = getAssetType(a)
     800            2 :         return type === 'output' || type === 'temp'
     801              :       })
     802            2 :       const hasInputAssets = assets.some((a) => getAssetType(a) === 'input')
     803              : 
     804            2 :       if (hasOutputAssets) {
     805            2 :         await assetsStore.outputAssets.invalidate()
     806              :       }
     807            2 :       if (hasInputAssets) {
     808            0 :         await assetsStore.inputAssets.invalidate()
     809              :       }
     810              :     }
     811              : 
     812            4 :     const outcome =
     813              :       failedDeletions.length === 0
     814              :         ? 'success'
     815              :         : deletedJobCount || deletedAssetCount
     816              :           ? 'warning'
     817              :           : 'error'
     818              : 
     819            4 :     const resultMessages: string[] = []
     820            4 :     if (plannedAssetCount) {
     821            0 :       resultMessages.push(
     822              :         t(
     823              :           'mediaAsset.assetsDeleted',
     824              :           { total: plannedAssetCount },
     825              :           deletedAssetCount
     826              :         )
     827              :       )
     828              :     }
     829            2 :     if (plannedJobCount) {
     830            2 :       resultMessages.push(
     831              :         t('mediaAsset.jobsDeleted', { total: plannedJobCount }, deletedJobCount)
     832              :       )
     833              :     }
     834              : 
     835            4 :     toast[outcome](t(`mediaAsset.assetDelete.${outcome}`), {
     836              :       description: resultMessages.join('\n'),
     837              :       duration: outcome === 'success' ? 2000 : 5000
     838              :     })
     839            4 :     return true
     840              :   }
     841              : 
     842          380 :   return {
     843              :     downloadAssets,
     844              :     deleteAssets,
     845              :     copyJobId,
     846              :     addWorkflow,
     847              :     addMultipleToWorkflow,
     848              :     openWorkflow,
     849              :     openMultipleWorkflows,
     850              :     exportWorkflow,
     851              :     exportMultipleWorkflows
     852              :   }
     853              : }
        

Generated by: LCOV version 2.0-1