LCOV - code coverage report
Current view: top level - src/platform/workflow/management/stores - comfyWorkflow.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 89.0 % 100 89
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { markRaw } from 'vue'
       2              : 
       3              : import { assert } from '@/base/assert'
       4              : import type { ExecutedWsMessage } from '@comfyorg/api-client/executionTypes'
       5              : import { UserFile } from '@/stores/userFileStore'
       6              : import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema'
       7              : import type { MissingModelCandidate } from '@/platform/workflowErrors/missingModel/types'
       8              : import type { MissingMediaCandidate } from '@/platform/workflowErrors/missingMedia/types'
       9              : import type { MissingNodeType } from '@/platform/workflowErrors/nodeReplacement/types'
      10              : import type { NodeLocatorId } from '@comfyorg/graph-model/nodeIdentification'
      11              : import type { SerializedNodeId } from '@comfyorg/graph-model/nodeId'
      12              : import type { AppMode } from '@comfyorg/graph-model/appMode'
      13              : import type { WidgetId } from '@comfyorg/graph-model/widgetId'
      14              : import { generateUUID } from '@/utils/formatUtil'
      15              : 
      16              : export interface InputWidgetConfig {
      17              :   height?: number
      18              :   description?: string
      19              : }
      20              : 
      21              : type LinearInputId = WidgetId | NodeLocatorId | SerializedNodeId
      22              : type LinearOutputNodeId = SerializedNodeId
      23              : export type LinearInput = [LinearInputId, string, InputWidgetConfig?]
      24              : 
      25              : export interface LinearData {
      26              :   inputs: LinearInput[]
      27              :   outputs: LinearOutputNodeId[]
      28              : }
      29              : 
      30              : export interface PendingWarnings {
      31              :   missingNodeTypes?: MissingNodeType[]
      32              :   missingModelCandidates?: MissingModelCandidate[]
      33              :   missingMediaCandidates?: MissingMediaCandidate[]
      34              : }
      35              : 
      36              : /**
      37              :  * Undo/redo history of a loaded workflow. Implemented by
      38              :  * `ChangeTracker` in `@/scripts/changeTracker`; declared here so the
      39              :  * workflow model stays independent of the canvas runtime.
      40              :  */
      41              : export interface WorkflowChangeTracker {
      42              :   workflow: ComfyWorkflow
      43              :   initialState: ComfyWorkflowJSON
      44              :   activeState: ComfyWorkflowJSON
      45              :   undoQueue: ComfyWorkflowJSON[]
      46              :   redoQueue: ComfyWorkflowJSON[]
      47              :   changeCount: number
      48              :   _restoringState: boolean
      49              :   ds?: { scale: number; offset: [number, number] }
      50              :   nodeOutputs?: Partial<Record<string, ExecutedWsMessage['output']>>
      51              :   reset(state?: ComfyWorkflowJSON): void
      52              :   store(): void
      53              :   deactivate(): void
      54              :   prepareForSave(): void
      55              :   restore(): void
      56              :   updateModified(previousState?: ComfyWorkflowJSON): void
      57              :   captureCanvasState(): void
      58              :   markModified(): void
      59              :   checkState(): void
      60              :   updateState(
      61              :     source: ComfyWorkflowJSON[],
      62              :     target: ComfyWorkflowJSON[]
      63              :   ): Promise<void>
      64              :   undo(): Promise<void>
      65              :   redo(): Promise<void>
      66              :   undoRedo(e: KeyboardEvent, selectOnly?: boolean): Promise<true | undefined>
      67              :   beforeChange(): void
      68              :   afterChange(): void
      69              : }
      70              : 
      71              : interface WorkflowDraft {
      72              :   data: string
      73              :   updatedAt: number
      74              : }
      75              : 
      76              : /**
      77              :  * Runtime services a workflow needs while loading and saving. Registered by
      78              :  * the workflow store so this module does not depend on the change tracker,
      79              :  * draft persistence, or settings.
      80              :  */
      81              : export interface WorkflowRuntime {
      82              :   createChangeTracker(
      83              :     workflow: ComfyWorkflow,
      84              :     initialState: ComfyWorkflowJSON
      85              :   ): WorkflowChangeTracker
      86              :   /** `ChangeTracker.graphEqual`: the comparison that decides unsaved changes. */
      87              :   graphEqual(a: ComfyWorkflowJSON, b: ComfyWorkflowJSON): boolean
      88              :   getDraft(path: string): WorkflowDraft | null
      89              :   removeDraft(path: string): void
      90              :   markDraftUsed(path: string): void
      91              :   isDraftPersistenceEnabled(): boolean
      92              :   promptSave(workflow: ComfyWorkflow): Promise<string | null>
      93              :   forgetNodeHistories(rootGraphId: string): void
      94              : }
      95              : 
      96         2356 : let registeredRuntime: WorkflowRuntime | null = null
      97              : 
      98         2356 : export function registerWorkflowRuntime(runtime: WorkflowRuntime): void {
      99         2356 :   registeredRuntime = runtime
     100              : }
     101              : 
     102       266863 : function workflowRuntime(): WorkflowRuntime {
     103       266863 :   assert(
     104              :     registeredRuntime,
     105              :     'Workflow runtime not registered; import the workflow store first'
     106              :   )
     107       266863 :   return registeredRuntime
     108              : }
     109              : 
     110              : /**
     111              :  * Coarse shape of a workflow file's stored text. Never includes the content.
     112              :  * - `unavailable`: the text was never loaded (`null` / `undefined`)
     113              :  * - `empty`: only whitespace
     114              :  * - `null`: parses to JSON `null`
     115              :  * - `object`: parses to a plain JSON object (the healthy case)
     116              :  * - `other`: parses to an array, string, number or boolean
     117              :  * - `unparseable`: not valid JSON
     118              :  */
     119              : export type OriginalContentKind =
     120              :   | 'unavailable'
     121              :   | 'empty'
     122              :   | 'null'
     123              :   | 'object'
     124              :   | 'other'
     125              :   | 'unparseable'
     126              : 
     127            3 : export function classifyWorkflowContent(
     128              :   content: string | null | undefined
     129              : ): OriginalContentKind {
     130            3 :   if (content == null) return 'unavailable'
     131            3 :   if (content.trim().length === 0) return 'empty'
     132            3 :   let parsed: unknown
     133            3 :   try {
     134            3 :     parsed = JSON.parse(content)
     135              :   } catch {
     136            1 :     return 'unparseable'
     137              :   }
     138            2 :   if (parsed === null) return 'null'
     139            3 :   if (typeof parsed === 'object' && !Array.isArray(parsed)) return 'object'
     140            0 :   return 'other'
     141              : }
     142              : 
     143              : /** The slice of a `ComfyWorkflow` that is safe to describe in telemetry. */
     144              : interface WorkflowStateProbe {
     145              :   path: string
     146              :   isLoaded: boolean
     147              :   isPersisted: boolean
     148              :   isTemporary: boolean
     149              :   changeTracker: unknown
     150              :   initialState: unknown
     151              :   activeState: unknown
     152              :   originalContent: string | null
     153              : }
     154              : 
     155         2356 : const reportedAnomalies = new Set<string>()
     156              : 
     157              : /** @internal Test-only: forgets which anomalies were already reported. */
     158              : export function resetReportedWorkflowStateAnomaliesForTests(): void {
     159              :   reportedAnomalies.clear()
     160              : }
     161              : 
     162              : /**
     163              :  * Reports a workflow whose in-memory state was not what the caller assumed
     164              :  * (for example an active workflow with no change tracker). Each call site
     165              :  * recovers locally; this only makes the occurrence visible so the real trigger
     166              :  * can be found.
     167              :  *
     168              :  * `message` must be a static description: reporters forward it to telemetry
     169              :  * and group on it. Diagnostic values go in the context, which carries only
     170              :  * booleans and enum-like strings and never workflow names, paths or content.
     171              :  * Reports are deduplicated per call site and workflow.
     172              :  *
     173              :  * @param method Stable name of the call site, e.g. `ComfyWorkflow.save`.
     174              :  * @param workflow The workflow involved, when there is one.
     175              :  * @param extra Further booleans/enums, e.g. `{ isActive: true }`.
     176              :  */
     177            3 : export function reportWorkflowStateAnomaly(
     178              :   message: string,
     179              :   method: string,
     180              :   workflow?: WorkflowStateProbe,
     181              :   extra: Record<string, boolean | number | string | undefined> = {}
     182              : ): void {
     183            3 :   const key = `${method}:${workflow?.path ?? ''}`
     184            3 :   if (reportedAnomalies.has(key)) return
     185            3 :   reportedAnomalies.add(key)
     186              : 
     187            3 :   assert(false, message, {
     188              :     method,
     189              :     ...(workflow && {
     190              :       isLoaded: workflow.isLoaded,
     191              :       hasChangeTracker: workflow.changeTracker != null,
     192              :       hasInitialState: workflow.initialState != null,
     193              :       hasActiveState: workflow.activeState != null,
     194              :       isPersisted: workflow.isPersisted,
     195              :       isTemporary: workflow.isTemporary,
     196              :       originalContentKind: classifyWorkflowContent(workflow.originalContent)
     197              :     }),
     198              :     ...extra
     199              :   })
     200              : }
     201              : 
     202              : /**
     203              :  * The saved draft to overlay on a freshly loaded workflow, if there is a usable
     204              :  * one. A stale or unparseable draft is removed.
     205              :  */
     206       266495 : function readUsableDraft(
     207              :   runtime: WorkflowRuntime,
     208              :   workflow: ComfyWorkflow
     209              : ): { state: ComfyWorkflowJSON; content: string } | null {
     210       266495 :   const draft = runtime.getDraft(workflow.path)
     211       266495 :   if (!draft) return null
     212         3907 :   if (draft.updatedAt < workflow.lastModified) {
     213           71 :     runtime.removeDraft(workflow.path)
     214           71 :     return null
     215              :   }
     216         3836 :   try {
     217           39 :     return { state: JSON.parse(draft.data), content: draft.data }
     218              :   } catch (err) {
     219            0 :     console.warn('Failed to parse workflow draft, clearing it', err)
     220            0 :     runtime.removeDraft(workflow.path)
     221            0 :     return null
     222              :   }
     223              : }
     224              : 
     225           38 : function draftMatchesSavedFile(
     226              :   runtime: WorkflowRuntime,
     227              :   saved: ComfyWorkflowJSON,
     228              :   draft: ComfyWorkflowJSON
     229              : ): boolean {
     230           38 :   return (
     231              :     Array.isArray(saved.nodes) &&
     232              :     Array.isArray(draft.nodes) &&
     233              :     runtime.graphEqual(saved, draft)
     234              :   )
     235              : }
     236              : 
     237              : /**
     238              :  * Stored workflow content is empty, not valid JSON, or not a JSON object, so it
     239              :  * can never open. The message is static; the path is on `workflowPath`.
     240              :  */
     241         2356 : export class UnreadableWorkflowError extends Error {
     242              :   override readonly name = 'UnreadableWorkflowError'
     243              : 
     244              :   constructor(
     245            3 :     readonly reason: 'empty' | 'unparseable' | 'not-object',
     246            3 :     readonly workflowPath: string
     247              :   ) {
     248            3 :     super(UNREADABLE_WORKFLOW_MESSAGES[reason])
     249              :   }
     250              : }
     251              : 
     252         2356 : const UNREADABLE_WORKFLOW_MESSAGES: Record<
     253              :   UnreadableWorkflowError['reason'],
     254              :   string
     255              : > = {
     256              :   empty: 'Workflow content is missing or empty',
     257              :   unparseable: 'Workflow content is not valid JSON',
     258              :   'not-object': 'Workflow content is not a JSON object'
     259              : }
     260              : 
     261       266608 : function parseStoredWorkflow(workflow: ComfyWorkflow): ComfyWorkflowJSON {
     262       266608 :   const content = workflow.originalContent
     263       266608 :   const parsed = content?.trim() ? parseContent(content, workflow) : undefined
     264       266608 :   if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
     265       266605 :     return parsed as ComfyWorkflowJSON
     266              :   }
     267       266608 :   throw unreadable(parsed === undefined ? 'empty' : 'not-object', workflow)
     268              : }
     269              : 
     270       266608 : function parseContent(content: string, workflow: ComfyWorkflow): unknown {
     271       266608 :   try {
     272       266608 :     return JSON.parse(content)
     273              :   } catch {
     274            1 :     throw unreadable('unparseable', workflow)
     275              :   }
     276              : }
     277              : 
     278            3 : function unreadable(
     279              :   reason: UnreadableWorkflowError['reason'],
     280              :   workflow: ComfyWorkflow
     281              : ): UnreadableWorkflowError {
     282            3 :   const error = new UnreadableWorkflowError(reason, workflow.path)
     283            3 :   reportUnreadableContent(error, workflow)
     284            3 :   return error
     285              : }
     286              : 
     287            3 : function reportUnreadableContent(
     288              :   error: UnreadableWorkflowError,
     289              :   workflow: ComfyWorkflow
     290              : ): void {
     291            3 :   try {
     292            3 :     reportWorkflowStateAnomaly(error.message, 'ComfyWorkflow.load', workflow)
     293              :   } catch (devAssertion) {
     294            0 :     console.warn('Unreadable stored workflow', devAssertion)
     295              :   }
     296              : }
     297              : 
     298              : /** i18n keys for the dialog shown when a workflow is saved without a name. */
     299              : export interface SaveNamePrompt {
     300              :   title: string
     301              :   message: string
     302              : }
     303              : 
     304              : /**
     305              :  * The serialized state to persist. An unloaded workflow has no state, and
     306              :  * `JSON.stringify(null)` would overwrite the stored file with `null`.
     307              :  */
     308          122 : function requireActiveStateForSave(
     309              :   workflow: ComfyWorkflow,
     310              :   method: string
     311              : ): ComfyWorkflowJSON {
     312          122 :   const state = workflow.activeState
     313          122 :   if (state) return state
     314            0 :   reportWorkflowStateAnomaly(
     315              :     'Workflow saved without an active state',
     316              :     method,
     317              :     workflow
     318              :   )
     319            0 :   throw new Error('Cannot save a workflow before it is loaded')
     320              : }
     321              : 
     322         2356 : export class ComfyWorkflow extends UserFile {
     323              :   static readonly basePath: string = 'workflows/'
     324              :   readonly tintCanvasBg?: string
     325              :   /** Unique, stable identity for this workflow instance in the current session. */
     326              :   readonly instanceId = generateUUID()
     327              : 
     328              :   /**
     329              :    * The change tracker for the workflow. Non-reactive raw object.
     330              :    */
     331              :   changeTracker: WorkflowChangeTracker | null = null
     332              :   /**
     333              :    * Whether the workflow has been modified comparing to the initial state.
     334              :    */
     335              :   _isModified: boolean = false
     336              :   /**
     337              :    * Warnings deferred from load time, shown when the workflow is first focused.
     338              :    */
     339              :   pendingWarnings: PendingWarnings | null = null
     340              :   /**
     341              :    * Initial app mode derived from the serialized workflow (extra.linearMode).
     342              :    * - `undefined`: not yet resolved (first load hasn't happened)
     343              :    * - `null`: resolved, but no mode was set (never builder-saved)
     344              :    * - `AppMode`: resolved to a specific mode
     345              :    */
     346              :   initialMode: AppMode | null | undefined = undefined
     347              :   /**
     348              :    * Current app mode set by the user during the session.
     349              :    * Takes precedence over initialMode when present.
     350              :    */
     351              :   activeMode: AppMode | null = null
     352              :   shareId?: string
     353              :   legacyId?: string
     354              :   readonly saveNamePrompt: SaveNamePrompt = {
     355              :     title: 'workflowService.saveWorkflow',
     356              :     message: 'workflowService.enterFilenamePrompt'
     357              :   }
     358              :   /**
     359              :    * @param options The path, modified, and size of the workflow.
     360              :    * Note: path is the full path, including the 'workflows/' prefix.
     361              :    */
     362              :   constructor(options: { path: string; modified: number; size: number }) {
     363       268681 :     super(options.path, options.modified, options.size)
     364              :   }
     365              : 
     366              :   override get key() {
     367        21693 :     return this.path.substring(ComfyWorkflow.basePath.length)
     368              :   }
     369              : 
     370              :   get activeState(): ComfyWorkflowJSON | null {
     371       265725 :     return this.changeTracker?.activeState ?? null
     372              :   }
     373              : 
     374              :   get initialState(): ComfyWorkflowJSON | null {
     375      1030756 :     return this.changeTracker?.initialState ?? null
     376              :   }
     377              : 
     378              :   override get isLoaded(): boolean {
     379       530358 :     return this.changeTracker !== null
     380              :   }
     381              : 
     382              :   override get isModified(): boolean {
     383         7069 :     return this._isModified
     384              :   }
     385              : 
     386              :   override set isModified(value: boolean) {
     387         1735 :     this._isModified = value
     388              :   }
     389              : 
     390              :   /**
     391              :    * Load the workflow content from remote storage. Directly returns the loaded
     392              :    * workflow if the content is already loaded.
     393              :    *
     394              :    * @param force Whether to force loading the content even if it is already loaded.
     395              :    * @returns this
     396              :    */
     397              :   override async load({ force = false }: { force?: boolean } = {}): Promise<
     398              :     this & LoadedComfyWorkflow
     399              :   > {
     400       266787 :     if (!force && this.isLoaded && this.changeTracker) {
     401          165 :       return this as this & LoadedComfyWorkflow
     402              :     }
     403              : 
     404       266622 :     const runtime = workflowRuntime()
     405       266787 :     const draft =
     406              :       !force && runtime.isDraftPersistenceEnabled()
     407              :         ? readUsableDraft(runtime, this)
     408              :         : null
     409              : 
     410       266787 :     await super.load({ force })
     411              : 
     412       266608 :     const initialState = parseStoredWorkflow(this)
     413       266608 :     this.changeTracker = markRaw(
     414              :       runtime.createChangeTracker(this, initialState)
     415              :     )
     416       266787 :     if (draft?.state && draft.content) {
     417           38 :       this.changeTracker.activeState = draft.state
     418           38 :       this.content = draft.content
     419           38 :       this._isModified = !draftMatchesSavedFile(
     420              :         runtime,
     421              :         initialState,
     422              :         draft.state
     423              :       )
     424           38 :       runtime.markDraftUsed(this.path)
     425              :     }
     426       266605 :     return this as this & LoadedComfyWorkflow
     427              :   }
     428              : 
     429              :   override unload(): void {
     430           31 :     const rootGraphId = this.changeTracker?.activeState.id
     431           31 :     if (rootGraphId) workflowRuntime().forgetNodeHistories(rootGraphId)
     432           31 :     this.changeTracker = null
     433           31 :     this.activeMode = null
     434           31 :     super.unload()
     435              :   }
     436              : 
     437              :   override async save() {
     438          122 :     this.content = JSON.stringify(
     439              :       requireActiveStateForSave(this, 'ComfyWorkflow.save')
     440              :     )
     441              :     // Force save to ensure the content is updated in remote storage incase
     442              :     // the isModified state is screwed by changeTracker.
     443          122 :     const ret = await super.save({ force: true })
     444          122 :     this.changeTracker?.reset()
     445          122 :     this.isModified = false
     446          122 :     workflowRuntime().removeDraft(this.path)
     447          122 :     return ret
     448              :   }
     449              : 
     450              :   /**
     451              :    * Save the workflow as a new file.
     452              :    * @param path The path to save the workflow to. Note: with 'workflows/' prefix.
     453              :    * @returns this
     454              :    */
     455              :   override async saveAs(path: string) {
     456            0 :     this.content = JSON.stringify(
     457              :       requireActiveStateForSave(this, 'ComfyWorkflow.saveAs')
     458              :     )
     459            0 :     const result = await super.saveAs(path)
     460            0 :     workflowRuntime().removeDraft(path)
     461            0 :     return result
     462              :   }
     463              : 
     464              :   async promptSave(): Promise<string | null> {
     465           95 :     return workflowRuntime().promptSave(this)
     466              :   }
     467              : }
     468              : 
     469              : export interface LoadedComfyWorkflow extends ComfyWorkflow {
     470              :   isLoaded: true
     471              :   originalContent: string
     472              :   content: string
     473              :   changeTracker: WorkflowChangeTracker
     474              :   initialState: ComfyWorkflowJSON
     475              :   activeState: ComfyWorkflowJSON
     476              : }
        

Generated by: LCOV version 2.0-1