LCOV - code coverage report
Current view: top level - src/services - dialogService.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 94.7 % 75 71
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { zPromptErrorResponse } from '@comfyorg/ingest-types/zod'
       2              : import { isPlainObject } from 'es-toolkit'
       3              : import { merge } from 'es-toolkit/compat'
       4              : import type { Component } from 'vue'
       5              : import type { ComponentAttrs } from 'vue-component-type-helpers'
       6              : 
       7              : import { assert } from '@/base/assert'
       8              : import ConfirmationDialogContent from '@/components/dialog/content/ConfirmationDialogContent.vue'
       9              : import ErrorDialogContent from '@/components/dialog/content/ErrorDialogContent.vue'
      10              : import PromptDialogContent from '@/components/dialog/content/PromptDialogContent.vue'
      11              : import { t } from '@/i18n'
      12              : import { isCloud } from '@/platform/distribution/types'
      13              : import type { RunErrorMessageSource } from '@/platform/workflowErrors/errorCatalog/types'
      14              : import type { PromptError } from '@comfyorg/api-client/types'
      15              : import { useTelemetry } from '@comfyorg/telemetry'
      16              : import { PromptExecutionError } from '@comfyorg/api-client/ComfyApi'
      17              : import { useDialogStore } from '@/stores/dialogStore'
      18              : import type {
      19              :   ConfirmOptions,
      20              :   CoreDialogService,
      21              :   ExecutionErrorDialogInput,
      22              :   ExtensionDialogService
      23              : } from '@/services/dialogServiceTypes'
      24              : import type {
      25              :   DialogComponentProps,
      26              :   ShowDialogOptions
      27              : } from '@/stores/dialogStore'
      28              : import { tryExtractValidationError } from '@/utils/executionErrorUtil'
      29              : 
      30         2356 : const GLOBAL_PROMPT_KEY = 'global-prompt'
      31              : 
      32           22 : function getCatalogPromptError(value: unknown): PromptError | null {
      33           22 :   if (typeof value === 'string')
      34            0 :     return { type: 'error', message: value, details: '' }
      35           22 :   if (!isPlainObject(value)) return null
      36              : 
      37           21 :   const {
      38              :     type = 'error',
      39              :     message = '',
      40              :     details = ''
      41              :   }: Record<string, unknown> = value
      42           22 :   return typeof type === 'string' &&
      43              :     typeof message === 'string' &&
      44              :     typeof details === 'string'
      45              :     ? { type, message, details }
      46              :     : null
      47              : }
      48              : 
      49           17 : function getPromptErrorSources(response: unknown): RunErrorMessageSource[] {
      50           17 :   const parsed = zPromptErrorResponse.safeParse(response)
      51           17 :   if (!parsed.success) return []
      52              : 
      53           13 :   const promptError = getCatalogPromptError(parsed.data.error)
      54           17 :   const nodeErrors: Record<string, unknown> = isPlainObject(
      55              :     parsed.data.node_errors
      56              :   )
      57              :     ? parsed.data.node_errors
      58              :     : {}
      59              : 
      60           17 :   return [
      61              :     ...(promptError
      62              :       ? [{ kind: 'prompt' as const, error: promptError, isCloud }]
      63              :       : []),
      64              :     ...Object.entries(nodeErrors).flatMap(([nodeId, value]) => {
      65            9 :       if (!isPlainObject(value)) return []
      66            9 :       const node: Record<string, unknown> = value
      67              :       const errors: unknown[] = Array.isArray(node.errors) ? node.errors : []
      68            9 :       return errors.flatMap((value): RunErrorMessageSource[] => {
      69            9 :         if (!isPlainObject(value)) return []
      70            9 :         const error = getCatalogPromptError(value)
      71            9 :         if (!error) return []
      72              : 
      73            9 :         const extraInfo: Record<string, unknown> = isPlainObject(
      74              :           value.extra_info
      75              :         )
      76              :           ? value.extra_info
      77              :           : {}
      78            9 :         return [
      79              :           {
      80              :             kind: 'node_validation',
      81              :             error: {
      82              :               ...error,
      83              :               extra_info: {
      84              :                 ...extraInfo,
      85              :                 input_name:
      86              :                   typeof extraInfo.input_name === 'string'
      87              :                     ? extraInfo.input_name
      88              :                     : undefined
      89              :               }
      90              :             },
      91              :             nodeDisplayName:
      92              :               typeof node.class_type === 'string'
      93              :                 ? `${node.class_type} (#${nodeId})`
      94              :                 : `#${nodeId}`
      95              :           }
      96              :         ]
      97              :       })
      98              :     })
      99              :   ]
     100              : }
     101              : 
     102           21 : function formatDialogError(error: Error): string {
     103           21 :   try {
     104           21 :     return error.toString()
     105              :   } catch (cause) {
     106            0 :     if (!(error instanceof PromptExecutionError)) throw cause
     107            0 :     return JSON.stringify(error.response)
     108              :   }
     109              : }
     110              : 
     111              : // dialogStore.showDialog raises an existing dialog with the same key instead of
     112              : // wiring the new caller's callbacks, so a second concurrent caller on that key
     113              : // would never settle. Serialize FIFO per key; distinct keys stay concurrent.
     114         2356 : const promptTails = new Map<string, Promise<unknown>>()
     115              : 
     116          148 : function enqueuePrompt<T>(
     117              :   key: string,
     118              :   show: (resolve: (value: T) => void) => void
     119              : ): Promise<T> {
     120              :   const tail = promptTails.get(key) ?? Promise.resolve()
     121          148 :   const result = tail.then(() => new Promise<T>(show))
     122          148 :   const settled = result.then(
     123              :     () => undefined,
     124              :     () => undefined
     125              :   )
     126          148 :   promptTails.set(key, settled)
     127          148 :   void settled.then(() => {
     128          140 :     if (promptTails.get(key) === settled) promptTails.delete(key)
     129              :   })
     130          148 :   return result
     131              : }
     132              : 
     133         2356 : export const useDialogService = (): CoreDialogService => {
     134        84373 :   const dialogStore = useDialogStore()
     135              : 
     136            4 :   function showExecutionErrorDialog(executionError: ExecutionErrorDialogInput) {
     137              :     const validationError = tryExtractValidationError(
     138              :       executionError.exception_message
     139              :     )
     140            4 :     const validationSources = getPromptErrorSources(validationError)
     141            4 :     const props: ComponentAttrs<typeof ErrorDialogContent> = {
     142              :       errorSources: validationSources.length
     143              :         ? validationSources
     144              :         : [
     145              :             {
     146              :               kind: 'execution',
     147              :               error: executionError,
     148              :               nodeDisplayName: executionError.node_type ?? ''
     149              :             }
     150              :           ],
     151              :       error: {
     152              :         exceptionType: executionError.exception_type,
     153              :         exceptionMessage: executionError.exception_message,
     154              :         nodeId: executionError.node_id?.toString(),
     155              :         nodeType: executionError.node_type ?? undefined,
     156              :         traceback: executionError.traceback?.join('\n') ?? '',
     157              :         reportType: 'graphExecutionError'
     158              :       }
     159              :     }
     160              : 
     161            4 :     dialogStore.showDialog({
     162              :       key: 'global-execution-error',
     163              :       component: ErrorDialogContent,
     164              :       props,
     165              :       dialogComponentProps: {
     166              :         size: 'lg',
     167              :         onClose: () => {
     168            0 :           useTelemetry()?.trackUiButtonClicked({
     169              :             button_id: 'error_dialog_closed',
     170              :             element_group: 'error_dialog'
     171              :           })
     172              :         }
     173              :       }
     174              :     })
     175              :   }
     176              : 
     177           21 :   function parseError(error: Error) {
     178           21 :     const filename =
     179              :       'fileName' in error
     180              :         ? (error.fileName as string)
     181              :         : error.stack?.match(/(\/extensions\/.*\.js)/)?.[1]
     182              : 
     183           21 :     const extensionFile = filename
     184              :       ? filename.substring(filename.indexOf('/extensions/'))
     185              :       : undefined
     186              : 
     187           21 :     return {
     188              :       errorMessage: formatDialogError(error),
     189              :       stackTrace: error.stack,
     190              :       extensionFile
     191              :     }
     192              :   }
     193              : 
     194              :   /**
     195              :    * Show a error dialog to the user when an error occurs.
     196              :    * @param error The error to show
     197              :    * @param options The options for the dialog
     198              :    */
     199           27 :   function showErrorDialog(
     200              :     error: unknown,
     201              :     options: {
     202              :       title?: string
     203              :       reportType?: string
     204              :     } = {}
     205              :   ) {
     206           27 :     const errorProps: {
     207              :       errorMessage: string
     208              :       stackTrace?: string
     209              :       extensionFile?: string
     210              :     } =
     211              :       error instanceof Error
     212              :         ? parseError(error)
     213              :         : {
     214              :             errorMessage: String(error)
     215              :           }
     216              : 
     217           27 :     const props: ComponentAttrs<typeof ErrorDialogContent> = {
     218              :       errorSources:
     219              :         error instanceof PromptExecutionError
     220              :           ? getPromptErrorSources(error.response)
     221              :           : undefined,
     222              :       error: {
     223              :         exceptionType: options.title ?? 'Unknown Error',
     224              :         exceptionMessage: errorProps.errorMessage,
     225              :         extensionFile: errorProps.extensionFile,
     226              :         traceback: errorProps.stackTrace ?? t('errorDialog.noStackTrace'),
     227              :         reportType: options.reportType
     228              :       }
     229              :     }
     230              : 
     231           27 :     dialogStore.showDialog({
     232              :       key: 'global-error',
     233              :       component: ErrorDialogContent,
     234              :       props,
     235              :       dialogComponentProps: {
     236              :         size: 'lg',
     237              :         onClose: () => {
     238            2 :           useTelemetry()?.trackUiButtonClicked({
     239              :             button_id: 'error_dialog_closed',
     240              :             element_group: 'error_dialog'
     241              :           })
     242              :         }
     243              :       }
     244              :     })
     245              :   }
     246              : 
     247          116 :   async function prompt({
     248              :     title,
     249              :     message,
     250              :     defaultValue = '',
     251              :     placeholder
     252              :   }: {
     253              :     title: string
     254              :     message: string
     255              :     defaultValue?: string
     256              :     placeholder?: string
     257              :   }): Promise<string | null> {
     258          116 :     return enqueuePrompt<string | null>(GLOBAL_PROMPT_KEY, (resolve) => {
     259          116 :       dialogStore.showDialog({
     260              :         key: GLOBAL_PROMPT_KEY,
     261              :         title,
     262              :         component: PromptDialogContent,
     263              :         props: {
     264              :           message,
     265              :           defaultValue,
     266              :           onConfirm: (value: string) => {
     267          108 :             resolve(value)
     268              :           },
     269              :           placeholder
     270              :         },
     271              :         dialogComponentProps: {
     272              :           size: 'md',
     273              :           onRemoved: () => {
     274          112 :             resolve(null)
     275              :           }
     276              :         }
     277              :       })
     278              :     })
     279              :   }
     280              : 
     281              :   /**
     282              :    * @returns `true` if the user confirms the dialog,
     283              :    * `false` if denied (e.g. no in yes/no/cancel), or
     284              :    * `null` if the dialog is cancelled or closed
     285              :    */
     286           32 :   async function confirm({
     287              :     title,
     288              :     message,
     289              :     type = 'default',
     290              :     itemList = [],
     291              :     hint,
     292              :     denyLabel,
     293              :     confirmLabel,
     294              :     key = GLOBAL_PROMPT_KEY
     295              :   }: ConfirmOptions): Promise<boolean | null> {
     296           32 :     const show = (resolve: (value: boolean | null) => void) => {
     297           32 :       const options: ShowDialogOptions = {
     298              :         key,
     299              :         title,
     300              :         component: ConfirmationDialogContent,
     301              :         props: {
     302              :           message,
     303              :           type,
     304              :           itemList,
     305              :           onConfirm: resolve,
     306              :           hint,
     307              :           denyLabel,
     308              :           confirmLabel
     309              :         },
     310              :         dialogComponentProps: {
     311              :           size: 'md',
     312              :           onRemoved: () => resolve(null)
     313              :         }
     314              :       }
     315              : 
     316           32 :       dialogStore.showDialog(options)
     317              :     }
     318              : 
     319           32 :     return enqueuePrompt<boolean | null>(key, show)
     320              :   }
     321              : 
     322              :   /**
     323              :    * Shows a dialog from a third party extension.
     324              :    * @param options - The dialog options.
     325              :    * @param options.key - The dialog key.
     326              :    * @param options.title - The dialog title.
     327              :    * @param options.headerComponent - The dialog header component.
     328              :    * @param options.footerComponent - The dialog footer component.
     329              :    * @param options.component - The dialog component.
     330              :    * @param options.props - The dialog props.
     331              :    * @returns The dialog instance and a function to close the dialog.
     332              :    */
     333            2 :   function showExtensionDialog(options: ShowDialogOptions & { key: string }) {
     334            2 :     return {
     335              :       dialog: dialogStore.showExtensionDialog(options),
     336              :       closeDialog: () => dialogStore.closeDialog({ key: options.key })
     337              :     }
     338              :   }
     339              : 
     340          104 :   function showLayoutDialog<C extends Component>(options: {
     341              :     key: string
     342              :     component: C
     343              :     props: ComponentAttrs<C>
     344              :     dialogComponentProps?: DialogComponentProps
     345              :   }) {
     346          104 :     const layoutDefaultProps: DialogComponentProps = {
     347              :       headless: true,
     348              :       closable: true
     349              :     }
     350              : 
     351          104 :     return dialogStore.showDialog({
     352              :       ...options,
     353              :       dialogComponentProps: merge(
     354              :         layoutDefaultProps,
     355              :         options.dialogComponentProps || {}
     356              :       )
     357              :     })
     358              :   }
     359              : 
     360           13 :   function showSmallLayoutDialog(
     361              :     options: Omit<ShowDialogOptions, 'dialogComponentProps'> & {
     362              :       dialogComponentProps?: DialogComponentProps
     363              :     }
     364              :   ) {
     365           13 :     const { dialogComponentProps: callerProps, ...rest } = options
     366              : 
     367           13 :     return dialogStore.showDialog({
     368              :       ...rest,
     369              :       dialogComponentProps: {
     370              :         closable: true,
     371              :         flush: true,
     372              :         size: 'fit',
     373              :         ...callerProps
     374              :       }
     375              :     })
     376              :   }
     377              : 
     378        84373 :   return {
     379              :     showExecutionErrorDialog,
     380              :     showErrorDialog,
     381              :     prompt,
     382              :     confirm,
     383              :     showExtensionDialog,
     384              :     showLayoutDialog,
     385              :     showSmallLayoutDialog
     386              :   }
     387              : }
     388              : 
     389              : export type {
     390              :   ExecutionErrorDialogInput,
     391              :   ExtensionDialogService
     392              : } from '@/services/dialogServiceTypes'
     393              : 
     394         2356 : let extensionDialogService: ExtensionDialogService | undefined
     395              : 
     396         2355 : export function registerExtensionDialogService(
     397              :   service: ExtensionDialogService
     398              : ) {
     399         2355 :   extensionDialogService = service
     400              : }
     401              : 
     402           64 : export function useExtensionDialogService(): ExtensionDialogService {
     403           64 :   assert(
     404              :     extensionDialogService,
     405              :     'Extension dialog service accessed before registerExtensionDialogService'
     406              :   )
     407           64 :   return extensionDialogService
     408              : }
        

Generated by: LCOV version 2.0-1