diff --git a/docs/adr/WORKFLOW-LINKS-0053-open-workflow-links-through-the-sidebar-file.md b/docs/adr/WORKFLOW-LINKS-0053-open-workflow-links-through-the-sidebar-file.md index af3b47f6eaa..8177166c7f0 100644 --- a/docs/adr/WORKFLOW-LINKS-0053-open-workflow-links-through-the-sidebar-file.md +++ b/docs/adr/WORKFLOW-LINKS-0053-open-workflow-links-through-the-sidebar-file.md @@ -50,8 +50,12 @@ older stashed link rather than clearing the stash: an older link cannot keep the empty one from being rejected as invalid, and while a guard holds the empty link, an earlier lookup still sees a newer link in flight and its cleanup cannot cancel that navigation. While the stash holds a link the loader never -started and the URL does not show, the sweep makes no replace either, so that -link's navigation is not cancelled. +started and the URL does not show, no URL action after the workflow-id link +runs, the sweep included: any replace would cancel that link's navigation. The +actions before it still run, since at boot the stash can hold a link the +loader has not reached yet. A load the link no longer owns, such as one still +waiting on an extension hook when the next link arrives, stops before the graph +is configured and again before the workflow is activated. The reply and the 409 body are validated with the generated `@comfyorg/ingest-types` schemas. The spec types the 409 as `ErrorResponse` and @@ -64,7 +68,8 @@ failing error's class name when it is a built-in JavaScript error class, or `other` for any other name or a name that cannot be read. They never carry the caught error, its message or a name it chose: a failed file read names the file, a parser error quotes the reply, and custom node code that runs while the -workflow loads can throw an error under any name. +workflow loads can throw an error under any name. The workflow service leaves +a failed link open to the loader's report and does not report it itself. ## Alternatives considered diff --git a/src/composables/useUrlActionLoaders.test.ts b/src/composables/useUrlActionLoaders.test.ts index 8d5182f784a..cc026fd23fb 100644 --- a/src/composables/useUrlActionLoaders.test.ts +++ b/src/composables/useUrlActionLoaders.test.ts @@ -516,7 +516,7 @@ describe('useUrlActionLoaders', () => { ).toHaveBeenCalledOnce() }) - it('lets a newer workflow-id link held in a navigation guard land instead of cancelling it', async () => { + it('runs only the loaders before the workflow-id link while a newer one waits in a navigation guard, so it lands', async () => { await router.replace({ query: { workflowId: 'workflow-a', topup: '1' } }) workflowLinkUrlLoader.openWorkflowLinkFromUrl.mockResolvedValue('opened') workflowLinkUrlLoader.isLinkSettled.mockImplementation( @@ -536,7 +536,8 @@ describe('useUrlActionLoaders', () => { releaseGuard() await newerLink - expect(mocks.loadTopUp).toHaveBeenCalledOnce() + expect(mocks.loadWorkspace).toHaveBeenCalledOnce() + expect(mocks.loadTopUp).not.toHaveBeenCalled() expect(router.currentRoute.value.query).toEqual({ workflowId: 'workflow-b' }) diff --git a/src/composables/useUrlActionLoaders.ts b/src/composables/useUrlActionLoaders.ts index 84539e4f5a5..8eb492a03b8 100644 --- a/src/composables/useUrlActionLoaders.ts +++ b/src/composables/useUrlActionLoaders.ts @@ -133,7 +133,6 @@ function sweepStep( return { failureMessage: 'Failed to clear handled deep-link params from the URL:', run: async () => { - if (loader?.hasLinkInFlight()) return clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.WORKFLOWS) const query = { ...router.currentRoute.value.query } const params = [ @@ -147,6 +146,16 @@ function sweepStep( } } +function unlessLinkInFlight( + loader: UrlActionLoaders['workflowLinkUrlLoader'], + steps: UrlActionStep[] +): UrlActionStep[] { + return steps.map(({ failureMessage, run }) => ({ + failureMessage, + run: () => (loader?.hasLinkInFlight() ? undefined : run()) + })) +} + /** * Orders the deep-link loaders: the deployment link first, since with * `?deployment` it owns `?workspace` too (it switches, then picks after the @@ -169,58 +178,59 @@ function buildUrlActionSteps( }) } steps.push(...workflowLinkSteps(loaders.workflowLinkUrlLoader)) + const laterSteps: UrlActionStep[] = [] if (loaders.inviteUrlLoader) { const loader = loaders.inviteUrlLoader - steps.push({ + laterSteps.push({ failureMessage: 'Failed to load invite from URL:', run: () => loader.loadInviteFromUrl() }) } if (loaders.createWorkspaceUrlLoader) { const loader = loaders.createWorkspaceUrlLoader - steps.push({ + laterSteps.push({ failureMessage: 'Failed to load create workspace from URL:', run: () => loader.loadCreateWorkspaceFromUrl() }) } if (loaders.pricingTableUrlLoader) { const loader = loaders.pricingTableUrlLoader - steps.push({ + laterSteps.push({ failureMessage: 'Failed to load pricing table from URL:', run: () => loader.loadPricingTableFromUrl() }) } - // Not gated on the team-workspaces flag: it also drives personal/legacy users. if (loaders.topUpUrlLoader) { const loader = loaders.topUpUrlLoader - steps.push({ + laterSteps.push({ failureMessage: 'Failed to load top-up dialog from URL:', run: () => loader.loadTopUpFromUrl() }) } if (loaders.settingsUrlLoader) { const loader = loaders.settingsUrlLoader - steps.push({ + laterSteps.push({ failureMessage: 'Failed to load settings panel from URL:', run: () => loader.loadSettingsFromUrl() }) } if (loaders.assetsUrlLoader) { const loader = loaders.assetsUrlLoader - steps.push({ + laterSteps.push({ failureMessage: 'Failed to open assets panel from URL:', run: () => loader.loadAssetsFromUrl() }) } if (loaders.localHandoffUrlLoader) { const loader = loaders.localHandoffUrlLoader - steps.push({ + laterSteps.push({ failureMessage: 'Failed to open the workflow handed over from local:', run: () => loader.loadLocalHandoffFromUrl() }) } - steps.push(sweepStep(loaders.workflowLinkUrlLoader, router)) + laterSteps.push(sweepStep(loaders.workflowLinkUrlLoader, router)) + steps.push(...unlessLinkInFlight(loaders.workflowLinkUrlLoader, laterSteps)) return steps } diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index ef6081e1873..b8d8bd6f534 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -786,6 +786,44 @@ describe('useWorkflowService', () => { expect(loading.isLoaded).toBe(false) }) + it('drops a fetched workflow and keeps the current one when the graph load sees the open superseded', async () => { + const workflows = useWorkflowStore() + const current = createModeTestWorkflow({ path: 'workflows/current.json' }) + const loading = createModeTestWorkflow({ + path: 'workflows/closed.json', + loaded: false + }) + workflows.activeWorkflow = current + vi.spyOn(loading, 'load').mockImplementation(async () => { + loading.originalContent = '{}' + loading.content = '{}' + loading.changeTracker = createMockChangeTracker() + return loading + }) + let currentRequest = true + vi.mocked(app.loadGraphData).mockImplementationOnce( + async (_data, _clean, _restoreView, _workflow, options) => { + currentRequest = false + return options?.isCurrent?.() !== false + } + ) + + const opened = await useWorkflowService().openWorkflow(loading, { + isCurrent: () => currentRequest + }) + + expect(opened).toBe(false) + expect(loading.isLoaded).toBe(false) + expect(workflows.activeWorkflow.path).toBe(current.path) + expect(app.loadGraphData).toHaveBeenLastCalledWith( + expect.anything(), + true, + true, + current, + expect.anything() + ) + }) + it('leaves a saved workflow clean after a superseded load applied its draft', async () => { const workflows = useWorkflowStore() const current = createModeTestWorkflow({ path: 'workflows/current.json' }) diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index 75843a6db4e..083dd72cc37 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -204,17 +204,20 @@ export function resetWorkflowLoadQueueForTests(): { function queueWorkflowLoad( load: () => Promise, - workflowPath?: string + { + workflowPath, + reportFailure = true + }: { workflowPath?: string; reportFailure?: boolean } = {} ): Promise { pendingWorkflowLoads++ const result = workflowLoadTail.then(load) const settledResult = result .catch((error) => { - // Keep fire-and-forget load failures observable. - reportError(error, { - surface: 'graph', - errorType: 'workflow_load_failure' - }) + if (reportFailure) + reportError(error, { + surface: 'graph', + errorType: 'workflow_load_failure' + }) return undefined }) .finally(() => { @@ -233,6 +236,36 @@ function queueWorkflowLoad( return result } +function loadWorkflowGraph( + workflow: ComfyWorkflow, + navigationIntentId: number, + loadFromRemote: boolean, + options: { + force?: boolean + isCurrent?: () => boolean + keepSavedBaseline?: boolean + } +) { + workflow.changeTracker?.prepareForSave() + const load = () => + useApp().loadGraphData( + toRaw(workflow.activeState) as ComfyWorkflowJSON, + true, + true, + workflow, + { + checkForRerouteMigration: false, + deferWarnings: true, + skipAssetScans: !loadFromRemote && !options.force, + workflowNavigationId: navigationIntentId, + isCurrent: options.isCurrent + } + ) + return options.keepSavedBaseline && workflow.isModified + ? keepingSavedBaseline(workflow, load) + : load() +} + const unreadableWorkflowToastIds = new Map() const unreadableWorkflows = new WeakSet() @@ -551,6 +584,7 @@ export const useWorkflowService = () => { isCurrent?: () => boolean initiator?: 'user' keepSavedBaseline?: boolean + reportLoadFailure?: boolean } = {} ): Promise => { if (options.isCurrent?.() === false) return Promise.resolve(false) @@ -569,6 +603,10 @@ export const useWorkflowService = () => { const navigationIntentId = options.navigationIntentId ?? useSubgraphNavigationStore().beginWorkflowNavigation() + const queueOptions = { + workflowPath: workflow.path, + reportFailure: options.reportLoadFailure !== false + } return queueWorkflowLoad(async () => { let wasUnreadable = false try { @@ -588,27 +626,17 @@ export const useWorkflowService = () => { return false } - workflow.changeTracker?.prepareForSave() - const load = () => - useApp().loadGraphData( - toRaw(workflow.activeState) as ComfyWorkflowJSON, - true, - true, - workflow, - { - checkForRerouteMigration: false, - deferWarnings: true, - skipAssetScans: !loadFromRemote && !options.force, - workflowNavigationId: navigationIntentId - } - ) - const loaded = - options.keepSavedBaseline && workflow.isModified - ? await keepingSavedBaseline(workflow, load) - : await load() + const loaded = await loadWorkflowGraph( + workflow, + navigationIntentId, + loadFromRemote, + options + ) if (loaded === false) { useSubgraphNavigationStore().endWorkflowNavigation(navigationIntentId) await restoreRetainedWorkflow(workflow) + if (loadFromRemote && options.isCurrent?.() === false) + discardSupersededLoad(workflow, wasModified) return false } dismissUnreadableWorkflowToast(workflow) @@ -629,7 +657,7 @@ export const useWorkflowService = () => { if (wasUnreadable && !isUnreadableWorkflow(workflow)) dismissUnreadableWorkflowToast(workflow) } - }, workflow.path) + }, queueOptions) } const markUnreadable = (workflow: ComfyWorkflow) => { @@ -802,14 +830,17 @@ export const useWorkflowService = () => { const loadWorkflowInBackground = ( workflow: ComfyWorkflow ): Promise => - queueWorkflowLoad(async () => { - const loaded: ComfyWorkflow = await workflow.load() - if (loaded.initialMode === undefined) - loaded.initialMode = - linearModeToAppMode(loaded.initialState?.extra?.linearMode) ?? - linearModeToAppMode(loaded.activeState?.extra?.linearMode) - return loaded - }, workflow.path) + queueWorkflowLoad( + async () => { + const loaded: ComfyWorkflow = await workflow.load() + if (loaded.initialMode === undefined) + loaded.initialMode = + linearModeToAppMode(loaded.initialState?.extra?.linearMode) ?? + linearModeToAppMode(loaded.activeState?.extra?.linearMode) + return loaded + }, + { workflowPath: workflow.path } + ) const renameWorkflow = async (workflow: ComfyWorkflow, newPath: string) => { const oldPath = workflow.path diff --git a/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.fileRead.test.ts b/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.fileRead.test.ts new file mode 100644 index 00000000000..ca156be7015 --- /dev/null +++ b/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.fileRead.test.ts @@ -0,0 +1,99 @@ +import { reportError } from '@comfyorg/telemetry/reportError' +import { + assert, + beforeEach, + describe, + expect, + it, + onTestFinished, + vi +} from 'vitest' +import { createApp, effectScope } from 'vue' +import type { App, EffectScope } from 'vue' +import { createMemoryHistory, createRouter } from 'vue-router' +import type { Router } from 'vue-router' + +import { clearPreservedQuery } from '@/platform/navigation/preservedQueryManager' +import { PRESERVED_QUERY_DEFINITIONS } from '@/platform/navigation/preservedQueryDefinitions' +import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces' +import { installPreservedQueryTracker } from '@/platform/navigation/preservedQueryTracker' +import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { api } from '@/scripts/api' +import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore' +import '@/scripts/changeTracker' + +import { useWorkflowLinkUrlLoader } from './useWorkflowLinkUrlLoader' + +vi.mock(import('@/scripts/app')) +vi.mock(import('@comfyorg/telemetry')) + +const distribution = vi.hoisted(() => ({ isCloud: true })) +vi.mock(import('@/platform/distribution/types'), () => ({ + get isCloud() { + return distribution.isCloud + } +})) + +const ID = '82b98188-0c8f-41d2-9b91-617b9152b809' +const PATH = 'workflows/Customer Jane Doe.json' +const MODIFIED_MS = 1_793_000_000_000 + +describe('a workflow-id link whose file read fails', () => { + let router: Router + let app: App + let scope: EffectScope + + function inApp(composable: () => T): T { + const result = app.runWithContext(() => scope.run(composable)) + assert.exists(result) + return result + } + + beforeEach(async () => { + distribution.isCloud = true + clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.WORKFLOW_ID) + clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.WORKFLOWS) + clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.DEPLOYMENT) + clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.WORKSPACE) + Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-1' }) + router = createRouter({ + history: createMemoryHistory(), + routes: [{ path: '/:pathMatch(.*)*', component: { render: () => null } }] + }) + installPreservedQueryTracker(router, PRESERVED_QUERY_DEFINITIONS) + app = createApp({}) + app.use(router) + await router.push('/') + scope = effectScope() + onTestFinished(() => scope.stop()) + }) + + it('reports the failure once, through the workflow service, without the file name', async () => { + vi.spyOn(api, 'fetchApi').mockResolvedValue( + Response.json({ path: PATH, size: 12, modified: MODIFIED_MS }) + ) + vi.spyOn(api, 'listUserDataFullInfo').mockResolvedValue([ + { path: PATH.slice('workflows/'.length), size: 12, modified: MODIFIED_MS } + ]) + vi.spyOn(api, 'getUserData').mockResolvedValue( + new Response(null, { status: 500, statusText: 'Internal Server Error' }) + ) + vi.mocked( + inApp(useSubgraphNavigationStore).endWorkflowNavigation + ).mockImplementation(() => {}) + await router.push({ path: '/', query: { workflowId: ID } }) + const loader = inApp(useWorkflowLinkUrlLoader) + + expect(await loader.openWorkflowLinkFromUrl()).toBe('failed') + + expect(api.getUserData).toHaveBeenCalledWith(PATH) + expect(reportError).toHaveBeenCalledExactlyOnceWith( + new Error('Could not open workflow link'), + { + surface: 'graph', + errorType: 'error_opening_workflow_link', + context: { error_name: 'Error' } + } + ) + }) +}) diff --git a/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.test.ts b/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.test.ts index 90b5b4daff0..aff53ad08b9 100644 --- a/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.test.ts +++ b/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.test.ts @@ -52,7 +52,7 @@ vi.mock(import('@/platform/billing/subscription/composables/useTopUpUrlLoader')) vi.mock( import('@/platform/billing/subscription/composables/useSubscriptionDialog') ) -vi.mock(import('@/platform/settings/composables/useSettingsUrlLoader')) +vi.mock(import('@/platform/settings/composables/useSettingsDialog')) vi.mock(import('@/platform/assets/composables/useAssetsUrlLoader')) vi.mock(import('@/platform/openOnCloud/composables/useLocalHandoffUrlLoader')) @@ -165,6 +165,7 @@ describe('workflow-id links', () => { clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.WORKFLOWS) clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.DEPLOYMENT) clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.WORKSPACE) + clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.SETTINGS) Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'workspace-1' }) router = createRouter({ history: createMemoryHistory(), @@ -830,6 +831,26 @@ describe('workflow-id links', () => { expect(currentQuery()).toEqual({ workflowId: NEXT_ID }) }) + it('lets a newer link a navigation guard holds land when the older link also opens Settings', async () => { + serveFile() + await navigate({ workflowId: ID, settings: 'plan-credits' }) + vi.mocked(useWorkflowService().openWorkflow).mockResolvedValue(true) + const cleanup = holdNavigation(isUrlCleanup) + const signIn = holdNavigation(isNewerLink) + + const actions = runUrlActions() + await cleanup.arrived + const newerLink = navigate({ workflowId: NEXT_ID }) + await signIn.arrived + cleanup.release() + await actions + signIn.release() + await newerLink + + expect(currentQuery()).toEqual({ workflowId: NEXT_ID }) + expect(getPreservedQueryParam(NAMESPACE, 'workflowId')).toBe(NEXT_ID) + }) + it('lets a newer link held in a navigation guard land when the URL actions run after the boot link opened', async () => { serveFile() await navigate({ workflowId: ID }) diff --git a/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.ts b/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.ts index caeec7c6bfd..3ad8da8c89f 100644 --- a/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.ts +++ b/src/platform/workflow/management/composables/useWorkflowLinkUrlLoader.ts @@ -243,7 +243,8 @@ function useWorkflowLinkUrlLoaderInternal() { return { kind: 'error' } } const opened = await useWorkflowService().openWorkflow(workflow, { - isCurrent + isCurrent, + reportLoadFailure: false }) return opened ? { kind: 'opened' } : { kind: 'error' } } catch (cause) { diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 15887e10d6d..fe6d2e1028c 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -703,6 +703,52 @@ describe('ComfyApp', () => { ).not.toHaveBeenCalledWith('afterConfigureGraph', expect.anything()) }) + it.for([ + { hook: 'beforeConfigureGraph', configureCalls: 0 }, + { hook: 'afterConfigureGraph', configureCalls: 1 } + ] as const)( + 'resolves false without activating the workflow when its caller gives the load up during $hook', + async ({ hook, configureCalls }) => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + const configure = vi.spyOn(graph, 'configure') + let releaseHook!: () => void + const paused = new Promise((resolve) => { + releaseHook = resolve + }) + let reachedHook = false + mockExtensionService.invokeExtensionsAsync.mockImplementation( + async (name) => { + if (name !== hook) return + reachedHook = true + await paused + } + ) + let owned = true + + const load = app.loadGraphData( + createWorkflowGraphData(), + false, + true, + null, + { isCurrent: () => owned } + ) + await vi.waitFor(() => expect(reachedHook).toBe(true)) + owned = false + releaseHook() + + await expect(load).resolves.toBe(false) + expect(configure).toHaveBeenCalledTimes(configureCalls) + expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'onGraphLoadError', + expect.objectContaining({ name: 'AbortError' }) + ) + expect(ChangeTracker.isLoadingGraph).toBe(false) + } + ) + it('resolves false and notifies onGraphLoadError when the outgoing preflight throws', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 28eae63d50d..d285ad6a228 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1222,7 +1222,8 @@ export class ComfyApp implements IComfyApp { deferWarnings = false, skipAssetScans = false, silentAssetErrors = false, - workflowNavigationId + workflowNavigationId, + isCurrent } = options await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') let reset_invalid_values = false @@ -1234,10 +1235,6 @@ export class ComfyApp implements IComfyApp { useExecutionErrorStore().setActiveGraph(null) if (skipAssetScans) { - // Only reset candidates; preserve UI state (fileSizes, etc.) - // so cached results restored by showPendingWarnings still display sizes. - // Abort any in-flight verification from the outgoing workflow so a late - // result cannot repopulate the store after we've switched workflows. useMissingModelStore().createVerificationAbortController().abort() useMissingMediaStore().createVerificationAbortController().abort() useMissingModelStore().setMissingModels([]) @@ -1248,17 +1245,11 @@ export class ComfyApp implements IComfyApp { } if (clean) { - // Reset canvas context before configuring a new graph so subgraph UI - // state from the previous workflow cannot leak into the newly loaded - // one, and so `clean()` can clear the root graph even when the user is - // currently inside a subgraph. this.canvas.setGraph(this.rootGraph) withGraphIntentSource('load', () => this.clean()) } - // Use explicit validation instead of falsy check to avoid replacing - // valid but falsy values (empty objects, 0, false, etc.) if ( !graphData || typeof graphData !== 'object' || @@ -1274,14 +1265,8 @@ export class ComfyApp implements IComfyApp { const { graphData: validatedGraphData } = await useWorkflowValidation().validateWorkflow(graphData) - // If the validation failed, use the original graph data. - // Ideally we should not block users from loading the workflow. graphData = validatedGraphData ?? graphData } - // Only show the reroute migration warning if the workflow does not have native - // reroutes. Merging reroute network has great complexity, and it is not supported - // for now. - // See: https://github.com/Comfy-Org/ComfyUI_frontend/issues/3317 if ( checkForRerouteMigration && graphData.version === 0.4 && @@ -1321,7 +1306,6 @@ export class ComfyApp implements IComfyApp { const nodeReplacementStore = useNodeReplacementStore() await nodeReplacementStore.load() - // Collect missing node types from all nodes (root + subgraphs) const collectMissingNodes = ( nodes: readonly FlattenableWorkflowNode[], pathPrefix: string = '', @@ -1336,8 +1320,6 @@ export class ComfyApp implements IComfyApp { } for (const n of nodes) { if (!(n.type in LiteGraph.registered_node_types)) { - // Always sanitize so configure() can handle unregistered types, - // but only report as missing if the node is active. const isMuted = n.mode === LGraphEventMode.NEVER || n.mode === LGraphEventMode.BYPASS @@ -1388,16 +1370,6 @@ export class ComfyApp implements IComfyApp { } } } catch (error) { - // This try wraps everything between `beforeLoadGraph` and - // `rootGraph.configure`: asset-scan resets, `clean()`, workflow - // cloning, `validateWorkflow`, reroute-migration inspection, a - // malformed subgraph definition, a `beforeConfigureGraph` extension - // hook throwing, or a node-replacement load failure. Any of those - // happens before `rootGraph.configure` and so reaches neither the - // `afterConfigureGraph` success path nor the `onGraphLoadError` catch - // below. Left unhandled, that would both reject silently and leak any - // suppression/loading-state a `beforeLoadGraph` listener opened for - // this load, since nothing ever notifies it the load ended. try { await this.reportGraphLoadFailure(error) } finally { @@ -1419,14 +1391,12 @@ export class ComfyApp implements IComfyApp { restore_view && useSettingStore().get('Comfy.EnableWorkflowViewRestore') ) { - // Always fit view for templates to ensure they're visible on load if (openSource === 'template') { useLitegraphService().fitView() } else if (savedCameraState) { this.canvas.ds.offset = savedCameraState.offset this.canvas.ds.scale = savedCameraState.scale - // Fit view if no nodes visible in restored viewport this.canvas.ds.computeVisibleArea(this.canvas.viewport) if ( this.canvas.visible_area.width && @@ -1447,19 +1417,24 @@ export class ComfyApp implements IComfyApp { let activatedWorkflow: LoadedComfyWorkflow | undefined let reconcileResourceErrors: (() => void) | undefined let resourceScanLoadCompleted = false + const cancelReplacedLoad = () => + useExtensionService().invokeExtensionsAsync( + 'onGraphLoadError', + new DOMException('Workflow load was replaced', 'AbortError') + ) try { + if (isCurrent?.() === false) { + await cancelReplacedLoad() + return false + } try { this.rootGraph.configure(graphData as ISerialisedGraph) - // Save original renderer version before scaling (it gets modified during scaling) const originalMainGraphRenderer = this.rootGraph.extra.workflowRendererVersion - // Scale main graph ensureCorrectLayoutScale(originalMainGraphRenderer, this.rootGraph) - // Scale all subgraphs that were loaded with the workflow - // Use original main graph renderer as fallback (not the modified one) for (const subgraph of this.rootGraph.subgraphs.values()) { ensureCorrectLayoutScale( subgraph.extra.workflowRendererVersion || originalMainGraphRenderer, @@ -1500,17 +1475,11 @@ export class ComfyApp implements IComfyApp { } } catch (error) { await this.reportGraphLoadFailure(error) - // Resolves rather than throws: the close/replacement guards read this outcome. return false } const configuredGraphState = this.rootGraph.state const isCurrentGraphLoad = () => configuredGraphState === this.rootGraph.state - const cancelReplacedLoad = () => - useExtensionService().invokeExtensionsAsync( - 'onGraphLoadError', - new DOMException('Workflow load was replaced', 'AbortError') - ) const snapTo = LiteGraph.alwaysSnapToGrid ? this.rootGraph.getSnapToGridSize() : 0 @@ -1522,8 +1491,6 @@ export class ComfyApp implements IComfyApp { snapPoint(size, snapTo, 'ceil') node.setSize(size) if (node.widgets) { - // If you break something in the backend and want to patch workflows in the frontend - // This is the place to do this for (const widget of node.widgets) { if (node.type == 'KSampler' || node.type == 'KSamplerAdvanced') { if (widget.name == 'sampler_name') { @@ -1581,6 +1548,10 @@ export class ComfyApp implements IComfyApp { await cancelReplacedLoad() return undefined } + if (isCurrent?.() === false) { + await cancelReplacedLoad() + return false + } const effectiveShareId = shareId ?? @@ -1615,14 +1586,8 @@ export class ComfyApp implements IComfyApp { return undefined } ChangeTracker.isLoadingGraph = false - // Capture the workflow this load activated before the asset-scan awaits - // below can hand control back and let the user switch to another one. activatedWorkflow = useWorkflowStore().activeWorkflow ?? undefined - // Drop missing-node entries whose enclosing subgraph is - // muted/bypassed. The initial JSON scan only checks each node's - // own mode; the cascade from an inactive container is applied here - // using the now-configured live graph. const activeMissingNodeTypes = missingNodeTypes.filter( (n) => typeof n === 'string' || @@ -1677,13 +1642,11 @@ export class ComfyApp implements IComfyApp { }) return activatedWorkflow ?? true } finally { - // Finally: a throwing load still repairs the URL. void useSubgraphNavigationStore().updateHash( 'workflow-load', workflowNavigationId ) ChangeTracker.isLoadingGraph = false - // The retirement watcher skips transitions made during the load. useExecutionErrorStore().retireResolvedMissingNodePromptError() reconcileResourceErrors?.() } diff --git a/src/types/comfy.ts b/src/types/comfy.ts index 41e95637f00..417e0a350b8 100644 --- a/src/types/comfy.ts +++ b/src/types/comfy.ts @@ -86,6 +86,7 @@ export interface LoadGraphDataOptions { skipAssetScans?: boolean silentAssetErrors?: boolean workflowNavigationId?: number + isCurrent?: () => boolean } /**