LCOV - code coverage report
Current view: top level - src/extensions/core - uploadAudio.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 56.5 % 209 118
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { MediaRecorder as ExtendableMediaRecorder } from 'extendable-media-recorder'
       2              : 
       3              : import { useNodeDragAndDrop } from '@/composables/node/useNodeDragAndDrop'
       4              : import { useNodeFileInput } from '@/composables/node/useNodeFileInput'
       5              : import { useNodePaste } from '@/composables/node/useNodePaste'
       6              : import { t } from '@/i18n'
       7              : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
       8              : import { resolveNodeRootGraphId } from '@/lib/litegraph/src/litegraph'
       9              : import type { IBaseWidget, IStringWidget } from '@comfyorg/graph-model/widgets'
      10              : import { reportError } from '@comfyorg/telemetry/reportError'
      11              : import { useToast } from '@/components/ui/toast/toastStore'
      12              : import {
      13              :   getResourceURL,
      14              :   splitFilePath
      15              : } from '@/renderer/extensions/vueNodes/widgets/utils/audioUtils'
      16              : import type { NodeExecutionOutput } from '@comfyorg/api-client/executionTypes'
      17              : import type { ComfyNodeDef, InputSpec } from '@comfyorg/object-info-parser'
      18              : import type { DOMWidget } from '@/types/domWidget'
      19              : import { useAudioService } from '@/services/audioService'
      20              : import type { NodeLocatorId } from '@/types'
      21              : import { widgetId } from '@comfyorg/graph-model/widgetId'
      22              : import { getErrorMessage } from '@comfyorg/shared-frontend-utils/errorUtil'
      23              : import { getNodeByLocatorId } from '@/utils/graphTraversalUtil'
      24              : 
      25              : import { api } from '@/scripts/api'
      26              : import { app } from '@/scripts/app'
      27              : import { useWidgetValueStore } from '@/stores/widgetValueStore'
      28              : import type { ComfyExtension } from '@/types/comfy'
      29              : 
      30           37 : function updateUIWidget(
      31              :   audioUIWidget: DOMWidget<HTMLAudioElement, string>,
      32              :   url: string = ''
      33              : ) {
      34           37 :   audioUIWidget.element.src = url
      35           37 :   audioUIWidget.value = url
      36           37 :   audioUIWidget.callback?.(url)
      37           37 :   if (url) audioUIWidget.element.classList.remove('empty-audio-widget')
      38           14 :   else audioUIWidget.element.classList.add('empty-audio-widget')
      39              : }
      40              : 
      41            1 : function appendWidgetValue(widget: IStringWidget, path: string) {
      42            1 :   const values = widget.options.values
      43            1 :   if (values && !values.includes(path)) values.push(path)
      44              : }
      45              : 
      46            1 : async function uploadFile(
      47              :   node: LGraphNode,
      48              :   audioWidget: IStringWidget,
      49              :   audioUIWidget: DOMWidget<HTMLAudioElement, string>,
      50              :   file: File,
      51              :   updateNode: boolean,
      52              :   pasted: boolean = false
      53              : ): Promise<boolean> {
      54            1 :   try {
      55              :     // Wrap file in formdata so it includes filename
      56            1 :     const body = new FormData()
      57            1 :     body.append('image', file)
      58            1 :     if (pasted) body.append('subfolder', 'pasted')
      59            1 :     const resp = await api.fetchApi('/upload/image', {
      60              :       method: 'POST',
      61              :       body
      62              :     })
      63              : 
      64            1 :     if (resp.status === 200) {
      65            1 :       const data: { name: string; subfolder?: string } = await resp.json()
      66              :       // Add the file to the dropdown list and update the widget value
      67            1 :       const path = data.subfolder ? `${data.subfolder}/${data.name}` : data.name
      68              : 
      69            1 :       appendWidgetValue(audioWidget, path)
      70              : 
      71            1 :       if (updateNode) {
      72            1 :         const oldValue = audioWidget.value
      73            1 :         updateUIWidget(
      74              :           audioUIWidget,
      75              :           api.apiURL(getResourceURL(...splitFilePath(path)))
      76              :         )
      77              : 
      78            1 :         audioWidget.value = path
      79              :         // Manually trigger the callback to update VueNodes
      80            1 :         audioWidget.callback?.(path)
      81            1 :         node.onWidgetChanged?.(audioWidget.name, path, oldValue, audioWidget)
      82              :       }
      83            1 :       return true
      84              :     } else {
      85            0 :       useToast().warning(
      86              :         t('g.uploadFailed', { reason: `${resp.status} - ${resp.statusText}` })
      87              :       )
      88            0 :       return false
      89              :     }
      90              :   } catch (error) {
      91            0 :     useToast().warning(
      92              :       t('g.uploadFailed', {
      93              :         reason: getErrorMessage(error) ?? t('g.unknownError')
      94              :       })
      95              :     )
      96            0 :     return false
      97              :   }
      98              : }
      99              : 
     100              : // AudioWidget MUST be registered first, as AUDIOUPLOAD depends on AUDIO_UI to be
     101              : // present.
     102         2355 : export const audioWidgetExtension: ComfyExtension = {
     103              :   name: 'Comfy.AudioWidget',
     104              :   async beforeRegisterNodeDef(
     105              :     nodeType: typeof LGraphNode,
     106              :     nodeData: ComfyNodeDef
     107              :   ) {
     108      2439372 :     const comfyClass = nodeType.prototype.comfyClass
     109      2439372 :     if (
     110              :       comfyClass &&
     111              :       [
     112              :         'LoadAudio',
     113              :         'SaveAudio',
     114              :         'PreviewAudio',
     115              :         'SaveAudioMP3',
     116              :         'SaveAudioOpus',
     117              :         'SaveAudioAdvanced'
     118              :       ].includes(comfyClass)
     119              :     ) {
     120        14196 :       const input = (nodeData.input ??= {})
     121        14196 :       const required = (input.required ??= {})
     122        14196 :       required.audioUI = ['AUDIO_UI', {}]
     123              :     }
     124              :   },
     125              :   getCustomWidgets() {
     126         2355 :     return {
     127              :       AUDIO_UI(node: LGraphNode, inputName: string) {
     128           16 :         const audio = document.createElement('audio')
     129           16 :         audio.controls = true
     130           16 :         audio.classList.add('comfy-audio')
     131           16 :         audio.setAttribute('name', 'media')
     132              : 
     133           16 :         const audioUIWidget: DOMWidget<HTMLAudioElement, string> =
     134              :           node.addDOMWidget(inputName, /* name=*/ 'audioUI', audio)
     135           16 :         audioUIWidget.serialize = false
     136           16 :         audioUIWidget.options.serialize = false
     137           16 :         const { nodeData } = node.constructor
     138           16 :         if (nodeData == null) throw new TypeError('nodeData is null')
     139              : 
     140              :         const isOutputNode = nodeData.output_node
     141           16 :         if (isOutputNode) {
     142              :           // Hide the audio widget when there is no audio initially.
     143            0 :           audioUIWidget.element.classList.add('empty-audio-widget')
     144              :           // Populate the audio widget UI on node execution.
     145            0 :           const onExecuted = node.onExecuted
     146            0 :           node.onExecuted = function (output: NodeExecutionOutput) {
     147            0 :             onExecuted?.call(this, output)
     148            0 :             const audios = output.audio
     149            0 :             if (!audios?.length) return
     150            0 :             const audio = audios[0]
     151            0 :             const resourceUrl = getResourceURL(
     152              :               audio.subfolder ?? '',
     153              :               audio.filename ?? '',
     154              :               audio.type
     155              :             )
     156            0 :             updateUIWidget(audioUIWidget, api.apiURL(resourceUrl))
     157              :           }
     158              :         }
     159              : 
     160           16 :         audioUIWidget.options.getValue = () => {
     161           16 :           const value = useWidgetValueStore().getWidget(
     162              :             widgetId(
     163              :               resolveNodeRootGraphId(node, app.rootGraph.id),
     164              :               node.id,
     165              :               inputName
     166              :             )
     167              :           )?.value
     168           16 :           return typeof value === 'string' ? value : ''
     169              :         }
     170           16 :         audioUIWidget.options.setValue = (v) => {
     171           37 :           const graphId = resolveNodeRootGraphId(node, app.rootGraph.id)
     172           37 :           const widgetState = useWidgetValueStore().getWidget(
     173              :             widgetId(graphId, node.id, inputName)
     174              :           )
     175           37 :           if (widgetState) widgetState.value = v
     176              :         }
     177              : 
     178           16 :         return { widget: audioUIWidget }
     179              :       }
     180              :     }
     181              :   },
     182              :   onNodeOutputsUpdated(
     183              :     nodeOutputs: Record<NodeLocatorId, NodeExecutionOutput>
     184              :   ) {
     185         4098 :     for (const [nodeLocatorId, output] of Object.entries(nodeOutputs)) {
     186            7 :       if (!output.audio?.length) continue
     187              : 
     188            0 :       const node = getNodeByLocatorId(app.rootGraph, nodeLocatorId)
     189            0 :       if (!node) continue
     190              : 
     191            7 :       const audioUIWidget = node.widgets?.find(
     192              :         (w) => w.name === 'audioUI'
     193              :       ) as unknown as DOMWidget<HTMLAudioElement, string>
     194            7 :       const audio = output.audio[0]
     195            7 :       const resourceUrl = getResourceURL(
     196              :         audio.subfolder ?? '',
     197              :         audio.filename ?? '',
     198              :         audio.type
     199              :       )
     200            7 :       updateUIWidget(audioUIWidget, api.apiURL(resourceUrl))
     201              :     }
     202              :   }
     203              : }
     204              : 
     205         2355 : export const uploadAudioExtension: ComfyExtension = {
     206              :   name: 'Comfy.UploadAudio',
     207              :   async beforeRegisterNodeDef(
     208              :     _nodeType: typeof LGraphNode,
     209              :     nodeData: ComfyNodeDef
     210              :   ) {
     211      2439372 :     const required: Partial<Record<string, InputSpec>> | undefined =
     212              :       nodeData.input?.required
     213      2439372 :     if (required?.audio?.[1]?.audio_upload === true) {
     214         2366 :       required.upload = ['AUDIOUPLOAD', {}]
     215              :     }
     216              :   },
     217              :   getCustomWidgets() {
     218         2355 :     return {
     219              :       AUDIOUPLOAD(node, inputName: string) {
     220              :         // The widget that allows user to select file.
     221           16 :         const audioWidget = node.widgets?.find(
     222              :           (w) => w.name === 'audio'
     223              :         ) as IStringWidget
     224           16 :         const audioUIWidget = node.widgets?.find(
     225              :           (w) => w.name === 'audioUI'
     226              :         ) as unknown as DOMWidget<HTMLAudioElement, string>
     227              : 
     228           16 :         const onAudioWidgetUpdate = () => {
     229           36 :           const value = audioWidget.value
     230           36 :           const values = audioWidget.options.values
     231           36 :           const isEmptySentinel =
     232              :             value === 'none' && values?.length === 1 && values[0] === value
     233           36 :           updateUIWidget(
     234              :             audioUIWidget,
     235              :             value && !isEmptySentinel
     236              :               ? api.apiURL(getResourceURL(...splitFilePath(value)))
     237              :               : ''
     238              :           )
     239              :         }
     240              :         // Initially load default audio file to audioUIWidget.
     241           16 :         onAudioWidgetUpdate()
     242              : 
     243           16 :         audioWidget.callback = onAudioWidgetUpdate
     244              : 
     245              :         // Load saved audio file widget values if restoring from workflow
     246           16 :         const onGraphConfigured = node.onGraphConfigured
     247           16 :         node.onGraphConfigured = function () {
     248           13 :           onGraphConfigured?.call(this)
     249           13 :           onAudioWidgetUpdate()
     250              :         }
     251              : 
     252           16 :         const handleUpload = async (files: File[]) => {
     253            1 :           if (!files.length) return files
     254              : 
     255            1 :           if (node.isUploading) {
     256            0 :             useToast().warning(t('g.uploadAlreadyInProgress'))
     257            0 :             return []
     258              :           }
     259              : 
     260            1 :           node.isUploading = true
     261            1 :           const previousValue = audioWidget.value
     262            1 :           audioWidget.value = files[0].name
     263            1 :           try {
     264              :             const success = await uploadFile(
     265              :               node,
     266              :               audioWidget,
     267              :               audioUIWidget,
     268              :               files[0],
     269              :               true
     270              :             )
     271            1 :             if (!success) {
     272            0 :               audioWidget.value = previousValue
     273              :             }
     274              :           } finally {
     275            1 :             node.isUploading = false
     276            1 :             node.graph?.setDirtyCanvas(true)
     277              :           }
     278            1 :           return files
     279              :         }
     280              : 
     281           16 :         const isAudioFile = (file: File) => file.type.startsWith('audio/')
     282              : 
     283           16 :         const { openFileSelection } = useNodeFileInput(node, {
     284              :           accept: 'audio/*',
     285              :           onSelect: handleUpload
     286              :         })
     287              : 
     288              :         // The widget to pop up the upload dialog.
     289           16 :         const uploadWidget = node.addWidget(
     290              :           'button',
     291              :           inputName,
     292              :           '',
     293              :           openFileSelection,
     294              :           {
     295              :             serialize: false,
     296              :             surfaces: { canvas: 'shown', vueNode: 'never', panel: 'never' }
     297              :           }
     298              :         )
     299           16 :         uploadWidget.label = t('g.choose_file_to_upload')
     300              : 
     301           16 :         useNodeDragAndDrop(node, {
     302              :           fileFilter: isAudioFile,
     303              :           onDrop: handleUpload
     304              :         })
     305              : 
     306           16 :         useNodePaste(node, {
     307              :           fileFilter: isAudioFile,
     308              :           onPaste: handleUpload
     309              :         })
     310              : 
     311           16 :         node.previewMediaType = 'audio'
     312              : 
     313           16 :         return { widget: uploadWidget }
     314              :       }
     315              :     }
     316              :   }
     317              : }
     318              : 
     319         2355 : export const recordAudioExtension: ComfyExtension = {
     320              :   name: 'Comfy.RecordAudio',
     321              : 
     322              :   getCustomWidgets() {
     323         2355 :     return {
     324              :       AUDIO_RECORD(node, inputName: string) {
     325            1 :         const audio = document.createElement('audio')
     326            1 :         audio.controls = true
     327            1 :         audio.classList.add('comfy-audio')
     328            1 :         audio.setAttribute('name', 'media')
     329            1 :         const audioUIWidget: DOMWidget<HTMLAudioElement, string> =
     330              :           node.addDOMWidget(inputName, /* name=*/ 'audioUI', audio)
     331              : 
     332            1 :         let mediaRecorder: MediaRecorder | null = null
     333            1 :         let isRecording = false
     334            1 :         let audioChunks: Blob[] = []
     335            1 :         let currentStream: MediaStream | null = null
     336            1 :         let recordWidget: IBaseWidget | null = null
     337              : 
     338            1 :         let stopPromise: Promise<void> | null = null
     339            1 :         let stopResolve: (() => void) | null = null
     340              : 
     341            1 :         const handleRecordingStartFailure = (error: unknown) => {
     342            0 :           reportError(error, {
     343              :             surface: 'assets',
     344              :             errorType: 'failure_starting_audio_recorder',
     345              :             tags: {
     346              :               failure_kind: 'caught_unexpected',
     347              :               feature_area: 'assets',
     348              :               operation: 'execute',
     349              :               outcome: 'recovered'
     350              :             },
     351              :             level: 'error'
     352              :           })
     353            0 :           useToast().warning(t('g.recordingFailedToStart'))
     354              : 
     355            0 :           if (mediaRecorder) {
     356            0 :             try {
     357            0 :               mediaRecorder.stop()
     358              :             } catch {
     359              :               // A recorder that never started throws on stop; recovery continues.
     360              :             }
     361              :           }
     362            0 :           mediaRecorder = null
     363            0 :           useAudioService().stopAllTracks(currentStream)
     364            0 :           currentStream = null
     365            0 :           isRecording = false
     366            0 :           if (recordWidget) {
     367            0 :             recordWidget.label = t('g.startRecording')
     368              :           }
     369              :         }
     370              : 
     371            1 :         audioUIWidget.serializeValue = async () => {
     372            0 :           if (isRecording && mediaRecorder) {
     373            0 :             stopPromise = new Promise((resolve) => {
     374            0 :               stopResolve = resolve
     375              :             })
     376              : 
     377            0 :             mediaRecorder.stop()
     378              : 
     379            0 :             await stopPromise
     380              :           }
     381              : 
     382            0 :           const audioSrc = audioUIWidget.element.src
     383              : 
     384            0 :           if (!audioSrc) {
     385            0 :             useToast().warning(t('g.noAudioRecorded'))
     386            0 :             return ''
     387              :           }
     388              : 
     389            0 :           const blob = await fetch(audioSrc).then((r) => r.blob())
     390              : 
     391            0 :           return await useAudioService().convertBlobToFileAndSubmit(blob)
     392              :         }
     393              : 
     394            1 :         recordWidget = node.addWidget(
     395              :           'button',
     396              :           inputName,
     397              :           '',
     398              :           async () => {
     399            0 :             if (isRecording) {
     400            0 :               mediaRecorder?.stop()
     401            0 :               return
     402              :             }
     403              : 
     404            0 :             try {
     405            0 :               currentStream = await navigator.mediaDevices.getUserMedia({
     406              :                 audio: true
     407              :               })
     408              :             } catch (err) {
     409            0 :               if (
     410              :                 err instanceof DOMException &&
     411              :                 err.name === 'NotAllowedError'
     412              :               ) {
     413            0 :                 console.error('Error accessing microphone:', err)
     414            0 :                 useToast().warning(t('g.micPermissionDenied'))
     415            0 :                 useAudioService().stopAllTracks(currentStream)
     416            0 :                 currentStream = null
     417              :               } else {
     418            0 :                 handleRecordingStartFailure(err)
     419              :               }
     420            0 :               return
     421              :             }
     422              : 
     423            0 :             try {
     424            0 :               mediaRecorder = new ExtendableMediaRecorder(currentStream, {
     425              :                 mimeType: 'audio/wav'
     426              :               }) as unknown as MediaRecorder
     427              : 
     428            0 :               audioChunks = []
     429              : 
     430            0 :               mediaRecorder.ondataavailable = (event) => {
     431            0 :                 audioChunks.push(event.data)
     432              :               }
     433              : 
     434            0 :               mediaRecorder.onstop = async () => {
     435            0 :                 const audioBlob = new Blob(audioChunks, { type: 'audio/wav' })
     436              : 
     437            0 :                 useAudioService().stopAllTracks(currentStream)
     438              : 
     439            0 :                 if (
     440              :                   audioUIWidget.element.src &&
     441              :                   audioUIWidget.element.src.startsWith('blob:')
     442              :                 ) {
     443            0 :                   URL.revokeObjectURL(audioUIWidget.element.src)
     444              :                 }
     445              : 
     446            0 :                 updateUIWidget(audioUIWidget, URL.createObjectURL(audioBlob))
     447              : 
     448            0 :                 isRecording = false
     449              : 
     450            0 :                 if (recordWidget) {
     451            0 :                   recordWidget.label = t('g.startRecording')
     452              :                 }
     453              : 
     454            0 :                 if (stopResolve) {
     455            0 :                   stopResolve()
     456            0 :                   stopResolve = null
     457            0 :                   stopPromise = null
     458              :                 }
     459              :               }
     460              : 
     461            0 :               mediaRecorder.onerror = (event) => {
     462            0 :                 console.error('MediaRecorder error:', event)
     463            0 :                 useAudioService().stopAllTracks(currentStream)
     464            0 :                 isRecording = false
     465              : 
     466            0 :                 if (recordWidget) {
     467            0 :                   recordWidget.label = t('g.startRecording')
     468              :                 }
     469              : 
     470            0 :                 if (stopResolve) {
     471            0 :                   stopResolve()
     472            0 :                   stopResolve = null
     473            0 :                   stopPromise = null
     474              :                 }
     475              :               }
     476              : 
     477            0 :               mediaRecorder.start()
     478            0 :               isRecording = true
     479            0 :               if (recordWidget) {
     480            0 :                 recordWidget.label = t('g.stopRecording')
     481              :               }
     482              :             } catch (err) {
     483            0 :               handleRecordingStartFailure(err)
     484              :             }
     485              :           },
     486              :           { serialize: false }
     487              :         )
     488              : 
     489            1 :         recordWidget.label = t('g.startRecording')
     490              :         // Override the type for Vue rendering while keeping 'button' for LiteGraph
     491            1 :         recordWidget.type = 'audiorecord'
     492              : 
     493            1 :         const originalOnRemoved = node.onRemoved
     494            1 :         node.onRemoved = function () {
     495            0 :           if (isRecording && mediaRecorder) {
     496            0 :             mediaRecorder.stop()
     497              :           }
     498            0 :           useAudioService().stopAllTracks(currentStream)
     499            0 :           if (audioUIWidget.element.src.startsWith('blob:')) {
     500            0 :             URL.revokeObjectURL(audioUIWidget.element.src)
     501              :           }
     502            0 :           originalOnRemoved?.call(this)
     503              :         }
     504              : 
     505            1 :         return { widget: recordWidget }
     506              :       }
     507              :     }
     508              :   },
     509              : 
     510              :   async nodeCreated(node: LGraphNode) {
     511        23115 :     if (node.constructor.comfyClass !== 'RecordAudio') return
     512              : 
     513            1 :     await useAudioService().registerWavEncoder()
     514              :   }
     515              : }
        

Generated by: LCOV version 2.0-1