LCOV - code coverage report
Current view: top level - src/composables/node - useNodeImageUpload.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 73.5 % 49 36
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { useNodeDragAndDrop } from '@/composables/node/useNodeDragAndDrop'
       2              : import { useNodeFileInput } from '@/composables/node/useNodeFileInput'
       3              : import { useNodePaste } from '@/composables/node/useNodePaste'
       4              : import { t } from '@/i18n'
       5              : import { ServerFeatureFlag } from '@/platform/remoteConfig/serverFeatureFlag'
       6              : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
       7              : import { useToast } from '@/components/ui/toast/toastStore'
       8              : import type { ResultItem } from '@comfyorg/api-client/executionTypes'
       9              : import type { ResultItemType } from '@comfyorg/api-client/resultItemTypeSchema'
      10              : import { useAssetsStore } from '@/stores/assetsStore'
      11              : import { api } from '@/scripts/api'
      12              : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
      13              : 
      14         2356 : const UPLOAD_TIMEOUT_MS = 120_000
      15         2356 : const BYTES_PER_MB = 1024 * 1024
      16              : 
      17            0 : function buildUploadErrorMessage(resp: Response) {
      18            0 :   if (resp.status === 413) {
      19            0 :     const maxUploadSize = api.getServerFeature<number>(
      20              :       ServerFeatureFlag.MAX_UPLOAD_SIZE
      21              :     )
      22            0 :     return typeof maxUploadSize === 'number' && maxUploadSize > 0
      23              :       ? t('g.uploadFileTooLargeWithLimit', {
      24              :           limit: Math.round(maxUploadSize / BYTES_PER_MB)
      25              :         })
      26              :       : t('g.uploadFileTooLarge')
      27              :   }
      28              : 
      29            0 :   return t('g.uploadFailed', {
      30              :     reason: resp.statusText || `HTTP ${resp.status}`
      31              :   })
      32              : }
      33              : 
      34              : interface ImageUploadFormFields {
      35              :   /**
      36              :    * The folder to upload the file to.
      37              :    * @example 'input', 'output', 'temp'
      38              :    */
      39              :   type: ResultItemType
      40              : }
      41              : 
      42         2356 : const uploadFile = async (
      43              :   file: File,
      44              :   formFields: Partial<ImageUploadFormFields> = {}
      45              : ) => {
      46           50 :   const body = new FormData()
      47           50 :   body.append('image', file)
      48           50 :   if (formFields.type) body.append('type', formFields.type)
      49              : 
      50           50 :   const resp = await api.fetchApi('/upload/image', {
      51              :     method: 'POST',
      52              :     body,
      53              :     timeoutMs: UPLOAD_TIMEOUT_MS
      54              :   })
      55              : 
      56           49 :   if (resp.status !== 200) {
      57            0 :     useToast().warning(buildUploadErrorMessage(resp))
      58            0 :     return
      59              :   }
      60              : 
      61           49 :   const data = await resp.json()
      62              : 
      63              :   // Update AssetsStore input assets when files are uploaded to input folder
      64           50 :   if (formFields.type === 'input' || !formFields.type) {
      65           49 :     await useAssetsStore().inputAssets.invalidate()
      66              :   }
      67              : 
      68           50 :   return data.subfolder ? `${data.subfolder}/${data.name}` : data.name
      69              : }
      70              : 
      71              : interface ImageUploadOptions {
      72              :   fileFilter?: (file: File) => boolean
      73              :   onUploadComplete: (paths: (string | ResultItem)[]) => void
      74              :   allow_batch?: boolean
      75              :   /**
      76              :    * The file types to accept.
      77              :    * @example 'image/png,image/jpeg,image/webp,video/webm,video/mp4'
      78              :    */
      79              :   accept?: string
      80              :   /**
      81              :    * The folder to upload the file to.
      82              :    * @example 'input', 'output', 'temp'
      83              :    */
      84              :   folder?: ResultItemType
      85              :   onUploadStart?: (files: File[]) => void
      86              :   onUploadError?: () => void
      87              :   onReject?: (files: File[]) => boolean
      88              : }
      89              : 
      90              : /**
      91              :  * Adds image upload to a node via drag & drop, paste, and file input.
      92              :  */
      93         2356 : export const useNodeImageUpload = (
      94              :   node: LGraphNode,
      95              :   options: ImageUploadOptions
      96              : ) => {
      97          244 :   const { fileFilter, onUploadComplete, allow_batch, accept } = options
      98              : 
      99          244 :   const handleUpload = async (file: File) => {
     100           50 :     try {
     101           50 :       const path = await uploadFile(file, {
     102              :         type: options.folder
     103              :       })
     104           49 :       if (!path) return
     105           47 :       return path
     106              :     } catch (error) {
     107            0 :       if (error instanceof DOMException && error.name === 'TimeoutError') {
     108            0 :         useToast().warning(t('g.uploadTimedOut'))
     109              :       } else {
     110            0 :         useToast().warning(
     111              :           t('g.uploadFailed', {
     112              :             reason: getErrorMessage(error) ?? t('g.unknownError')
     113              :           })
     114              :         )
     115              :       }
     116              :     }
     117              :   }
     118              : 
     119          244 :   const handleUploadBatch = async (files: File[]) => {
     120           50 :     if (node.isUploading) {
     121            0 :       useToast().warning(t('g.uploadAlreadyInProgress'))
     122            0 :       return []
     123              :     }
     124           50 :     node.isUploading = true
     125              : 
     126           50 :     try {
     127           50 :       node.imgs = undefined
     128           50 :       node.graph?.setDirtyCanvas(true)
     129           50 :       options.onUploadStart?.(files)
     130              : 
     131              :       const paths = await Promise.all(files.map(handleUpload))
     132           50 :       const validPaths = paths.filter((p): p is string => !!p)
     133           49 :       if (validPaths.length) {
     134           47 :         onUploadComplete(validPaths)
     135              :       } else {
     136            0 :         options.onUploadError?.()
     137              :       }
     138           47 :       return validPaths
     139              :     } finally {
     140           47 :       node.isUploading = false
     141           47 :       node.graph?.setDirtyCanvas(true)
     142              :     }
     143              :   }
     144              : 
     145              :   // Handle drag & drop
     146          244 :   useNodeDragAndDrop(node, {
     147              :     fileFilter,
     148              :     onReject: options.onReject,
     149              :     onDrop: handleUploadBatch,
     150              :     onResultItemDrop: (item) => onUploadComplete([item])
     151              :   })
     152              : 
     153              :   // Handle paste
     154          244 :   useNodePaste(node, {
     155              :     fileFilter,
     156              :     onReject: options.onReject,
     157              :     allow_batch,
     158              :     onPaste: handleUploadBatch
     159              :   })
     160              : 
     161              :   // Handle file input
     162          244 :   const { openFileSelection } = useNodeFileInput(node, {
     163              :     fileFilter,
     164              :     onReject: options.onReject,
     165              :     allow_batch,
     166              :     accept,
     167              :     onSelect: handleUploadBatch
     168              :   })
     169              : 
     170          244 :   return { openFileSelection, handleUpload }
     171              : }
        

Generated by: LCOV version 2.0-1