LCOV - code coverage report
Current view: top level - src/platform/workflow/management/composables - useWorkflowLinkUrlLoader.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 53.3 % 30 16
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import {
       2              :   zErrorResponse,
       3              :   zWorkflowSidebarFileResponse
       4              : } from '@comfyorg/ingest-types/zod'
       5              : import { useTelemetry } from '@comfyorg/telemetry'
       6              : import { reportError } from '@comfyorg/telemetry/reportError'
       7              : import type {
       8              :   WorkflowLinkOpenedMetadata,
       9              :   WorkflowLinkOutOfSyncReason
      10              : } from '@comfyorg/telemetry/types'
      11              : import { createSharedComposable } from '@vueuse/core'
      12              : import { onScopeDispose } from 'vue'
      13              : import { useRoute, useRouter } from 'vue-router'
      14              : import { z } from 'zod'
      15              : 
      16              : import { useToast } from '@/components/ui/toast/toastStore'
      17              : import { t } from '@/i18n'
      18              : import { isCloud } from '@/platform/distribution/types'
      19              : import {
      20              :   clearPreservedQuery,
      21              :   getPreservedQueryParam,
      22              :   hydratePreservedQuery,
      23              :   mergePreservedQueryIntoQuery
      24              : } from '@/platform/navigation/preservedQueryManager'
      25              : import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces'
      26              : import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
      27              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
      28              : import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
      29              : import { api } from '@/scripts/api'
      30              : 
      31         2355 : const NAMESPACE = PRESERVED_QUERY_NAMESPACES.WORKFLOW_ID
      32         2355 : const workflowIdSchema = z.uuid()
      33         2355 : const outOfSyncReasonSchema = z.enum([
      34              :   'no_sidebar_path',
      35              :   'name_ambiguous',
      36              :   'file_missing',
      37              :   'content_mismatch'
      38              : ])
      39         2355 : const outOfSyncBodySchema = zErrorResponse.pick({ code: true, details: true })
      40              : 
      41              : type WorkflowLinkLoadStatus = 'absent' | 'pending' | 'opened' | 'failed'
      42              : type LinkOutcome =
      43              :   | { kind: 'opened' }
      44              :   | { kind: 'not_found' }
      45              :   | { kind: 'out_of_sync'; reason: WorkflowLinkOutOfSyncReason }
      46              :   | { kind: 'error' }
      47              : type ResolveOutcome = LinkOutcome | { kind: 'pending' }
      48              : type LookupResult =
      49              :   | { kind: 'found'; path: string }
      50              :   | Exclude<LinkOutcome, { kind: 'opened' }>
      51              : type LinkCarriers = { route: unknown; stash: string | undefined }
      52              : type Ownership = {
      53              :   owns: () => boolean
      54              :   unreplaced: () => boolean
      55              : }
      56              : 
      57              : function isWorkflowId(value: unknown): value is string {
      58              :   return typeof value === 'string' && workflowIdSchema.safeParse(value).success
      59              : }
      60              : 
      61            0 : function linkIdentity(value: unknown): unknown {
      62            0 :   if (value === null || value === '') return ','
      63            0 :   if (!Array.isArray(value)) return value
      64            0 :   if (value.length === 1) return linkIdentity(value[0])
      65            0 :   return value.map((entry: unknown) => entry ?? '').join(',')
      66              : }
      67              : 
      68            0 : function isSameLink(carried: unknown, workflowId: unknown): boolean {
      69            0 :   return linkIdentity(carried) === linkIdentity(workflowId)
      70              : }
      71              : 
      72              : const BUILT_IN_ERROR_NAMES: ReadonlySet<string> = new Set([
      73              :   'Error',
      74              :   'TypeError',
      75              :   'RangeError',
      76              :   'SyntaxError',
      77              :   'ReferenceError',
      78              :   'EvalError',
      79              :   'URIError',
      80              :   'AggregateError'
      81              : ])
      82              : 
      83              : function failureContext(cause: unknown) {
      84              :   try {
      85              :     if (!(cause instanceof Error)) return { error_name: typeof cause }
      86              :     const name = cause.name
      87              :     return { error_name: BUILT_IN_ERROR_NAMES.has(name) ? name : 'other' }
      88              :   } catch {
      89              :     return { error_name: 'other' }
      90              :   }
      91              : }
      92              : 
      93              : function isWorkflowPath(path: string): boolean {
      94              :   return (
      95              :     path.startsWith('workflows/') &&
      96              :     path.endsWith('.json') &&
      97              :     !path.includes('\\') &&
      98              :     path
      99              :       .split('/')
     100              :       .every((part) => part !== '' && part !== '.' && part !== '..')
     101              :   )
     102              : }
     103              : 
     104              : async function readOutOfSyncReason(
     105              :   response: Response
     106              : ): Promise<WorkflowLinkOutOfSyncReason> {
     107              :   const body: unknown = await response.json().catch(() => undefined)
     108              :   const parsed = outOfSyncBodySchema.safeParse(body)
     109              :   if (!parsed.success || parsed.data.code !== 'WORKFLOW_OUT_OF_SYNC')
     110              :     return 'unknown'
     111              :   const reason = outOfSyncReasonSchema.safeParse(parsed.data.details?.reason)
     112              :   return reason.success ? reason.data : 'unknown'
     113              : }
     114              : 
     115              : async function readLookupResponse(response: Response): Promise<LookupResult> {
     116              :   if (response.status === 404) return { kind: 'not_found' }
     117              :   if (response.status === 409)
     118              :     return { kind: 'out_of_sync', reason: await readOutOfSyncReason(response) }
     119              :   if (!response.ok) {
     120              :     reportError(new Error('Workflow link lookup failed'), {
     121              :       surface: 'graph',
     122              :       errorType: 'error_loading_workflow_link',
     123              :       context: { status: response.status }
     124              :     })
     125              :     return { kind: 'error' }
     126              :   }
     127              :   const body: unknown = await response.json()
     128              :   const parsed = zWorkflowSidebarFileResponse.safeParse(body)
     129              :   if (!parsed.success || !isWorkflowPath(parsed.data.path)) {
     130              :     reportError(new Error('Invalid workflow link lookup response'), {
     131              :       surface: 'graph',
     132              :       errorType: 'error_loading_workflow_link'
     133              :     })
     134              :     return { kind: 'error' }
     135              :   }
     136              :   return { kind: 'found', path: parsed.data.path }
     137              : }
     138              : 
     139              : async function lookupSidebarFile(workflowId: string): Promise<LookupResult> {
     140              :   try {
     141              :     const response = await api.fetchApi(`/workflows/${workflowId}/sidebar-file`)
     142              :     return await readLookupResponse(response)
     143              :   } catch (cause) {
     144              :     reportError(new Error('Could not read workflow link'), {
     145              :       surface: 'graph',
     146              :       errorType: 'error_loading_workflow_link',
     147              :       context: failureContext(cause)
     148              :     })
     149              :     return { kind: 'error' }
     150              :   }
     151              : }
     152              : 
     153              : function navigationPending(query: Record<string, unknown>): boolean {
     154              :   return [
     155              :     PRESERVED_QUERY_NAMESPACES.WORKSPACE,
     156              :     PRESERVED_QUERY_NAMESPACES.DEPLOYMENT
     157              :   ].some(
     158              :     (namespace) =>
     159              :       namespace in query ||
     160              :       getPreservedQueryParam(namespace, namespace) !== undefined
     161              :   )
     162              : }
     163              : 
     164              : function toTelemetry(
     165              :   outcome: LinkOutcome,
     166              :   workspaceId: string | null
     167              : ): WorkflowLinkOpenedMetadata {
     168              :   return outcome.kind === 'out_of_sync'
     169              :     ? {
     170              :         outcome: 'out_of_sync',
     171              :         reason: outcome.reason,
     172              :         workspace_id: workspaceId
     173              :       }
     174              :     : { outcome: outcome.kind, workspace_id: workspaceId }
     175              : }
     176              : 
     177         2355 : function useWorkflowLinkUrlLoaderInternal() {
     178         2355 :   const route = useRoute()
     179         2355 :   const router = useRouter()
     180         2355 :   const workflowStore = useWorkflowStore()
     181         2355 :   const workspaceStore = useTeamWorkspaceStore()
     182         2355 :   const toast = useToast()
     183              :   let completed:
     184              :     | {
     185              :         value: unknown
     186              :         workspaceId: string | null
     187              :         status: 'opened' | 'failed'
     188              :       }
     189              :     | undefined
     190         2355 :   const startedLinks = new Set<unknown>()
     191              :   let disposed = false
     192         2355 :   onScopeDispose(() => {
     193              :     disposed = true
     194              :   })
     195              : 
     196              :   async function stripLinkFromUrl(): Promise<boolean> {
     197              :     if (!('workflowId' in route.query) && !('workflows' in route.query))
     198              :       return true
     199              :     const query = { ...route.query }
     200              :     delete query.workflowId
     201              :     delete query.workflows
     202              :     try {
     203              :       return (await router.replace({ query })) === undefined
     204              :     } catch (cause) {
     205              :       reportError(new Error('Could not clear workflow link'), {
     206              :         surface: 'graph',
     207              :         errorType: 'error_clearing_workflow_link',
     208              :         context: failureContext(cause)
     209              :       })
     210              :       return true
     211              :     }
     212              :   }
     213              : 
     214              :   async function clearOwnedIntent(ownership: Ownership) {
     215              :     if (!ownership.owns()) return
     216              :     hydratePreservedQuery(PRESERVED_QUERY_NAMESPACES.WORKFLOWS)
     217              :     if (!(await stripLinkFromUrl()) || !ownership.unreplaced()) return
     218              :     clearPreservedQuery(NAMESPACE)
     219              :     clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.WORKFLOWS)
     220              :   }
     221              : 
     222              :   async function openPath(
     223              :     path: string,
     224              :     isCurrent: () => boolean
     225              :   ): Promise<ResolveOutcome> {
     226              :     try {
     227              :       await workflowStore.loadWorkflows()
     228              :       if (!isCurrent()) return { kind: 'pending' }
     229              :       let workflow = workflowStore.getWorkflowByPath(path)
     230              :       if (!workflow) {
     231              :         await workflowStore.syncWorkflows()
     232              :         if (!isCurrent()) return { kind: 'pending' }
     233              :         workflow = workflowStore.getWorkflowByPath(path)
     234              :       }
     235              :       if (!workflow) {
     236              :         reportError(
     237              :           new Error('Workflow link file is not in the workflow list'),
     238              :           {
     239              :             surface: 'graph',
     240              :             errorType: 'error_opening_workflow_link'
     241              :           }
     242              :         )
     243              :         return { kind: 'error' }
     244              :       }
     245              :       const opened = await useWorkflowService().openWorkflow(workflow, {
     246              :         isCurrent
     247              :       })
     248              :       return opened ? { kind: 'opened' } : { kind: 'error' }
     249              :     } catch (cause) {
     250              :       reportError(new Error('Could not open workflow link'), {
     251              :         surface: 'graph',
     252              :         errorType: 'error_opening_workflow_link',
     253              :         context: failureContext(cause)
     254              :       })
     255              :       return { kind: 'error' }
     256              :     }
     257              :   }
     258              : 
     259              :   async function resolveLink(
     260              :     value: unknown,
     261              :     isCurrent: () => boolean
     262              :   ): Promise<ResolveOutcome> {
     263              :     if (!isWorkflowId(value)) return { kind: 'not_found' }
     264              :     const result = await lookupSidebarFile(value)
     265              :     if (!isCurrent()) return { kind: 'pending' }
     266              :     return result.kind === 'found' ? openPath(result.path, isCurrent) : result
     267              :   }
     268              : 
     269              :   function reportOutcome(outcome: LinkOutcome, workspaceId: string | null) {
     270              :     if (outcome.kind !== 'opened') {
     271              :       toast.error(
     272              :         t(
     273              :           outcome.kind === 'error'
     274              :             ? 'toastMessages.linkedWorkflowLoadFailed'
     275              :             : 'toastMessages.linkedWorkflowNotOpened'
     276              :         )
     277              :       )
     278              :     }
     279              :     useTelemetry()?.trackWorkflowLinkOpened(toTelemetry(outcome, workspaceId))
     280              :   }
     281              : 
     282              :   function linkQuery() {
     283              :     hydratePreservedQuery(NAMESPACE)
     284              :     return 'workflowId' in route.query
     285              :       ? route.query
     286              :       : (mergePreservedQueryIntoQuery(NAMESPACE, route.query) ?? route.query)
     287              :   }
     288              : 
     289            0 :   function linkCarriers(): LinkCarriers {
     290            0 :     return {
     291              :       route: route.query.workflowId,
     292              :       stash: getPreservedQueryParam(NAMESPACE, 'workflowId')
     293              :     }
     294              :   }
     295              : 
     296              :   function carriesOnly(workflowId: unknown): boolean {
     297              :     const { route, stash } = linkCarriers()
     298              :     return (
     299              :       (route === undefined || isSameLink(route, workflowId)) &&
     300              :       (stash === undefined || isSameLink(stash, workflowId))
     301              :     )
     302              :   }
     303              : 
     304              :   function hasLink(): boolean {
     305              :     const current = linkCarriers()
     306              :     return current.route !== undefined || current.stash !== undefined
     307              :   }
     308              : 
     309              :   function attemptOwnership(
     310              :     workflowId: unknown,
     311              :     workspaceId: string | null
     312              :   ): Ownership {
     313              :     const unreplaced = () =>
     314              :       !disposed &&
     315              :       workspaceStore.activeWorkspaceId === workspaceId &&
     316              :       carriesOnly(workflowId)
     317              :     return { owns: () => hasLink() && unreplaced(), unreplaced }
     318              :   }
     319              : 
     320              :   function completedStatus(value: unknown, workspaceId: string | null) {
     321              :     if (
     322              :       !completed ||
     323              :       !isSameLink(completed.value, value) ||
     324              :       completed.workspaceId !== workspaceId
     325              :     )
     326              :       return undefined
     327              :     return completed.status
     328              :   }
     329              : 
     330         2355 :   async function openWorkflowLinkFromUrl(
     331              :     afterNavigation = false
     332              :   ): Promise<WorkflowLinkLoadStatus> {
     333         2355 :     if (!isCloud) return 'absent'
     334              :     const query = linkQuery()
     335              :     if (!('workflowId' in query)) return 'absent'
     336              :     if (!afterNavigation && navigationPending(query)) return 'pending'
     337              :     return settleLink(query.workflowId, workspaceStore.activeWorkspaceId)
     338              :   }
     339              : 
     340              :   async function settleLink(
     341              :     workflowId: unknown,
     342              :     workspaceId: string | null
     343              :   ): Promise<WorkflowLinkLoadStatus> {
     344              :     startedLinks.add(linkIdentity(workflowId))
     345              :     const ownership = attemptOwnership(workflowId, workspaceId)
     346              :     const priorStatus = completedStatus(workflowId, workspaceId)
     347              :     if (priorStatus) {
     348              :       await clearOwnedIntent(ownership)
     349              :       return priorStatus
     350              :     }
     351              :     const outcome = await resolveLink(workflowId, ownership.owns)
     352              :     if (outcome.kind === 'pending' || !ownership.owns()) return 'pending'
     353              :     const status = outcome.kind === 'opened' ? 'opened' : 'failed'
     354              :     completed = { value: workflowId, workspaceId, status }
     355              :     await clearOwnedIntent(ownership)
     356              :     reportOutcome(outcome, workspaceId)
     357              :     return status
     358              :   }
     359              : 
     360            0 :   function isLinkSettled(workflowId: unknown): boolean {
     361            0 :     return (
     362              :       completedStatus(workflowId, workspaceStore.activeWorkspaceId) !==
     363              :       undefined
     364              :     )
     365              :   }
     366              : 
     367            0 :   function hasLinkInFlight(): boolean {
     368            0 :     const { route, stash } = linkCarriers()
     369            0 :     return (
     370              :       stash !== undefined &&
     371              :       !isSameLink(stash, route) &&
     372              :       !startedLinks.has(linkIdentity(stash))
     373              :     )
     374              :   }
     375              : 
     376         2355 :   return { openWorkflowLinkFromUrl, isLinkSettled, hasLinkInFlight }
     377              : }
     378              : 
     379         2355 : export const useWorkflowLinkUrlLoader = createSharedComposable(
     380              :   useWorkflowLinkUrlLoaderInternal
     381              : )
        

Generated by: LCOV version 2.0-1