diff --git a/browser_tests/tests/sidebar/workflows.spec.ts b/browser_tests/tests/sidebar/workflows.spec.ts index 159ce6d2ac6..177fdbc797e 100644 --- a/browser_tests/tests/sidebar/workflows.spec.ts +++ b/browser_tests/tests/sidebar/workflows.spec.ts @@ -4,6 +4,7 @@ import type { Route } from '@playwright/test' import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' import { TestIds } from '@e2e/fixtures/selectors' import { openErrorsTab } from '@e2e/fixtures/helpers/ErrorsTabHelper' +import defaultWorkflow from '@e2e/assets/default.json' with { type: 'json' } import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' test.describe('Workflows sidebar', () => { @@ -497,6 +498,6 @@ test.describe('Workflows sidebar', () => { // Wait for nodes to be inserted after drag-drop with retryable assertion await expect .poll(() => comfyPage.nodeOps.getGraphNodesCount()) - .toBe(nodeCount * 2) + .toBe(nodeCount + defaultWorkflow.nodes.length) }) }) diff --git a/browser_tests/tests/subgraph/subgraphSeed.spec.ts b/browser_tests/tests/subgraph/subgraphSeed.spec.ts index 64851aa603f..0adae86f24e 100644 --- a/browser_tests/tests/subgraph/subgraphSeed.spec.ts +++ b/browser_tests/tests/subgraph/subgraphSeed.spec.ts @@ -9,6 +9,8 @@ import { webSocketFixture } from '@e2e/fixtures/ws' const wstest = mergeTests(test, webSocketFixture) +wstest.use({ initialSettings: { 'Comfy.Minimap.Visible': false } }) + wstest( 'Seed handling', { tag: '@vue-nodes' }, diff --git a/browser_tests/tests/workflow/workflowLoadQueue.spec.ts b/browser_tests/tests/workflow/workflowLoadQueue.spec.ts new file mode 100644 index 00000000000..ec56fd98c74 --- /dev/null +++ b/browser_tests/tests/workflow/workflowLoadQueue.spec.ts @@ -0,0 +1,94 @@ +import { expect } from '@playwright/test' + +import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' + +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' + +function noteWorkflow(title: string): ComfyWorkflowJSON { + return { + last_node_id: 1, + last_link_id: 0, + nodes: [ + { + id: 1, + type: 'Note', + title, + pos: [120, 120], + size: [260, 120], + flags: {}, + order: 0, + mode: 0, + properties: {}, + widgets_values: [''] + } + ], + links: [], + groups: [], + config: {}, + extra: {}, + version: 0.4 + } +} + +test.describe('Workflow load queue', { tag: '@vue-nodes' }, () => { + test('workflow loads finish in FIFO order', async ({ comfyPage }) => { + const { page, vueNodes } = comfyPage + + const result = + await test.step('hold the first load open, then queue a second', async () => + await page.evaluate( + async ([older, newer]) => { + let release!: () => void + const held = new Promise((resolve) => { + release = resolve + }) + let entered!: () => void + const firstEntered = new Promise((resolve) => { + entered = resolve + }) + let holdNext = true + let beforeLoadGraphCalls = 0 + window.app!.registerExtension({ + name: 'e2e.stallBeforeLoadGraph', + beforeLoadGraph: async () => { + beforeLoadGraphCalls++ + if (!holdNext) return + holdNext = false + entered() + await held + } + }) + + const order: string[] = [] + const olderLoad = window.app!.loadGraphData(older) + await firstEntered + const newerLoad = window + .app!.loadGraphData(newer) + .then(() => order.push('newer')) + await Promise.resolve() + const loadsStartedWhileOlderWasHeld = beforeLoadGraphCalls + release() + await olderLoad.then(() => order.push('older')) + await newerLoad + return { order, loadsStartedWhileOlderWasHeld } + }, + [ + noteWorkflow('older workflow'), + noteWorkflow('newer workflow') + ] as const + )) + + expect(result).toEqual({ + order: ['older', 'newer'], + loadsStartedWhileOlderWasHeld: 1 + }) + + await test.step('the canvas shows the last queued workflow', async () => { + await expect(vueNodes.nodes).toHaveCount(1) + await expect( + vueNodes.getNodeByTitle('newer workflow').first() + ).toBeVisible() + await expect(vueNodes.getNodeByTitle('older workflow')).toHaveCount(0) + }) + }) +}) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 20219dc84d3..142c62f9bae 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -774,30 +774,28 @@ describe('ComfyApp', () => { ]) }) - it('closes every beforeLoadGraph when a newer load overtakes an older one', async () => { + it('closes beforeLoadGraph with an abort when the graph is cleared during activation', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) - let releaseFirstLoad!: () => void - const firstLoadBlocked = new Promise((resolve) => { - releaseFirstLoad = resolve + mockWorkflowService.afterLoadNewGraph.mockImplementation(async () => { + app.clean() }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('beforeLoadGraph') - .thenReturnOnce(firstLoadBlocked) - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await app.loadGraphData(createWorkflowGraphData(), false) - releaseFirstLoad() - await expect(olderLoad).resolves.toBeUndefined() + await expect( + app.loadGraphData(createWorkflowGraphData(), false) + ).resolves.toBeUndefined() - const hooks = mockExtensionService.invokeExtensionsAsync.mock.calls.map( - ([hook]) => hook - ) - const opened = hooks.filter((hook) => hook === 'beforeLoadGraph') - const closed = hooks.filter( - (hook) => hook === 'afterConfigureGraph' || hook === 'onGraphLoadError' + const terminalHooks = + mockExtensionService.invokeExtensionsAsync.mock.calls + .map(([hook]) => hook) + .filter( + (hook) => hook === 'afterLoadGraph' || hook === 'onGraphLoadError' + ) + expect(terminalHooks).toEqual(['onGraphLoadError']) + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'onGraphLoadError', + expect.objectContaining({ name: 'AbortError' }) ) - expect(closed).toHaveLength(opened.length) }) it('does not assign a newer workflow graph to an Undo load waiting after configuration', async () => { @@ -851,25 +849,21 @@ describe('ComfyApp', () => { expect.anything() ) ) - await app.loadGraphData(other, false, false, secondWorkflow, { + const newerLoad = app.loadGraphData(other, false, false, secondWorkflow, { skipAssetScans: true }) - try { - expect(ChangeTracker.isLoadingGraph).toBe(false) - } finally { - releasePending() - await undoLoad - } - await expect(undoLoad).resolves.toBeUndefined() + releasePending() + await expect(undoLoad).resolves.toBeTruthy() + await expect(newerLoad).resolves.toBeTruthy() - expect(firstTracker.activeState).toEqual(changed) - expect(firstTracker.initialState).toEqual(saved) + expect(firstTracker.activeState.extra).toMatchObject({ marker: 'saved' }) + expect(firstTracker.initialState.extra).toMatchObject({ marker: 'saved' }) expect(secondTracker.activeState.extra).toMatchObject({ marker: 'other' }) expect(app.rootGraph.extra).toMatchObject({ marker: 'other' }) }) it.for(['activation', 'tracker restoration', 'afterLoadGraph'] as const)( - 'cancels an older restore overtaken during %s without replacing the newer workflow', + 'finishes an older restore paused during %s before the newer workflow loads', async (pauseAt) => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() @@ -960,15 +954,19 @@ describe('ComfyApp', () => { skipAssetScans: true } ) - try { - await vi.waitFor(() => expect(reachedPause).toBe(true)) - await app.loadGraphData(other, false, false, secondWorkflow, { + await vi.waitFor(() => expect(reachedPause).toBe(true)) + const newerLoad = app.loadGraphData( + other, + false, + false, + secondWorkflow, + { skipAssetScans: true - }) - } finally { - releasePause() - } - const result = await olderLoad + } + ) + releasePause() + await expect(olderLoad).resolves.toBeTruthy() + await expect(newerLoad).resolves.toBeTruthy() expect(workflowStore.activeWorkflow?.path).toBe(secondWorkflow.path) expect(workflowStore.activeWorkflow?.changeTracker).toBe(secondTracker) @@ -980,105 +978,50 @@ describe('ComfyApp', () => { }) expect(firstTracker.initialState).toEqual(saved) expect(firstTracker.activeState.extra).toMatchObject({ - marker: pauseAt === 'afterLoadGraph' ? 'saved' : 'changed' + marker: 'saved' }) expect(graph.extra).toMatchObject({ marker: 'other' }) expect(ChangeTracker.isLoadingGraph).toBe(false) - expect(result).toBeUndefined() } ) it('does not assign a cleared canvas to Undo while the newer workflow is still preparing', async () => { app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - const firstWorkflow = new ComfyWorkflow({ - path: 'workflows/undo.json', - modified: 0, - size: 0 + const graph = new LGraph() + graph.add(new LGraphNode('outgoing')) + const previousGraph = singletonApp.rootGraphOrUndefined + onTestFinished(() => { + Reflect.set(singletonApp, 'rootGraphInternal', previousGraph) }) - const saved = createWorkflowGraphData() - saved.extra = { marker: 'saved' } - const changed = structuredClone(saved) - changed.extra = { marker: 'changed' } - const tracker = new ChangeTracker(firstWorkflow, saved) - tracker.activeState = changed - tracker._restoringState = true - firstWorkflow.changeTracker = tracker - const secondWorkflow = new ComfyWorkflow({ - path: 'workflows/other.json', + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + const outgoing = new ComfyWorkflow({ + path: 'workflows/outgoing.json', modified: 0, size: 0 }) - const other = createWorkflowGraphData() - other.extra = { marker: 'other' } - mockWorkflowService.afterLoadNewGraph.mockImplementation( - async ( - workflow: string | ComfyWorkflow | null, - state: ComfyWorkflowJSON - ) => { - assert(workflow instanceof ComfyWorkflow) - workflow.changeTracker?.reset(state) + const outgoingState = structuredClone( + graph.serialize() + ) as ComfyWorkflowJSON + const tracker = markRaw(new ChangeTracker(outgoing, outgoingState)) + const loadedOutgoing = markLoaded(outgoing) + loadedOutgoing.changeTracker = tracker + useWorkflowStore().activeWorkflow = loadedOutgoing + mockExtensionService.invokeExtensionsAsync.mockImplementation( + async (hook) => { + if (hook === 'beforeConfigureGraph') tracker.captureCanvasState() } ) - let releaseAfterConfigure!: () => void - const afterConfigure = new Promise((resolve) => { - releaseAfterConfigure = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('afterConfigureGraph', expect.anything()) - .thenReturnOnce(afterConfigure) - const undoLoad = app.loadGraphData(saved, false, false, firstWorkflow, { - skipAssetScans: true - }) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'afterConfigureGraph', - expect.anything() - ) - ) - let releaseBeforeConfigure!: () => void - const beforeConfigure = new Promise((resolve) => { - releaseBeforeConfigure = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith( - 'beforeConfigureGraph', - expect.anything(), - expect.anything() - ) - .thenReturnOnce(beforeConfigure) - const newerLoad = app.loadGraphData(other, true, false, secondWorkflow, { - skipAssetScans: true - }) - try { - await vi.waitFor(() => expect(app.rootGraph.extra).toEqual({})) - releaseAfterConfigure() - await expect(undoLoad).resolves.toBeUndefined() - expect(ChangeTracker.isLoadingGraph).toBe(true) - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'onGraphLoadError', - expect.objectContaining({ name: 'AbortError' }) - ) + await app.loadGraphData(createWorkflowGraphData(), true) - expect(tracker.activeState).toEqual(changed) - expect(tracker.initialState).toEqual(saved) - } finally { - releaseAfterConfigure() - releaseBeforeConfigure() - await Promise.all([undoLoad, newerLoad]) - } - expect(app.rootGraph.extra).toMatchObject({ marker: 'other' }) - expect(ChangeTracker.isLoadingGraph).toBe(false) + expect(tracker.activeState).toEqual(outgoingState) + expect(tracker.undoQueue).toHaveLength(0) }) - it('allows capture after a newer workflow finishes while old resource scans remain pending', async () => { + it('allows capture while the loaded workflow resource scans are pending', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) - const oldGraph = createWorkflowGraphData() - oldGraph.extra = { marker: 'old' } - const currentGraph = createWorkflowGraphData() - currentGraph.extra = { marker: 'current' } let releaseModels!: () => void const modelsPending = new Promise((resolve) => { releaseModels = resolve @@ -1087,24 +1030,20 @@ describe('ComfyApp', () => { await modelsPending return { missingModels: [], confirmedCandidates: [] } }) - const oldLoad = app.loadGraphData(oldGraph, false, false) + const load = app.loadGraphData(createWorkflowGraphData(), false, false) try { await vi.waitFor(() => expect(runMissingModelPipeline).toHaveBeenCalledOnce() ) - await app.loadGraphData(currentGraph, false, false, null, { - skipAssetScans: true - }) - expect(app.rootGraph.extra).toMatchObject({ marker: 'current' }) expect(ChangeTracker.isLoadingGraph).toBe(false) } finally { releaseModels() - await oldLoad + await load } }) - it('keeps a configured load when a newer configure fails without clearing it', async () => { + it('keeps a configured load when the next queued configure fails without clearing it', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) const graph = createWorkflowGraphData() @@ -1119,31 +1058,30 @@ describe('ComfyApp', () => { const firstLoad = app.loadGraphData(graph, false, false, null, { skipAssetScans: true }) - try { - await vi.waitFor(() => - expect( - mockExtensionService.invokeExtensionsAsync - ).toHaveBeenCalledWith('afterConfigureGraph', expect.anything()) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterConfigureGraph', + expect.anything() ) - vi.spyOn(app.rootGraph, 'configure').mockImplementationOnce(() => { - throw new Error('Configuration failed before clearing') - }) - await expect( - app.loadGraphData(createWorkflowGraphData(), false, false, null, { - skipAssetScans: true - }) - ).resolves.toBe(false) - releaseFirst() + ) + vi.spyOn(app.rootGraph, 'configure').mockImplementationOnce(() => { + throw new Error('Configuration failed before clearing') + }) + const failedLoad = app.loadGraphData( + createWorkflowGraphData(), + false, + false, + null, + { skipAssetScans: true } + ) + releaseFirst() - expect(await firstLoad).toBeTruthy() - expect(app.rootGraph.extra).toMatchObject({ marker: 'configured' }) - } finally { - releaseFirst() - await firstLoad - } + await expect(firstLoad).resolves.toBeTruthy() + await expect(failedLoad).resolves.toBe(false) + expect(app.rootGraph.extra).toMatchObject({ marker: 'configured' }) }) - it('lets an older valid load commit when its newer replacement fails', async () => { + it('lets an older valid load commit when its queued replacement fails', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) let releaseOlderLoad!: () => void @@ -1153,21 +1091,25 @@ describe('ComfyApp', () => { vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith('beforeLoadGraph') .thenReturnOnce(olderLoadBlocked) + const older = createWorkflowGraphData() + older.extra = { marker: 'older' } + const newer = createWorkflowGraphData() + newer.extra = { marker: 'newer' } vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith( 'beforeConfigureGraph', - expect.anything(), + expect.objectContaining({ extra: { marker: 'newer' } }), expect.anything() ) - .thenRejectOnce(new Error('newer load failed')) + .thenReject(new Error('newer load failed')) - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await expect( - app.loadGraphData(createWorkflowGraphData(), false) - ).resolves.toBe(false) + const olderLoad = app.loadGraphData(older, false) + const newerLoad = app.loadGraphData(newer, false) releaseOlderLoad() await expect(olderLoad).resolves.toBe(true) + await expect(newerLoad).resolves.toBe(false) + expect(app.rootGraph.extra).toMatchObject({ marker: 'older' }) }) describe('pending camera restore while the canvas is hidden', () => { @@ -3341,6 +3283,107 @@ describe('ComfyApp', () => { ) }) + describe('graph-load FIFO across import paths', () => { + beforeEach(() => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + const previousGraph = singletonApp.rootGraphOrUndefined + onTestFinished(() => { + Reflect.set(singletonApp, 'rootGraphInternal', previousGraph) + }) + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + }) + + it('runs the next workflow after a load rejects', async () => { + mockWorkflowService.afterLoadNewGraph.mockRejectedValueOnce( + new Error('activation failed') + ) + + const first = app.loadGraphData(createWorkflowGraphData(), true) + const second = app.loadGraphData(createWorkflowGraphData(), true) + + await expect(first).rejects.toThrow('activation failed') + await expect(second).resolves.toBeTruthy() + }) + + it('queues an API JSON import behind an in-flight workflow load', async () => { + let releaseWorkflow!: () => void + const workflowBlocked = new Promise((resolve) => { + releaseWorkflow = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('beforeLoadGraph') + .thenReturnOnce(workflowBlocked) + + const workflow = app.loadGraphData(createWorkflowGraphData(), true) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'beforeLoadGraph' + ) + ) + const apiImport = app.loadApiJson( + { '1': { class_type: 'KSampler', inputs: {} } }, + 'queued.json' + ) + releaseWorkflow() + await workflow + await apiImport + + expect(app.rootGraph.nodes).toHaveLength(1) + expect(app.rootGraph.nodes[0].type).toBe('KSampler') + }) + + it('starts an A1111 import only after the in-flight workflow load finishes', async () => { + let releaseWorkflow!: () => void + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('beforeLoadGraph') + .thenReturnOnce( + new Promise((resolve) => { + releaseWorkflow = resolve + }) + ) + vi.mocked(getWorkflowDataFromFile).mockImplementation(async () => { + releaseWorkflow() + return { parameters: 'positive\nNegative prompt: negative\nSteps: 20' } + }) + let workflowFinishedBeforeImport: boolean | undefined + mockImportA1111.mockImplementation(async () => { + workflowFinishedBeforeImport = + mockExtensionService.invokeExtensionsAsync.mock.calls.some( + ([hook]) => hook === 'afterLoadGraph' + ) + return 'imported' + }) + + const workflow = app.loadGraphData(createWorkflowGraphData(), true) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'beforeLoadGraph' + ) + ) + await app.handleFile(createTestFile('queued-a1111.png', 'image/png')) + await workflow + + expect(workflowFinishedBeforeImport).toBe(true) + }) + + it('cleans before extensions prepare the incoming workflow', async () => { + app.rootGraph.add(new LGraphNode('outgoing')) + let nodesDuringPreparation: number | undefined + mockExtensionService.invokeExtensionsAsync.mockImplementation( + async (hook) => { + if (hook === 'beforeConfigureGraph') + nodesDuringPreparation = app.rootGraph.nodes.length + } + ) + + await app.loadGraphData(createWorkflowGraphData(), true) + + expect(nodesDuringPreparation).toBe(0) + }) + }) + describe('clean', () => { it('clears missing node packs when the graph is discarded', () => { const graph = new LGraph() diff --git a/src/scripts/app.ts b/src/scripts/app.ts index cbe95bef446..ef6136f47cd 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -432,8 +432,7 @@ export class ComfyApp implements IComfyApp { private configuringGraphLevel: number = 0 private graphLoadSequence = 0 - private committedGraphLoadSequence = 0 - private readonly pendingGraphLoads = new Set() + private graphLoadQueue: Promise = Promise.resolve() private pendingCamera: | { id: number; workflow: string | null | ComfyWorkflow } | undefined @@ -1185,12 +1184,33 @@ export class ComfyApp implements IComfyApp { await useExtensionService().invokeExtensionsAsync('onGraphLoadError', error) } + private enqueueGraphLoad(operation: () => Promise): Promise { + const result = this.graphLoadQueue.then(operation) + this.graphLoadQueue = result.then( + () => undefined, + () => undefined + ) + return result + } + async loadGraphData( graphData?: ComfyWorkflowJSON, clean: boolean = true, restore_view: boolean = true, workflow: string | null | ComfyWorkflow = null, options: LoadGraphDataOptions = {} + ): Promise { + return this.enqueueGraphLoad(() => + this.loadGraphDataNow(graphData, clean, restore_view, workflow, options) + ) + } + + private async loadGraphDataNow( + graphData: ComfyWorkflowJSON | undefined, + clean: boolean, + restore_view: boolean, + workflow: string | null | ComfyWorkflow, + options: LoadGraphDataOptions ): Promise { const canvasScheduler = useCanvasScheduler() const loadId = ++this.graphLoadSequence @@ -1207,13 +1227,7 @@ export class ComfyApp implements IComfyApp { useWorkflowService().beforeLoadNewGraph(clean) await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') - this.pendingGraphLoads.add(loadId) ChangeTracker.isLoadingGraph = true - const releaseGraphLoad = () => { - this.pendingGraphLoads.delete(loadId) - if (this.pendingGraphLoads.size === 0) - ChangeTracker.isLoadingGraph = false - } let reset_invalid_values = false const missingNodeTypes: MissingNodeType[] = [] try { @@ -1387,7 +1401,7 @@ export class ComfyApp implements IComfyApp { try { await this.reportGraphLoadFailure(error) } finally { - releaseGraphLoad() + ChangeTracker.isLoadingGraph = false } void useSubgraphNavigationStore().updateHash( 'workflow-load', @@ -1435,17 +1449,6 @@ export class ComfyApp implements IComfyApp { let resourceScanLoadCompleted = false try { try { - if (loadId < this.committedGraphLoadSequence) { - await useExtensionService().invokeExtensionsAsync( - 'onGraphLoadError', - new DOMException( - 'Graph load superseded by a newer load', - 'AbortError' - ) - ) - return undefined - } - this.rootGraph.configure(graphData as ISerialisedGraph) // Save original renderer version before scaling (it gets modified during scaling) @@ -1464,10 +1467,6 @@ export class ComfyApp implements IComfyApp { ) } - this.committedGraphLoadSequence = Math.max( - loadId, - this.committedGraphLoadSequence - ) const preservesPendingCamera = !restore_view && workflow !== null && @@ -1505,10 +1504,8 @@ export class ComfyApp implements IComfyApp { return false } const configuredGraphState = this.rootGraph.state - const configuredLoadId = this.committedGraphLoadSequence const isCurrentGraphLoad = () => - configuredGraphState === this.rootGraph.state && - configuredLoadId === this.committedGraphLoadSequence + configuredGraphState === this.rootGraph.state const cancelReplacedLoad = () => useExtensionService().invokeExtensionsAsync( 'onGraphLoadError', @@ -1615,11 +1612,7 @@ export class ComfyApp implements IComfyApp { await cancelReplacedLoad() return undefined } - for (const pendingLoadId of this.pendingGraphLoads) { - if (pendingLoadId <= loadId) - this.pendingGraphLoads.delete(pendingLoadId) - } - ChangeTracker.isLoadingGraph = this.pendingGraphLoads.size > 0 + 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 @@ -1687,7 +1680,7 @@ export class ComfyApp implements IComfyApp { 'workflow-load', workflowNavigationId ) - releaseGraphLoad() + ChangeTracker.isLoadingGraph = false // The retirement watcher skips transitions made during the load. useExecutionErrorStore().retireResolvedMissingNodePromptError() reconcileResourceErrors?.() @@ -2219,53 +2212,57 @@ export class ComfyApp implements IComfyApp { // Use parameters strictly as the final fallback if (parameters && typeof parameters === 'string') { - const outcome = await importA1111( - this.rootGraph, - parameters, - async () => { - try { - // false: final destination; no later load republishes the hash. - useWorkflowService().beforeLoadNewGraph(false) - await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') - } finally { - useMissingNodesErrorStore().setMissingNodeTypes([]) + return await this.enqueueGraphLoad(async () => { + const outcome = await importA1111( + this.rootGraph, + parameters, + async () => { + try { + // false: final destination; no later load republishes the hash. + useWorkflowService().beforeLoadNewGraph(false) + await useExtensionService().invokeExtensionsAsync( + 'beforeLoadGraph' + ) + } finally { + useMissingNodesErrorStore().setMissingNodeTypes([]) + } + this.canvas.setGraph(this.rootGraph) + } + ) + switch (outcome) { + case 'core-nodes-unavailable': + useToast().warning(t('toastMessages.a1111CoreNodesUnavailable')) + return + case 'not-a1111': + this.showErrorOnFileLoad(file) + return + case 'imported-without-embeddings': + useToast().warning(t('g.warning'), { + description: t('toastMessages.a1111EmbeddingsUnavailable') + }) + break + case 'imported': + break + default: { + const unexpectedOutcome: never = outcome + throw new Error( + `Unhandled A1111 import outcome: ${unexpectedOutcome}` + ) } - this.canvas.setGraph(this.rootGraph) - } - ) - switch (outcome) { - case 'core-nodes-unavailable': - useToast().warning(t('toastMessages.a1111CoreNodesUnavailable')) - return - case 'not-a1111': - this.showErrorOnFileLoad(file) - return - case 'imported-without-embeddings': - useToast().warning(t('g.warning'), { - description: t('toastMessages.a1111EmbeddingsUnavailable') - }) - break - case 'imported': - break - default: { - const unexpectedOutcome: never = outcome - throw new Error( - `Unhandled A1111 import outcome: ${unexpectedOutcome}` - ) } - } - // Intentionally no beforeConfigureGraph: A1111 has no mutable - // workflow JSON before graph construction, so there is no payload. - await useExtensionService().invokeExtensionsAsync( - 'afterConfigureGraph', - [] - ) - await useWorkflowService().afterLoadNewGraph( - fileName, - this.rootGraph.serialize() as unknown as ComfyWorkflowJSON - ) - await useExtensionService().invokeExtensionsAsync('afterLoadGraph') - return + // Intentionally no beforeConfigureGraph: A1111 has no mutable + // workflow JSON before graph construction, so there is no payload. + await useExtensionService().invokeExtensionsAsync( + 'afterConfigureGraph', + [] + ) + await useWorkflowService().afterLoadNewGraph( + fileName, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON + ) + await useExtensionService().invokeExtensionsAsync('afterLoadGraph') + return + }) } this.showErrorOnFileLoad(file) @@ -2397,6 +2394,16 @@ export class ComfyApp implements IComfyApp { apiData: ComfyApiWorkflow, fileName: string, options: { deferWarnings?: boolean } = {} + ): Promise { + return this.enqueueGraphLoad(() => + this.loadApiJsonNow(apiData, fileName, options) + ) + } + + private async loadApiJsonNow( + apiData: ComfyApiWorkflow, + fileName: string, + options: { deferWarnings?: boolean } ): Promise { // false: no workflow load follows to republish the hash. useWorkflowService().beforeLoadNewGraph(false) diff --git a/src/services/extensionService.test.ts b/src/services/extensionService.test.ts index 4d05f8cf56a..6412b55f3d0 100644 --- a/src/services/extensionService.test.ts +++ b/src/services/extensionService.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { legacyMenuCompat } from '@/lib/litegraph/src/contextMenuCompat' +import { useApp } from '@/scripts/appInstance' import { useExtensionStore } from '@/stores/extensionStore' import { useExtensionService } from './extensionService' @@ -147,6 +148,61 @@ describe('invokeExtensionsAsync', () => { expect(hook.mock.contexts[0]).toBe(useExtensionStore().extensions[0]) }) + type HookApp = ReturnType + + it.for([ + { + entrypoint: 'loadGraphData', + call: (app: HookApp) => app.loadGraphData() + }, + { + entrypoint: 'loadApiJson', + call: (app: HookApp) => app.loadApiJson({}, 'nested.json') + }, + { + entrypoint: 'handleFile', + call: (app: HookApp) => app.handleFile(new File([], 'nested.png')) + } + ])( + 'rejects $entrypoint started after an await in a graph-load hook', + async ({ call }) => { + let nested: Promise | undefined + register({ + name: 'nested-loader', + beforeLoadGraph: async (app: HookApp) => { + await Promise.resolve() + nested = call(app) + await nested.catch(() => {}) + } + }) + + await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + + await expect(nested).rejects.toThrow( + 'A graph-load lifecycle hook cannot start a nested graph load' + ) + } + ) + + it('lets a retained hook app load once the hook dispatch has finished', async () => { + let retained: HookApp | undefined + register({ + name: 'retaining-extension', + afterLoadGraph: (app: HookApp) => { + retained = app + } + }) + await useExtensionService().invokeExtensionsAsync('afterLoadGraph') + const handleFile = vi + .spyOn(useApp(), 'handleFile') + .mockResolvedValue(undefined) + const file = new File([], 'later.png') + + await retained?.handleFile(file) + + expect(handleFile).toHaveBeenCalledWith(file) + }) + it('silently ignores a non-function property of the same name', async () => { const after = vi.fn() register( diff --git a/src/services/extensionService.ts b/src/services/extensionService.ts index 1af99507805..b76e8c47eec 100644 --- a/src/services/extensionService.ts +++ b/src/services/extensionService.ts @@ -22,6 +22,44 @@ function isPromiseLike(value: unknown): value is PromiseLike { ) } +const graphLoadLifecycleHooks = new Set([ + 'beforeLoadGraph', + 'beforeConfigureGraph', + 'afterConfigureGraph', + 'afterLoadGraph', + 'onGraphLoadError' +] satisfies (keyof ComfyExtension)[]) + +const graphLoadEntrypoints = new Set([ + 'loadGraphData', + 'loadApiJson', + 'handleFile' +] satisfies (keyof ComfyApp)[]) + +function rejectNestedGraphLoad() { + return Promise.reject( + new Error('A graph-load lifecycle hook cannot start a nested graph load') + ) +} + +function createGraphLoadHookApp(app: ComfyApp) { + let dispatching = true + const hookApp = new Proxy(app, { + get(target, property) { + if (dispatching && graphLoadEntrypoints.has(property)) + return rejectNestedGraphLoad + const value: unknown = Reflect.get(target, property, target) + return typeof value === 'function' ? value.bind(target) : value + } + }) + return { + hookApp, + endDispatch: () => { + dispatching = false + } + } +} + export const useExtensionService = () => { const extensionStore = useExtensionStore() const settingStore = useSettingStore() @@ -179,6 +217,10 @@ export const useExtensionService = () => { method: T, ...args: Parameters> ) => { + const graphLoadHook = graphLoadLifecycleHooks.has(method) + ? createGraphLoadHookApp(useApp()) + : undefined + const app = graphLoadHook?.hookApp ?? useApp() const logError = (ext: ComfyExtension, error: unknown) => console.error( `Error calling extension '${ext.name}' method '${method}'`, @@ -203,7 +245,7 @@ export const useExtensionService = () => { (async () => { legacyMenuCompat.setCurrentExtension(ext.name) try { - return await fn.call(ext, ...args, useApp()) + return await fn.call(ext, ...args, app) } finally { legacyMenuCompat.setCurrentExtension(null) } @@ -212,7 +254,7 @@ export const useExtensionService = () => { continue } - const result: unknown = fn.call(ext, ...args, useApp()) + const result: unknown = fn.call(ext, ...args, app) pending.push( isPromiseLike(result) ? Promise.resolve(result).catch((error) => logError(ext, error)) @@ -222,7 +264,11 @@ export const useExtensionService = () => { logError(ext, error) } } - return await Promise.all(pending) + try { + return await Promise.all(pending) + } finally { + graphLoadHook?.endDispatch() + } } return {