LCOV - code coverage report
Current view: top level - src/renderer/extensions/firstRunTour/tour - useFirstRunTourController.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 33.3 % 144 48
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import {
       2              :   breakpointsTailwind,
       3              :   createSharedComposable,
       4              :   useBreakpoints,
       5              :   useEventListener
       6              : } from '@vueuse/core'
       7              : import { delay } from 'es-toolkit'
       8              : import { computed, readonly, ref, shallowRef, watch } from 'vue'
       9              : 
      10              : import { useBillingContext } from '@/platform/billing/composables/useBillingContext'
      11              : import { useOnboardingTourStore } from '@/platform/onboarding/onboardingTourStore'
      12              : import { registerTour } from '@/platform/onboarding/onboardingTours'
      13              : import { useSettingStore } from '@/platform/settings/settingStore'
      14              : import type { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore'
      15              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
      16              : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
      17              : import { api } from '@/scripts/api'
      18              : import { useExecutionErrorStore } from '@/stores/executionErrorStore'
      19              : import { useExecutionStore } from '@/stores/executionStore'
      20              : 
      21              : import {
      22              :   firstRunTourSteps,
      23              :   releaseFirstRunTargets
      24              : } from './firstRunTourDefinition'
      25              : import type { RunState } from './firstRunTourDefinition'
      26              : 
      27         2355 : const RUN_BUTTON_SELECTOR =
      28              :   '[data-testid="queue-button"], [data-testid="subscribe-to-run-button"]'
      29              : 
      30              : /** An undimmed look at the workflow the user chose, before the tour dims it. */
      31         2355 : const INTRO_PREVIEW_MS = 500
      32              : 
      33         2355 : const OFFLINE_GRACE_MS = 20_000
      34              : 
      35              : /** How long a submitted run has to be accepted before the card stops promising. */
      36         2355 : const ACCEPT_DEADLINE_MS = 15_000
      37              : 
      38              : type TourStartState =
      39              :   | { phase: 'idle' }
      40              :   | {
      41              :       phase: 'claimed'
      42              :       ownership: symbol
      43              :       restoreRenderer: boolean
      44              :     }
      45              :   | {
      46              :       phase: 'writingRenderer'
      47              :       ownership: symbol
      48              :       restoreRenderer: boolean
      49              :       write: Promise<void>
      50              :     }
      51              :   | {
      52              :       phase: 'previewing'
      53              :       ownership: symbol
      54              :       restoreRenderer: boolean
      55              :     }
      56              : 
      57         2355 : function useFirstRunTourControllerInternal() {
      58         2355 :   const engine = useOnboardingTourStore()
      59         2355 :   const billing = useBillingContext()
      60         2355 :   const executionStore = useExecutionStore()
      61         2355 :   const executionErrorStore = useExecutionErrorStore()
      62         2355 :   const workflowStore = useWorkflowStore()
      63         2355 :   const canvasStore = useCanvasStore()
      64         2355 :   const settingStore = useSettingStore()
      65         2355 :   const desktopLayout = useBreakpoints(breakpointsTailwind).greaterOrEqual('md')
      66         2355 :   const tourWorkflow = shallowRef<ComfyWorkflow | null>(null)
      67         2355 :   const nudgeArmed = ref(false)
      68         2355 :   let tourStart: TourStartState = { phase: 'idle' }
      69              :   /** Only a tour walked to the end made a first result to be congratulated for. */
      70         2355 :   const tourWasCompleted = ref(false)
      71              : 
      72              :   /**
      73              :    * The half of the tour's context that exists before the tour does: a canvas
      74              :    * the steps can point at. Linear mode `display:none`s it entirely, and below
      75              :    * the desktop layout the spotlights are placed against a screen that isn't
      76              :    * there. Split out so it can also serve as the precondition for opening one.
      77              :    */
      78         2355 :   const canvasContextHolds = computed(
      79              :     () => desktopLayout.value && !canvasStore.linearMode
      80              :   )
      81              : 
      82              :   // The tour's node ids are graph-local, so they only describe the workflow it
      83              :   // resolved against: swapping workflows leaves it pointing at strangers.
      84         2355 :   const tourContextHolds = computed(
      85              :     () =>
      86              :       canvasContextHolds.value &&
      87              :       workflowStore.activeWorkflow === tourWorkflow.value
      88              :   )
      89              : 
      90         2355 :   const onRunStep = computed(
      91              :     () =>
      92              :       engine.activeTour === 'firstRun' &&
      93              :       engine.step?.kind === 'spotlight' &&
      94              :       engine.step.selfAdvancing === true
      95              :   )
      96              : 
      97              :   /** Recorded, not derived: the queue clears a status as soon as it turns terminal. */
      98         2355 :   const runState = ref<RunState>('idle')
      99         2355 :   watch(
     100              :     () => [
     101              :       executionStore.getWorkflowStatus(tourWorkflow.value),
     102              :       executionErrorStore.hasNodeError || executionErrorStore.hasPromptError
     103              :     ],
     104              :     ([status, refused], previous) => {
     105           45 :       if (status !== undefined) stopAcceptDeadline()
     106              :       // Only an actual transition into `running` starts the wait. This source
     107              :       // re-evaluates whenever the `workflowStatus` map is replaced — which
     108              :       // `mutateStatus` does for *any* workflow — or whenever an error flag
     109              :       // flips. Paths that drop a job without clearing its status leave
     110              :       // `running` behind forever (`handleServiceLevelError` is the live one),
     111              :       // so an unconditional branch here would re-read that stale value and put
     112              :       // the card back on "your result lands right here" after the watcher
     113              :       // below has already failed the run.
     114           45 :       if (status === 'running' && previous[0] !== 'running')
     115            0 :         runState.value = 'generating'
     116           45 :       else if (status === 'completed') runState.value = 'succeeded'
     117           45 :       else if (status === 'failed') runState.value = 'failed'
     118              :       // A refused run never queues; a stopped one drops its status rather than
     119              :       // reporting an outcome. Both end the run, and neither says so.
     120           45 :       else if (refused && runState.value === 'generating')
     121            0 :         runState.value = 'failed'
     122           45 :       else if (status === undefined && previous[0] === 'running')
     123            0 :         runState.value = 'failed'
     124              :     }
     125              :   )
     126              : 
     127              :   /**
     128              :    * The queue stores a job the moment it accepts a submission, so a job
     129              :    * carrying this tour's workflow is proof of acceptance. A refused submission
     130              :    * never gets one.
     131              :    *
     132              :    * Deliberately *not* the workflow status: that is only written by
     133              :    * `handleExecutionStart`, and a cloud job sits accepted in
     134              :    * `initializingJobIds` — "Waiting for a machine" — with no status at all
     135              :    * while a worker is allocated. Allocation routinely outlasts any deadline
     136              :    * short enough to be useful, so keying on status would fail healthy runs.
     137              :    */
     138         2355 :   const tourRunAccepted = computed(() =>
     139              :     Object.values(executionStore.queuedJobs).some(
     140              :       (job) => job.workflow === tourWorkflow.value
     141              :     )
     142              :   )
     143              : 
     144              :   /**
     145              :    * A submission the backend refuses never gets a prompt_id, so no status ever
     146              :    * appears and none of the branches above can fire. Account preconditions —
     147              :    * sign-in, subscription, credits — are deliberately kept out of the error
     148              :    * stores by `ComfyApp.queuePrompt`, so the refusal is invisible there too.
     149              :    *
     150              :    * Give *acceptance* a deadline, not the run. Acceptance arrives on the
     151              :    * queuePrompt response rather than the socket, so this cannot pre-empt the
     152              :    * longer offline grace: a run accepted at all disarms this immediately and
     153              :    * leaves the connection question to `OFFLINE_GRACE_MS`.
     154              :    *
     155              :    * Acceptance is not the only disarm. `resetExecutionState` drops a job from
     156              :    * `queuedJobs` without clearing its status, so a run can report a status
     157              :    * while this reads false. A refusal produces neither signal.
     158              :    *
     159              :    * Losing acceptance is itself a signal, not a re-armed deadline. Two paths
     160              :    * drop the job without ever writing an outcome:
     161              :    *
     162              :    * - an accepted job that disappears with **no status written at all** — the
     163              :    *   cloud "waiting for a machine" job that is cancelled or reconciled away
     164              :    * - `handleServiceLevelError` ("Job has stagnated"), which drops the job and
     165              :    *   records a prompt error but never touches `workflowStatus`, so the
     166              :    *   `running` written by `handleExecutionStart` outlives the run
     167              :    *
     168              :    * Not the mid-run credits path: #15161 made
     169              :    * `handleAccountPreconditionError` clear the status, so that one already
     170              :    * ends via the `undefined`-after-`running` branch above.
     171              :    *
     172              :    * A finished run leaves the queue too, but reports a terminal status in the
     173              :    * same flush, and the terminal branches above overwrite unconditionally — so
     174              :    * the outcome wins whichever watcher runs first.
     175              :    */
     176         2355 :   watch(tourRunAccepted, (accepted) => {
     177            0 :     if (accepted) stopAcceptDeadline()
     178            0 :     else if (runState.value === 'generating') runState.value = 'failed'
     179              :   })
     180              : 
     181         2355 :   let acceptTimer: ReturnType<typeof setTimeout> | undefined
     182            0 :   function stopAcceptDeadline() {
     183            0 :     clearTimeout(acceptTimer)
     184            0 :     acceptTimer = undefined
     185              :   }
     186            0 :   function startAcceptDeadline() {
     187            0 :     stopAcceptDeadline()
     188            0 :     if (tourRunAccepted.value) return
     189            0 :     acceptTimer = setTimeout(() => {
     190            0 :       stopAcceptDeadline()
     191            0 :       if (runState.value === 'generating') runState.value = 'failed'
     192              :     }, ACCEPT_DEADLINE_MS)
     193              :   }
     194              : 
     195         2355 :   let offlineTimer: ReturnType<typeof setTimeout> | undefined
     196            8 :   function stopOfflineGrace() {
     197            8 :     clearTimeout(offlineTimer)
     198            8 :     offlineTimer = undefined
     199              :   }
     200         2355 :   useEventListener(api, 'reconnecting', () => {
     201           11 :     if (runState.value !== 'generating' || offlineTimer) return
     202            0 :     offlineTimer = setTimeout(() => {
     203            0 :       stopOfflineGrace()
     204            0 :       if (runState.value === 'generating') runState.value = 'failed'
     205              :     }, OFFLINE_GRACE_MS)
     206              :   })
     207         2355 :   useEventListener(api, 'reconnected', stopOfflineGrace)
     208              : 
     209              :   /**
     210              :    * A run outlives the step that starts it, so the click moves the tour on. One
     211              :    * the paywall will refuse never queues, so the tour parks and leaves the
     212              :    * subscribe button to open its own dialog.
     213              :    */
     214         2355 :   useEventListener(
     215              :     document,
     216              :     'click',
     217              :     (event: MouseEvent) => {
     218         5440 :       if (!onRunStep.value) return
     219            0 :       if (!(event.target instanceof Element)) return
     220            0 :       if (!event.target.closest(RUN_BUTTON_SELECTOR)) return
     221              : 
     222         5440 :       if (billing.type.value !== 'unknown' && !billing.canRunWorkflows.value) {
     223            0 :         engine.postpone()
     224            0 :         return
     225              :       }
     226              : 
     227            0 :       runState.value = 'generating'
     228            0 :       startAcceptDeadline()
     229            0 :       engine.next()
     230              :     },
     231              :     { capture: true }
     232              :   )
     233              : 
     234         2355 :   watch(
     235              :     () => engine.activeTour === 'firstRun',
     236              :     (active) => {
     237            0 :       if (active) return
     238              :       // Every ending leaves the user somewhere to go next, so every ending arms
     239              :       // the nudge; only what it says depends on how the tour ended.
     240            0 :       const ending = engine.lastEnding
     241            0 :       tourWasCompleted.value =
     242              :         ending?.tour === 'firstRun' && ending.outcome === 'completed'
     243            0 :       nudgeArmed.value = true
     244            0 :       stopOfflineGrace()
     245            0 :       stopAcceptDeadline()
     246            0 :       releaseFirstRunTargets()
     247            0 :       tourWorkflow.value = null
     248            0 :       runState.value = 'idle'
     249              :     }
     250              :   )
     251              : 
     252            0 :   function dismissNudge() {
     253            0 :     nudgeArmed.value = false
     254              :   }
     255              : 
     256            0 :   function ownsTourStart(ownership: symbol): boolean {
     257            0 :     return tourStart.phase !== 'idle' && tourStart.ownership === ownership
     258              :   }
     259              : 
     260            0 :   function releaseTourStart(ownership: symbol): void {
     261            0 :     if (ownsTourStart(ownership)) tourStart = { phase: 'idle' }
     262              :   }
     263              : 
     264            0 :   async function writeRenderer(
     265              :     ownership: symbol,
     266              :     enabled: boolean,
     267              :     restoreRenderer: boolean
     268              :   ): Promise<void> {
     269            0 :     const write = settingStore.set('Comfy.VueNodes.Enabled', enabled)
     270            0 :     const writingState: TourStartState = {
     271              :       phase: 'writingRenderer',
     272              :       ownership,
     273              :       restoreRenderer,
     274              :       write
     275              :     }
     276            0 :     tourStart = writingState
     277            0 :     try {
     278            0 :       await write
     279              :     } finally {
     280            0 :       if (tourStart === writingState) {
     281            0 :         tourStart = { phase: 'claimed', ownership, restoreRenderer }
     282              :       }
     283              :     }
     284              :   }
     285              : 
     286            0 :   async function cleanUpFailedTourStart(
     287              :     ownership: symbol,
     288              :     shouldCancel: () => boolean
     289              :   ) {
     290            0 :     const currentStart = tourStart
     291            0 :     if (currentStart.phase === 'idle' || currentStart.ownership !== ownership)
     292            0 :       return
     293            0 :     releaseFirstRunTargets()
     294            0 :     tourWorkflow.value = null
     295            0 :     const { restoreRenderer } = currentStart
     296            0 :     if (restoreRenderer && shouldCancel()) return
     297            0 :     if (restoreRenderer) await writeRenderer(ownership, false, restoreRenderer)
     298            0 :     releaseTourStart(ownership)
     299              :   }
     300              : 
     301            0 :   function canBeginTour(shouldCancel: () => boolean): boolean {
     302            0 :     return !shouldCancel() && !engine.activeTour && canvasContextHolds.value
     303              :   }
     304              : 
     305            0 :   async function claimTourStart(ownership: symbol): Promise<boolean> {
     306            0 :     const previousStart = tourStart
     307            0 :     const restoreRenderer =
     308              :       previousStart.phase === 'idle'
     309              :         ? !settingStore.get('Comfy.VueNodes.Enabled')
     310              :         : previousStart.restoreRenderer
     311              : 
     312            0 :     if (previousStart.phase === 'writingRenderer') {
     313            0 :       tourStart = { ...previousStart, ownership }
     314            0 :       await previousStart.write.catch(() => undefined)
     315            0 :       if (ownsTourStart(ownership))
     316            0 :         tourStart = { phase: 'claimed', ownership, restoreRenderer }
     317              :     } else {
     318            0 :       tourStart = { phase: 'claimed', ownership, restoreRenderer }
     319              :     }
     320            0 :     return restoreRenderer
     321              :   }
     322              : 
     323            0 :   async function claimRendererForTour(ownership: symbol): Promise<boolean> {
     324            0 :     const restoreRenderer = await claimTourStart(ownership)
     325            0 :     if (!ownsTourStart(ownership)) return restoreRenderer
     326            0 :     if (restoreRenderer && !settingStore.get('Comfy.VueNodes.Enabled'))
     327            0 :       await writeRenderer(ownership, true, restoreRenderer)
     328            0 :     return restoreRenderer
     329              :   }
     330              : 
     331            1 :   async function cancelPendingStart(): Promise<void> {
     332              :     const previousStart = tourStart
     333            1 :     if (previousStart.phase === 'idle') return
     334            0 :     const ownership = Symbol('cancelled-first-run-tour-start')
     335            1 :     try {
     336            0 :       const restoreRenderer = await claimTourStart(ownership)
     337            1 :       if (
     338              :         ownsTourStart(ownership) &&
     339              :         restoreRenderer &&
     340              :         settingStore.get('Comfy.VueNodes.Enabled')
     341              :       )
     342            0 :         await writeRenderer(ownership, false, restoreRenderer)
     343              :     } finally {
     344            0 :       releaseTourStart(ownership)
     345              :     }
     346              :   }
     347              : 
     348              :   /** False when there is no tour to give; any renderer switch is undone. */
     349            0 :   async function beginTour(
     350              :     templateId?: string,
     351              :     shouldCancel: () => boolean = () => false
     352              :   ): Promise<boolean> {
     353            0 :     const ownership = Symbol('first-run-tour-start')
     354              :     // Holds only ever end a tour that is already running, and only when they
     355              :     // change — a context lost before the tour opens (`?template=X&mode=linear`
     356              :     // boots straight into linear mode) never produces that change. Refused
     357              :     // here, ahead of the renderer switch below, so nothing is left to undo.
     358            0 :     if (!canBeginTour(shouldCancel)) return false
     359              : 
     360            0 :     const restoreRenderer = await claimRendererForTour(ownership)
     361            0 :     if (!ownsTourStart(ownership) || shouldCancel()) return false
     362              : 
     363            0 :     tourStart = { phase: 'previewing', ownership, restoreRenderer }
     364            0 :     tourWorkflow.value = workflowStore.activeWorkflow ?? null
     365            0 :     runState.value = 'idle'
     366            0 :     nudgeArmed.value = false
     367            0 :     registerTour(
     368              :       'firstRun',
     369              :       () => firstRunTourSteps(templateId, runState),
     370              :       tourContextHolds
     371              :     )
     372            0 :     await delay(INTRO_PREVIEW_MS)
     373              :     // The preview is long enough for the canvas to go away underneath it, and
     374              :     // the holds watcher cannot catch that: there is no active tour to end yet.
     375            0 :     const contextStillHolds = (): boolean => canvasContextHolds.value
     376            0 :     const started =
     377              :       ownsTourStart(ownership) &&
     378              :       contextStillHolds() &&
     379              :       !shouldCancel() &&
     380              :       (await engine.startTour('firstRun'))
     381            0 :     if (!started) {
     382            0 :       await cleanUpFailedTourStart(ownership, shouldCancel)
     383            0 :     } else releaseTourStart(ownership)
     384            0 :     return started
     385              :   }
     386              : 
     387         2355 :   return {
     388              :     beginTour,
     389              :     cancelPendingStart,
     390              :     nudgeArmed: readonly(nudgeArmed),
     391              :     tourWasCompleted: readonly(tourWasCompleted),
     392              :     dismissNudge
     393              :   }
     394              : }
     395              : 
     396         2355 : export const useFirstRunTourController = createSharedComposable(
     397              :   useFirstRunTourControllerInternal
     398              : )
        

Generated by: LCOV version 2.0-1