From 7e1d1772bcf6edb747aa994a1d9c44d702ecbce8 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 19:00:42 -0700 Subject: [PATCH 01/31] fix(canvas): make overlapping graph loads ownership-aware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `loadGraphData` awaited `beforeLoadGraph` and then immediately aborted asset verification, cleared the missing-resource stores, and called `canvas.setGraph()` / `clean()` — but did not compare its own load id with the committed one until after `rootGraph.configure`. An older load resuming from that await therefore erased the graph a newer load had already committed, and only then reported itself superseded. The user was left on the workflow they had navigated away from, or on an empty canvas. Ownership is now checked before the first destructive mutation, and again after each awaited lifecycle hook downstream of the commit: `afterConfigureGraph` (before the telemetry payload and before `afterLoadNewGraph` binds a workflow to `rootGraph.serialize()`), `afterLoadGraph` (before the asset pipelines scan the live graph), and after those pipelines (before warnings are posted). All four gates share one predicate and one rejection path, so a superseded load always notifies `onGraphLoadError` and closes whatever loading state a `beforeLoadGraph` listener opened for it. `ChangeTracker.isLoadingGraph` was a single shared boolean that every load wrote true and every path's `finally` wrote false, so a superseded older load ended the newer load's suppression window and ran global error retirement early. It is now held by count: it still reads as a boolean, but each load opens and closes only its own window, and the catch-up retirement in `finally` waits for the last one to close. Refs #19971. --- .../agentOverlappingWorkflowLoad.spec.ts | 105 ++++++++++++++++++ src/scripts/app.test.ts | 89 +++++++++++++++ src/scripts/app.ts | 80 ++++++++++--- src/scripts/changeTracker.ts | 34 +++++- 4 files changed, 294 insertions(+), 14 deletions(-) create mode 100644 browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts diff --git a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts new file mode 100644 index 00000000000..5ee82d7aeb9 --- /dev/null +++ b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts @@ -0,0 +1,105 @@ +import { expect } from '@playwright/test' + +import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' + +import { agentTest as test } from '@e2e/tests/agent/agentPanelMocks' + +/** + * Regression for https://github.com/Comfy-Org/ComfyUI_frontend/issues/19971: + * "Reject a superseded graph load before its first destructive store/canvas + * mutation" and "Re-check graph-load ownership after awaited lifecycle hooks". + * + * `loadGraphData` awaits `beforeLoadGraph` and then immediately clears the + * canvas and the resource stores, but it did not compare its own load id with + * the committed one until well after that. So when two loads overlap — the + * user switching workflows faster than the first load resolves, or any + * extension holding `beforeLoadGraph` open — the older load woke up, erased + * the graph the newer load had already committed, and only then reported + * itself superseded. The canvas was left holding the workflow the user had + * navigated away from, or nothing at all. + */ +const STALL_EXTENSION = 'e2e.op329.stallBeforeLoadGraph' + +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( + 'Overlapping workflow loads', + { tag: ['@cloud', '@agent', '@vue-nodes'] }, + () => { + test('the newer workflow survives an older load resuming', async ({ + comfyPage, + agentPanel + }) => { + test.setTimeout(60_000) + const { page, vueNodes } = comfyPage + + await agentPanel.open() + await vueNodes.setEnabled(true) + + await test.step('hold the first load open, then start a second', async () => { + await page.evaluate( + async ([extensionName, older, newer]) => { + let release!: () => void + const held = new Promise((resolve) => { + release = resolve + }) + let holdNext = true + window.app!.registerExtension({ + name: extensionName, + beforeLoadGraph: async () => { + if (!holdNext) return + holdNext = false + await held + } + }) + + const olderLoad = window.app!.loadGraphData(older as never) + const newerLoad = window.app!.loadGraphData(newer as never) + // The newer load runs to completion and commits its graph while + // the older one is still parked inside `beforeLoadGraph`. + await newerLoad + release() + await olderLoad + }, + [ + STALL_EXTENSION, + noteWorkflow('older workflow'), + noteWorkflow('newer workflow') + ] as const + ) + }) + + await test.step('the canvas still shows the newer 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 22ea5c28813..e349af0eff4 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -46,6 +46,7 @@ import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/ import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import type { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation' import { createMockChangeTracker } from '@/utils/__tests__/litegraphTestUtils' +import { ChangeTracker } from '@/scripts/changeTracker' import { createTestCanvasElement, createTestDragAndScale, @@ -711,6 +712,94 @@ describe('ComfyApp', () => { expect(closed).toHaveLength(opened.length) }) + it('does not destroy the newer committed graph when a superseded load resumes', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + const setGraph = vi.fn() + Reflect.set(mockCanvas, 'setGraph', setGraph) + const clean = vi.spyOn(app, 'clean').mockImplementation(() => {}) + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('beforeLoadGraph') + .thenReturnOnce(olderLoadBlocked) + + const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) + await app.loadGraphData(createWorkflowGraphData(), true) + setGraph.mockClear() + clean.mockClear() + releaseOlderLoad() + await expect(olderLoad).resolves.toBeUndefined() + + // Both of these erase the graph the newer load just committed, and the + // supersession check used to sit downstream of them. + expect(setGraph).not.toHaveBeenCalled() + expect(clean).not.toHaveBeenCalled() + }) + + it('does not bind an older load’s workflow to a newer load’s graph', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + // The older load commits, then suspends inside a lifecycle hook that + // runs after the point where its ownership was last checked. + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('afterConfigureGraph', expect.anything()) + .thenReturnOnce(olderLoadBlocked) + + const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) + await app.loadGraphData(createWorkflowGraphData(), false) + releaseOlderLoad() + await expect(olderLoad).resolves.toBeUndefined() + + // Only the newer load may bind a workflow to the live graph. + expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() + }) + + it('keeps a newer load’s suppression window open when a superseded load returns', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + ChangeTracker.isLoadingGraph = false + onTestFinished(() => { + ChangeTracker.isLoadingGraph = false + }) + const releaseScan: Array<() => void> = [] + vi.mocked(runMissingModelPipeline).mockImplementation(async () => { + await new Promise((resolve) => releaseScan.push(resolve)) + return { missingModels: [], confirmedCandidates: [] } + }) + vi.spyOn( + missingMediaPipeline, + 'runMissingMediaPipeline' + ).mockResolvedValue(undefined) + + // The older load owns the graph when it reaches its asset scan, and + // suspends there. + const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) + await vi.waitFor(() => expect(releaseScan).toHaveLength(1)) + // A newer load then commits and suspends on its own scan, so both are + // inside a suppression window at once. + const newerLoad = app.loadGraphData(createWorkflowGraphData(), false) + await vi.waitFor(() => expect(releaseScan).toHaveLength(2)) + + releaseScan[0]() + await olderLoad + + // A single shared boolean let the superseded load's `finally` end the + // newer load's suppression window, un-gating change capture and error + // retirement while the newer load was still mid-flight. + expect(ChangeTracker.isLoadingGraph).toBe(true) + + releaseScan[1]() + await newerLoad + expect(ChangeTracker.isLoadingGraph).toBe(false) + }) + it('lets an older valid load commit when its newer replacement fails', 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 212b98b4885..45dd8800e28 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1299,6 +1299,28 @@ export class ComfyApp { await useExtensionService().invokeExtensionsAsync('onGraphLoadError', error) } + /** + * Whether `loadId` still owns the graph. A newer load that has committed its + * graph owns everything downstream of that commit, so an older load resuming + * from an await must not mutate state, bind a workflow, or frame the canvas. + */ + private ownsGraphLoad(loadId: number): boolean { + return loadId >= this.committedGraphLoadSequence + } + + /** + * End a superseded load the way a failed one ends: notify `onGraphLoadError` + * so any loading state a `beforeLoadGraph` listener opened for this load is + * closed out. Resolves rather than throws; callers return its result. + */ + private async rejectSupersededGraphLoad(): Promise { + await useExtensionService().invokeExtensionsAsync( + 'onGraphLoadError', + new DOMException('Graph load superseded by a newer load', 'AbortError') + ) + return undefined + } + async loadGraphData( graphData?: ComfyWorkflowJSON, clean: boolean = true, @@ -1329,6 +1351,15 @@ export class ComfyApp { useWorkflowService().beforeLoadNewGraph(clean) await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + // `beforeLoadGraph` listeners can await for as long as they like, and a + // newer load can commit its graph while this one is suspended there. Every + // statement below this point is destructive — aborting in-flight asset + // verification, clearing the missing-resource stores, `canvas.setGraph()` + // and `clean()` all erase live state. The later supersession check at the + // `configure` boundary is too late to stop that, so a superseded load used + // to wipe the newer committed graph and only then report itself stale. + if (!this.ownsGraphLoad(loadId)) return this.rejectSupersededGraphLoad() + let reset_invalid_values = false const missingNodeTypes: MissingNodeType[] = [] try { @@ -1523,21 +1554,16 @@ export class ComfyApp { } } - ChangeTracker.isLoadingGraph = true + // Scoped rather than assigned: overlapping loads each hold their own + // suppression window, so this load's `finally` cannot end another's. + const endGraphLoadSuppression = ChangeTracker.beginGraphLoad() let activatedWorkflow: LoadedComfyWorkflow | undefined let reconcileResourceErrors: (() => void) | undefined 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 + if (!this.ownsGraphLoad(loadId)) { + return await this.rejectSupersededGraphLoad() } this.rootGraph.configure(graphData as ISerialisedGraph) @@ -1663,6 +1689,15 @@ export class ComfyApp { missingNodeTypes ) + // Ownership is committed once, before this hook. Everything after it is + // graph-derived: the telemetry payload, and `afterLoadNewGraph` binding + // `workflow` to `rootGraph.serialize()`. A newer load that committed + // while this hook awaited owns the live graph, so continuing would + // serialize the newer graph into this load's older workflow. + if (!this.ownsGraphLoad(loadId)) { + return await this.rejectSupersededGraphLoad() + } + const effectiveShareId = shareId ?? (workflow instanceof ComfyWorkflow ? workflow.shareId : undefined) @@ -1683,6 +1718,13 @@ export class ComfyApp { effectiveShareId ) await useExtensionService().invokeExtensionsAsync('afterLoadGraph') + + // Same reason again: the asset pipelines below scan `this.rootGraph`, and + // their results are reported against this load's workflow. + if (!this.ownsGraphLoad(loadId)) { + return await this.rejectSupersededGraphLoad() + } + // 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 @@ -1733,6 +1775,13 @@ export class ComfyApp { }) } + // Both asset pipelines await the network. A newer load that committed + // while they ran owns the warnings surface and the canvas, and will post + // its own; this load's results describe a graph that is no longer live. + if (!this.ownsGraphLoad(loadId)) { + return await this.rejectSupersededGraphLoad() + } + if (!deferWarnings) { useWorkflowService().showPendingWarnings(undefined, { silent: silentAssetErrors @@ -1750,9 +1799,14 @@ export class ComfyApp { 'workflow-load', workflowNavigationId ) - ChangeTracker.isLoadingGraph = false - // The retirement watcher skips transitions made during the load. - useExecutionErrorStore().retireResolvedMissingNodePromptError() + endGraphLoadSuppression() + // The retirement watcher skips transitions made during the load, so the + // catch-up runs here — but only once the last overlapping load has + // closed its window. Running it while a newer load is still configuring + // retires that load's errors before it has recorded them. + if (!ChangeTracker.isLoadingGraph) { + useExecutionErrorStore().retireResolvedMissingNodePromptError() + } reconcileResourceErrors?.() } } diff --git a/src/scripts/changeTracker.ts b/src/scripts/changeTracker.ts index e936b33d2b5..5a7a0ea4792 100644 --- a/src/scripts/changeTracker.ts +++ b/src/scripts/changeTracker.ts @@ -252,14 +252,46 @@ function reportInactiveTrackerCall(method: string, workflowPath: string) { export class ChangeTracker { static MAX_HISTORY = 50 + /** Number of graph loads currently inside their suppression window. */ + private static graphLoadDepth = 0 + /** * Guard flag to prevent captureCanvasState from running during loadGraphData. * Between rootGraph.configure() and afterLoadNewGraph(), the rootGraph * contains the NEW workflow's data while activeWorkflow still points to * the OLD workflow. Any captureCanvasState call in that window would * serialize the wrong graph into the old workflow's activeState, corrupting it. + * + * Reads as a boolean, but is held by count rather than by assignment: loads + * overlap, and a single shared boolean let a superseded older load's + * `finally` end the newer load's suppression window. + * @see {@link beginGraphLoad} */ - static isLoadingGraph = false + static get isLoadingGraph(): boolean { + return ChangeTracker.graphLoadDepth > 0 + } + + static set isLoadingGraph(value: boolean) { + ChangeTracker.graphLoadDepth = value ? 1 : 0 + } + + /** + * Open a suppression window for one graph load. + * @returns A function that closes this load's window and no other's. Safe to + * call more than once. + */ + static beginGraphLoad(): () => void { + ChangeTracker.graphLoadDepth++ + let closed = false + return () => { + if (closed) return + closed = true + ChangeTracker.graphLoadDepth = Math.max( + 0, + ChangeTracker.graphLoadDepth - 1 + ) + } + } /** * The active state of the workflow. */ From dfb4756856bd514cb16434ae1b32f242cae5faf8 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 19:01:42 -0700 Subject: [PATCH 02/31] fix(canvas): keep the viewport's DPR transform, CSS sizing and caches honest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four defects in the viewport lifecycle, all sharing one root cause: assigning `canvas.width` or `canvas.height` resets a 2D context to the identity transform, and nothing tracked that. - `measureViewportFromElement` probes the CSS box by zeroing the backing store and restoring it, which resets the context. `applyViewport` then re-applied `scale(dpr, dpr)` only when it saw a size or DPR change, so a sub-pixel layout change that re-probed but rounded back to the same physical size left the canvas drawing at 1x inside a 2x backing store. The applied DPR transform is now recorded per canvas and invalidated by the probe, and `applySurfaceViewport` owns sizing and scaling together because they share that one mechanism. The no-reset optimization is unchanged when the transform is already correct. - `LGraphCanvas.resize(width, height)` pinned the logical CSS size only for the parent-fallback path. With explicit dimensions and no external CSS constraint the backing store alone drove layout, so `resize(800, 600)` at DPR 2 laid the canvas out at 1600x1200 while every viewport consumer believed it was 800x600. Explicit dimensions are CSS pixels too, so they are pinned the same way; `applyParentSizedCanvasStyle` is renamed `applyLogicalCanvasStyle` to match what it now does. - That pinning inspected only *inline* `style.width`/`height`, so a class-sized canvas read as caller-unsized and had its stylesheet rule replaced by an inline snapshot — the graph canvas is `absolute inset-0 size-full`, and a 0x0 parent measured during mount pinned `0px`. It now declines a degenerate size outright, and declines when CSS already lays the canvas out at the target size. - `DragAndScale`'s viewport cache returned any cached tuple including `[0, 0]`, handed out the mutable array itself, and survived `setCanvas()` replacing the element it described. A non-positive size is no longer cached (consumers all reject an empty rectangle, and the measurement fallbacks can still find a real size), reads return a copy, and `setCanvas()` invalidates it. Also recomputes the LOD threshold when DPR changes: `_lowQualityZoomThreshold` derives from `sqrt(dpr)` but `applyViewport` assigned `consumer.dpr` directly, leaving the threshold stale, so moving to a different-DPR display kept rendering low-quality text at zoom levels that are now readable. `dpr` is an accessor that derives the threshold on change. Refs #19971. --- src/lib/litegraph/src/DragAndScale.ts | 24 +++- .../litegraph/src/LGraphCanvas.resize.test.ts | 33 ++++++ src/lib/litegraph/src/LGraphCanvas.ts | 30 ++++- .../DragAndScale.viewportSize.test.ts | 51 ++++++++ .../canvas/__tests__/canvasViewport.test.ts | 58 ++++++++- src/renderer/core/canvas/canvasViewport.ts | 110 +++++++++++++----- 6 files changed, 263 insertions(+), 43 deletions(-) create mode 100644 src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts diff --git a/src/lib/litegraph/src/DragAndScale.ts b/src/lib/litegraph/src/DragAndScale.ts index 185f993407f..de4b3d36147 100644 --- a/src/lib/litegraph/src/DragAndScale.ts +++ b/src/lib/litegraph/src/DragAndScale.ts @@ -121,12 +121,32 @@ export class DragAndScale { visible_area.resizeBottomRight(endx, endy) } + /** + * Record the applied CSS viewport size. A non-positive size is not a usable + * viewport, so it clears the cache rather than being stored: every consumer + * rejects a zero rectangle, and the measurement fallbacks below can still + * find a real size. + */ setViewportSize(width: number, height: number): void { - this.viewportSize = [width, height] + this.viewportSize = + width > 0 && + height > 0 && + Number.isFinite(width) && + Number.isFinite(height) + ? [width, height] + : undefined + } + + /** Discard the cached viewport size, e.g. because the element was replaced. */ + invalidateViewportSize(): void { + this.viewportSize = undefined } getViewportSize(): [number, number] { - if (this.viewportSize) return this.viewportSize + const cached = this.viewportSize + // Return a copy: callers mutate the rectangles they are handed, and the + // cache is read by every hit test and framing operation. + if (cached) return [cached[0], cached[1]] const rect = this.element.getBoundingClientRect() if (rect.width > 0 && rect.height > 0) { diff --git a/src/lib/litegraph/src/LGraphCanvas.resize.test.ts b/src/lib/litegraph/src/LGraphCanvas.resize.test.ts index 0f800c3c6d7..1af5c96e189 100644 --- a/src/lib/litegraph/src/LGraphCanvas.resize.test.ts +++ b/src/lib/litegraph/src/LGraphCanvas.resize.test.ts @@ -56,4 +56,37 @@ describe('LGraphCanvas.resize', () => { 1200 ]) }) + + it('keeps explicit dimensions in CSS pixels rather than letting the backing store size the layout', () => { + const { canvas } = createParentSizedCanvas() + + canvas.resize(800, 600) + + const { style, width, height } = canvas.canvas + expect([style.width, style.height, width, height]).toEqual([ + '800px', + '600px', + 1600, + 1200 + ]) + }) + + it('recomputes the LOD threshold when a resize changes DPR', () => { + const { canvas } = createParentSizedCanvas() + vi.stubGlobal('devicePixelRatio', 1) + canvas.resize(800, 600) + // A zoom level below the DPR-1 readability threshold (8 / (14 * √1)). + canvas.ds.scale = 0.4 + canvas.ds.computeVisibleArea(undefined) + expect(canvas.low_quality).toBe(true) + + // Moving to a high-DPR display raises readability, so the same zoom is + // now above the threshold (8 / (14 * √4)) and should render at full + // quality. The threshold derives from DPR, so applying one has to + // recompute it. + vi.stubGlobal('devicePixelRatio', 4) + canvas.resize(800, 600) + + expect(canvas.low_quality).toBe(false) + }) }) diff --git a/src/lib/litegraph/src/LGraphCanvas.ts b/src/lib/litegraph/src/LGraphCanvas.ts index 32eb0e89295..3db414771f9 100644 --- a/src/lib/litegraph/src/LGraphCanvas.ts +++ b/src/lib/litegraph/src/LGraphCanvas.ts @@ -32,7 +32,7 @@ import { import { useSelectionStore } from '@/core/selection/selectionStore' import { useLinkPresentationStore } from '@/stores/linkPresentationStore' import { - applyParentSizedCanvasStyle, + applyLogicalCanvasStyle, applyViewport, measureViewport, readBrowserDpr @@ -1040,8 +1040,23 @@ export class LGraphCanvas implements CustomEventDispatcher /** Link rendering adapter for litegraph-to-canvas integration */ linkRenderer: LitegraphLinkAdapter | null = null + private _dpr: number = 1 + /** Device pixel ratio applied with the current viewport dimensions. */ - dpr: number = 1 + get dpr(): number { + return this._dpr + } + + /** + * Applying a new DPR changes the zoom level at which text stops being + * readable, so the LOD threshold is derived here rather than left for a + * caller to remember. + */ + set dpr(value: number) { + if (this._dpr === value) return + this._dpr = value + this.updateLowQualityThreshold() + } /** If true, enable drag zoom. Ctrl+Shift+Drag Up/Down: zoom canvas. */ dragZoomEnabled: boolean = false @@ -2196,6 +2211,8 @@ export class LGraphCanvas implements CustomEventDispatcher // maybe detach events from old_canvas this.canvas = element this.ds.element = element + // The cached CSS viewport describes the outgoing element, not this one. + this.ds.invalidateViewportSize() this.pointer.element = element this._setCursor = createCursorCache(element) @@ -6675,7 +6692,6 @@ export class LGraphCanvas implements CustomEventDispatcher * This method remains for legacy callers that rely on parent-element fallback sizing. */ resize(width?: number, height?: number): void { - const usesParentSize = !width && !height if (!width && !height) { const parent = this.canvas.parentElement if (!parent) @@ -6686,9 +6702,11 @@ export class LGraphCanvas implements CustomEventDispatcher height = parent.offsetHeight } - if (usesParentSize) { - applyParentSizedCanvasStyle(this.canvas, width ?? 0, height ?? 0) - } + // Explicit dimensions are CSS pixels, exactly as the parent fallback is. + // Without pinning them the backing store alone drives layout, so a + // `resize(800, 600)` at DPR 2 lays the canvas out at 1600x1200 while every + // viewport consumer believes it is 800x600. + applyLogicalCanvasStyle(this.canvas, width ?? 0, height ?? 0) const viewport = measureViewport( width ?? 0, diff --git a/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts b/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts new file mode 100644 index 00000000000..bc3ad39c519 --- /dev/null +++ b/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts @@ -0,0 +1,51 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { + DragAndScale, + LGraph, + LGraphCanvas +} from '@/lib/litegraph/src/litegraph' +import { createTestCanvasElement } from '@/utils/__tests__/canvasTestUtils' + +describe('DragAndScale viewport size cache', () => { + beforeEach(() => { + vi.stubGlobal('devicePixelRatio', 1) + }) + + it('does not cache an unusable viewport size', () => { + // A hidden or not-yet-laid-out canvas measures 0x0. Caching that makes + // every later fit a silent no-op, because fitting rejects an empty + // rectangle — so fall back to measuring the element instead. + const ds = new DragAndScale( + createTestCanvasElement({ width: 800, height: 600 }) + ) + + ds.setViewportSize(0, 0) + + expect(ds.getViewportSize()).toEqual([800, 600]) + }) + + it('hands out a copy so a caller cannot poison the cache', () => { + const ds = new DragAndScale(createTestCanvasElement()) + ds.setViewportSize(800, 600) + + const mutated = ds.getViewportSize() + mutated[0] = 0 + mutated[1] = 0 + + expect(ds.getViewportSize()).toEqual([800, 600]) + }) + + it('forgets the previous element’s viewport when the canvas is replaced', () => { + const element = createTestCanvasElement({ width: 800, height: 600 }) + const canvas = new LGraphCanvas(element, new LGraph(), { + skip_render: true, + skip_events: true + }) + canvas.ds.setViewportSize(800, 600) + + canvas.setCanvas(createTestCanvasElement({ width: 400, height: 300 }), true) + + expect(canvas.ds.getViewportSize()).toEqual([400, 300]) + }) +}) diff --git a/src/renderer/core/canvas/__tests__/canvasViewport.test.ts b/src/renderer/core/canvas/__tests__/canvasViewport.test.ts index 0b368bf1595..26546ac93c1 100644 --- a/src/renderer/core/canvas/__tests__/canvasViewport.test.ts +++ b/src/renderer/core/canvas/__tests__/canvasViewport.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { - applyParentSizedCanvasStyle, + applyLogicalCanvasStyle, applyViewport, measureViewport, measureViewportFromElement @@ -121,6 +121,34 @@ describe('applyViewport', () => { expect(consumer.ds.setViewportSize).toHaveBeenCalledWith(800, 600) }) + it('restores the DPR transform a measurement probe reset, even when the backing size rounds back', () => { + // A CSS-sized canvas whose layout does not depend on its backing store, + // as `absolute inset-0 size-full` makes the real graph canvas. + const ctx = createMockCanvasRenderingContext2D() + const canvas = createTestCanvasElement({ ctx }) + const cssSize = { width: 800.1, height: 600 } + vi.spyOn(canvas, 'getBoundingClientRect').mockImplementation( + () => new DOMRect(0, 0, cssSize.width, cssSize.height) + ) + + applyViewport(measureViewportFromElement(canvas, 2), canvas, canvas) + expect(ctx.scale).toHaveBeenCalledExactlyOnceWith(2, 2) + + // A sub-pixel layout change: enough to re-probe, not enough to change the + // rounded backing-store size. The probe assigns `width`/`height`, which + // resets the 2D context to the identity transform. + cssSize.width = 800.2 + const reprobed = measureViewportFromElement(canvas, 2) + expect([reprobed.physicalWidth, reprobed.physicalHeight]).toEqual([ + canvas.width, + canvas.height + ]) + + applyViewport(reprobed, canvas, canvas) + + expect(ctx.scale).toHaveBeenNthCalledWith(2, 2, 2) + }) + it('does not reset backing stores that already match', () => { const viewport = measureViewport(800, 600, 2) const fg = createTestCanvasElement() @@ -141,12 +169,12 @@ describe('applyViewport', () => { }) }) -describe('applyParentSizedCanvasStyle', () => { +describe('applyLogicalCanvasStyle', () => { it('follows the parent while the canvas style is its own', () => { const canvas = createTestCanvasElement() - applyParentSizedCanvasStyle(canvas, 800, 600) - applyParentSizedCanvasStyle(canvas, 1000, 700) + applyLogicalCanvasStyle(canvas, 800, 600) + applyLogicalCanvasStyle(canvas, 1000, 700) expect([canvas.style.width, canvas.style.height]).toEqual([ '1000px', @@ -159,8 +187,28 @@ describe('applyParentSizedCanvasStyle', () => { canvas.style.width = '75%' canvas.style.height = '50vh' - applyParentSizedCanvasStyle(canvas, 800, 600) + applyLogicalCanvasStyle(canvas, 800, 600) expect([canvas.style.width, canvas.style.height]).toEqual(['75%', '50vh']) }) + + it('never pins a degenerate measurement', () => { + const canvas = createTestCanvasElement() + + // A parent measured before layout settles reports 0x0. Pinning that would + // hide the canvas until something else resized it. + applyLogicalCanvasStyle(canvas, 0, 0) + + expect([canvas.style.width, canvas.style.height]).toEqual(['', '']) + }) + + it('leaves a class-sized canvas to its stylesheet', () => { + // No inline style, but CSS already lays it out at the target size — as a + // `size-full` canvas inside an 800x600 parent does. + const canvas = createTestCanvasElement({ cssSize: [800, 600] }) + + applyLogicalCanvasStyle(canvas, 800, 600) + + expect([canvas.style.width, canvas.style.height]).toEqual(['', '']) + }) }) diff --git a/src/renderer/core/canvas/canvasViewport.ts b/src/renderer/core/canvas/canvasViewport.ts index a2e3285a3b3..bc0e171f5b6 100644 --- a/src/renderer/core/canvas/canvasViewport.ts +++ b/src/renderer/core/canvas/canvasViewport.ts @@ -16,12 +16,50 @@ const autoSizedStyleByCanvas = new WeakMap< HTMLCanvasElement, { width?: string; height?: string } >() +/** + * DPR the 2D context transform of each canvas was last scaled by. Assigning + * `width` or `height` resets a 2D context to the identity transform, so this + * is the only reliable record of whether the DPR transform is still applied. + */ +const appliedContextDprByCanvas = new WeakMap() -function applyParentSizedCanvasStyle( +/** + * Forget the DPR transform recorded for a canvas, because something assigned + * its backing-store dimensions and so reset its 2D context. + */ +function invalidateCanvasContextTransform(canvas: HTMLCanvasElement): void { + appliedContextDprByCanvas.delete(canvas) +} + +/** + * Pin the canvas's CSS box to its logical size, so layout follows the logical + * viewport rather than the DPR-scaled backing store. Applies to both the + * parent-derived fallback size and an explicit `resize(width, height)`; + * declines when the caller or a stylesheet already owns the box. + */ +function applyLogicalCanvasStyle( canvas: HTMLCanvasElement, width: number, height: number ): void { + // A degenerate measurement is never worth pinning: a 0x0 parent measured + // during mount would freeze the canvas at zero inline pixels, and the + // caller's own sizing would have been correct all along. + if (!(width > 0) || !(height > 0)) return + + // CSS already laying the canvas out at exactly this size means a class or + // stylesheet rule owns the box (the app canvas is `absolute inset-0 + // size-full`). Inline pixels would replace a live rule with a snapshot and + // stop the canvas following its parent. + const rect = canvas.getBoundingClientRect() + if ( + Math.abs(rect.width - width) < 1 && + Math.abs(rect.height - height) < 1 && + rect.width > 0 && + rect.height > 0 + ) + return + const { style } = canvas const previousStyle = autoSizedStyleByCanvas.get(canvas) ?? {} const nextStyle: { width?: string; height?: string } = {} @@ -95,6 +133,10 @@ function measureViewportFromElement( } finally { element.width = savedWidth element.height = savedHeight + // Restoring the backing store leaves the 2D context at the identity + // transform, so the DPR scale has to be re-applied even when the applied + // viewport is about to come back byte-identical. + invalidateCanvasContextTransform(element) } const width = cssRect.width || previousViewport?.cssWidth || initialRect.width const height = @@ -102,40 +144,48 @@ function measureViewportFromElement( return measureViewport(width, height, rawDpr) } +/** + * Size one canvas's backing store to `viewport` and leave its 2D context + * scaled by the applied DPR. + * + * Both are one concern because they share one mechanism: assigning `width` or + * `height` resets the context to the identity transform. So a size change + * always costs a re-scale, and a DPR-only change has to force a reset before + * scaling, since `scale()` multiplies the existing transform. + */ +function applySurfaceViewport( + canvas: HTMLCanvasElement, + viewport: CanvasViewport +): void { + const { physicalWidth, physicalHeight, dpr } = viewport + let contextReset = false + if (canvas.width !== physicalWidth) { + canvas.width = physicalWidth + contextReset = true + } + if (canvas.height !== physicalHeight) { + canvas.height = physicalHeight + contextReset = true + } + if (contextReset) invalidateCanvasContextTransform(canvas) + + if (appliedContextDprByCanvas.get(canvas) === dpr) return + + // The transform is unknown or wrong while the backing store already matches, + // so reassign one dimension purely to return the context to identity. + if (!contextReset) canvas.width = physicalWidth + canvas.getContext('2d')?.scale(dpr, dpr) + appliedContextDprByCanvas.set(canvas, dpr) +} + function applyViewport( viewport: CanvasViewport, fg: HTMLCanvasElement, bg: HTMLCanvasElement, consumer?: CanvasViewportConsumer ): CanvasViewport { - const previousForegroundViewport = appliedViewportByCanvas.get(fg) - const foregroundChanged = - fg.width !== viewport.physicalWidth || - fg.height !== viewport.physicalHeight || - previousForegroundViewport?.dpr !== viewport.dpr - if ( - fg.width !== viewport.physicalWidth || - previousForegroundViewport?.dpr !== viewport.dpr - ) - fg.width = viewport.physicalWidth - if (fg.height !== viewport.physicalHeight) fg.height = viewport.physicalHeight - if (foregroundChanged) fg.getContext('2d')?.scale(viewport.dpr, viewport.dpr) - if (bg !== fg) { - const previousBackgroundViewport = appliedViewportByCanvas.get(bg) - const backgroundChanged = - bg.width !== viewport.physicalWidth || - bg.height !== viewport.physicalHeight || - previousBackgroundViewport?.dpr !== viewport.dpr - if ( - bg.width !== viewport.physicalWidth || - previousBackgroundViewport?.dpr !== viewport.dpr - ) - bg.width = viewport.physicalWidth - if (bg.height !== viewport.physicalHeight) - bg.height = viewport.physicalHeight - if (backgroundChanged) - bg.getContext('2d')?.scale(viewport.dpr, viewport.dpr) - } + applySurfaceViewport(fg, viewport) + if (bg !== fg) applySurfaceViewport(bg, viewport) appliedViewportByCanvas.set(fg, viewport) appliedViewportByCanvas.set(bg, viewport) @@ -150,6 +200,6 @@ export { readBrowserDpr, measureViewport, measureViewportFromElement, - applyParentSizedCanvasStyle, + applyLogicalCanvasStyle, applyViewport } From 36527414bd6915d4d291fd36531f4755aedcd598 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 19:02:04 -0700 Subject: [PATCH 03/31] fix(canvas): give panel-aware framing a fallback and cancel stale subgraph fits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `visibleCanvasViewport` clamped `width - panel.width` to zero. Fitting and animating both reject a non-positive rectangle, so an empty remainder discarded the user's framing request outright instead of framing anything. It now falls back to the whole canvas: content partly behind the panel is still reachable by panning, whereas a dropped fit leaves the camera wherever it was with no feedback. Reachability note, measured on this branch: with the docked panel's current clamp (`window - reservedWorkspaceWidth`, reserved being at least the 56px toolbar rail) the uncovered strip cannot actually reach zero through the panel path today — a 900px window with the panel maximized leaves `[0, 0, 56, 800]`. So this is a guard against a latent trap in a shared helper, not a live user-facing bug, and it is covered at the function boundary rather than with a browser case that would only pass vacuously. `restoreViewport` scheduled a first-visit fit under the shared `subgraph-navigation-fit` key whose ownership predicate was the active graph id alone, and the cache-hit path returned without cancelling it. Leaving A for an already-visited B and coming back to A therefore made A's queued first-visit fit current again, so once the canvas became visible it ran and overwrote the cached viewport that had just been restored. Every arrival now cancels whatever an earlier arrival queued, including an earlier arrival at the same graph. Refs #19971. --- .../canvas/visibleCanvasViewport.test.ts | 15 +++++++ .../canvas/visibleCanvasViewport.ts | 9 ++++- src/stores/subgraphNavigationStore.ts | 6 +++ .../subgraphNavigationStore.viewport.test.ts | 40 ++++++++++++++++++- 4 files changed, 68 insertions(+), 2 deletions(-) diff --git a/src/composables/canvas/visibleCanvasViewport.test.ts b/src/composables/canvas/visibleCanvasViewport.test.ts index 858aba738aa..63d633e84aa 100644 --- a/src/composables/canvas/visibleCanvasViewport.test.ts +++ b/src/composables/canvas/visibleCanvasViewport.test.ts @@ -28,4 +28,19 @@ describe('visibleCanvasViewport', () => { visibleCanvasViewport({ ds: createTestDragAndScale(800, 450) }) ).toEqual([0, 0, 300, 450]) }) + + it('falls back to the whole canvas when the panel leaves nothing uncovered', () => { + const panel = useAgentPanelStore() + panel.enabled = true + panel.consentAccepted = true + panel.isOpen = true + panel.setWidth(500) + + // A narrow canvas fully covered by the panel. An empty rectangle is + // rejected by every fit and animate path, so the user's framing request + // would be discarded rather than deferred — fit the whole canvas instead. + expect( + visibleCanvasViewport({ ds: createTestDragAndScale(480, 450) }) + ).toEqual([0, 0, 480, 450]) + }) }) diff --git a/src/composables/canvas/visibleCanvasViewport.ts b/src/composables/canvas/visibleCanvasViewport.ts index bcc7a8162eb..a1bb4e1986b 100644 --- a/src/composables/canvas/visibleCanvasViewport.ts +++ b/src/composables/canvas/visibleCanvasViewport.ts @@ -8,5 +8,12 @@ export function visibleCanvasViewport( const panel = useAgentPanelStore() const [width, height] = canvas.ds.getViewportSize() const coveredWidth = panel.isVisible ? panel.width : 0 - return [0, 0, Math.max(width - coveredWidth, 0), height] + const uncoveredWidth = width - coveredWidth + // A panel wider than the canvas leaves nothing uncovered. Every fitting and + // animation path rejects a non-positive rectangle, so returning one silently + // discards the user's framing request instead of framing anything. Fall back + // to the whole canvas: content partly behind the panel is still reachable by + // panning, whereas a dropped fit leaves the canvas wherever it was. + if (!(uncoveredWidth > 0)) return [0, 0, width, height] + return [0, 0, uncoveredWidth, height] } diff --git a/src/stores/subgraphNavigationStore.ts b/src/stores/subgraphNavigationStore.ts index 27ac064d5f1..1af7bfc184f 100644 --- a/src/stores/subgraphNavigationStore.ts +++ b/src/stores/subgraphNavigationStore.ts @@ -137,6 +137,12 @@ export const useSubgraphNavigationStore = defineStore( const canvas = canvasStore.canvas if (!canvas) return + // Any queued fit belongs to an earlier arrival, including an earlier + // arrival at this same graph. Leaving A and returning to it makes a fit + // queued on A's first visit current again by graph id alone, so without + // this it runs after the cache restore below and overwrites it. + canvasScheduler.cancel('subgraph-navigation-fit') + const expectedKey = buildCacheKey(graphId) const viewport = viewportCache.get(expectedKey) if (viewport) { diff --git a/src/stores/subgraphNavigationStore.viewport.test.ts b/src/stores/subgraphNavigationStore.viewport.test.ts index 173466cf46e..5bceecaa196 100644 --- a/src/stores/subgraphNavigationStore.viewport.test.ts +++ b/src/stores/subgraphNavigationStore.viewport.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { nextTick } from 'vue' @@ -212,6 +212,44 @@ describe('useSubgraphNavigationStore - Viewport Persistence', () => { mockGraph._nodes = [] }) + it('does not let a first-visit fit queued for a hidden canvas overwrite a later cache restore', () => { + const store = useSubgraphNavigationStore() + store.viewportCache.delete(':sub-a') + setCanvasVisible(mockCanvas.canvas, false) + const mockGraph = app.graph as { nodes: unknown[]; _nodes: unknown[] } + mockGraph.nodes = [{ pos: [0, 0], size: [100, 100] }] + mockGraph._nodes = mockGraph.nodes + onTestFinished(() => { + mockGraph.nodes = [] + mockGraph._nodes = [] + }) + + // First visit to A while hidden: no cached viewport, so a fit is queued. + mockCanvas.subgraph = { id: 'sub-a' } as never + store.restoreViewport('sub-a') + + // Navigate away to an already-visited B. A cache hit applies the cached + // viewport and returns, leaving A's queued fit in the scheduler. + store.viewportCache.set(':sub-b', { scale: 1, offset: [0, 0] }) + mockCanvas.subgraph = { id: 'sub-b' } as never + store.restoreViewport('sub-b') + + // Back to A, now cached too, so this is also a cache hit. + mockCanvas.subgraph = { id: 'sub-a' } as never + store.viewportCache.set(':sub-a', { scale: 3, offset: [11, 22] }) + store.restoreViewport('sub-a') + + // The canvas becomes visible. The fit queued for A's first visit names + // the graph that is active again, so a graph-id-only ownership test + // makes it current and it clobbers the restore. + setCanvasVisible(mockCanvas.canvas, true) + useCanvasScheduler().flush() + + expect(useLitegraphService().fitView).not.toHaveBeenCalled() + expect(mockCanvas.ds.scale).toBe(3) + expect(mockCanvas.ds.offset).toEqual([11, 22]) + }) + it('skips a queued fit if the active graph changes while hidden', () => { const store = useSubgraphNavigationStore() store.viewportCache.delete(':root') From 356ae5284435c9be2c09568a978ee9bf23f8b881 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 19:42:23 -0700 Subject: [PATCH 04/31] test(canvas): pin the DPR transform resets applyViewport performs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The DPR-restore test asserted `ctx.scale` call counts against a context double whose `scale` is a no-op, so it could not tell an identity transform from a compounded one. Three resets in `applySurfaceViewport` / `measureViewportFromElement` were therefore unpinned, and deleting the reset-forcing `canvas.width = physicalWidth` write left the whole file green. Model the browser contract in the double instead: `scale()` multiplies an effective transform, and writing `width`/`height` resets it — including a same-value write, which is why `canvas.width = canvas.width` clears a canvas. Assert the effective transform. Two gaps the stronger assertion exposed, both on the `LGraphCanvas.resize` path where no measurement probe runs to reset the context for us: - A new DPR landing on an unchanged backing store (800px@2 then 533.33px@3, both 1600 physical) compounds to 6x without the forced reset. - A size change at an unchanged DPR leaves the context at identity if the recorded DPR is taken as proof the transform survived the write, drawing a 2x backing store at half size. This one is an ordinary window resize. Mutation-proved: removing the reset-forcing write, the probe's transform invalidation, the size-change invalidation, the recorded-DPR early return, or the degenerate-size guard each turns the file red. All five survived before. No production code changed. --- .../canvas/__tests__/canvasViewport.test.ts | 87 +++++++++++++++++-- 1 file changed, 80 insertions(+), 7 deletions(-) diff --git a/src/renderer/core/canvas/__tests__/canvasViewport.test.ts b/src/renderer/core/canvas/__tests__/canvasViewport.test.ts index 26546ac93c1..9d81bcfa068 100644 --- a/src/renderer/core/canvas/__tests__/canvasViewport.test.ts +++ b/src/renderer/core/canvas/__tests__/canvasViewport.test.ts @@ -11,6 +11,48 @@ import { createTestCanvasElement } from '@/utils/__tests__/canvasTestUtils' +/** + * A canvas whose context double tracks its *effective* scale, and whose + * backing-store writes reset that scale the way a real 2D context does — + * including when the value written is the one already there, which is why + * `canvas.width = canvas.width` clears a canvas. + * + * Call counts cannot tell an identity transform from a compounded one, so a + * `toHaveBeenNthCalledWith(2, 2, 2)` assertion passes just as happily on a 4x + * transform as on the correct 2x. Assert `transform` instead. + */ +function createTransformTrackingCanvas(cssSize?: { + width: number + height: number +}) { + const transform = { x: 1, y: 1 } + const ctx = createMockCanvasRenderingContext2D({ + scale: vi.fn((x: number, y: number) => { + transform.x *= x + transform.y *= y + }) + }) + const canvas = createTestCanvasElement({ ctx }) + for (const dimension of ['width', 'height'] as const) { + let backingStore = canvas[dimension] + Object.defineProperty(canvas, dimension, { + configurable: true, + get: () => backingStore, + set: (value: number) => { + backingStore = value + transform.x = 1 + transform.y = 1 + } + }) + } + if (cssSize) { + vi.spyOn(canvas, 'getBoundingClientRect').mockImplementation( + () => new DOMRect(0, 0, cssSize.width, cssSize.height) + ) + } + return { canvas, ctx, transform } +} + describe('measureViewport', () => { it('computes physical dimensions from CSS dimensions and DPR', () => { expect(measureViewport(800, 600, 2)).toEqual({ @@ -124,15 +166,11 @@ describe('applyViewport', () => { it('restores the DPR transform a measurement probe reset, even when the backing size rounds back', () => { // A CSS-sized canvas whose layout does not depend on its backing store, // as `absolute inset-0 size-full` makes the real graph canvas. - const ctx = createMockCanvasRenderingContext2D() - const canvas = createTestCanvasElement({ ctx }) const cssSize = { width: 800.1, height: 600 } - vi.spyOn(canvas, 'getBoundingClientRect').mockImplementation( - () => new DOMRect(0, 0, cssSize.width, cssSize.height) - ) + const { canvas, transform } = createTransformTrackingCanvas(cssSize) applyViewport(measureViewportFromElement(canvas, 2), canvas, canvas) - expect(ctx.scale).toHaveBeenCalledExactlyOnceWith(2, 2) + expect(transform).toEqual({ x: 2, y: 2 }) // A sub-pixel layout change: enough to re-probe, not enough to change the // rounded backing-store size. The probe assigns `width`/`height`, which @@ -143,10 +181,45 @@ describe('applyViewport', () => { canvas.width, canvas.height ]) + expect(transform).toEqual({ x: 1, y: 1 }) applyViewport(reprobed, canvas, canvas) - expect(ctx.scale).toHaveBeenNthCalledWith(2, 2, 2) + expect(transform).toEqual({ x: 2, y: 2 }) + }) + + it('does not compound the DPR scale when a new DPR lands on an unchanged backing store', () => { + const { canvas, transform } = createTransformTrackingCanvas() + + // The same 1600x1200 backing store described two ways: 800 CSS px at DPR + // 2, then 533.33 at DPR 3. `LGraphCanvas.resize` builds viewports with + // `measureViewport` directly, so no measurement probe runs in between to + // reset the context — `applyViewport` is the only thing that can know the + // transform is stale, and neither dimension changes to tell it. + applyViewport(measureViewport(800, 600, 2), canvas, canvas) + expect(transform).toEqual({ x: 2, y: 2 }) + + applyViewport(measureViewport(1600 / 3, 400, 3), canvas, canvas) + + // `scale()` multiplies the existing transform, so skipping the reset + // leaves 6x here and draws every node at twice its size. + expect(transform).toEqual({ x: 3, y: 3 }) + }) + + it('re-scales after a size change at an unchanged DPR', () => { + const { canvas, transform } = createTransformTrackingCanvas() + + // The ordinary window resize, again on the `LGraphCanvas.resize` path + // where no probe runs: writing the new backing size has already reset the + // context, while the recorded DPR still matches the requested one. + applyViewport(measureViewport(800, 600, 2), canvas, canvas) + expect(transform).toEqual({ x: 2, y: 2 }) + + applyViewport(measureViewport(1000, 700, 2), canvas, canvas) + + // Taking the recorded DPR as proof the transform survived leaves the + // context at identity, drawing a 2x backing store at half size. + expect(transform).toEqual({ x: 2, y: 2 }) }) it('does not reset backing stores that already match', () => { From ebe1fc69018564f907ea5db0f5e3b8bf84c8a139 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 19:51:05 -0700 Subject: [PATCH 05/31] test(app): pin the supersession gates after afterLoadGraph and the asset scans MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four ownership gates were added for one defect and the suite carried one test for them, so a mutation sweep that reverts them one at a time rather than one per defect finds three survivors: - the gate after `afterLoadGraph` could be deleted and the file stayed green, letting a superseded load run both asset pipelines against the newer load's live graph; - so could the gate after those pipelines, letting it post warnings that describe a graph that is no longer live; - so could the `!ChangeTracker.isLoadingGraph` guard on the retirement catch-up, which is the whole point of holding the suppression window by count — without it the scoped depth is tracked and then ignored. Two tests cover all three, reusing the overlapping-load scaffolds already here. The asset-scan one waits for the older load to reach `afterLoadGraph` before starting its replacement: `thenReturnOnce` blocks whichever load arrives first, and without the wait the newer load won it and hung. Sweep after this change — reverting any of the four gates, the scoped suppression, or the retirement guard turns the file red. The gate before `configure` still survives alone; it predates this PR and is unreachable while the earlier gate stands. No production code changed. --- src/scripts/app.test.ts | 83 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index e349af0eff4..513ccd5940e 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -800,6 +800,89 @@ describe('ComfyApp', () => { expect(ChangeTracker.isLoadingGraph).toBe(false) }) + it('does not post a superseded load’s warnings or retire errors a newer load has not recorded yet', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + ChangeTracker.isLoadingGraph = false + onTestFinished(() => { + ChangeTracker.isLoadingGraph = false + }) + const retireErrors = vi.spyOn( + useExecutionErrorStore(), + 'retireResolvedMissingNodePromptError' + ) + const releaseScan: Array<() => void> = [] + vi.mocked(runMissingModelPipeline).mockImplementation(async () => { + await new Promise((resolve) => releaseScan.push(resolve)) + return { missingModels: [], confirmedCandidates: [] } + }) + vi.spyOn( + missingMediaPipeline, + 'runMissingMediaPipeline' + ).mockResolvedValue(undefined) + + const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) + await vi.waitFor(() => expect(releaseScan).toHaveLength(1)) + const newerLoad = app.loadGraphData(createWorkflowGraphData(), false) + await vi.waitFor(() => expect(releaseScan).toHaveLength(2)) + + releaseScan[0]() + await olderLoad + + // The older load's scan results describe a graph that is no longer + // live, and the newer load owns the warnings surface and will post its + // own. + expect(mockWorkflowService.showPendingWarnings).not.toHaveBeenCalled() + // The retirement catch-up has to wait for the last overlapping window: + // running it here retires the newer load's errors before it has + // recorded them. + expect(retireErrors).not.toHaveBeenCalled() + + releaseScan[1]() + await newerLoad + + expect(mockWorkflowService.showPendingWarnings).toHaveBeenCalledOnce() + expect(retireErrors).toHaveBeenCalledOnce() + }) + + it('does not run a superseded load’s asset scans against the newer load’s graph', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + vi.mocked(runMissingModelPipeline).mockResolvedValue({ + missingModels: [], + confirmedCandidates: [] + }) + vi.spyOn( + missingMediaPipeline, + 'runMissingMediaPipeline' + ).mockResolvedValue(undefined) + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + // The older load commits and clears the `afterConfigureGraph` gate, + // then suspends in the last hook before the asset pipelines. + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('afterLoadGraph') + .thenReturnOnce(olderLoadBlocked) + + const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) + // `thenReturnOnce` blocks whichever load reaches the hook first, so wait + // for the older one to get there before starting its replacement. + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterLoadGraph' + ) + ) + await app.loadGraphData(createWorkflowGraphData(), false) + releaseOlderLoad() + await expect(olderLoad).resolves.toBeUndefined() + + // Both pipelines scan `rootGraph` and report against the load's own + // workflow, so only the load that owns the live graph may run them. + expect(runMissingModelPipeline).toHaveBeenCalledOnce() + }) + it('lets an older valid load commit when its newer replacement fails', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) From 582e3f2766fac280cbcebdcc50690a650615d674 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 20:21:37 -0700 Subject: [PATCH 06/31] test(app): record why the retirement guard is asserted as a call MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit asked for state verification here, per the repo's testing principles, and that is the right default. It does not work at this point in the test: the only moment a prompt error can be seeded is while both loads are parked in their asset scans, and `recordPromptError` does not persist a missing-node error inside an open suppression window — `lastPromptError` reads null immediately after recording, so there is no error to watch survive. Rather than contort the scenario around that, the comment now states the constraint and names the mutation that keeps the assertion honest. --- src/scripts/app.test.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 513ccd5940e..e95ed63ab17 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -807,6 +807,11 @@ describe('ComfyApp', () => { onTestFinished(() => { ChangeTracker.isLoadingGraph = false }) + // Asserted as a call rather than as retired state: `recordPromptError` + // does not persist a missing-node error while a suppression window is + // open, which is the only moment this test can seed one, so there is no + // error to watch survive. The mutation sweep is what keeps this honest + // — reverting the `!ChangeTracker.isLoadingGraph` guard turns it red. const retireErrors = vi.spyOn( useExecutionErrorStore(), 'retireResolvedMissingNodePromptError' @@ -833,15 +838,15 @@ describe('ComfyApp', () => { // live, and the newer load owns the warnings surface and will post its // own. expect(mockWorkflowService.showPendingWarnings).not.toHaveBeenCalled() - // The retirement catch-up has to wait for the last overlapping window: - // running it here retires the newer load's errors before it has - // recorded them. + // Retiring here would clear errors the newer load is still mid-flight + // over, before it has had the chance to record its own. expect(retireErrors).not.toHaveBeenCalled() releaseScan[1]() await newerLoad expect(mockWorkflowService.showPendingWarnings).toHaveBeenCalledOnce() + // Once the last window closes, the catch-up runs exactly once. expect(retireErrors).toHaveBeenCalledOnce() }) From 2278cf2d16248ab23b6774371ba2b62017c98925 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 04:14:35 -0700 Subject: [PATCH 07/31] test(app): pin the supersession gate between beforeLoadGraph and configure The ownership gate immediately before `rootGraph.configure` survived mutation on its own, and was flagged as unreachable defence on the grounds that the earlier `beforeLoadGraph` gate already stands. It is not unreachable: the two gates are not adjacent. `validateWorkflow`, the `beforeConfigureGraph` hook and `nodeReplacementStore.load()` all await between them, so a load that owned the graph at the first gate can lose it before reaching the second, and configuring then overwrites the newer committed graph with the older workflow. Removing the gate now turns exactly this test red and nothing else in the file, so it is load-bearing rather than defensive. Test-only; no production change. --- src/scripts/app.test.ts | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index e95ed63ab17..8d85da7a989 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -888,6 +888,45 @@ describe('ComfyApp', () => { expect(runMissingModelPipeline).toHaveBeenCalledOnce() }) + it('does not configure the graph when superseded between its two pre-commit gates', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + const configure = vi.spyOn(graph, 'configure') + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + // The gates at `beforeLoadGraph` and at `configure` are not adjacent: + // `validateWorkflow`, this hook and `nodeReplacementStore.load()` all + // await between them, so a load that owned the graph at the first gate + // can lose it before reaching the second. + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith( + 'beforeConfigureGraph', + expect.anything(), + expect.anything() + ) + .thenReturnOnce(olderLoadBlocked) + + const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'beforeConfigureGraph', + expect.anything(), + expect.anything() + ) + ) + await app.loadGraphData(createWorkflowGraphData(), false) + configure.mockClear() + releaseOlderLoad() + await expect(olderLoad).resolves.toBeUndefined() + + // Configuring here would overwrite the graph the newer load committed + // with this load's older workflow. + expect(configure).not.toHaveBeenCalled() + }) + it('lets an older valid load commit when its newer replacement fails', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) From d63d7f375b623b76805d838364dc0cfa9db5fda8 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 04:14:59 -0700 Subject: [PATCH 08/31] fix(app): extend graph-load ownership to the API JSON and A1111 imports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `loadGraphData` now refuses to mutate the graph once a newer load has committed, but it was the only one of three entry points taking part in that sequence. `loadApiJson` and the A1111 import await the same `beforeLoadGraph` hook and then run the same destructive `setGraph()`/`clean()` pair, and neither read nor advanced the committed sequence — so the hole stayed open in both directions: a superseded import erased the graph a newer load had just committed, and a load still suspended in its own hook erased a graph an import had just built, because the import was invisible to its ownership check. Both now take their id from the same sequence and commit through one helper. `loadApiJson` gates after `beforeLoadGraph` (before `setGraph`/`clean`), after the node-replacement fetch (before it creates nodes), and after `afterConfigureGraph` (before `afterLoadNewGraph` binds the file name to `rootGraph.serialize()`), and claims the graph once it is built. The A1111 path needs one extra mechanism: `importA1111` calls `graph.clear()` unconditionally the moment its pre-clear hook resolves, so the hook throws a private `SupersededGraphLoad` to stop it. A sentinel class rather than an `AbortError`, so an extension aborting its own `beforeLoadGraph` cannot be read as supersession; nothing has mutated the graph when it throws. It gates once on entry (the embeddings fetch precedes it, and the hook's `finally` clears the missing-node store that belongs to the newer load) and once before the clear. Every one of the seven guards is mutation-proved: removing any one turns exactly one of these tests red, with no overlap, so none is redundant defence. The browser case drives an API JSON import against an overlapping workflow load and asserts the rendered nodes; with the pre-destruction gate removed it fails with the user-visible symptom, `[data-node-id]` resolving to 0 elements. --- .../agentOverlappingWorkflowLoad.spec.ts | 69 +++++ src/scripts/app.test.ts | 285 ++++++++++++++++++ src/scripts/app.ts | 96 +++++- 3 files changed, 439 insertions(+), 11 deletions(-) diff --git a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts index 5ee82d7aeb9..01e18150e70 100644 --- a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts +++ b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts @@ -101,5 +101,74 @@ test.describe( await expect(vueNodes.getNodeByTitle('older workflow')).toHaveCount(0) }) }) + + /** + * The same defect in the sibling entry point. An API-JSON import awaits the + * same `beforeLoadGraph` hook and then runs the same destructive + * `setGraph()`/`clean()` pair, but took no part in the ownership sequence + * `loadGraphData` commits to — so it both erased a newer committed graph + * and could itself be erased by a load that was still suspended. + */ + test('the newer workflow survives a superseded API JSON import', async ({ + comfyPage, + agentPanel + }) => { + test.setTimeout(60_000) + const { page, vueNodes } = comfyPage + + await agentPanel.open() + await vueNodes.setEnabled(true) + + await test.step('hold an API JSON import open, then load a workflow', async () => { + await page.evaluate( + async ([extensionName, apiPrompt, newer]) => { + let release!: () => void + const held = new Promise((resolve) => { + release = resolve + }) + let holdNext = true + window.app!.registerExtension({ + name: extensionName, + beforeLoadGraph: async () => { + if (!holdNext) return + holdNext = false + await held + } + }) + + const apiImport = window.app!.loadApiJson( + apiPrompt, + 'superseded-api-prompt.json' + ) + // The workflow load commits while the import is parked inside + // `beforeLoadGraph`, before the import has touched the canvas. + await window.app!.loadGraphData(newer as never) + release() + await apiImport + }, + [ + `${STALL_EXTENSION}.apiJson`, + { + '1': { + class_type: 'EmptyLatentImage', + inputs: {}, + _meta: { title: 'superseded api import' } + } + }, + noteWorkflow('newer workflow') + ] as const + ) + }) + + await test.step('the canvas still shows the newer workflow', async () => { + await expect(vueNodes.nodes).toHaveCount(1) + await expect( + vueNodes.getNodeByTitle('newer workflow').first() + ).toBeVisible() + await expect( + vueNodes.getNodeByTitle('superseded api import') + ).toHaveCount(0) + }) + }) } ) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 8d85da7a989..0c30164b4cf 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -2929,6 +2929,291 @@ describe('ComfyApp', () => { ) }) + describe('graph-load ownership across the import paths', () => { + function markerNode(): LGraphNode { + const node = new LGraphNode('marker', 'marker') + node.id = toNodeId('marker') + return node + } + + it('does not let a superseded API JSON import erase the newer graph', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + const clean = vi.spyOn(app, 'clean').mockImplementation(() => {}) + let releaseImport!: () => void + const importBlocked = new Promise((resolve) => { + releaseImport = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('beforeLoadGraph') + .thenReturnOnce(importBlocked) + + // The import suspends in the same `beforeLoadGraph` hook `loadGraphData` + // awaits, and then clears the graph just as destructively. + const apiImport = app.loadApiJson({}, 'superseded.json') + await app.loadGraphData(createWorkflowGraphData(), true) + const survivor = markerNode() + graph.add(survivor) + vi.mocked(mockCanvas.setGraph).mockClear() + clean.mockClear() + releaseImport() + await apiImport + + expect(mockCanvas.setGraph).not.toHaveBeenCalled() + expect(clean).not.toHaveBeenCalled() + expect(graph.getNodeById(survivor.id)).toBe(survivor) + }) + + it('does not let a load still awaiting its hooks erase a committed API JSON import', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + const clean = vi.spyOn(app, 'clean').mockImplementation(() => {}) + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('beforeLoadGraph') + .thenReturnOnce(olderLoadBlocked) + + // The other direction of the same hole: an import that commits while a + // workflow load is suspended is invisible to the load's ownership check, + // so the load resumes believing it still owns the graph. + const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) + await app.loadApiJson({}, 'committed.json') + const survivor = markerNode() + graph.add(survivor) + vi.mocked(mockCanvas.setGraph).mockClear() + clean.mockClear() + releaseOlderLoad() + await olderLoad + + expect(mockCanvas.setGraph).not.toHaveBeenCalled() + expect(clean).not.toHaveBeenCalled() + expect(graph.getNodeById(survivor.id)).toBe(survivor) + }) + + it('does not add a superseded API JSON import’s nodes to the newer graph', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + vi.spyOn(app, 'clean').mockImplementation(() => {}) + let releaseReplacements!: () => void + const replacementsBlocked = new Promise((resolve) => { + releaseReplacements = resolve + }) + // The replacement manifest is fetched between this import's first + // ownership gate and the block that creates its nodes. + vi.spyOn(useNodeReplacementStore(), 'load').mockReturnValueOnce( + replacementsBlocked + ) + + const apiImport = app.loadApiJson( + { '1': { class_type: 'KSampler', inputs: {} } }, + 'superseded.json' + ) + await vi.waitFor(() => + expect(useNodeReplacementStore().load).toHaveBeenCalled() + ) + await app.loadGraphData(createWorkflowGraphData(), true) + releaseReplacements() + await apiImport + + expect(graph.nodes).toHaveLength(0) + }) + + it('does not bind a superseded API JSON import’s workflow to the newer graph', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + vi.spyOn(app, 'clean').mockImplementation(() => {}) + let releaseImport!: () => void + const importBlocked = new Promise((resolve) => { + releaseImport = resolve + }) + // The import has already built its graph and claimed ownership, then + // suspends in the last hook before it binds a workflow. + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('afterConfigureGraph', expect.anything()) + .thenReturnOnce(importBlocked) + + const apiImport = app.loadApiJson({}, 'superseded.json') + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterConfigureGraph', + expect.anything() + ) + ) + await app.loadGraphData(createWorkflowGraphData(), true) + mockWorkflowService.afterLoadNewGraph.mockClear() + releaseImport() + await apiImport + + // `afterLoadNewGraph` serializes the live graph into the workflow it is + // given, and the live graph is the newer load's. + expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() + }) + + it('does not let a superseded A1111 import clear the newer load’s missing nodes', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ + parameters: 'positive\nNegative prompt: negative\nSteps: 20' + }) + let releaseEmbeddings!: () => void + const embeddingsBlocked = new Promise((resolve) => { + releaseEmbeddings = resolve + }) + mockImportA1111.mockImplementation( + async (importGraph, _parameters, beforeGraphClear) => { + await embeddingsBlocked + await beforeGraphClear?.() + importGraph.clear() + return 'imported' + } + ) + + const a1111Import = app.handleFile( + createTestFile('a1111.png', 'image/png') + ) + await vi.waitFor(() => expect(mockImportA1111).toHaveBeenCalled()) + await app.loadGraphData(createWorkflowGraphData(), true) + const missingNodesStore = useMissingNodesErrorStore() + missingNodesStore.setMissingNodeTypes(['NewerLoadMissingNode']) + releaseEmbeddings() + await a1111Import + + // The import's pre-clear hook clears this store in a `finally`, so an + // import that lost the graph during the embeddings fetch has to refuse + // before that hook starts, not only before the clear. + expect(missingNodesStore.missingNodesError?.nodeTypes).toEqual([ + 'NewerLoadMissingNode' + ]) + }) + + it('does not let an A1111 import superseded inside beforeLoadGraph clear the newer graph', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ + parameters: 'positive\nNegative prompt: negative\nSteps: 20' + }) + let releaseBeforeLoad!: () => void + const beforeLoadBlocked = new Promise((resolve) => { + releaseBeforeLoad = resolve + }) + // The import owns the graph when its hook starts and loses it part-way + // through, so the gate at the top of the hook cannot catch this one. + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('beforeLoadGraph') + .thenReturnOnce(beforeLoadBlocked) + mockImportA1111.mockImplementation( + async (importGraph, _parameters, beforeGraphClear) => { + await beforeGraphClear?.() + importGraph.clear() + return 'imported' + } + ) + + const a1111Import = app.handleFile( + createTestFile('a1111.png', 'image/png') + ) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'beforeLoadGraph' + ) + ) + await app.loadGraphData(createWorkflowGraphData(), true) + const survivor = markerNode() + graph.add(survivor) + releaseBeforeLoad() + await a1111Import + + expect(graph.getNodeById(survivor.id)).toBe(survivor) + }) + + it('does not let a load still awaiting its hooks erase a committed A1111 import', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ + parameters: 'positive\nNegative prompt: negative\nSteps: 20' + }) + const clean = vi.spyOn(app, 'clean').mockImplementation(() => {}) + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('beforeLoadGraph') + .thenReturnOnce(olderLoadBlocked) + mockImportA1111.mockImplementation( + async (importGraph, _parameters, beforeGraphClear) => { + await beforeGraphClear?.() + importGraph.clear() + return 'imported' + } + ) + + // The workflow load suspends first and so consumes the blocked hook; the + // import that follows it runs through and claims the graph. + const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) + await app.handleFile(createTestFile('a1111.png', 'image/png')) + vi.mocked(mockCanvas.setGraph).mockClear() + clean.mockClear() + releaseOlderLoad() + await olderLoad + + expect(mockCanvas.setGraph).not.toHaveBeenCalled() + expect(clean).not.toHaveBeenCalled() + }) + + it('does not let a superseded A1111 import clear the newer graph', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ + parameters: 'positive\nNegative prompt: negative\nSteps: 20' + }) + let releaseEmbeddings!: () => void + const embeddingsBlocked = new Promise((resolve) => { + releaseEmbeddings = resolve + }) + // Mirrors the real `importA1111`: it awaits the embeddings endpoint, then + // the pre-clear hook, and only then clears the graph and builds into it. + mockImportA1111.mockImplementation( + async (importGraph, _parameters, beforeGraphClear) => { + await embeddingsBlocked + await beforeGraphClear?.() + importGraph.clear() + return 'imported' + } + ) + + const a1111Import = app.handleFile( + createTestFile('a1111.png', 'image/png') + ) + await vi.waitFor(() => expect(mockImportA1111).toHaveBeenCalled()) + await app.loadGraphData(createWorkflowGraphData(), true) + const survivor = markerNode() + graph.add(survivor) + releaseEmbeddings() + await a1111Import + + // `graph.clear()` is unconditional once the hook resolves, so refusing + // inside the hook is the last point that leaves the newer graph intact. + expect(graph.getNodeById(survivor.id)).toBe(survivor) + expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() + }) + }) + 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 45dd8800e28..c837e43ccad 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -166,7 +166,8 @@ import { deserialiseAndCreate } from '@/utils/vintageClipboard' import { PromptExecutionError, api } from './api' import type { ComfyApi } from './api' import { defaultGraph } from './defaultGraph' -import { importA1111 } from './pnginfo' +import { importA1111 } from './pnginfo'; +import type { A1111ImportOutcome } from './pnginfo'; import { applyPromotedWidgetControl } from './promotedWidgetControl' import { $el, ComfyUI } from './ui' import { ComfyAppMenu } from './ui/menu/index' @@ -303,6 +304,19 @@ function createNodeOutputsMutationView( }) } +/** + * Thrown out of an import's pre-clear hook when a newer graph load has already + * committed, because that hook's only way to stop the clear that follows it is + * to not return. A private class rather than an `AbortError` so that an + * extension aborting its own `beforeLoadGraph` cannot be read as supersession. + */ +class SupersededGraphLoad extends Error { + constructor() { + super('Graph load superseded by a newer load') + this.name = 'SupersededGraphLoad' + } +} + export class ComfyApp { /** * List of entries to queue @@ -1308,6 +1322,19 @@ export class ComfyApp { return loadId >= this.committedGraphLoadSequence } + /** + * Claim the graph for `loadId`, so any load or import still suspended in an + * earlier hook sees itself as superseded. Every path that builds a graph + * commits through here, which is what makes the three of them one sequence + * rather than three that cannot see each other. + */ + private commitGraphLoad(loadId: number): void { + this.committedGraphLoadSequence = Math.max( + loadId, + this.committedGraphLoadSequence + ) + } + /** * End a superseded load the way a failed one ends: notify `onGraphLoadError` * so any loading state a `beforeLoadGraph` listener opened for this load is @@ -1584,10 +1611,7 @@ export class ComfyApp { ) } - this.committedGraphLoadSequence = Math.max( - loadId, - this.committedGraphLoadSequence - ) + this.commitGraphLoad(loadId) const preservesPendingCamera = !restore_view && workflow !== null && @@ -2324,10 +2348,15 @@ export class ComfyApp { // Use parameters strictly as the final fallback if (parameters && typeof parameters === 'string') { - const outcome = await importA1111( - this.rootGraph, - parameters, - async () => { + // An A1111 import is a graph load too, and a slower one than most: it + // awaits the embeddings endpoint before its pre-clear hook runs, and the + // hook awaits `beforeLoadGraph` after that. + const loadId = ++this.graphLoadSequence + let outcome: A1111ImportOutcome + try { + outcome = await importA1111(this.rootGraph, parameters, async () => { + // `importA1111` awaited the embeddings endpoint to get here. + if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() try { // false: final destination; no later load republishes the hash. useWorkflowService().beforeLoadNewGraph(false) @@ -2335,9 +2364,21 @@ export class ComfyApp { } finally { useMissingNodesErrorStore().setMissingNodeTypes([]) } + // `graph.clear()` is unconditional once this hook resolves, so + // throwing out of it is the only way to stop the clear — and the + // last point at which a superseded import leaves the newer graph + // intact. Nothing has mutated the graph yet when this throws. + if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() this.canvas.setGraph(this.rootGraph) - } - ) + // Claimed here rather than after the import returns: everything + // `importA1111` does from this point on is synchronous. + this.commitGraphLoad(loadId) + }) + } catch (error) { + if (!(error instanceof SupersededGraphLoad)) throw error + await this.rejectSupersededGraphLoad() + return + } switch (outcome) { case 'core-nodes-unavailable': useToastStore().addAlert(t('toastMessages.a1111CoreNodesUnavailable')) @@ -2505,9 +2546,22 @@ export class ComfyApp { fileName: string, options: { deferWarnings?: boolean } = {} ): Promise { + // An API-JSON import is a graph load: it awaits the same `beforeLoadGraph` + // hook, then calls the same destructive `setGraph()`/`clean()` pair, and + // ends by binding a workflow to `rootGraph.serialize()`. It therefore takes + // its ownership from the same sequence `loadGraphData` uses, rather than + // being invisible to it in both directions. + const loadId = ++this.graphLoadSequence // false: no workflow load follows to republish the hash. useWorkflowService().beforeLoadNewGraph(false) await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + + // A newer load can commit while that hook awaits; `setGraph()` and + // `clean()` would then erase the graph it just committed. + if (!this.ownsGraphLoad(loadId)) { + await this.rejectSupersededGraphLoad() + return + } this.canvas.setGraph(this.rootGraph) withGraphIntentSource('load', () => this.clean()) @@ -2534,6 +2588,13 @@ export class ComfyApp { const missingNodeTypes: MissingNodeType[] = [] const nodeReplacementStore = useNodeReplacementStore() await nodeReplacementStore.load() + + // The replacement manifest is fetched, and the block below adds this + // import's nodes to whatever graph is live. + if (!this.ownsGraphLoad(loadId)) { + await this.rejectSupersededGraphLoad() + return + } withGraphIntentSource('load', () => { for (const id of ids) { const data = apiData[id] @@ -2704,12 +2765,25 @@ export class ComfyApp { app.rootGraph.arrange() }) + // The graph is built, which is this path's equivalent of `configure` + // returning: claim it so a `loadGraphData` still suspended in its own + // `beforeLoadGraph` cannot resume and wipe this import. + this.commitGraphLoad(loadId) + // Intentionally no beforeConfigureGraph: API JSON builds nodes directly // and never passes a ComfyWorkflowJSON through the configure stage. await useExtensionService().invokeExtensionsAsync( 'afterConfigureGraph', missingNodeTypes ) + + // Same reason as in `loadGraphData`: `afterLoadNewGraph` binds `fileName` + // to `rootGraph.serialize()`, so a newer load that committed while that + // hook awaited would be serialized into this import's workflow. + if (!this.ownsGraphLoad(loadId)) { + await this.rejectSupersededGraphLoad() + return + } await useWorkflowService().afterLoadNewGraph( fileName, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON From 4f660aadc7dbb933470f0ddddea4f66afbc5528a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 04:15:51 -0700 Subject: [PATCH 09/31] docs(canvas): record the intrinsic-size residual at the logical-style guard The early return that stops `applyLogicalCanvasStyle` clobbering a stylesheet-owned box also declines for an unstyled canvas whose own backing store is what sizes its shrink-to-fit parent, which makes a parent-sized `resize()` grow it by `dpr` on every pass. Reproduced and left unfixed, because each cheap discriminator for "unstyled" misclassifies a real stylesheet-owned canvas somewhere that matters more: `rect` against the backing store collides at DPR 1, `getComputedStyle` resolves to the used value and cannot see a specified `auto`, and "requested equals the previously applied physical size" fires on an ordinary 800 -> 1600 CSS px window resize at DPR 2. Writing the counterexamples down next to the guard so the next reader does not re-derive them, or trade a reachable defect for an unreachable one. Comment only; no behaviour change. --- src/renderer/core/canvas/canvasViewport.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/renderer/core/canvas/canvasViewport.ts b/src/renderer/core/canvas/canvasViewport.ts index bc0e171f5b6..bd28c51824e 100644 --- a/src/renderer/core/canvas/canvasViewport.ts +++ b/src/renderer/core/canvas/canvasViewport.ts @@ -51,6 +51,19 @@ function applyLogicalCanvasStyle( // stylesheet rule owns the box (the app canvas is `absolute inset-0 // size-full`). Inline pixels would replace a live rule with a snapshot and // stop the canvas following its parent. + // + // Known residual: an *unstyled* canvas whose own backing store is what sizes + // its shrink-to-fit parent satisfies this test too, so a parent-sized + // `resize()` on one grows it by `dpr` each pass. It is accepted rather than + // fixed because every cheap discriminator for "unstyled" misclassifies a + // real stylesheet-owned canvas: `rect` against the backing store collides at + // DPR 1, `getComputedStyle` resolves to the used value and cannot see that + // the specified value is `auto`, and "requested equals the previously + // applied physical size" fires on an ordinary 800 -> 1600 CSS px window + // resize at DPR 2. The only sound test is a zero-size layout probe, which + // costs a forced reflow and a context reset on every resize. The product + // path is unaffected: `GraphCanvas.vue` is the only `LGraphCanvas` + // construction and its canvas is stylesheet-sized. const rect = canvas.getBoundingClientRect() if ( Math.abs(rect.width - width) < 1 && From 64d36ad3e77b02e32329c8d5e17f8bdd67411d67 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 3 Oct 2026 11:22:03 +0000 Subject: [PATCH 10/31] [automated] Apply ESLint and Oxfmt fixes --- src/scripts/app.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index c837e43ccad..8ddf72938c9 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -166,8 +166,8 @@ import { deserialiseAndCreate } from '@/utils/vintageClipboard' import { PromptExecutionError, api } from './api' import type { ComfyApi } from './api' import { defaultGraph } from './defaultGraph' -import { importA1111 } from './pnginfo'; -import type { A1111ImportOutcome } from './pnginfo'; +import { importA1111 } from './pnginfo' +import type { A1111ImportOutcome } from './pnginfo' import { applyPromotedWidgetControl } from './promotedWidgetControl' import { $el, ComfyUI } from './ui' import { ComfyAppMenu } from './ui/menu/index' From 4e4adb2b8cf4d4ce5c2f09206395f9472d70c5de Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 04:44:21 -0700 Subject: [PATCH 11/31] fix(app): fence A1111 post-commit ownership --- src/scripts/app.test.ts | 78 +++++++++++++++++++++++++++++++++++++++++ src/scripts/app.ts | 8 ++++- 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 0c30164b4cf..185f6dfae19 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -3139,6 +3139,84 @@ describe('ComfyApp', () => { expect(graph.getNodeById(survivor.id)).toBe(survivor) }) + it('does not let an A1111 import superseded inside beforeLoadGraph clear the newer load’s missing nodes', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ + parameters: 'positive\nNegative prompt: negative\nSteps: 20' + }) + let releaseBeforeLoad!: () => void + const beforeLoadBlocked = new Promise((resolve) => { + releaseBeforeLoad = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('beforeLoadGraph') + .thenReturnOnce(beforeLoadBlocked) + mockImportA1111.mockImplementation( + async (_importGraph, _parameters, beforeGraphClear) => { + await beforeGraphClear?.() + return 'imported' + } + ) + + const a1111Import = app.handleFile( + createTestFile('a1111.png', 'image/png') + ) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'beforeLoadGraph' + ) + ) + await app.loadGraphData(createWorkflowGraphData(), true) + const missingNodesStore = useMissingNodesErrorStore() + missingNodesStore.setMissingNodeTypes(['NewerLoadMissingNode']) + releaseBeforeLoad() + await a1111Import + + expect(missingNodesStore.missingNodesError?.nodeTypes).toEqual([ + 'NewerLoadMissingNode' + ]) + }) + + it('does not bind a superseded A1111 import’s workflow to the newer graph', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ + parameters: 'positive\nNegative prompt: negative\nSteps: 20' + }) + let releaseAfterConfigure!: () => void + const afterConfigureBlocked = new Promise((resolve) => { + releaseAfterConfigure = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('afterConfigureGraph', expect.anything()) + .thenReturnOnce(afterConfigureBlocked) + mockImportA1111.mockImplementation( + async (_importGraph, _parameters, beforeGraphClear) => { + await beforeGraphClear?.() + return 'imported' + } + ) + + const a1111Import = app.handleFile( + createTestFile('a1111.png', 'image/png') + ) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterConfigureGraph', + expect.anything() + ) + ) + await app.loadGraphData(createWorkflowGraphData(), true) + mockWorkflowService.afterLoadNewGraph.mockClear() + releaseAfterConfigure() + await a1111Import + + expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() + }) + it('does not let a load still awaiting its hooks erase a committed A1111 import', async () => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 8ddf72938c9..7216701fb84 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -2362,7 +2362,9 @@ export class ComfyApp { useWorkflowService().beforeLoadNewGraph(false) await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') } finally { - useMissingNodesErrorStore().setMissingNodeTypes([]) + if (this.ownsGraphLoad(loadId)) { + useMissingNodesErrorStore().setMissingNodeTypes([]) + } } // `graph.clear()` is unconditional once this hook resolves, so // throwing out of it is the only way to stop the clear — and the @@ -2408,6 +2410,10 @@ export class ComfyApp { 'afterConfigureGraph', [] ) + if (!this.ownsGraphLoad(loadId)) { + await this.rejectSupersededGraphLoad() + return + } await useWorkflowService().afterLoadNewGraph( fileName, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON From 8a9a0fa8e9abce196776eb152397bd024c27e9f9 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 12:09:17 -0700 Subject: [PATCH 12/31] refactor: drop the justification comments flagged in review The repo AGENTS.md forbids multi-line block comments that justify a trivial change, and this PR had accumulated 88 of them across production code, unit tests and the browser spec. Applies the reviewer's per-site delete suggestions, drops three `as never` casts the typechecker does not need, and keeps the #19971 provenance link on the browser spec as a single line. Declined, with reasons, rather than applied: - Deleting agentOverlappingWorkflowLoad.spec.ts. It is the only black-box proof of the overlapping-load behaviour. - Removing `vueNodes.setEnabled(true)`. The `@vue-nodes` tag does set `Comfy.VueNodes.Enabled`, but `setEnabled` also awaits `waitForNodes()`, which is the readiness barrier before `page.evaluate(window.app!...)`. - Replacing `{ id: 'sub-a' } as never` with `createTestSubgraph`. The reviewer notes they did not check that the fixture works under this file's `@/scripts/app` mock, and the surrounding tests use the same cast. --- .../agentOverlappingWorkflowLoad.spec.ts | 32 ++------- .../canvas/visibleCanvasViewport.test.ts | 3 - .../canvas/visibleCanvasViewport.ts | 5 -- src/lib/litegraph/src/DragAndScale.ts | 9 --- .../litegraph/src/LGraphCanvas.resize.test.ts | 5 -- src/lib/litegraph/src/LGraphCanvas.ts | 10 --- .../DragAndScale.viewportSize.test.ts | 3 - .../canvas/__tests__/canvasViewport.test.ts | 31 -------- src/renderer/core/canvas/canvasViewport.ts | 49 ------------- src/scripts/app.test.ts | 57 --------------- src/scripts/app.ts | 70 ------------------- src/scripts/changeTracker.ts | 11 --- src/stores/subgraphNavigationStore.ts | 4 -- .../subgraphNavigationStore.viewport.test.ts | 7 -- 14 files changed, 4 insertions(+), 292 deletions(-) diff --git a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts index 01e18150e70..d2568edd464 100644 --- a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts +++ b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts @@ -4,20 +4,6 @@ import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/w import { agentTest as test } from '@e2e/tests/agent/agentPanelMocks' -/** - * Regression for https://github.com/Comfy-Org/ComfyUI_frontend/issues/19971: - * "Reject a superseded graph load before its first destructive store/canvas - * mutation" and "Re-check graph-load ownership after awaited lifecycle hooks". - * - * `loadGraphData` awaits `beforeLoadGraph` and then immediately clears the - * canvas and the resource stores, but it did not compare its own load id with - * the committed one until well after that. So when two loads overlap — the - * user switching workflows faster than the first load resolves, or any - * extension holding `beforeLoadGraph` open — the older load woke up, erased - * the graph the newer load had already committed, and only then reported - * itself superseded. The canvas was left holding the workflow the user had - * navigated away from, or nothing at all. - */ const STALL_EXTENSION = 'e2e.op329.stallBeforeLoadGraph' function noteWorkflow(title: string): ComfyWorkflowJSON { @@ -46,6 +32,7 @@ function noteWorkflow(title: string): ComfyWorkflowJSON { } } +// Regression for https://github.com/Comfy-Org/ComfyUI_frontend/issues/19971 test.describe( 'Overlapping workflow loads', { tag: ['@cloud', '@agent', '@vue-nodes'] }, @@ -77,10 +64,8 @@ test.describe( } }) - const olderLoad = window.app!.loadGraphData(older as never) - const newerLoad = window.app!.loadGraphData(newer as never) - // The newer load runs to completion and commits its graph while - // the older one is still parked inside `beforeLoadGraph`. + const olderLoad = window.app!.loadGraphData(older) + const newerLoad = window.app!.loadGraphData(newer) await newerLoad release() await olderLoad @@ -102,13 +87,6 @@ test.describe( }) }) - /** - * The same defect in the sibling entry point. An API-JSON import awaits the - * same `beforeLoadGraph` hook and then runs the same destructive - * `setGraph()`/`clean()` pair, but took no part in the ownership sequence - * `loadGraphData` commits to — so it both erased a newer committed graph - * and could itself be erased by a load that was still suspended. - */ test('the newer workflow survives a superseded API JSON import', async ({ comfyPage, agentPanel @@ -140,9 +118,7 @@ test.describe( apiPrompt, 'superseded-api-prompt.json' ) - // The workflow load commits while the import is parked inside - // `beforeLoadGraph`, before the import has touched the canvas. - await window.app!.loadGraphData(newer as never) + await window.app!.loadGraphData(newer) release() await apiImport }, diff --git a/src/composables/canvas/visibleCanvasViewport.test.ts b/src/composables/canvas/visibleCanvasViewport.test.ts index 63d633e84aa..02883089354 100644 --- a/src/composables/canvas/visibleCanvasViewport.test.ts +++ b/src/composables/canvas/visibleCanvasViewport.test.ts @@ -36,9 +36,6 @@ describe('visibleCanvasViewport', () => { panel.isOpen = true panel.setWidth(500) - // A narrow canvas fully covered by the panel. An empty rectangle is - // rejected by every fit and animate path, so the user's framing request - // would be discarded rather than deferred — fit the whole canvas instead. expect( visibleCanvasViewport({ ds: createTestDragAndScale(480, 450) }) ).toEqual([0, 0, 480, 450]) diff --git a/src/composables/canvas/visibleCanvasViewport.ts b/src/composables/canvas/visibleCanvasViewport.ts index a1bb4e1986b..478b72cdb13 100644 --- a/src/composables/canvas/visibleCanvasViewport.ts +++ b/src/composables/canvas/visibleCanvasViewport.ts @@ -9,11 +9,6 @@ export function visibleCanvasViewport( const [width, height] = canvas.ds.getViewportSize() const coveredWidth = panel.isVisible ? panel.width : 0 const uncoveredWidth = width - coveredWidth - // A panel wider than the canvas leaves nothing uncovered. Every fitting and - // animation path rejects a non-positive rectangle, so returning one silently - // discards the user's framing request instead of framing anything. Fall back - // to the whole canvas: content partly behind the panel is still reachable by - // panning, whereas a dropped fit leaves the canvas wherever it was. if (!(uncoveredWidth > 0)) return [0, 0, width, height] return [0, 0, uncoveredWidth, height] } diff --git a/src/lib/litegraph/src/DragAndScale.ts b/src/lib/litegraph/src/DragAndScale.ts index de4b3d36147..695a2e70f0c 100644 --- a/src/lib/litegraph/src/DragAndScale.ts +++ b/src/lib/litegraph/src/DragAndScale.ts @@ -121,12 +121,6 @@ export class DragAndScale { visible_area.resizeBottomRight(endx, endy) } - /** - * Record the applied CSS viewport size. A non-positive size is not a usable - * viewport, so it clears the cache rather than being stored: every consumer - * rejects a zero rectangle, and the measurement fallbacks below can still - * find a real size. - */ setViewportSize(width: number, height: number): void { this.viewportSize = width > 0 && @@ -137,15 +131,12 @@ export class DragAndScale { : undefined } - /** Discard the cached viewport size, e.g. because the element was replaced. */ invalidateViewportSize(): void { this.viewportSize = undefined } getViewportSize(): [number, number] { const cached = this.viewportSize - // Return a copy: callers mutate the rectangles they are handed, and the - // cache is read by every hit test and framing operation. if (cached) return [cached[0], cached[1]] const rect = this.element.getBoundingClientRect() diff --git a/src/lib/litegraph/src/LGraphCanvas.resize.test.ts b/src/lib/litegraph/src/LGraphCanvas.resize.test.ts index 1af5c96e189..5d1014807cb 100644 --- a/src/lib/litegraph/src/LGraphCanvas.resize.test.ts +++ b/src/lib/litegraph/src/LGraphCanvas.resize.test.ts @@ -75,15 +75,10 @@ describe('LGraphCanvas.resize', () => { const { canvas } = createParentSizedCanvas() vi.stubGlobal('devicePixelRatio', 1) canvas.resize(800, 600) - // A zoom level below the DPR-1 readability threshold (8 / (14 * √1)). canvas.ds.scale = 0.4 canvas.ds.computeVisibleArea(undefined) expect(canvas.low_quality).toBe(true) - // Moving to a high-DPR display raises readability, so the same zoom is - // now above the threshold (8 / (14 * √4)) and should render at full - // quality. The threshold derives from DPR, so applying one has to - // recompute it. vi.stubGlobal('devicePixelRatio', 4) canvas.resize(800, 600) diff --git a/src/lib/litegraph/src/LGraphCanvas.ts b/src/lib/litegraph/src/LGraphCanvas.ts index 3db414771f9..48abf0084d9 100644 --- a/src/lib/litegraph/src/LGraphCanvas.ts +++ b/src/lib/litegraph/src/LGraphCanvas.ts @@ -1047,11 +1047,6 @@ export class LGraphCanvas implements CustomEventDispatcher return this._dpr } - /** - * Applying a new DPR changes the zoom level at which text stops being - * readable, so the LOD threshold is derived here rather than left for a - * caller to remember. - */ set dpr(value: number) { if (this._dpr === value) return this._dpr = value @@ -2211,7 +2206,6 @@ export class LGraphCanvas implements CustomEventDispatcher // maybe detach events from old_canvas this.canvas = element this.ds.element = element - // The cached CSS viewport describes the outgoing element, not this one. this.ds.invalidateViewportSize() this.pointer.element = element @@ -6702,10 +6696,6 @@ export class LGraphCanvas implements CustomEventDispatcher height = parent.offsetHeight } - // Explicit dimensions are CSS pixels, exactly as the parent fallback is. - // Without pinning them the backing store alone drives layout, so a - // `resize(800, 600)` at DPR 2 lays the canvas out at 1600x1200 while every - // viewport consumer believes it is 800x600. applyLogicalCanvasStyle(this.canvas, width ?? 0, height ?? 0) const viewport = measureViewport( diff --git a/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts b/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts index bc3ad39c519..d5ebde10a6c 100644 --- a/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts +++ b/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts @@ -13,9 +13,6 @@ describe('DragAndScale viewport size cache', () => { }) it('does not cache an unusable viewport size', () => { - // A hidden or not-yet-laid-out canvas measures 0x0. Caching that makes - // every later fit a silent no-op, because fitting rejects an empty - // rectangle — so fall back to measuring the element instead. const ds = new DragAndScale( createTestCanvasElement({ width: 800, height: 600 }) ) diff --git a/src/renderer/core/canvas/__tests__/canvasViewport.test.ts b/src/renderer/core/canvas/__tests__/canvasViewport.test.ts index 9d81bcfa068..b2b2f0cde66 100644 --- a/src/renderer/core/canvas/__tests__/canvasViewport.test.ts +++ b/src/renderer/core/canvas/__tests__/canvasViewport.test.ts @@ -11,16 +11,6 @@ import { createTestCanvasElement } from '@/utils/__tests__/canvasTestUtils' -/** - * A canvas whose context double tracks its *effective* scale, and whose - * backing-store writes reset that scale the way a real 2D context does — - * including when the value written is the one already there, which is why - * `canvas.width = canvas.width` clears a canvas. - * - * Call counts cannot tell an identity transform from a compounded one, so a - * `toHaveBeenNthCalledWith(2, 2, 2)` assertion passes just as happily on a 4x - * transform as on the correct 2x. Assert `transform` instead. - */ function createTransformTrackingCanvas(cssSize?: { width: number height: number @@ -164,17 +154,12 @@ describe('applyViewport', () => { }) it('restores the DPR transform a measurement probe reset, even when the backing size rounds back', () => { - // A CSS-sized canvas whose layout does not depend on its backing store, - // as `absolute inset-0 size-full` makes the real graph canvas. const cssSize = { width: 800.1, height: 600 } const { canvas, transform } = createTransformTrackingCanvas(cssSize) applyViewport(measureViewportFromElement(canvas, 2), canvas, canvas) expect(transform).toEqual({ x: 2, y: 2 }) - // A sub-pixel layout change: enough to re-probe, not enough to change the - // rounded backing-store size. The probe assigns `width`/`height`, which - // resets the 2D context to the identity transform. cssSize.width = 800.2 const reprobed = measureViewportFromElement(canvas, 2) expect([reprobed.physicalWidth, reprobed.physicalHeight]).toEqual([ @@ -191,34 +176,22 @@ describe('applyViewport', () => { it('does not compound the DPR scale when a new DPR lands on an unchanged backing store', () => { const { canvas, transform } = createTransformTrackingCanvas() - // The same 1600x1200 backing store described two ways: 800 CSS px at DPR - // 2, then 533.33 at DPR 3. `LGraphCanvas.resize` builds viewports with - // `measureViewport` directly, so no measurement probe runs in between to - // reset the context — `applyViewport` is the only thing that can know the - // transform is stale, and neither dimension changes to tell it. applyViewport(measureViewport(800, 600, 2), canvas, canvas) expect(transform).toEqual({ x: 2, y: 2 }) applyViewport(measureViewport(1600 / 3, 400, 3), canvas, canvas) - // `scale()` multiplies the existing transform, so skipping the reset - // leaves 6x here and draws every node at twice its size. expect(transform).toEqual({ x: 3, y: 3 }) }) it('re-scales after a size change at an unchanged DPR', () => { const { canvas, transform } = createTransformTrackingCanvas() - // The ordinary window resize, again on the `LGraphCanvas.resize` path - // where no probe runs: writing the new backing size has already reset the - // context, while the recorded DPR still matches the requested one. applyViewport(measureViewport(800, 600, 2), canvas, canvas) expect(transform).toEqual({ x: 2, y: 2 }) applyViewport(measureViewport(1000, 700, 2), canvas, canvas) - // Taking the recorded DPR as proof the transform survived leaves the - // context at identity, drawing a 2x backing store at half size. expect(transform).toEqual({ x: 2, y: 2 }) }) @@ -268,16 +241,12 @@ describe('applyLogicalCanvasStyle', () => { it('never pins a degenerate measurement', () => { const canvas = createTestCanvasElement() - // A parent measured before layout settles reports 0x0. Pinning that would - // hide the canvas until something else resized it. applyLogicalCanvasStyle(canvas, 0, 0) expect([canvas.style.width, canvas.style.height]).toEqual(['', '']) }) it('leaves a class-sized canvas to its stylesheet', () => { - // No inline style, but CSS already lays it out at the target size — as a - // `size-full` canvas inside an 800x600 parent does. const canvas = createTestCanvasElement({ cssSize: [800, 600] }) applyLogicalCanvasStyle(canvas, 800, 600) diff --git a/src/renderer/core/canvas/canvasViewport.ts b/src/renderer/core/canvas/canvasViewport.ts index bd28c51824e..96aa9042f81 100644 --- a/src/renderer/core/canvas/canvasViewport.ts +++ b/src/renderer/core/canvas/canvasViewport.ts @@ -16,54 +16,19 @@ const autoSizedStyleByCanvas = new WeakMap< HTMLCanvasElement, { width?: string; height?: string } >() -/** - * DPR the 2D context transform of each canvas was last scaled by. Assigning - * `width` or `height` resets a 2D context to the identity transform, so this - * is the only reliable record of whether the DPR transform is still applied. - */ const appliedContextDprByCanvas = new WeakMap() -/** - * Forget the DPR transform recorded for a canvas, because something assigned - * its backing-store dimensions and so reset its 2D context. - */ function invalidateCanvasContextTransform(canvas: HTMLCanvasElement): void { appliedContextDprByCanvas.delete(canvas) } -/** - * Pin the canvas's CSS box to its logical size, so layout follows the logical - * viewport rather than the DPR-scaled backing store. Applies to both the - * parent-derived fallback size and an explicit `resize(width, height)`; - * declines when the caller or a stylesheet already owns the box. - */ function applyLogicalCanvasStyle( canvas: HTMLCanvasElement, width: number, height: number ): void { - // A degenerate measurement is never worth pinning: a 0x0 parent measured - // during mount would freeze the canvas at zero inline pixels, and the - // caller's own sizing would have been correct all along. if (!(width > 0) || !(height > 0)) return - // CSS already laying the canvas out at exactly this size means a class or - // stylesheet rule owns the box (the app canvas is `absolute inset-0 - // size-full`). Inline pixels would replace a live rule with a snapshot and - // stop the canvas following its parent. - // - // Known residual: an *unstyled* canvas whose own backing store is what sizes - // its shrink-to-fit parent satisfies this test too, so a parent-sized - // `resize()` on one grows it by `dpr` each pass. It is accepted rather than - // fixed because every cheap discriminator for "unstyled" misclassifies a - // real stylesheet-owned canvas: `rect` against the backing store collides at - // DPR 1, `getComputedStyle` resolves to the used value and cannot see that - // the specified value is `auto`, and "requested equals the previously - // applied physical size" fires on an ordinary 800 -> 1600 CSS px window - // resize at DPR 2. The only sound test is a zero-size layout probe, which - // costs a forced reflow and a context reset on every resize. The product - // path is unaffected: `GraphCanvas.vue` is the only `LGraphCanvas` - // construction and its canvas is stylesheet-sized. const rect = canvas.getBoundingClientRect() if ( Math.abs(rect.width - width) < 1 && @@ -146,9 +111,6 @@ function measureViewportFromElement( } finally { element.width = savedWidth element.height = savedHeight - // Restoring the backing store leaves the 2D context at the identity - // transform, so the DPR scale has to be re-applied even when the applied - // viewport is about to come back byte-identical. invalidateCanvasContextTransform(element) } const width = cssRect.width || previousViewport?.cssWidth || initialRect.width @@ -157,15 +119,6 @@ function measureViewportFromElement( return measureViewport(width, height, rawDpr) } -/** - * Size one canvas's backing store to `viewport` and leave its 2D context - * scaled by the applied DPR. - * - * Both are one concern because they share one mechanism: assigning `width` or - * `height` resets the context to the identity transform. So a size change - * always costs a re-scale, and a DPR-only change has to force a reset before - * scaling, since `scale()` multiplies the existing transform. - */ function applySurfaceViewport( canvas: HTMLCanvasElement, viewport: CanvasViewport @@ -184,8 +137,6 @@ function applySurfaceViewport( if (appliedContextDprByCanvas.get(canvas) === dpr) return - // The transform is unknown or wrong while the backing store already matches, - // so reassign one dimension purely to return the context to identity. if (!contextReset) canvas.width = physicalWidth canvas.getContext('2d')?.scale(dpr, dpr) appliedContextDprByCanvas.set(canvas, dpr) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 185f6dfae19..f921279a478 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -733,8 +733,6 @@ describe('ComfyApp', () => { releaseOlderLoad() await expect(olderLoad).resolves.toBeUndefined() - // Both of these erase the graph the newer load just committed, and the - // supersession check used to sit downstream of them. expect(setGraph).not.toHaveBeenCalled() expect(clean).not.toHaveBeenCalled() }) @@ -746,8 +744,6 @@ describe('ComfyApp', () => { const olderLoadBlocked = new Promise((resolve) => { releaseOlderLoad = resolve }) - // The older load commits, then suspends inside a lifecycle hook that - // runs after the point where its ownership was last checked. vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith('afterConfigureGraph', expect.anything()) .thenReturnOnce(olderLoadBlocked) @@ -757,7 +753,6 @@ describe('ComfyApp', () => { releaseOlderLoad() await expect(olderLoad).resolves.toBeUndefined() - // Only the newer load may bind a workflow to the live graph. expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() }) @@ -778,21 +773,14 @@ describe('ComfyApp', () => { 'runMissingMediaPipeline' ).mockResolvedValue(undefined) - // The older load owns the graph when it reaches its asset scan, and - // suspends there. const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) await vi.waitFor(() => expect(releaseScan).toHaveLength(1)) - // A newer load then commits and suspends on its own scan, so both are - // inside a suppression window at once. const newerLoad = app.loadGraphData(createWorkflowGraphData(), false) await vi.waitFor(() => expect(releaseScan).toHaveLength(2)) releaseScan[0]() await olderLoad - // A single shared boolean let the superseded load's `finally` end the - // newer load's suppression window, un-gating change capture and error - // retirement while the newer load was still mid-flight. expect(ChangeTracker.isLoadingGraph).toBe(true) releaseScan[1]() @@ -807,11 +795,6 @@ describe('ComfyApp', () => { onTestFinished(() => { ChangeTracker.isLoadingGraph = false }) - // Asserted as a call rather than as retired state: `recordPromptError` - // does not persist a missing-node error while a suppression window is - // open, which is the only moment this test can seed one, so there is no - // error to watch survive. The mutation sweep is what keeps this honest - // — reverting the `!ChangeTracker.isLoadingGraph` guard turns it red. const retireErrors = vi.spyOn( useExecutionErrorStore(), 'retireResolvedMissingNodePromptError' @@ -834,19 +817,13 @@ describe('ComfyApp', () => { releaseScan[0]() await olderLoad - // The older load's scan results describe a graph that is no longer - // live, and the newer load owns the warnings surface and will post its - // own. expect(mockWorkflowService.showPendingWarnings).not.toHaveBeenCalled() - // Retiring here would clear errors the newer load is still mid-flight - // over, before it has had the chance to record its own. expect(retireErrors).not.toHaveBeenCalled() releaseScan[1]() await newerLoad expect(mockWorkflowService.showPendingWarnings).toHaveBeenCalledOnce() - // Once the last window closes, the catch-up runs exactly once. expect(retireErrors).toHaveBeenCalledOnce() }) @@ -865,15 +842,11 @@ describe('ComfyApp', () => { const olderLoadBlocked = new Promise((resolve) => { releaseOlderLoad = resolve }) - // The older load commits and clears the `afterConfigureGraph` gate, - // then suspends in the last hook before the asset pipelines. vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith('afterLoadGraph') .thenReturnOnce(olderLoadBlocked) const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - // `thenReturnOnce` blocks whichever load reaches the hook first, so wait - // for the older one to get there before starting its replacement. await vi.waitFor(() => expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( 'afterLoadGraph' @@ -883,8 +856,6 @@ describe('ComfyApp', () => { releaseOlderLoad() await expect(olderLoad).resolves.toBeUndefined() - // Both pipelines scan `rootGraph` and report against the load's own - // workflow, so only the load that owns the live graph may run them. expect(runMissingModelPipeline).toHaveBeenCalledOnce() }) @@ -897,10 +868,6 @@ describe('ComfyApp', () => { const olderLoadBlocked = new Promise((resolve) => { releaseOlderLoad = resolve }) - // The gates at `beforeLoadGraph` and at `configure` are not adjacent: - // `validateWorkflow`, this hook and `nodeReplacementStore.load()` all - // await between them, so a load that owned the graph at the first gate - // can lose it before reaching the second. vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith( 'beforeConfigureGraph', @@ -922,8 +889,6 @@ describe('ComfyApp', () => { releaseOlderLoad() await expect(olderLoad).resolves.toBeUndefined() - // Configuring here would overwrite the graph the newer load committed - // with this load's older workflow. expect(configure).not.toHaveBeenCalled() }) @@ -2950,8 +2915,6 @@ describe('ComfyApp', () => { .calledWith('beforeLoadGraph') .thenReturnOnce(importBlocked) - // The import suspends in the same `beforeLoadGraph` hook `loadGraphData` - // awaits, and then clears the graph just as destructively. const apiImport = app.loadApiJson({}, 'superseded.json') await app.loadGraphData(createWorkflowGraphData(), true) const survivor = markerNode() @@ -2980,9 +2943,6 @@ describe('ComfyApp', () => { .calledWith('beforeLoadGraph') .thenReturnOnce(olderLoadBlocked) - // The other direction of the same hole: an import that commits while a - // workflow load is suspended is invisible to the load's ownership check, - // so the load resumes believing it still owns the graph. const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) await app.loadApiJson({}, 'committed.json') const survivor = markerNode() @@ -3007,8 +2967,6 @@ describe('ComfyApp', () => { const replacementsBlocked = new Promise((resolve) => { releaseReplacements = resolve }) - // The replacement manifest is fetched between this import's first - // ownership gate and the block that creates its nodes. vi.spyOn(useNodeReplacementStore(), 'load').mockReturnValueOnce( replacementsBlocked ) @@ -3037,8 +2995,6 @@ describe('ComfyApp', () => { const importBlocked = new Promise((resolve) => { releaseImport = resolve }) - // The import has already built its graph and claimed ownership, then - // suspends in the last hook before it binds a workflow. vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith('afterConfigureGraph', expect.anything()) .thenReturnOnce(importBlocked) @@ -3055,8 +3011,6 @@ describe('ComfyApp', () => { releaseImport() await apiImport - // `afterLoadNewGraph` serializes the live graph into the workflow it is - // given, and the live graph is the newer load's. expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() }) @@ -3090,9 +3044,6 @@ describe('ComfyApp', () => { releaseEmbeddings() await a1111Import - // The import's pre-clear hook clears this store in a `finally`, so an - // import that lost the graph during the embeddings fetch has to refuse - // before that hook starts, not only before the clear. expect(missingNodesStore.missingNodesError?.nodeTypes).toEqual([ 'NewerLoadMissingNode' ]) @@ -3109,8 +3060,6 @@ describe('ComfyApp', () => { const beforeLoadBlocked = new Promise((resolve) => { releaseBeforeLoad = resolve }) - // The import owns the graph when its hook starts and loses it part-way - // through, so the gate at the top of the hook cannot catch this one. vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith('beforeLoadGraph') .thenReturnOnce(beforeLoadBlocked) @@ -3240,8 +3189,6 @@ describe('ComfyApp', () => { } ) - // The workflow load suspends first and so consumes the blocked hook; the - // import that follows it runs through and claims the graph. const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) await app.handleFile(createTestFile('a1111.png', 'image/png')) vi.mocked(mockCanvas.setGraph).mockClear() @@ -3264,8 +3211,6 @@ describe('ComfyApp', () => { const embeddingsBlocked = new Promise((resolve) => { releaseEmbeddings = resolve }) - // Mirrors the real `importA1111`: it awaits the embeddings endpoint, then - // the pre-clear hook, and only then clears the graph and builds into it. mockImportA1111.mockImplementation( async (importGraph, _parameters, beforeGraphClear) => { await embeddingsBlocked @@ -3285,8 +3230,6 @@ describe('ComfyApp', () => { releaseEmbeddings() await a1111Import - // `graph.clear()` is unconditional once the hook resolves, so refusing - // inside the hook is the last point that leaves the newer graph intact. expect(graph.getNodeById(survivor.id)).toBe(survivor) expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() }) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 7216701fb84..680a1d69100 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -304,12 +304,6 @@ function createNodeOutputsMutationView( }) } -/** - * Thrown out of an import's pre-clear hook when a newer graph load has already - * committed, because that hook's only way to stop the clear that follows it is - * to not return. A private class rather than an `AbortError` so that an - * extension aborting its own `beforeLoadGraph` cannot be read as supersession. - */ class SupersededGraphLoad extends Error { constructor() { super('Graph load superseded by a newer load') @@ -1313,21 +1307,10 @@ export class ComfyApp { await useExtensionService().invokeExtensionsAsync('onGraphLoadError', error) } - /** - * Whether `loadId` still owns the graph. A newer load that has committed its - * graph owns everything downstream of that commit, so an older load resuming - * from an await must not mutate state, bind a workflow, or frame the canvas. - */ private ownsGraphLoad(loadId: number): boolean { return loadId >= this.committedGraphLoadSequence } - /** - * Claim the graph for `loadId`, so any load or import still suspended in an - * earlier hook sees itself as superseded. Every path that builds a graph - * commits through here, which is what makes the three of them one sequence - * rather than three that cannot see each other. - */ private commitGraphLoad(loadId: number): void { this.committedGraphLoadSequence = Math.max( loadId, @@ -1335,11 +1318,6 @@ export class ComfyApp { ) } - /** - * End a superseded load the way a failed one ends: notify `onGraphLoadError` - * so any loading state a `beforeLoadGraph` listener opened for this load is - * closed out. Resolves rather than throws; callers return its result. - */ private async rejectSupersededGraphLoad(): Promise { await useExtensionService().invokeExtensionsAsync( 'onGraphLoadError', @@ -1378,13 +1356,6 @@ export class ComfyApp { useWorkflowService().beforeLoadNewGraph(clean) await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') - // `beforeLoadGraph` listeners can await for as long as they like, and a - // newer load can commit its graph while this one is suspended there. Every - // statement below this point is destructive — aborting in-flight asset - // verification, clearing the missing-resource stores, `canvas.setGraph()` - // and `clean()` all erase live state. The later supersession check at the - // `configure` boundary is too late to stop that, so a superseded load used - // to wipe the newer committed graph and only then report itself stale. if (!this.ownsGraphLoad(loadId)) return this.rejectSupersededGraphLoad() let reset_invalid_values = false @@ -1581,8 +1552,6 @@ export class ComfyApp { } } - // Scoped rather than assigned: overlapping loads each hold their own - // suppression window, so this load's `finally` cannot end another's. const endGraphLoadSuppression = ChangeTracker.beginGraphLoad() let activatedWorkflow: LoadedComfyWorkflow | undefined let reconcileResourceErrors: (() => void) | undefined @@ -1713,11 +1682,6 @@ export class ComfyApp { missingNodeTypes ) - // Ownership is committed once, before this hook. Everything after it is - // graph-derived: the telemetry payload, and `afterLoadNewGraph` binding - // `workflow` to `rootGraph.serialize()`. A newer load that committed - // while this hook awaited owns the live graph, so continuing would - // serialize the newer graph into this load's older workflow. if (!this.ownsGraphLoad(loadId)) { return await this.rejectSupersededGraphLoad() } @@ -1743,8 +1707,6 @@ export class ComfyApp { ) await useExtensionService().invokeExtensionsAsync('afterLoadGraph') - // Same reason again: the asset pipelines below scan `this.rootGraph`, and - // their results are reported against this load's workflow. if (!this.ownsGraphLoad(loadId)) { return await this.rejectSupersededGraphLoad() } @@ -1799,9 +1761,6 @@ export class ComfyApp { }) } - // Both asset pipelines await the network. A newer load that committed - // while they ran owns the warnings surface and the canvas, and will post - // its own; this load's results describe a graph that is no longer live. if (!this.ownsGraphLoad(loadId)) { return await this.rejectSupersededGraphLoad() } @@ -1824,10 +1783,6 @@ export class ComfyApp { workflowNavigationId ) endGraphLoadSuppression() - // The retirement watcher skips transitions made during the load, so the - // catch-up runs here — but only once the last overlapping load has - // closed its window. Running it while a newer load is still configuring - // retires that load's errors before it has recorded them. if (!ChangeTracker.isLoadingGraph) { useExecutionErrorStore().retireResolvedMissingNodePromptError() } @@ -2348,14 +2303,10 @@ export class ComfyApp { // Use parameters strictly as the final fallback if (parameters && typeof parameters === 'string') { - // An A1111 import is a graph load too, and a slower one than most: it - // awaits the embeddings endpoint before its pre-clear hook runs, and the - // hook awaits `beforeLoadGraph` after that. const loadId = ++this.graphLoadSequence let outcome: A1111ImportOutcome try { outcome = await importA1111(this.rootGraph, parameters, async () => { - // `importA1111` awaited the embeddings endpoint to get here. if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() try { // false: final destination; no later load republishes the hash. @@ -2366,14 +2317,8 @@ export class ComfyApp { useMissingNodesErrorStore().setMissingNodeTypes([]) } } - // `graph.clear()` is unconditional once this hook resolves, so - // throwing out of it is the only way to stop the clear — and the - // last point at which a superseded import leaves the newer graph - // intact. Nothing has mutated the graph yet when this throws. if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() this.canvas.setGraph(this.rootGraph) - // Claimed here rather than after the import returns: everything - // `importA1111` does from this point on is synchronous. this.commitGraphLoad(loadId) }) } catch (error) { @@ -2552,18 +2497,11 @@ export class ComfyApp { fileName: string, options: { deferWarnings?: boolean } = {} ): Promise { - // An API-JSON import is a graph load: it awaits the same `beforeLoadGraph` - // hook, then calls the same destructive `setGraph()`/`clean()` pair, and - // ends by binding a workflow to `rootGraph.serialize()`. It therefore takes - // its ownership from the same sequence `loadGraphData` uses, rather than - // being invisible to it in both directions. const loadId = ++this.graphLoadSequence // false: no workflow load follows to republish the hash. useWorkflowService().beforeLoadNewGraph(false) await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') - // A newer load can commit while that hook awaits; `setGraph()` and - // `clean()` would then erase the graph it just committed. if (!this.ownsGraphLoad(loadId)) { await this.rejectSupersededGraphLoad() return @@ -2595,8 +2533,6 @@ export class ComfyApp { const nodeReplacementStore = useNodeReplacementStore() await nodeReplacementStore.load() - // The replacement manifest is fetched, and the block below adds this - // import's nodes to whatever graph is live. if (!this.ownsGraphLoad(loadId)) { await this.rejectSupersededGraphLoad() return @@ -2771,9 +2707,6 @@ export class ComfyApp { app.rootGraph.arrange() }) - // The graph is built, which is this path's equivalent of `configure` - // returning: claim it so a `loadGraphData` still suspended in its own - // `beforeLoadGraph` cannot resume and wipe this import. this.commitGraphLoad(loadId) // Intentionally no beforeConfigureGraph: API JSON builds nodes directly @@ -2783,9 +2716,6 @@ export class ComfyApp { missingNodeTypes ) - // Same reason as in `loadGraphData`: `afterLoadNewGraph` binds `fileName` - // to `rootGraph.serialize()`, so a newer load that committed while that - // hook awaited would be serialized into this import's workflow. if (!this.ownsGraphLoad(loadId)) { await this.rejectSupersededGraphLoad() return diff --git a/src/scripts/changeTracker.ts b/src/scripts/changeTracker.ts index 5a7a0ea4792..a35d5838c59 100644 --- a/src/scripts/changeTracker.ts +++ b/src/scripts/changeTracker.ts @@ -252,7 +252,6 @@ function reportInactiveTrackerCall(method: string, workflowPath: string) { export class ChangeTracker { static MAX_HISTORY = 50 - /** Number of graph loads currently inside their suppression window. */ private static graphLoadDepth = 0 /** @@ -261,11 +260,6 @@ export class ChangeTracker { * contains the NEW workflow's data while activeWorkflow still points to * the OLD workflow. Any captureCanvasState call in that window would * serialize the wrong graph into the old workflow's activeState, corrupting it. - * - * Reads as a boolean, but is held by count rather than by assignment: loads - * overlap, and a single shared boolean let a superseded older load's - * `finally` end the newer load's suppression window. - * @see {@link beginGraphLoad} */ static get isLoadingGraph(): boolean { return ChangeTracker.graphLoadDepth > 0 @@ -275,11 +269,6 @@ export class ChangeTracker { ChangeTracker.graphLoadDepth = value ? 1 : 0 } - /** - * Open a suppression window for one graph load. - * @returns A function that closes this load's window and no other's. Safe to - * call more than once. - */ static beginGraphLoad(): () => void { ChangeTracker.graphLoadDepth++ let closed = false diff --git a/src/stores/subgraphNavigationStore.ts b/src/stores/subgraphNavigationStore.ts index 1af7bfc184f..eeca5af7abf 100644 --- a/src/stores/subgraphNavigationStore.ts +++ b/src/stores/subgraphNavigationStore.ts @@ -137,10 +137,6 @@ export const useSubgraphNavigationStore = defineStore( const canvas = canvasStore.canvas if (!canvas) return - // Any queued fit belongs to an earlier arrival, including an earlier - // arrival at this same graph. Leaving A and returning to it makes a fit - // queued on A's first visit current again by graph id alone, so without - // this it runs after the cache restore below and overwrites it. canvasScheduler.cancel('subgraph-navigation-fit') const expectedKey = buildCacheKey(graphId) diff --git a/src/stores/subgraphNavigationStore.viewport.test.ts b/src/stores/subgraphNavigationStore.viewport.test.ts index 5bceecaa196..9e269c89138 100644 --- a/src/stores/subgraphNavigationStore.viewport.test.ts +++ b/src/stores/subgraphNavigationStore.viewport.test.ts @@ -224,24 +224,17 @@ describe('useSubgraphNavigationStore - Viewport Persistence', () => { mockGraph._nodes = [] }) - // First visit to A while hidden: no cached viewport, so a fit is queued. mockCanvas.subgraph = { id: 'sub-a' } as never store.restoreViewport('sub-a') - // Navigate away to an already-visited B. A cache hit applies the cached - // viewport and returns, leaving A's queued fit in the scheduler. store.viewportCache.set(':sub-b', { scale: 1, offset: [0, 0] }) mockCanvas.subgraph = { id: 'sub-b' } as never store.restoreViewport('sub-b') - // Back to A, now cached too, so this is also a cache hit. mockCanvas.subgraph = { id: 'sub-a' } as never store.viewportCache.set(':sub-a', { scale: 3, offset: [11, 22] }) store.restoreViewport('sub-a') - // The canvas becomes visible. The fit queued for A's first visit names - // the graph that is active again, so a graph-id-only ownership test - // makes it current and it clobbers the restore. setCanvasVisible(mockCanvas.canvas, true) useCanvasScheduler().flush() From 5c02816199cc392f234e514bdfe826452e99e95d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 12:10:15 -0700 Subject: [PATCH 13/31] fix(app): gate loadApiJson's missing-node report on graph ownership `loadApiJson` awaited `afterLoadGraph` and then called `showMissingNodesError` with no ownership re-check, while `loadGraphData` gates the equivalent point. `showMissingNodesError` reads `useWorkspaceStore().workflow.activeWorkflow` when it runs, so an import superseded inside that hook wrote its missing-node list onto the newer load's workflow and opened the missing-nodes dialog over it. Reported in review on #19976 and reproduced before the fix: the new case fails on the parent with the superseded import's `UninstalledScratchNode` attached to the newer workflow. Each of its two assertions was checked independently against the unguarded source. --- src/scripts/app.test.ts | 43 +++++++++++++++++++++++++++++++++++++++++ src/scripts/app.ts | 4 ++++ 2 files changed, 47 insertions(+) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index f921279a478..b5f8ad435b6 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -3014,6 +3014,49 @@ describe('ComfyApp', () => { expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() }) + it('does not attach a superseded API JSON import’s missing nodes to the newer workflow', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + vi.spyOn(app, 'clean').mockImplementation(() => {}) + const nodeReplacementStore = useNodeReplacementStore() + vi.spyOn(nodeReplacementStore, 'load').mockResolvedValue() + vi.spyOn(nodeReplacementStore, 'getReplacementFor').mockReturnValue(null) + let releaseImport!: () => void + const importBlocked = new Promise((resolve) => { + releaseImport = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('afterLoadGraph') + .thenReturnOnce(importBlocked) + + const apiImport = app.loadApiJson( + { '1': { class_type: 'UninstalledScratchNode', inputs: {} } }, + 'superseded.json' + ) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterLoadGraph' + ) + ) + await app.loadGraphData(createWorkflowGraphData(), true) + const newerWorkflow = markLoaded( + new ComfyWorkflow({ + path: 'workflows/newer.json', + modified: 0, + size: 0 + }) + ) + useWorkflowStore().activeWorkflow = newerWorkflow + mockWorkflowService.showPendingWarnings.mockClear() + releaseImport() + await apiImport + + expect(mockWorkflowService.showPendingWarnings).not.toHaveBeenCalled() + expect(newerWorkflow.pendingWarnings).toBeNull() + }) + it('does not let a superseded A1111 import clear the newer load’s missing nodes', async () => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 680a1d69100..6862c25932a 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -2725,6 +2725,10 @@ export class ComfyApp { this.rootGraph.serialize() as unknown as ComfyWorkflowJSON ) await useExtensionService().invokeExtensionsAsync('afterLoadGraph') + if (!this.ownsGraphLoad(loadId)) { + await this.rejectSupersededGraphLoad() + return + } if (missingNodeTypes.length) { this.showMissingNodesError(missingNodeTypes, options) } From 44455fc1a37faf92ae8b8388997536ba2160e5e9 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 15:39:46 -0700 Subject: [PATCH 14/31] fix(workflow): stop a superseded load activating inside afterLoadNewGraph MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the open P2 from review: `afterLoadNewGraph` can be superseded while it runs, and no `ownsGraphLoad` check in `app.ts` can reach inside it. `activateLoadedWorkflow` awaits `workflowStore.openWorkflow` at three points, and `openWorkflow` awaits `workflow.load()` on the persisted-but-unloaded path, so the suspension is network-length rather than a bare microtask. On resume it unconditionally ran `activateRunErrors` and `changeTracker.reset`/`restore`. `ChangeTracker.restore()` writes `app.canvas.ds.scale`/`offset` and calls `app.canvas.setGraph`, so a superseded load painted the older workflow's frozen camera onto the graph the newer load had already committed — #19971's own bug class, reached through a seam outside the gated region. The fix hands the load's existing ownership predicate to the callee instead of adding a 14th check in `app.ts`: a fourth `options.isCurrent` parameter on `afterLoadNewGraph`/`activateLoadedWorkflow`, bailed on after each `openWorkflow` await, with the previews restore skipped on bail. This is the idiom already used by `workflowService.openWorkflow`, `useCanvasScheduler`, `subgraphNavigationStore` and this PR's own `graph-load-camera` schedule, so it moves toward the reviewer's option B rather than adding more of what the P1 objects to. `app.ts` adds no check; it only passes the predicate. Wired at all three call sites, not just `loadGraphData`: `loadApiJson` (`app.ts:2367`) and `importA1111` (`app.ts:2730`) both pass a `string`, which is the branch that takes the network-length window, so leaving them unwired would have left the widest case open. Red on the parent and green here, in `workflowService.test.ts`: `does not write the newer graph camera when the predicate says it is stale` fails at 5c02816199 with the older camera (0.3) landing on the newer graph, and passes with this change. It asserts the newer camera is still live immediately before the release, so the write is observed happening on resume rather than never having been reachable. Two companion cases pin that an un-superseded load, and a load with no predicate at all, still activate normally — those pass on the parent too, so they are regression guards, not part of the red. Not addressed here, deliberately: - The P1 single-serialization-model redesign. It changes ownership semantics that shipped on `main` in #11420, so it is a larger change than reverting this PR and wants an architecture ruling and its own ticket. - `workflowStore.openWorkflow` writes `activeWorkflow.value` and `canvas.bg_tint` before returning, so a bail at the call site cannot undo them. Pre-existing, traced rather than run, and closing it needs the predicate inside the store action. Belongs with the redesign ticket. --- .../core/services/workflowService.test.ts | 116 ++++++++++++++++++ .../workflow/core/services/workflowService.ts | 30 ++++- src/scripts/app.ts | 11 +- 3 files changed, 148 insertions(+), 9 deletions(-) diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index beef1ea78d5..452de92ed95 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -2455,6 +2455,122 @@ describe('useWorkflowService', () => { ) }) }) + + // A graph load can be superseded while it is suspended *inside* this + // service: activation awaits workflowStore.openWorkflow, which awaits a + // network fetch on the persisted-but-unloaded path, and every + // ownsGraphLoad() check in app.ts sits outside this call. Without the + // isCurrent predicate the superseded load's resume restored the older + // workflow's frozen camera onto the graph the newer load had already + // committed - #19971's own bug class, through a seam the per-call-site + // checks cannot reach. + describe('when a newer load supersedes this one mid-flight', () => { + const newerCamera = { scale: 1.75, offset: [10, 20] as [number, number] } + const rootGraphId = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' + let releaseOpen: () => void + let setGraph: ReturnType + + beforeEach(() => { + // Pin the run-error graph scope so setActiveGraph's first argument is + // deterministic regardless of which sibling describe ran before this + // one; adoptRootGraphId returns null when isGraphReady is unset. + Reflect.set(app, 'isGraphReady', true) + app.rootGraph.id = rootGraphId + + setGraph = vi.fn() + Reflect.set(app, 'canvas', { + ds: { scale: newerCamera.scale, offset: newerCamera.offset }, + setGraph, + bg_tint: undefined + }) + + // The older workflow's camera, frozen by deactivate() at 0.3 zoom. + // A real ChangeTracker so restore() is the production write, not a + // stand-in: it is what moves app.canvas.ds and calls setGraph. + const tracker = new ChangeTracker(existingWorkflow, makeWorkflowData()) + Reflect.set(tracker, 'ds', { scale: 0.3, offset: [-999, -999] }) + Reflect.set(tracker, 'subgraphState', { navigation: [] }) + existingWorkflow.changeTracker = tracker + + const blocked = new Promise((resolve) => { + releaseOpen = resolve + }) + vi.mocked(workflowStore.openWorkflow).mockImplementation(async () => { + await blocked + return existingWorkflow + }) + }) + + afterEach(() => { + Reflect.deleteProperty(app, 'isGraphReady') + Reflect.deleteProperty(app.rootGraph, 'id') + }) + + it('does not write the newer graph camera when the predicate says it is stale', async () => { + let isCurrent = true + + const supersededLoad = useWorkflowService().afterLoadNewGraph( + 'repeat', + makeWorkflowData(), + undefined, + { isCurrent: () => isCurrent } + ) + await Promise.resolve() + + // Non-vacuity: the newer load's camera is live at the moment of + // supersession, so the writes below are observed on resume rather + // than having never been reachable. + expect(app.canvas.ds.scale).toBe(newerCamera.scale) + + // The newer load commits and finishes while this one is suspended. + isCurrent = false + releaseOpen() + await supersededLoad + + expect(app.canvas.ds.scale).toBe(newerCamera.scale) + expect(app.canvas.ds.offset).toEqual(newerCamera.offset) + expect(setGraph).not.toHaveBeenCalled() + expect(useExecutionErrorStore().setActiveGraph).not.toHaveBeenCalled() + expect( + useNodeOutputStore().restorePreviewsForWorkflow + ).not.toHaveBeenCalled() + }) + + it('still activates normally when the load is not superseded', async () => { + const liveLoad = useWorkflowService().afterLoadNewGraph( + 'repeat', + makeWorkflowData(), + undefined, + { isCurrent: () => true } + ) + await Promise.resolve() + releaseOpen() + await liveLoad + + expect(app.canvas.ds.scale).toBe(0.3) + expect(setGraph).toHaveBeenCalled() + expect(useExecutionErrorStore().setActiveGraph).toHaveBeenCalledWith( + rootGraphId, + existingWorkflow.path + ) + expect( + useNodeOutputStore().restorePreviewsForWorkflow + ).toHaveBeenCalled() + }) + + it('activates normally when no predicate is supplied', async () => { + const liveLoad = useWorkflowService().afterLoadNewGraph( + 'repeat', + makeWorkflowData() + ) + await Promise.resolve() + releaseOpen() + await liveLoad + + expect(app.canvas.ds.scale).toBe(0.3) + expect(setGraph).toHaveBeenCalled() + }) + }) }) describe('per-workflow mode switching', () => { diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index ae96e2459f7..6af69ab66f6 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -703,23 +703,37 @@ export const useWorkflowService = () => { * * @param value The value to set as the active workflow. * @param workflowData The initial workflow data loaded to the graph editor. + * @param options.isCurrent Tells this activation whether the graph load it + * belongs to still owns the graph. Activation suspends on `openWorkflow`, + * which can await a network fetch, so a newer load can commit meanwhile; the + * caller's own ownership checks all sit outside this call and cannot reach + * the resume points inside it. Same idiom as `openWorkflow` below and + * `useCanvasScheduler`. */ const afterLoadNewGraph = async ( value: string | ComfyWorkflow | null, workflowData: ComfyWorkflowJSON, - shareId?: string + shareId?: string, + options: { isCurrent?: () => boolean } = {} ) => { - await activateLoadedWorkflow(value, workflowData, shareId) + if (!(await activateLoadedWorkflow(value, workflowData, shareId, options))) + return useNodeOutputStore().restorePreviewsForWorkflow( useWorkspaceStore().workflow.activeWorkflow?.path ) } + /** + * @returns Whether the workflow was activated. `false` means a newer graph + * load superseded this one while this call was suspended, so it stopped + * without writing any further global state. + */ const activateLoadedWorkflow = async ( value: string | ComfyWorkflow | null, workflowData: ComfyWorkflowJSON, - shareId?: string - ) => { + shareId?: string, + options: { isCurrent?: () => boolean } = {} + ): Promise => { const workflowStore = useWorkspaceStore().workflow const { isAppMode } = useAppMode() const wasAppMode = isAppMode.value @@ -770,6 +784,7 @@ export const useWorkflowService = () => { ) { const loadedWorkflow = await workflowStore.openWorkflow(existingWorkflow) + if (options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) if (loadedWorkflow.initialMode === undefined) { // Prefer the file's linearMode over the draft's since the file @@ -791,7 +806,7 @@ export const useWorkflowService = () => { ) ) loadedWorkflow.changeTracker.restore() - return + return true } } @@ -805,11 +820,13 @@ export const useWorkflowService = () => { } trackIfEnteringApp(tempWorkflow) const loadedWorkflow = await workflowStore.openWorkflow(tempWorkflow) + if (options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) - return + return true } const loadedWorkflow = await workflowStore.openWorkflow(value) + if (options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) if (shareId) { loadedWorkflow.shareId = shareId @@ -823,6 +840,7 @@ export const useWorkflowService = () => { ensureWorkflowId(workflowData, activeStateFallbackId(loadedWorkflow)) ) loadedWorkflow.changeTracker.restore() + return true } /** diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 6862c25932a..3c5dbc604b4 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1703,7 +1703,8 @@ export class ComfyApp { await useWorkflowService().afterLoadNewGraph( workflow, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, - effectiveShareId + effectiveShareId, + { isCurrent: () => this.ownsGraphLoad(loadId) } ) await useExtensionService().invokeExtensionsAsync('afterLoadGraph') @@ -2361,7 +2362,9 @@ export class ComfyApp { } await useWorkflowService().afterLoadNewGraph( fileName, - this.rootGraph.serialize() as unknown as ComfyWorkflowJSON + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, + undefined, + { isCurrent: () => this.ownsGraphLoad(loadId) } ) await useExtensionService().invokeExtensionsAsync('afterLoadGraph') return @@ -2722,7 +2725,9 @@ export class ComfyApp { } await useWorkflowService().afterLoadNewGraph( fileName, - this.rootGraph.serialize() as unknown as ComfyWorkflowJSON + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, + undefined, + { isCurrent: () => this.ownsGraphLoad(loadId) } ) await useExtensionService().invokeExtensionsAsync('afterLoadGraph') if (!this.ownsGraphLoad(loadId)) { From c1d968b252faff750364d48176e5fd443849e27c Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 3 Oct 2026 17:33:26 -0700 Subject: [PATCH 15/31] refactor(canvas): complete the viewport/framing split onto #20025 #20025 ("split viewport lifecycle and framing repairs") was opened to carry this branch's viewport and framing work so it could be reviewed and landed independently of the graph-load work. Its description states the intended end state: it "contains none of the graph-load sequence, app import, change-tracker, or Agent browser changes. The graph-load work remains on #19976." The viewport half was never removed here, so both branches carried it. Once #20025 repaired its own intrinsic-sizing regression the duplicate stopped being merely redundant and became a content conflict in four files -- canvasViewport.ts, its test, LGraphCanvas.ts and LGraphCanvas.resize.test.ts -- in *both* merge orders, so no landing sequence avoided it. This restores the ten viewport/framing files to their base content, leaving this branch with only the graph-load lifecycle work it is now scoped to: src/scripts/app.ts, app.test.ts src/scripts/changeTracker.ts src/platform/workflow/core/services/workflowService.ts, .test.ts browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts No coverage is lost. Every viewport test case dropped here is present on #20025, either byte-identical or strengthened: the DragAndScale viewport-size file is identical content at its colocated path, and the one case whose title differs ("restores the DPR transform a measurement probe reset" vs "keeps the DPR transform across a measurement probe") is the same scenario with the same final assertion, asserting the stronger invariant that #20025's absolute setTransform makes true -- the transform now survives the probe rather than being restored after it. --- .../canvas/visibleCanvasViewport.test.ts | 12 --- .../canvas/visibleCanvasViewport.ts | 4 +- src/lib/litegraph/src/DragAndScale.ts | 15 +-- .../litegraph/src/LGraphCanvas.resize.test.ts | 28 ----- src/lib/litegraph/src/LGraphCanvas.ts | 20 ++-- .../DragAndScale.viewportSize.test.ts | 48 --------- .../canvas/__tests__/canvasViewport.test.ts | 100 +----------------- src/renderer/core/canvas/canvasViewport.ts | 74 ++++++------- src/stores/subgraphNavigationStore.ts | 2 - .../subgraphNavigationStore.viewport.test.ts | 33 +----- 10 files changed, 45 insertions(+), 291 deletions(-) delete mode 100644 src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts diff --git a/src/composables/canvas/visibleCanvasViewport.test.ts b/src/composables/canvas/visibleCanvasViewport.test.ts index 02883089354..858aba738aa 100644 --- a/src/composables/canvas/visibleCanvasViewport.test.ts +++ b/src/composables/canvas/visibleCanvasViewport.test.ts @@ -28,16 +28,4 @@ describe('visibleCanvasViewport', () => { visibleCanvasViewport({ ds: createTestDragAndScale(800, 450) }) ).toEqual([0, 0, 300, 450]) }) - - it('falls back to the whole canvas when the panel leaves nothing uncovered', () => { - const panel = useAgentPanelStore() - panel.enabled = true - panel.consentAccepted = true - panel.isOpen = true - panel.setWidth(500) - - expect( - visibleCanvasViewport({ ds: createTestDragAndScale(480, 450) }) - ).toEqual([0, 0, 480, 450]) - }) }) diff --git a/src/composables/canvas/visibleCanvasViewport.ts b/src/composables/canvas/visibleCanvasViewport.ts index 478b72cdb13..bcc7a8162eb 100644 --- a/src/composables/canvas/visibleCanvasViewport.ts +++ b/src/composables/canvas/visibleCanvasViewport.ts @@ -8,7 +8,5 @@ export function visibleCanvasViewport( const panel = useAgentPanelStore() const [width, height] = canvas.ds.getViewportSize() const coveredWidth = panel.isVisible ? panel.width : 0 - const uncoveredWidth = width - coveredWidth - if (!(uncoveredWidth > 0)) return [0, 0, width, height] - return [0, 0, uncoveredWidth, height] + return [0, 0, Math.max(width - coveredWidth, 0), height] } diff --git a/src/lib/litegraph/src/DragAndScale.ts b/src/lib/litegraph/src/DragAndScale.ts index 695a2e70f0c..185f993407f 100644 --- a/src/lib/litegraph/src/DragAndScale.ts +++ b/src/lib/litegraph/src/DragAndScale.ts @@ -122,22 +122,11 @@ export class DragAndScale { } setViewportSize(width: number, height: number): void { - this.viewportSize = - width > 0 && - height > 0 && - Number.isFinite(width) && - Number.isFinite(height) - ? [width, height] - : undefined - } - - invalidateViewportSize(): void { - this.viewportSize = undefined + this.viewportSize = [width, height] } getViewportSize(): [number, number] { - const cached = this.viewportSize - if (cached) return [cached[0], cached[1]] + if (this.viewportSize) return this.viewportSize const rect = this.element.getBoundingClientRect() if (rect.width > 0 && rect.height > 0) { diff --git a/src/lib/litegraph/src/LGraphCanvas.resize.test.ts b/src/lib/litegraph/src/LGraphCanvas.resize.test.ts index 5d1014807cb..0f800c3c6d7 100644 --- a/src/lib/litegraph/src/LGraphCanvas.resize.test.ts +++ b/src/lib/litegraph/src/LGraphCanvas.resize.test.ts @@ -56,32 +56,4 @@ describe('LGraphCanvas.resize', () => { 1200 ]) }) - - it('keeps explicit dimensions in CSS pixels rather than letting the backing store size the layout', () => { - const { canvas } = createParentSizedCanvas() - - canvas.resize(800, 600) - - const { style, width, height } = canvas.canvas - expect([style.width, style.height, width, height]).toEqual([ - '800px', - '600px', - 1600, - 1200 - ]) - }) - - it('recomputes the LOD threshold when a resize changes DPR', () => { - const { canvas } = createParentSizedCanvas() - vi.stubGlobal('devicePixelRatio', 1) - canvas.resize(800, 600) - canvas.ds.scale = 0.4 - canvas.ds.computeVisibleArea(undefined) - expect(canvas.low_quality).toBe(true) - - vi.stubGlobal('devicePixelRatio', 4) - canvas.resize(800, 600) - - expect(canvas.low_quality).toBe(false) - }) }) diff --git a/src/lib/litegraph/src/LGraphCanvas.ts b/src/lib/litegraph/src/LGraphCanvas.ts index 48abf0084d9..32eb0e89295 100644 --- a/src/lib/litegraph/src/LGraphCanvas.ts +++ b/src/lib/litegraph/src/LGraphCanvas.ts @@ -32,7 +32,7 @@ import { import { useSelectionStore } from '@/core/selection/selectionStore' import { useLinkPresentationStore } from '@/stores/linkPresentationStore' import { - applyLogicalCanvasStyle, + applyParentSizedCanvasStyle, applyViewport, measureViewport, readBrowserDpr @@ -1040,18 +1040,8 @@ export class LGraphCanvas implements CustomEventDispatcher /** Link rendering adapter for litegraph-to-canvas integration */ linkRenderer: LitegraphLinkAdapter | null = null - private _dpr: number = 1 - /** Device pixel ratio applied with the current viewport dimensions. */ - get dpr(): number { - return this._dpr - } - - set dpr(value: number) { - if (this._dpr === value) return - this._dpr = value - this.updateLowQualityThreshold() - } + dpr: number = 1 /** If true, enable drag zoom. Ctrl+Shift+Drag Up/Down: zoom canvas. */ dragZoomEnabled: boolean = false @@ -2206,7 +2196,6 @@ export class LGraphCanvas implements CustomEventDispatcher // maybe detach events from old_canvas this.canvas = element this.ds.element = element - this.ds.invalidateViewportSize() this.pointer.element = element this._setCursor = createCursorCache(element) @@ -6686,6 +6675,7 @@ export class LGraphCanvas implements CustomEventDispatcher * This method remains for legacy callers that rely on parent-element fallback sizing. */ resize(width?: number, height?: number): void { + const usesParentSize = !width && !height if (!width && !height) { const parent = this.canvas.parentElement if (!parent) @@ -6696,7 +6686,9 @@ export class LGraphCanvas implements CustomEventDispatcher height = parent.offsetHeight } - applyLogicalCanvasStyle(this.canvas, width ?? 0, height ?? 0) + if (usesParentSize) { + applyParentSizedCanvasStyle(this.canvas, width ?? 0, height ?? 0) + } const viewport = measureViewport( width ?? 0, diff --git a/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts b/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts deleted file mode 100644 index d5ebde10a6c..00000000000 --- a/src/lib/litegraph/src/__tests__/DragAndScale.viewportSize.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -import { - DragAndScale, - LGraph, - LGraphCanvas -} from '@/lib/litegraph/src/litegraph' -import { createTestCanvasElement } from '@/utils/__tests__/canvasTestUtils' - -describe('DragAndScale viewport size cache', () => { - beforeEach(() => { - vi.stubGlobal('devicePixelRatio', 1) - }) - - it('does not cache an unusable viewport size', () => { - const ds = new DragAndScale( - createTestCanvasElement({ width: 800, height: 600 }) - ) - - ds.setViewportSize(0, 0) - - expect(ds.getViewportSize()).toEqual([800, 600]) - }) - - it('hands out a copy so a caller cannot poison the cache', () => { - const ds = new DragAndScale(createTestCanvasElement()) - ds.setViewportSize(800, 600) - - const mutated = ds.getViewportSize() - mutated[0] = 0 - mutated[1] = 0 - - expect(ds.getViewportSize()).toEqual([800, 600]) - }) - - it('forgets the previous element’s viewport when the canvas is replaced', () => { - const element = createTestCanvasElement({ width: 800, height: 600 }) - const canvas = new LGraphCanvas(element, new LGraph(), { - skip_render: true, - skip_events: true - }) - canvas.ds.setViewportSize(800, 600) - - canvas.setCanvas(createTestCanvasElement({ width: 400, height: 300 }), true) - - expect(canvas.ds.getViewportSize()).toEqual([400, 300]) - }) -}) diff --git a/src/renderer/core/canvas/__tests__/canvasViewport.test.ts b/src/renderer/core/canvas/__tests__/canvasViewport.test.ts index b2b2f0cde66..0b368bf1595 100644 --- a/src/renderer/core/canvas/__tests__/canvasViewport.test.ts +++ b/src/renderer/core/canvas/__tests__/canvasViewport.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { - applyLogicalCanvasStyle, + applyParentSizedCanvasStyle, applyViewport, measureViewport, measureViewportFromElement @@ -11,38 +11,6 @@ import { createTestCanvasElement } from '@/utils/__tests__/canvasTestUtils' -function createTransformTrackingCanvas(cssSize?: { - width: number - height: number -}) { - const transform = { x: 1, y: 1 } - const ctx = createMockCanvasRenderingContext2D({ - scale: vi.fn((x: number, y: number) => { - transform.x *= x - transform.y *= y - }) - }) - const canvas = createTestCanvasElement({ ctx }) - for (const dimension of ['width', 'height'] as const) { - let backingStore = canvas[dimension] - Object.defineProperty(canvas, dimension, { - configurable: true, - get: () => backingStore, - set: (value: number) => { - backingStore = value - transform.x = 1 - transform.y = 1 - } - }) - } - if (cssSize) { - vi.spyOn(canvas, 'getBoundingClientRect').mockImplementation( - () => new DOMRect(0, 0, cssSize.width, cssSize.height) - ) - } - return { canvas, ctx, transform } -} - describe('measureViewport', () => { it('computes physical dimensions from CSS dimensions and DPR', () => { expect(measureViewport(800, 600, 2)).toEqual({ @@ -153,48 +121,6 @@ describe('applyViewport', () => { expect(consumer.ds.setViewportSize).toHaveBeenCalledWith(800, 600) }) - it('restores the DPR transform a measurement probe reset, even when the backing size rounds back', () => { - const cssSize = { width: 800.1, height: 600 } - const { canvas, transform } = createTransformTrackingCanvas(cssSize) - - applyViewport(measureViewportFromElement(canvas, 2), canvas, canvas) - expect(transform).toEqual({ x: 2, y: 2 }) - - cssSize.width = 800.2 - const reprobed = measureViewportFromElement(canvas, 2) - expect([reprobed.physicalWidth, reprobed.physicalHeight]).toEqual([ - canvas.width, - canvas.height - ]) - expect(transform).toEqual({ x: 1, y: 1 }) - - applyViewport(reprobed, canvas, canvas) - - expect(transform).toEqual({ x: 2, y: 2 }) - }) - - it('does not compound the DPR scale when a new DPR lands on an unchanged backing store', () => { - const { canvas, transform } = createTransformTrackingCanvas() - - applyViewport(measureViewport(800, 600, 2), canvas, canvas) - expect(transform).toEqual({ x: 2, y: 2 }) - - applyViewport(measureViewport(1600 / 3, 400, 3), canvas, canvas) - - expect(transform).toEqual({ x: 3, y: 3 }) - }) - - it('re-scales after a size change at an unchanged DPR', () => { - const { canvas, transform } = createTransformTrackingCanvas() - - applyViewport(measureViewport(800, 600, 2), canvas, canvas) - expect(transform).toEqual({ x: 2, y: 2 }) - - applyViewport(measureViewport(1000, 700, 2), canvas, canvas) - - expect(transform).toEqual({ x: 2, y: 2 }) - }) - it('does not reset backing stores that already match', () => { const viewport = measureViewport(800, 600, 2) const fg = createTestCanvasElement() @@ -215,12 +141,12 @@ describe('applyViewport', () => { }) }) -describe('applyLogicalCanvasStyle', () => { +describe('applyParentSizedCanvasStyle', () => { it('follows the parent while the canvas style is its own', () => { const canvas = createTestCanvasElement() - applyLogicalCanvasStyle(canvas, 800, 600) - applyLogicalCanvasStyle(canvas, 1000, 700) + applyParentSizedCanvasStyle(canvas, 800, 600) + applyParentSizedCanvasStyle(canvas, 1000, 700) expect([canvas.style.width, canvas.style.height]).toEqual([ '1000px', @@ -233,24 +159,8 @@ describe('applyLogicalCanvasStyle', () => { canvas.style.width = '75%' canvas.style.height = '50vh' - applyLogicalCanvasStyle(canvas, 800, 600) + applyParentSizedCanvasStyle(canvas, 800, 600) expect([canvas.style.width, canvas.style.height]).toEqual(['75%', '50vh']) }) - - it('never pins a degenerate measurement', () => { - const canvas = createTestCanvasElement() - - applyLogicalCanvasStyle(canvas, 0, 0) - - expect([canvas.style.width, canvas.style.height]).toEqual(['', '']) - }) - - it('leaves a class-sized canvas to its stylesheet', () => { - const canvas = createTestCanvasElement({ cssSize: [800, 600] }) - - applyLogicalCanvasStyle(canvas, 800, 600) - - expect([canvas.style.width, canvas.style.height]).toEqual(['', '']) - }) }) diff --git a/src/renderer/core/canvas/canvasViewport.ts b/src/renderer/core/canvas/canvasViewport.ts index 96aa9042f81..a2e3285a3b3 100644 --- a/src/renderer/core/canvas/canvasViewport.ts +++ b/src/renderer/core/canvas/canvasViewport.ts @@ -16,28 +16,12 @@ const autoSizedStyleByCanvas = new WeakMap< HTMLCanvasElement, { width?: string; height?: string } >() -const appliedContextDprByCanvas = new WeakMap() -function invalidateCanvasContextTransform(canvas: HTMLCanvasElement): void { - appliedContextDprByCanvas.delete(canvas) -} - -function applyLogicalCanvasStyle( +function applyParentSizedCanvasStyle( canvas: HTMLCanvasElement, width: number, height: number ): void { - if (!(width > 0) || !(height > 0)) return - - const rect = canvas.getBoundingClientRect() - if ( - Math.abs(rect.width - width) < 1 && - Math.abs(rect.height - height) < 1 && - rect.width > 0 && - rect.height > 0 - ) - return - const { style } = canvas const previousStyle = autoSizedStyleByCanvas.get(canvas) ?? {} const nextStyle: { width?: string; height?: string } = {} @@ -111,7 +95,6 @@ function measureViewportFromElement( } finally { element.width = savedWidth element.height = savedHeight - invalidateCanvasContextTransform(element) } const width = cssRect.width || previousViewport?.cssWidth || initialRect.width const height = @@ -119,37 +102,40 @@ function measureViewportFromElement( return measureViewport(width, height, rawDpr) } -function applySurfaceViewport( - canvas: HTMLCanvasElement, - viewport: CanvasViewport -): void { - const { physicalWidth, physicalHeight, dpr } = viewport - let contextReset = false - if (canvas.width !== physicalWidth) { - canvas.width = physicalWidth - contextReset = true - } - if (canvas.height !== physicalHeight) { - canvas.height = physicalHeight - contextReset = true - } - if (contextReset) invalidateCanvasContextTransform(canvas) - - if (appliedContextDprByCanvas.get(canvas) === dpr) return - - if (!contextReset) canvas.width = physicalWidth - canvas.getContext('2d')?.scale(dpr, dpr) - appliedContextDprByCanvas.set(canvas, dpr) -} - function applyViewport( viewport: CanvasViewport, fg: HTMLCanvasElement, bg: HTMLCanvasElement, consumer?: CanvasViewportConsumer ): CanvasViewport { - applySurfaceViewport(fg, viewport) - if (bg !== fg) applySurfaceViewport(bg, viewport) + const previousForegroundViewport = appliedViewportByCanvas.get(fg) + const foregroundChanged = + fg.width !== viewport.physicalWidth || + fg.height !== viewport.physicalHeight || + previousForegroundViewport?.dpr !== viewport.dpr + if ( + fg.width !== viewport.physicalWidth || + previousForegroundViewport?.dpr !== viewport.dpr + ) + fg.width = viewport.physicalWidth + if (fg.height !== viewport.physicalHeight) fg.height = viewport.physicalHeight + if (foregroundChanged) fg.getContext('2d')?.scale(viewport.dpr, viewport.dpr) + if (bg !== fg) { + const previousBackgroundViewport = appliedViewportByCanvas.get(bg) + const backgroundChanged = + bg.width !== viewport.physicalWidth || + bg.height !== viewport.physicalHeight || + previousBackgroundViewport?.dpr !== viewport.dpr + if ( + bg.width !== viewport.physicalWidth || + previousBackgroundViewport?.dpr !== viewport.dpr + ) + bg.width = viewport.physicalWidth + if (bg.height !== viewport.physicalHeight) + bg.height = viewport.physicalHeight + if (backgroundChanged) + bg.getContext('2d')?.scale(viewport.dpr, viewport.dpr) + } appliedViewportByCanvas.set(fg, viewport) appliedViewportByCanvas.set(bg, viewport) @@ -164,6 +150,6 @@ export { readBrowserDpr, measureViewport, measureViewportFromElement, - applyLogicalCanvasStyle, + applyParentSizedCanvasStyle, applyViewport } diff --git a/src/stores/subgraphNavigationStore.ts b/src/stores/subgraphNavigationStore.ts index eeca5af7abf..27ac064d5f1 100644 --- a/src/stores/subgraphNavigationStore.ts +++ b/src/stores/subgraphNavigationStore.ts @@ -137,8 +137,6 @@ export const useSubgraphNavigationStore = defineStore( const canvas = canvasStore.canvas if (!canvas) return - canvasScheduler.cancel('subgraph-navigation-fit') - const expectedKey = buildCacheKey(graphId) const viewport = viewportCache.get(expectedKey) if (viewport) { diff --git a/src/stores/subgraphNavigationStore.viewport.test.ts b/src/stores/subgraphNavigationStore.viewport.test.ts index 9e269c89138..173466cf46e 100644 --- a/src/stores/subgraphNavigationStore.viewport.test.ts +++ b/src/stores/subgraphNavigationStore.viewport.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { nextTick } from 'vue' @@ -212,37 +212,6 @@ describe('useSubgraphNavigationStore - Viewport Persistence', () => { mockGraph._nodes = [] }) - it('does not let a first-visit fit queued for a hidden canvas overwrite a later cache restore', () => { - const store = useSubgraphNavigationStore() - store.viewportCache.delete(':sub-a') - setCanvasVisible(mockCanvas.canvas, false) - const mockGraph = app.graph as { nodes: unknown[]; _nodes: unknown[] } - mockGraph.nodes = [{ pos: [0, 0], size: [100, 100] }] - mockGraph._nodes = mockGraph.nodes - onTestFinished(() => { - mockGraph.nodes = [] - mockGraph._nodes = [] - }) - - mockCanvas.subgraph = { id: 'sub-a' } as never - store.restoreViewport('sub-a') - - store.viewportCache.set(':sub-b', { scale: 1, offset: [0, 0] }) - mockCanvas.subgraph = { id: 'sub-b' } as never - store.restoreViewport('sub-b') - - mockCanvas.subgraph = { id: 'sub-a' } as never - store.viewportCache.set(':sub-a', { scale: 3, offset: [11, 22] }) - store.restoreViewport('sub-a') - - setCanvasVisible(mockCanvas.canvas, true) - useCanvasScheduler().flush() - - expect(useLitegraphService().fitView).not.toHaveBeenCalled() - expect(mockCanvas.ds.scale).toBe(3) - expect(mockCanvas.ds.offset).toEqual([11, 22]) - }) - it('skips a queued fit if the active graph changes while hidden', () => { const store = useSubgraphNavigationStore() store.viewportCache.delete(':root') From 60a260dcbba5b26e98314f9456d261361154d47c Mon Sep 17 00:00:00 2001 From: bymyself Date: Sun, 4 Oct 2026 21:38:32 +0000 Subject: [PATCH 16/31] fix(app): finish superseded load activation --- .../agentOverlappingWorkflowLoad.spec.ts | 17 ++------ .../services/__mocks__/workflowService.ts | 2 +- .../core/services/workflowService.test.ts | 41 ++++--------------- .../workflow/core/services/workflowService.ts | 16 ++------ src/scripts/app.test.ts | 7 ++-- src/scripts/app.ts | 15 +++++-- 6 files changed, 32 insertions(+), 66 deletions(-) diff --git a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts index d2568edd464..d26d17f9c31 100644 --- a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts +++ b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts @@ -2,7 +2,7 @@ import { expect } from '@playwright/test' import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' -import { agentTest as test } from '@e2e/tests/agent/agentPanelMocks' +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' const STALL_EXTENSION = 'e2e.op329.stallBeforeLoadGraph' @@ -32,21 +32,16 @@ function noteWorkflow(title: string): ComfyWorkflowJSON { } } -// Regression for https://github.com/Comfy-Org/ComfyUI_frontend/issues/19971 test.describe( 'Overlapping workflow loads', - { tag: ['@cloud', '@agent', '@vue-nodes'] }, + { tag: ['@cloud', '@vue-nodes'] }, () => { test('the newer workflow survives an older load resuming', async ({ - comfyPage, - agentPanel + comfyPage }) => { test.setTimeout(60_000) const { page, vueNodes } = comfyPage - await agentPanel.open() - await vueNodes.setEnabled(true) - await test.step('hold the first load open, then start a second', async () => { await page.evaluate( async ([extensionName, older, newer]) => { @@ -88,15 +83,11 @@ test.describe( }) test('the newer workflow survives a superseded API JSON import', async ({ - comfyPage, - agentPanel + comfyPage }) => { test.setTimeout(60_000) const { page, vueNodes } = comfyPage - await agentPanel.open() - await vueNodes.setEnabled(true) - await test.step('hold an API JSON import open, then load a workflow', async () => { await page.evaluate( async ([extensionName, apiPrompt, newer]) => { diff --git a/src/platform/workflow/core/services/__mocks__/workflowService.ts b/src/platform/workflow/core/services/__mocks__/workflowService.ts index f514e35acb9..6e8bc863d5a 100644 --- a/src/platform/workflow/core/services/__mocks__/workflowService.ts +++ b/src/platform/workflow/core/services/__mocks__/workflowService.ts @@ -18,7 +18,7 @@ const workflowService: ReturnType = { loadPreviousOpenedWorkflow: vi.fn(async () => {}), duplicateWorkflow: vi.fn(async () => {}), showPendingWarnings: vi.fn(), - afterLoadNewGraph: vi.fn(async () => {}), + afterLoadNewGraph: vi.fn(async () => true), beforeLoadNewGraph: vi.fn() } diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 452de92ed95..c55f7d88373 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -2456,24 +2456,15 @@ describe('useWorkflowService', () => { }) }) - // A graph load can be superseded while it is suspended *inside* this - // service: activation awaits workflowStore.openWorkflow, which awaits a - // network fetch on the persisted-but-unloaded path, and every - // ownsGraphLoad() check in app.ts sits outside this call. Without the - // isCurrent predicate the superseded load's resume restored the older - // workflow's frozen camera onto the graph the newer load had already - // committed - #19971's own bug class, through a seam the per-call-site - // checks cannot reach. describe('when a newer load supersedes this one mid-flight', () => { const newerCamera = { scale: 1.75, offset: [10, 20] as [number, number] } const rootGraphId = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' let releaseOpen: () => void let setGraph: ReturnType + let originalCanvas: typeof app.canvas beforeEach(() => { - // Pin the run-error graph scope so setActiveGraph's first argument is - // deterministic regardless of which sibling describe ran before this - // one; adoptRootGraphId returns null when isGraphReady is unset. + originalCanvas = app.canvas Reflect.set(app, 'isGraphReady', true) app.rootGraph.id = rootGraphId @@ -2484,12 +2475,12 @@ describe('useWorkflowService', () => { bg_tint: undefined }) - // The older workflow's camera, frozen by deactivate() at 0.3 zoom. - // A real ChangeTracker so restore() is the production write, not a - // stand-in: it is what moves app.canvas.ds and calls setGraph. const tracker = new ChangeTracker(existingWorkflow, makeWorkflowData()) - Reflect.set(tracker, 'ds', { scale: 0.3, offset: [-999, -999] }) - Reflect.set(tracker, 'subgraphState', { navigation: [] }) + app.canvas.ds.scale = 0.3 + app.canvas.ds.offset = [-999, -999] + tracker.store() + app.canvas.ds.scale = newerCamera.scale + app.canvas.ds.offset = newerCamera.offset existingWorkflow.changeTracker = tracker const blocked = new Promise((resolve) => { @@ -2504,6 +2495,7 @@ describe('useWorkflowService', () => { afterEach(() => { Reflect.deleteProperty(app, 'isGraphReady') Reflect.deleteProperty(app.rootGraph, 'id') + Reflect.set(app, 'canvas', originalCanvas) }) it('does not write the newer graph camera when the predicate says it is stale', async () => { @@ -2517,12 +2509,8 @@ describe('useWorkflowService', () => { ) await Promise.resolve() - // Non-vacuity: the newer load's camera is live at the moment of - // supersession, so the writes below are observed on resume rather - // than having never been reachable. expect(app.canvas.ds.scale).toBe(newerCamera.scale) - // The newer load commits and finishes while this one is suspended. isCurrent = false releaseOpen() await supersededLoad @@ -2557,19 +2545,6 @@ describe('useWorkflowService', () => { useNodeOutputStore().restorePreviewsForWorkflow ).toHaveBeenCalled() }) - - it('activates normally when no predicate is supplied', async () => { - const liveLoad = useWorkflowService().afterLoadNewGraph( - 'repeat', - makeWorkflowData() - ) - await Promise.resolve() - releaseOpen() - await liveLoad - - expect(app.canvas.ds.scale).toBe(0.3) - expect(setGraph).toHaveBeenCalled() - }) }) }) diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index 6af69ab66f6..43c80d16061 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -703,31 +703,21 @@ export const useWorkflowService = () => { * * @param value The value to set as the active workflow. * @param workflowData The initial workflow data loaded to the graph editor. - * @param options.isCurrent Tells this activation whether the graph load it - * belongs to still owns the graph. Activation suspends on `openWorkflow`, - * which can await a network fetch, so a newer load can commit meanwhile; the - * caller's own ownership checks all sit outside this call and cannot reach - * the resume points inside it. Same idiom as `openWorkflow` below and - * `useCanvasScheduler`. */ const afterLoadNewGraph = async ( value: string | ComfyWorkflow | null, workflowData: ComfyWorkflowJSON, shareId?: string, options: { isCurrent?: () => boolean } = {} - ) => { + ): Promise => { if (!(await activateLoadedWorkflow(value, workflowData, shareId, options))) - return + return false useNodeOutputStore().restorePreviewsForWorkflow( useWorkspaceStore().workflow.activeWorkflow?.path ) + return true } - /** - * @returns Whether the workflow was activated. `false` means a newer graph - * load superseded this one while this call was suspended, so it stopped - * without writing any further global state. - */ const activateLoadedWorkflow = async ( value: string | ComfyWorkflow | null, workflowData: ComfyWorkflowJSON, diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index b5f8ad435b6..ed97b699a2f 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -308,7 +308,7 @@ describe('ComfyApp', () => { mockExtensionService.invokeExtensionsAsync.mockResolvedValue(undefined) vi.mocked(extractFilesFromDragEvent).mockResolvedValue([]) mockImportA1111.mockResolvedValue('imported') - mockWorkflowService.afterLoadNewGraph.mockResolvedValue() + mockWorkflowService.afterLoadNewGraph.mockResolvedValue(true) useSettingStore().settingValues['Comfy.RightSidePanel.ShowErrorsTab'] = true mockValidateWorkflow.mockReset().mockResolvedValue({ graphData: null }) vi.mocked(useWorkflowStore().getWorkflowByPath).mockReturnValue(null) @@ -344,6 +344,7 @@ describe('ComfyApp', () => { ]) mockWorkflowService.afterLoadNewGraph.mockImplementation(async () => { store.setActiveGraph(graphId) + return true }) return store } @@ -4126,8 +4127,8 @@ describe('ComfyApp', () => { } ) let resolveAfterLoad: (() => void) | undefined - const afterLoad = new Promise((resolve) => { - resolveAfterLoad = resolve + const afterLoad = new Promise((resolve) => { + resolveAfterLoad = () => resolve(true) }) mockWorkflowService.afterLoadNewGraph.mockReturnValue(afterLoad) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 3c5dbc604b4..2faa48f5afc 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1700,12 +1700,13 @@ export class ComfyApp { } useTelemetry()?.trackWorkflowOpened(telemetryPayload) useTelemetry()?.trackWorkflowImported(telemetryPayload) - await useWorkflowService().afterLoadNewGraph( + const activated = await useWorkflowService().afterLoadNewGraph( workflow, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, effectiveShareId, { isCurrent: () => this.ownsGraphLoad(loadId) } ) + if (!activated) return await this.rejectSupersededGraphLoad() await useExtensionService().invokeExtensionsAsync('afterLoadGraph') if (!this.ownsGraphLoad(loadId)) { @@ -2360,12 +2361,16 @@ export class ComfyApp { await this.rejectSupersededGraphLoad() return } - await useWorkflowService().afterLoadNewGraph( + const activated = await useWorkflowService().afterLoadNewGraph( fileName, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, undefined, { isCurrent: () => this.ownsGraphLoad(loadId) } ) + if (!activated) { + await this.rejectSupersededGraphLoad() + return + } await useExtensionService().invokeExtensionsAsync('afterLoadGraph') return } @@ -2723,12 +2728,16 @@ export class ComfyApp { await this.rejectSupersededGraphLoad() return } - await useWorkflowService().afterLoadNewGraph( + const activated = await useWorkflowService().afterLoadNewGraph( fileName, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, undefined, { isCurrent: () => this.ownsGraphLoad(loadId) } ) + if (!activated) { + await this.rejectSupersededGraphLoad() + return + } await useExtensionService().invokeExtensionsAsync('afterLoadGraph') if (!this.ownsGraphLoad(loadId)) { await this.rejectSupersededGraphLoad() From 47623e6bdd8ba715017add6d66c8d83f473820bb Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 8 Oct 2026 09:24:18 +0000 Subject: [PATCH 17/31] fix(workflow): make graph load ownership transactional --- .../workflow/core/services/workflowService.ts | 11 +- .../management/stores/workflowStore.ts | 7 +- src/scripts/app.test.ts | 120 ++++++++++++++++-- src/scripts/app.ts | 22 ++-- src/scripts/changeTracker.test.ts | 11 ++ src/scripts/changeTracker.ts | 19 +-- 6 files changed, 156 insertions(+), 34 deletions(-) diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index 43c80d16061..e75a3ed51a2 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -725,6 +725,10 @@ export const useWorkflowService = () => { options: { isCurrent?: () => boolean } = {} ): Promise => { const workflowStore = useWorkspaceStore().workflow + const openCurrentWorkflow = (workflow: ComfyWorkflow) => + options.isCurrent + ? workflowStore.openWorkflow(workflow, options) + : workflowStore.openWorkflow(workflow) const { isAppMode } = useAppMode() const wasAppMode = isAppMode.value const rootGraphId = adoptRootGraphId(workflowData) @@ -772,8 +776,7 @@ export const useWorkflowService = () => { ((existingWorkflow.isPersisted && !existingWorkflow.isLoaded) || isSameActiveWorkflowLoad) ) { - const loadedWorkflow = - await workflowStore.openWorkflow(existingWorkflow) + const loadedWorkflow = await openCurrentWorkflow(existingWorkflow) if (options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) if (loadedWorkflow.initialMode === undefined) { @@ -809,13 +812,13 @@ export const useWorkflowService = () => { tempWorkflow.shareId = shareId } trackIfEnteringApp(tempWorkflow) - const loadedWorkflow = await workflowStore.openWorkflow(tempWorkflow) + const loadedWorkflow = await openCurrentWorkflow(tempWorkflow) if (options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) return true } - const loadedWorkflow = await workflowStore.openWorkflow(value) + const loadedWorkflow = await openCurrentWorkflow(value) if (options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) if (shareId) { diff --git a/src/platform/workflow/management/stores/workflowStore.ts b/src/platform/workflow/management/stores/workflowStore.ts index 185c9793a58..1d3ce0ca02e 100644 --- a/src/platform/workflow/management/stores/workflowStore.ts +++ b/src/platform/workflow/management/stores/workflowStore.ts @@ -204,14 +204,17 @@ export const useWorkflowStore = defineStore('workflow', () => { * @param workflow The workflow to open. */ const openWorkflow = async ( - workflow: ComfyWorkflow + workflow: ComfyWorkflow, + options: { isCurrent?: () => boolean } = {} ): Promise => { + if (options.isCurrent?.() === false) return workflow as LoadedComfyWorkflow if (isActive(workflow)) return workflow as LoadedComfyWorkflow + const loadedWorkflow = await workflow.load() + if (options.isCurrent?.() === false) return loadedWorkflow if (!openWorkflowPaths.value.includes(workflow.path)) { openWorkflowPaths.value.push(workflow.path) } - const loadedWorkflow = await workflow.load() activeWorkflow.value = loadedWorkflow comfyApp.canvas.bg_tint = loadedWorkflow.tintCanvasBg diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index ed97b699a2f..fd0eee944c0 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -687,7 +687,7 @@ describe('ComfyApp', () => { ]) }) - it('closes every beforeLoadGraph when a newer load overtakes an older one', async () => { + it('does not broadcast a superseded load as an error', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) let releaseFirstLoad!: () => void @@ -701,16 +701,16 @@ describe('ComfyApp', () => { const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) await app.loadGraphData(createWorkflowGraphData(), false) releaseFirstLoad() - await expect(olderLoad).resolves.toBeUndefined() + await expect(olderLoad).resolves.toBe(false) 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' - ) - expect(closed).toHaveLength(opened.length) + expect(hooks.filter((hook) => hook === 'beforeLoadGraph')).toHaveLength(2) + expect( + hooks.filter((hook) => hook === 'afterConfigureGraph') + ).toHaveLength(1) + expect(hooks).not.toContain('onGraphLoadError') }) it('does not destroy the newer committed graph when a superseded load resumes', async () => { @@ -732,7 +732,7 @@ describe('ComfyApp', () => { setGraph.mockClear() clean.mockClear() releaseOlderLoad() - await expect(olderLoad).resolves.toBeUndefined() + await expect(olderLoad).resolves.toBe(false) expect(setGraph).not.toHaveBeenCalled() expect(clean).not.toHaveBeenCalled() @@ -752,7 +752,7 @@ describe('ComfyApp', () => { const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) await app.loadGraphData(createWorkflowGraphData(), false) releaseOlderLoad() - await expect(olderLoad).resolves.toBeUndefined() + await expect(olderLoad).resolves.toBe(false) expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() }) @@ -855,7 +855,7 @@ describe('ComfyApp', () => { ) await app.loadGraphData(createWorkflowGraphData(), false) releaseOlderLoad() - await expect(olderLoad).resolves.toBeUndefined() + await expect(olderLoad).resolves.toBe(false) expect(runMissingModelPipeline).toHaveBeenCalledOnce() }) @@ -888,7 +888,7 @@ describe('ComfyApp', () => { await app.loadGraphData(createWorkflowGraphData(), false) configure.mockClear() releaseOlderLoad() - await expect(olderLoad).resolves.toBeUndefined() + await expect(olderLoad).resolves.toBe(false) expect(configure).not.toHaveBeenCalled() }) @@ -2902,6 +2902,54 @@ describe('ComfyApp', () => { return node } + it('reports a rejected workflow activation from loadGraphData', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + mockWorkflowService.afterLoadNewGraph.mockResolvedValueOnce(false) + + await expect( + app.loadGraphData(createWorkflowGraphData(), false) + ).resolves.toBe(false) + expect( + mockExtensionService.invokeExtensionsAsync + ).not.toHaveBeenCalledWith('afterLoadGraph') + }) + + it('stops an API JSON import when workflow activation is rejected', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + mockWorkflowService.afterLoadNewGraph.mockResolvedValueOnce(false) + + await app.loadApiJson({}, 'rejected.json') + + expect( + mockExtensionService.invokeExtensionsAsync + ).not.toHaveBeenCalledWith('afterLoadGraph') + }) + + it('stops an A1111 import when workflow activation is rejected', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ + parameters: 'positive\nNegative prompt: negative\nSteps: 20' + }) + mockImportA1111.mockImplementation( + async (_graph, _parameters, beforeGraphClear) => { + await beforeGraphClear?.() + return 'imported' + } + ) + mockWorkflowService.afterLoadNewGraph.mockResolvedValueOnce(false) + + await app.handleFile(createTestFile('a1111.png', 'image/png')) + + expect( + mockExtensionService.invokeExtensionsAsync + ).not.toHaveBeenCalledWith('afterLoadGraph') + }) + it('does not let a superseded API JSON import erase the newer graph', async () => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() @@ -2986,6 +3034,56 @@ describe('ComfyApp', () => { expect(graph.nodes).toHaveLength(0) }) + it('restarts API JSON construction after an older load commits during preparation', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + const clean = vi.spyOn(app, 'clean') + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith( + 'beforeConfigureGraph', + expect.anything(), + expect.anything() + ) + .thenReturnOnce(olderLoadBlocked) + + const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'beforeConfigureGraph', + expect.anything(), + expect.anything() + ) + ) + + let releaseReplacements!: () => void + const replacementsBlocked = new Promise((resolve) => { + releaseReplacements = resolve + }) + vi.spyOn(useNodeReplacementStore(), 'load').mockReturnValueOnce( + replacementsBlocked + ) + const apiImport = app.loadApiJson( + { '1': { class_type: 'KSampler', inputs: {} } }, + 'newer.json' + ) + await vi.waitFor(() => expect(clean).toHaveBeenCalledTimes(2)) + + releaseOlderLoad() + await olderLoad + releaseReplacements() + await apiImport + + expect(clean).toHaveBeenCalledTimes(3) + expect(graph.nodes).toHaveLength(1) + expect(graph.nodes[0].type).toBe('KSampler') + }) + it('does not bind a superseded API JSON import’s workflow to the newer graph', async () => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 2faa48f5afc..f72b91bb6bc 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1318,12 +1318,8 @@ export class ComfyApp { ) } - private async rejectSupersededGraphLoad(): Promise { - await useExtensionService().invokeExtensionsAsync( - 'onGraphLoadError', - new DOMException('Graph load superseded by a newer load', 'AbortError') - ) - return undefined + private rejectSupersededGraphLoad(): false { + return false } async loadGraphData( @@ -1408,6 +1404,9 @@ export class ComfyApp { // Ideally we should not block users from loading the workflow. graphData = validatedGraphData ?? graphData } + if (!this.ownsGraphLoad(loadId)) { + return this.rejectSupersededGraphLoad() + } // 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. @@ -1510,6 +1509,7 @@ export class ComfyApp { // 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. + if (!this.ownsGraphLoad(loadId)) return this.rejectSupersededGraphLoad() await this.reportGraphLoadFailure(error) void useSubgraphNavigationStore().updateHash( 'workflow-load', @@ -1613,6 +1613,9 @@ export class ComfyApp { } } } catch (error) { + if (!this.ownsGraphLoad(loadId)) { + return this.rejectSupersededGraphLoad() + } await this.reportGraphLoadFailure(error) // Resolves rather than throws: the close/replacement guards read this outcome. return false @@ -2201,6 +2204,7 @@ export class ComfyApp { } ) { const fileName = file.name.replace(/\.\w+$/, '') // Strip file extension + const loadId = ++this.graphLoadSequence const workflowData = await getWorkflowDataFromFile(file) const { workflow, prompt, parameters, templates } = workflowData ?? {} @@ -2305,7 +2309,6 @@ export class ComfyApp { // Use parameters strictly as the final fallback if (parameters && typeof parameters === 'string') { - const loadId = ++this.graphLoadSequence let outcome: A1111ImportOutcome try { outcome = await importA1111(this.rootGraph, parameters, async () => { @@ -2545,6 +2548,9 @@ export class ComfyApp { await this.rejectSupersededGraphLoad() return } + this.canvas.setGraph(this.rootGraph) + withGraphIntentSource('load', () => this.clean()) + this.commitGraphLoad(loadId) withGraphIntentSource('load', () => { for (const id of ids) { const data = apiData[id] @@ -2715,8 +2721,6 @@ export class ComfyApp { app.rootGraph.arrange() }) - this.commitGraphLoad(loadId) - // Intentionally no beforeConfigureGraph: API JSON builds nodes directly // and never passes a ComfyWorkflowJSON through the configure stage. await useExtensionService().invokeExtensionsAsync( diff --git a/src/scripts/changeTracker.test.ts b/src/scripts/changeTracker.test.ts index 6c2b00bff70..fa76334ae8f 100644 --- a/src/scripts/changeTracker.test.ts +++ b/src/scripts/changeTracker.test.ts @@ -676,6 +676,17 @@ describe('ChangeTracker', () => { } ) + it('lets the newest graph load release suppression without waiting for an older load', () => { + const endOlderLoad = ChangeTracker.beginGraphLoad() + const endNewerLoad = ChangeTracker.beginGraphLoad() + + endNewerLoad() + + expect(ChangeTracker.isLoadingGraph).toBe(false) + endOlderLoad() + expect(ChangeTracker.isLoadingGraph).toBe(false) + }) + it('does not push when state is identical', () => { const state = createState() const tracker = createTracker(state) diff --git a/src/scripts/changeTracker.ts b/src/scripts/changeTracker.ts index a35d5838c59..81b4df6d3fc 100644 --- a/src/scripts/changeTracker.ts +++ b/src/scripts/changeTracker.ts @@ -252,7 +252,8 @@ function reportInactiveTrackerCall(method: string, workflowPath: string) { export class ChangeTracker { static MAX_HISTORY = 50 - private static graphLoadDepth = 0 + private static graphLoadGeneration = 0 + private static activeGraphLoadGeneration: number | undefined /** * Guard flag to prevent captureCanvasState from running during loadGraphData. @@ -262,23 +263,25 @@ export class ChangeTracker { * serialize the wrong graph into the old workflow's activeState, corrupting it. */ static get isLoadingGraph(): boolean { - return ChangeTracker.graphLoadDepth > 0 + return ChangeTracker.activeGraphLoadGeneration !== undefined } static set isLoadingGraph(value: boolean) { - ChangeTracker.graphLoadDepth = value ? 1 : 0 + ChangeTracker.activeGraphLoadGeneration = value + ? ++ChangeTracker.graphLoadGeneration + : undefined } static beginGraphLoad(): () => void { - ChangeTracker.graphLoadDepth++ + const generation = ++ChangeTracker.graphLoadGeneration + ChangeTracker.activeGraphLoadGeneration = generation let closed = false return () => { if (closed) return closed = true - ChangeTracker.graphLoadDepth = Math.max( - 0, - ChangeTracker.graphLoadDepth - 1 - ) + if (ChangeTracker.activeGraphLoadGeneration === generation) { + ChangeTracker.activeGraphLoadGeneration = undefined + } } } /** From 67bf8b6e7a93a36174b83d330e7fbee264e63fdc Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 8 Oct 2026 15:25:58 +0000 Subject: [PATCH 18/31] fix: preserve graph load ownership Addresses review feedback:\nhttps://github.com/Comfy-Org/ComfyUI_frontend/pull/19976#discussion_r4218310697\nhttps://github.com/Comfy-Org/ComfyUI_frontend/pull/19976#discussion_r4218310720\nhttps://github.com/Comfy-Org/ComfyUI_frontend/pull/19976#discussion_r4218310737\nhttps://github.com/Comfy-Org/ComfyUI_frontend/pull/19976#discussion_r4218310753 --- .../core/services/workflowService.test.ts | 15 +++++ .../workflow/core/services/workflowService.ts | 10 ++- .../management/stores/workflowStore.test.ts | 1 + .../management/stores/workflowStore.ts | 11 ++-- src/scripts/app.test.ts | 65 ++++++++++++++++--- src/scripts/app.ts | 25 ++----- 6 files changed, 91 insertions(+), 36 deletions(-) diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index c55f7d88373..07d534320be 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -477,6 +477,21 @@ describe('useWorkflowService', () => { expect(loading.isLoaded).toBe(false) }) + it('does not restore the retained workflow after a superseded graph load', async () => { + const workflows = useWorkflowStore() + const current = createModeTestWorkflow({ path: 'workflows/current.json' }) + const loading = createModeTestWorkflow({ path: 'workflows/loading.json' }) + workflows.activeWorkflow = current + vi.mocked(app.loadGraphData).mockResolvedValue('superseded') + + await expect(useWorkflowService().openWorkflow(loading)).resolves.toBe( + false + ) + + expect(app.loadGraphData).toHaveBeenCalledOnce() + expect(workflows.activeWorkflow.path).toBe(current.path) + }) + 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 e75a3ed51a2..ab5ac5b4507 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -485,6 +485,10 @@ export const useWorkflowService = () => { await restoreRetainedWorkflow(workflow) return false } + if (loaded === 'superseded') { + useSubgraphNavigationStore().endWorkflowNavigation(navigationIntentId) + return false + } showPendingWarnings(undefined, { silent: !loadFromRemote && !options.force }) @@ -777,7 +781,7 @@ export const useWorkflowService = () => { isSameActiveWorkflowLoad) ) { const loadedWorkflow = await openCurrentWorkflow(existingWorkflow) - if (options.isCurrent?.() === false) return false + if (!loadedWorkflow || options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) if (loadedWorkflow.initialMode === undefined) { // Prefer the file's linearMode over the draft's since the file @@ -813,13 +817,13 @@ export const useWorkflowService = () => { } trackIfEnteringApp(tempWorkflow) const loadedWorkflow = await openCurrentWorkflow(tempWorkflow) - if (options.isCurrent?.() === false) return false + if (!loadedWorkflow || options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) return true } const loadedWorkflow = await openCurrentWorkflow(value) - if (options.isCurrent?.() === false) return false + if (!loadedWorkflow || options.isCurrent?.() === false) return false activateRunErrors(loadedWorkflow) if (shareId) { loadedWorkflow.shareId = shareId diff --git a/src/platform/workflow/management/stores/workflowStore.test.ts b/src/platform/workflow/management/stores/workflowStore.test.ts index 852ec62c230..e69dfd7bba6 100644 --- a/src/platform/workflow/management/stores/workflowStore.test.ts +++ b/src/platform/workflow/management/stores/workflowStore.test.ts @@ -441,6 +441,7 @@ describe('useWorkflowStore', () => { const loadedWorkflow = await store.openWorkflow(workflow) expect(loadedWorkflow).toBe(workflow) + if (!loadedWorkflow) throw new Error('workflow did not load') expect(loadedWorkflow.path).toBe('workflows/a.json') expect(store.activeWorkflow?.path).toBe('workflows/a.json') expect(store.isOpen(loadedWorkflow)).toBe(true) diff --git a/src/platform/workflow/management/stores/workflowStore.ts b/src/platform/workflow/management/stores/workflowStore.ts index 1d3ce0ca02e..95966b4e6db 100644 --- a/src/platform/workflow/management/stores/workflowStore.ts +++ b/src/platform/workflow/management/stores/workflowStore.ts @@ -51,7 +51,10 @@ interface WorkflowStore { openWorkflows: ComfyWorkflow[] openedWorkflowIndexShift: (shift: number) => ComfyWorkflow | null getMostRecentWorkflow: () => ComfyWorkflow | null - openWorkflow: (workflow: ComfyWorkflow) => Promise + openWorkflow: ( + workflow: ComfyWorkflow, + options?: { isCurrent?: () => boolean } + ) => Promise openWorkflowsInBackground: (paths: { left?: string[] right?: string[] @@ -206,12 +209,12 @@ export const useWorkflowStore = defineStore('workflow', () => { const openWorkflow = async ( workflow: ComfyWorkflow, options: { isCurrent?: () => boolean } = {} - ): Promise => { - if (options.isCurrent?.() === false) return workflow as LoadedComfyWorkflow + ): Promise => { + if (options.isCurrent?.() === false) return undefined if (isActive(workflow)) return workflow as LoadedComfyWorkflow const loadedWorkflow = await workflow.load() - if (options.isCurrent?.() === false) return loadedWorkflow + if (options.isCurrent?.() === false) return undefined if (!openWorkflowPaths.value.includes(workflow.path)) { openWorkflowPaths.value.push(workflow.path) } diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index fd0eee944c0..3f9910c0e6d 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -701,7 +701,7 @@ describe('ComfyApp', () => { const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) await app.loadGraphData(createWorkflowGraphData(), false) releaseFirstLoad() - await expect(olderLoad).resolves.toBe(false) + await expect(olderLoad).resolves.toBe('superseded') const hooks = mockExtensionService.invokeExtensionsAsync.mock.calls.map( ([hook]) => hook @@ -732,7 +732,7 @@ describe('ComfyApp', () => { setGraph.mockClear() clean.mockClear() releaseOlderLoad() - await expect(olderLoad).resolves.toBe(false) + await expect(olderLoad).resolves.toBe('superseded') expect(setGraph).not.toHaveBeenCalled() expect(clean).not.toHaveBeenCalled() @@ -752,7 +752,7 @@ describe('ComfyApp', () => { const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) await app.loadGraphData(createWorkflowGraphData(), false) releaseOlderLoad() - await expect(olderLoad).resolves.toBe(false) + await expect(olderLoad).resolves.toBe('superseded') expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() }) @@ -855,7 +855,7 @@ describe('ComfyApp', () => { ) await app.loadGraphData(createWorkflowGraphData(), false) releaseOlderLoad() - await expect(olderLoad).resolves.toBe(false) + await expect(olderLoad).resolves.toBe('superseded') expect(runMissingModelPipeline).toHaveBeenCalledOnce() }) @@ -888,7 +888,7 @@ describe('ComfyApp', () => { await app.loadGraphData(createWorkflowGraphData(), false) configure.mockClear() releaseOlderLoad() - await expect(olderLoad).resolves.toBe(false) + await expect(olderLoad).resolves.toBe('superseded') expect(configure).not.toHaveBeenCalled() }) @@ -2909,7 +2909,7 @@ describe('ComfyApp', () => { await expect( app.loadGraphData(createWorkflowGraphData(), false) - ).resolves.toBe(false) + ).resolves.toBe('superseded') expect( mockExtensionService.invokeExtensionsAsync ).not.toHaveBeenCalledWith('afterLoadGraph') @@ -3006,6 +3006,53 @@ describe('ComfyApp', () => { expect(graph.getNodeById(survivor.id)).toBe(survivor) }) + it('keeps the newer load suppression active when an older load resumes stale', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + let releaseNewerLoad!: () => void + const newerLoadBlocked = new Promise((resolve) => { + releaseNewerLoad = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith( + 'beforeConfigureGraph', + expect.anything(), + expect.anything() + ) + .thenReturnOnce(olderLoadBlocked) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('afterConfigureGraph', expect.anything()) + .thenReturnOnce(newerLoadBlocked) + + const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'beforeConfigureGraph', + expect.anything(), + expect.anything() + ) + ) + const newerLoad = app.loadGraphData(createWorkflowGraphData(), true) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterConfigureGraph', + expect.anything() + ) + ) + + releaseOlderLoad() + await olderLoad + + expect(ChangeTracker.isLoadingGraph).toBe(true) + + releaseNewerLoad() + await newerLoad + }) + it('does not add a superseded API JSON import’s nodes to the newer graph', async () => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() @@ -3039,7 +3086,6 @@ describe('ComfyApp', () => { const graph = new LGraph() Reflect.set(app, 'rootGraphInternal', graph) Reflect.set(singletonApp, 'rootGraphInternal', graph) - const clean = vi.spyOn(app, 'clean') let releaseOlderLoad!: () => void const olderLoadBlocked = new Promise((resolve) => { releaseOlderLoad = resolve @@ -3072,14 +3118,15 @@ describe('ComfyApp', () => { { '1': { class_type: 'KSampler', inputs: {} } }, 'newer.json' ) - await vi.waitFor(() => expect(clean).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => + expect(useNodeReplacementStore().load).toHaveBeenCalled() + ) releaseOlderLoad() await olderLoad releaseReplacements() await apiImport - expect(clean).toHaveBeenCalledTimes(3) expect(graph.nodes).toHaveLength(1) expect(graph.nodes[0].type).toBe('KSampler') }) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index f72b91bb6bc..2ffd84232c1 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1318,8 +1318,8 @@ export class ComfyApp { ) } - private rejectSupersededGraphLoad(): false { - return false + private rejectSupersededGraphLoad(): 'superseded' { + return 'superseded' } async loadGraphData( @@ -1336,7 +1336,7 @@ export class ComfyApp { silentAssetErrors?: boolean workflowNavigationId?: number } = {} - ): Promise { + ): Promise { const canvasScheduler = useCanvasScheduler() const loadId = ++this.graphLoadSequence @@ -1373,16 +1373,6 @@ export class ComfyApp { useMissingMediaStore().clearMissingMedia() } - 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 ( @@ -1552,16 +1542,14 @@ export class ComfyApp { } } + if (!this.ownsGraphLoad(loadId)) return this.rejectSupersededGraphLoad() + const endGraphLoadSuppression = ChangeTracker.beginGraphLoad() let activatedWorkflow: LoadedComfyWorkflow | undefined let reconcileResourceErrors: (() => void) | undefined let resourceScanLoadCompleted = false try { try { - if (!this.ownsGraphLoad(loadId)) { - return await this.rejectSupersededGraphLoad() - } - this.rootGraph.configure(graphData as ISerialisedGraph) // Save original renderer version before scaling (it gets modified during scaling) @@ -2517,9 +2505,6 @@ export class ComfyApp { await this.rejectSupersededGraphLoad() return } - this.canvas.setGraph(this.rootGraph) - withGraphIntentSource('load', () => this.clean()) - const ids = Object.keys(apiData) // Export (API) flattens subgraph nodes to ids like "194:45". At the root // graph a colon reads as an execution-id path: Locate walks into node From 48296c603f9afd4f1ba81eaed2e41482ec08443b Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 9 Oct 2026 09:20:54 +0000 Subject: [PATCH 19/31] fix: restore graph load cleanup at commit --- .../composables/useTemplateWorkflows.test.ts | 4 ++-- .../composables/useTemplateWorkflows.ts | 3 ++- src/scripts/app.test.ts | 17 +++++++++++++++++ src/scripts/app.ts | 19 ++++++++++++++++--- 4 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts b/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts index abaa6751167..8b6178ef8d5 100644 --- a/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts +++ b/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts @@ -1140,8 +1140,8 @@ describe('useTemplateWorkflows', () => { expect(useFeatureUsageTracker(SURVEY_ID).useCount.value).toBe(0) }) - it('does not count a template whose graph load was superseded', async () => { - vi.mocked(app.loadGraphData).mockResolvedValueOnce(undefined) + it('does not count or report a template whose graph load was superseded', async () => { + vi.mocked(app.loadGraphData).mockResolvedValueOnce('superseded') const { loader } = mountTemplateWorkflows() expect(await loader.loadWorkflowTemplate('template1', 'default')).toBe( diff --git a/src/platform/workflow/templates/composables/useTemplateWorkflows.ts b/src/platform/workflow/templates/composables/useTemplateWorkflows.ts index c9ea955a34b..55390649269 100644 --- a/src/platform/workflow/templates/composables/useTemplateWorkflows.ts +++ b/src/platform/workflow/templates/composables/useTemplateWorkflows.ts @@ -229,7 +229,8 @@ export function useTemplateWorkflows() { { openSource: 'template' } ) if (loadedWorkflow === false) return 'graph-failed' - if (loadedWorkflow === undefined) return 'not-started' + if (loadedWorkflow === undefined || loadedWorkflow === 'superseded') + return 'not-started' updateTemplateEducation(template?.isPartnerNode, loadedWorkflow) if (sourceModule === 'default') trackFeatureUsed() diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 3f9910c0e6d..50a7e036a0f 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -738,6 +738,23 @@ describe('ComfyApp', () => { expect(clean).not.toHaveBeenCalled() }) + it('cleans the outgoing workflow at the winning load commit boundary', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + const setGraph = vi.fn() + Reflect.set(mockCanvas, 'setGraph', setGraph) + const clean = vi.spyOn(app, 'clean') + const missingNodesStore = useMissingNodesErrorStore() + missingNodesStore.setMissingNodeTypes(['OutgoingMissingNode']) + + await app.loadGraphData(createWorkflowGraphData(), true) + + expect(setGraph).toHaveBeenCalledWith(graph) + expect(clean).toHaveBeenCalledOnce() + expect(missingNodesStore.missingNodesError).toBeNull() + }) + it('does not bind an older load’s workflow to a newer load’s graph', 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 2ffd84232c1..d01552d199d 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1413,8 +1413,6 @@ export class ComfyApp { }) } - useSubgraphService().loadSubgraphs(graphData) - await useExtensionService().invokeExtensionsAsync( 'beforeConfigureGraph', graphData, @@ -1550,6 +1548,22 @@ export class ComfyApp { let resourceScanLoadCompleted = false try { try { + // From this point through configure there are no awaits: claim the + // graph immediately before replacing any shared graph state. + this.commitGraphLoad(loadId) + + 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()) + } + + // Subgraph registration mutates the shared root graph, so it belongs + // after the ownership commit and after the outgoing graph is cleared. + useSubgraphService().loadSubgraphs(graphData) this.rootGraph.configure(graphData as ISerialisedGraph) // Save original renderer version before scaling (it gets modified during scaling) @@ -1568,7 +1582,6 @@ export class ComfyApp { ) } - this.commitGraphLoad(loadId) const preservesPendingCamera = !restore_view && workflow !== null && From 7f13a447e56b94a0288d362a8f19caafc7b55c51 Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 9 Oct 2026 09:34:03 +0000 Subject: [PATCH 20/31] fix: normalize subgraphs before load hooks --- src/scripts/app.test.ts | 60 +++++++++++++++++++++++++++++++-- src/scripts/app.ts | 10 +++--- src/services/subgraphService.ts | 17 +++++++--- 3 files changed, 76 insertions(+), 11 deletions(-) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 50a7e036a0f..d8b429a263d 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -744,17 +744,73 @@ describe('ComfyApp', () => { Reflect.set(app, 'rootGraphInternal', graph) const setGraph = vi.fn() Reflect.set(mockCanvas, 'setGraph', setGraph) - const clean = vi.spyOn(app, 'clean') const missingNodesStore = useMissingNodesErrorStore() missingNodesStore.setMissingNodeTypes(['OutgoingMissingNode']) await app.loadGraphData(createWorkflowGraphData(), true) expect(setGraph).toHaveBeenCalledWith(graph) - expect(clean).toHaveBeenCalledOnce() expect(missingNodesStore.missingNodesError).toBeNull() }) + it('does not report a new subgraph instance as a missing node', async () => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + const subgraphId = '00000000-0000-4000-8000-000000000001' + const graphData = { + ...createWorkflowGraphData(), + nodes: [ + { + id: 1, + type: subgraphId, + pos: [0, 0], + size: [100, 100], + flags: {}, + order: 0, + mode: 0, + inputs: [], + outputs: [], + properties: {} + } + ], + definitions: { + subgraphs: [ + { + id: subgraphId, + version: 1, + state: { + lastGroupId: 0, + lastNodeId: 0, + lastLinkId: 0, + lastRerouteId: 0 + }, + revision: 0, + config: {}, + name: 'Review fixture', + inputNode: { id: -10, bounding: [0, 0, 100, 60] }, + outputNode: { id: -20, bounding: [200, 0, 100, 60] }, + inputs: [], + outputs: [], + widgets: [], + nodes: [], + groups: [], + links: [], + extra: {} + } + ] + } + } as ComfyWorkflowJSON + + await app.loadGraphData(graphData, true) + + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterConfigureGraph', + [] + ) + }) + it('does not bind an older load’s workflow to a newer load’s graph', 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 d01552d199d..d37af97da99 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1397,6 +1397,7 @@ export class ComfyApp { if (!this.ownsGraphLoad(loadId)) { return this.rejectSupersededGraphLoad() } + const subgraphTypes = useSubgraphService().normalizeSubgraphs(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. @@ -1436,7 +1437,10 @@ export class ComfyApp { return } for (const n of nodes) { - if (!(n.type in LiteGraph.registered_node_types)) { + if ( + !(n.type in LiteGraph.registered_node_types) && + !subgraphTypes.has(n.type) + ) { // Always sanitize so configure() can handle unregistered types, // but only report as missing if the node is active. const isMuted = @@ -1548,8 +1552,6 @@ export class ComfyApp { let resourceScanLoadCompleted = false try { try { - // From this point through configure there are no awaits: claim the - // graph immediately before replacing any shared graph state. this.commitGraphLoad(loadId) if (clean) { @@ -1561,8 +1563,6 @@ export class ComfyApp { withGraphIntentSource('load', () => this.clean()) } - // Subgraph registration mutates the shared root graph, so it belongs - // after the ownership commit and after the outgoing graph is cleared. useSubgraphService().loadSubgraphs(graphData) this.rootGraph.configure(graphData as ISerialisedGraph) diff --git a/src/services/subgraphService.ts b/src/services/subgraphService.ts index bf47b34da70..4b3632aed53 100644 --- a/src/services/subgraphService.ts +++ b/src/services/subgraphService.ts @@ -60,10 +60,10 @@ export const useSubgraphService = () => { return nodeDef } - /** Loads all exported subgraph definitions from workflow */ - function loadSubgraphs(graphData: ComfyWorkflowJSON) { + /** Normalizes exported subgraph ids without mutating shared graph state. */ + function normalizeSubgraphs(graphData: ComfyWorkflowJSON) { const subgraphs = graphData.definitions?.subgraphs - if (!subgraphs) return + if (!subgraphs) return new Set() const normalized = normalizeSubgraphDefinitionIds( subgraphs, @@ -71,8 +71,16 @@ export const useSubgraphService = () => { ) graphData.definitions!.subgraphs = normalized.subgraphs if (normalized.rootNodes) graphData.nodes = normalized.rootNodes + return new Set(normalized.subgraphs.map(({ id }) => id)) + } + + /** Loads all normalized exported subgraph definitions from workflow. */ + function loadSubgraphs(graphData: ComfyWorkflowJSON) { + const subgraphs = graphData.definitions?.subgraphs + if (!subgraphs) return + // Assertion: overriding Zod schema - const exportedSubgraphs = normalized.subgraphs as ExportedSubgraph[] + const exportedSubgraphs = subgraphs as ExportedSubgraph[] const missingSubgraphs = exportedSubgraphs.filter( ({ id }) => !comfyApp.rootGraph.subgraphs.has(id) ) @@ -101,6 +109,7 @@ export const useSubgraphService = () => { } return { + normalizeSubgraphs, loadSubgraphs, registerNewSubgraph } From 42cdf9a036dfa99bba500616c3f2e838aa8fda03 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 13 Oct 2026 09:31:29 +0000 Subject: [PATCH 21/31] fix(workflow): serialize graph imports before preparation --- src/scripts/app.test.ts | 790 +++++----------------------------------- src/scripts/app.ts | 179 +++++---- 2 files changed, 198 insertions(+), 771 deletions(-) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index d708578c313..4e1a40811f5 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -55,7 +55,6 @@ import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/ import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import type { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation' import { createMockChangeTracker } from '@/utils/__tests__/litegraphTestUtils' -import { ChangeTracker } from '@/scripts/changeTracker' import { createTestCanvasElement, createTestDragAndScale, @@ -737,72 +736,6 @@ describe('ComfyApp', () => { ]) }) - it('does not broadcast a superseded load as an error', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - let releaseFirstLoad!: () => void - const firstLoadBlocked = new Promise((resolve) => { - releaseFirstLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('beforeLoadGraph') - .thenReturnOnce(firstLoadBlocked) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await app.loadGraphData(createWorkflowGraphData(), false) - releaseFirstLoad() - await expect(olderLoad).resolves.toBe('superseded') - - const hooks = mockExtensionService.invokeExtensionsAsync.mock.calls.map( - ([hook]) => hook - ) - expect(hooks.filter((hook) => hook === 'beforeLoadGraph')).toHaveLength(2) - expect( - hooks.filter((hook) => hook === 'afterConfigureGraph') - ).toHaveLength(1) - expect(hooks).not.toContain('onGraphLoadError') - }) - - it('does not destroy the newer committed graph when a superseded load resumes', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - const setGraph = vi.fn() - Reflect.set(mockCanvas, 'setGraph', setGraph) - const clean = vi.spyOn(app, 'clean').mockImplementation(() => {}) - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('beforeLoadGraph') - .thenReturnOnce(olderLoadBlocked) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) - await app.loadGraphData(createWorkflowGraphData(), true) - setGraph.mockClear() - clean.mockClear() - releaseOlderLoad() - await expect(olderLoad).resolves.toBe('superseded') - - expect(setGraph).not.toHaveBeenCalled() - expect(clean).not.toHaveBeenCalled() - }) - - it('cleans the outgoing workflow at the winning load commit boundary', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - const setGraph = vi.fn() - Reflect.set(mockCanvas, 'setGraph', setGraph) - const missingNodesStore = useMissingNodesErrorStore() - missingNodesStore.setMissingNodeTypes(['OutgoingMissingNode']) - - await app.loadGraphData(createWorkflowGraphData(), true) - - expect(setGraph).toHaveBeenCalledWith(graph) - expect(missingNodesStore.missingNodesError).toBeNull() - }) - it('does not report a new subgraph instance as a missing node', async () => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() @@ -861,188 +794,6 @@ describe('ComfyApp', () => { ) }) - it('does not bind an older load’s workflow to a newer load’s graph', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('afterConfigureGraph', expect.anything()) - .thenReturnOnce(olderLoadBlocked) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await app.loadGraphData(createWorkflowGraphData(), false) - releaseOlderLoad() - await expect(olderLoad).resolves.toBe('superseded') - - expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() - }) - - it('keeps a newer load’s suppression window open when a superseded load returns', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - ChangeTracker.isLoadingGraph = false - onTestFinished(() => { - ChangeTracker.isLoadingGraph = false - }) - const releaseScan: Array<() => void> = [] - vi.mocked(runMissingModelPipeline).mockImplementation(async () => { - await new Promise((resolve) => releaseScan.push(resolve)) - return { missingModels: [], confirmedCandidates: [] } - }) - vi.spyOn( - missingMediaPipeline, - 'runMissingMediaPipeline' - ).mockResolvedValue(undefined) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await vi.waitFor(() => expect(releaseScan).toHaveLength(1)) - const newerLoad = app.loadGraphData(createWorkflowGraphData(), false) - await vi.waitFor(() => expect(releaseScan).toHaveLength(2)) - - releaseScan[0]() - await olderLoad - - expect(ChangeTracker.isLoadingGraph).toBe(true) - - releaseScan[1]() - await newerLoad - expect(ChangeTracker.isLoadingGraph).toBe(false) - }) - - it('does not post a superseded load’s warnings or retire errors a newer load has not recorded yet', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - ChangeTracker.isLoadingGraph = false - onTestFinished(() => { - ChangeTracker.isLoadingGraph = false - }) - const retireErrors = vi.spyOn( - useExecutionErrorStore(), - 'retireResolvedMissingNodePromptError' - ) - const releaseScan: Array<() => void> = [] - vi.mocked(runMissingModelPipeline).mockImplementation(async () => { - await new Promise((resolve) => releaseScan.push(resolve)) - return { missingModels: [], confirmedCandidates: [] } - }) - vi.spyOn( - missingMediaPipeline, - 'runMissingMediaPipeline' - ).mockResolvedValue(undefined) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await vi.waitFor(() => expect(releaseScan).toHaveLength(1)) - const newerLoad = app.loadGraphData(createWorkflowGraphData(), false) - await vi.waitFor(() => expect(releaseScan).toHaveLength(2)) - - releaseScan[0]() - await olderLoad - - expect(mockWorkflowService.showPendingWarnings).not.toHaveBeenCalled() - expect(retireErrors).not.toHaveBeenCalled() - - releaseScan[1]() - await newerLoad - - expect(mockWorkflowService.showPendingWarnings).toHaveBeenCalledOnce() - expect(retireErrors).toHaveBeenCalledOnce() - }) - - it('does not run a superseded load’s asset scans against the newer load’s graph', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - vi.mocked(runMissingModelPipeline).mockResolvedValue({ - missingModels: [], - confirmedCandidates: [] - }) - vi.spyOn( - missingMediaPipeline, - 'runMissingMediaPipeline' - ).mockResolvedValue(undefined) - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('afterLoadGraph') - .thenReturnOnce(olderLoadBlocked) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'afterLoadGraph' - ) - ) - await app.loadGraphData(createWorkflowGraphData(), false) - releaseOlderLoad() - await expect(olderLoad).resolves.toBe('superseded') - - expect(runMissingModelPipeline).toHaveBeenCalledOnce() - }) - - it('does not configure the graph when superseded between its two pre-commit gates', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - const configure = vi.spyOn(graph, 'configure') - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith( - 'beforeConfigureGraph', - expect.anything(), - expect.anything() - ) - .thenReturnOnce(olderLoadBlocked) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'beforeConfigureGraph', - expect.anything(), - expect.anything() - ) - ) - await app.loadGraphData(createWorkflowGraphData(), false) - configure.mockClear() - releaseOlderLoad() - await expect(olderLoad).resolves.toBe('superseded') - - expect(configure).not.toHaveBeenCalled() - }) - - it('lets an older valid load commit when its newer replacement fails', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('beforeLoadGraph') - .thenReturnOnce(olderLoadBlocked) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith( - 'beforeConfigureGraph', - expect.anything(), - expect.anything() - ) - .thenRejectOnce(new Error('newer load failed')) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), false) - await expect( - app.loadGraphData(createWorkflowGraphData(), false) - ).resolves.toBe(false) - releaseOlderLoad() - - await expect(olderLoad).resolves.toBe(true) - }) - describe('pending camera restore while the canvas is hidden', () => { let canvasElement: HTMLCanvasElement @@ -3214,532 +2965,173 @@ describe('ComfyApp', () => { ) }) - describe('graph-load ownership across the import paths', () => { - function markerNode(): LGraphNode { - const node = new LGraphNode('marker', 'marker') - node.id = toNodeId('marker') - return node - } - - it('reports a rejected workflow activation from loadGraphData', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - mockWorkflowService.afterLoadNewGraph.mockResolvedValueOnce(false) - - await expect( - app.loadGraphData(createWorkflowGraphData(), false) - ).resolves.toBe('superseded') - expect( - mockExtensionService.invokeExtensionsAsync - ).not.toHaveBeenCalledWith('afterLoadGraph') - }) - - it('stops an API JSON import when workflow activation is rejected', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - Reflect.set(singletonApp, 'rootGraphInternal', graph) - mockWorkflowService.afterLoadNewGraph.mockResolvedValueOnce(false) - - await app.loadApiJson({}, 'rejected.json') - - expect( - mockExtensionService.invokeExtensionsAsync - ).not.toHaveBeenCalledWith('afterLoadGraph') - }) - - it('stops an A1111 import when workflow activation is rejected', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ - parameters: 'positive\nNegative prompt: negative\nSteps: 20' - }) - mockImportA1111.mockImplementation( - async (_graph, _parameters, beforeGraphClear) => { - await beforeGraphClear?.() - return 'imported' - } - ) - mockWorkflowService.afterLoadNewGraph.mockResolvedValueOnce(false) - - await app.handleFile(createTestFile('a1111.png', 'image/png')) - - expect( - mockExtensionService.invokeExtensionsAsync - ).not.toHaveBeenCalledWith('afterLoadGraph') - }) - - it('does not let a superseded API JSON import erase the newer graph', async () => { + describe('graph-load FIFO across import paths', () => { + beforeEach(() => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() Reflect.set(app, 'rootGraphInternal', graph) Reflect.set(singletonApp, 'rootGraphInternal', graph) - const clean = vi.spyOn(app, 'clean').mockImplementation(() => {}) - let releaseImport!: () => void - const importBlocked = new Promise((resolve) => { - releaseImport = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('beforeLoadGraph') - .thenReturnOnce(importBlocked) - - const apiImport = app.loadApiJson({}, 'superseded.json') - await app.loadGraphData(createWorkflowGraphData(), true) - const survivor = markerNode() - graph.add(survivor) - vi.mocked(mockCanvas.setGraph).mockClear() - clean.mockClear() - releaseImport() - await apiImport - - expect(mockCanvas.setGraph).not.toHaveBeenCalled() - expect(clean).not.toHaveBeenCalled() - expect(graph.getNodeById(survivor.id)).toBe(survivor) }) - it('does not let a load still awaiting its hooks erase a committed API JSON import', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - Reflect.set(singletonApp, 'rootGraphInternal', graph) - const clean = vi.spyOn(app, 'clean').mockImplementation(() => {}) - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve + it('runs workflow loads in call order', async () => { + let releaseFirst!: () => void + const firstBlocked = new Promise((resolve) => { + releaseFirst = resolve }) vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith('beforeLoadGraph') - .thenReturnOnce(olderLoadBlocked) - - const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) - await app.loadApiJson({}, 'committed.json') - const survivor = markerNode() - graph.add(survivor) - vi.mocked(mockCanvas.setGraph).mockClear() - clean.mockClear() - releaseOlderLoad() - await olderLoad - - expect(mockCanvas.setGraph).not.toHaveBeenCalled() - expect(clean).not.toHaveBeenCalled() - expect(graph.getNodeById(survivor.id)).toBe(survivor) - }) - - it('keeps the newer load suppression active when an older load resumes stale', async () => { - app.canvasElRef.value = document.createElement('canvas') - Reflect.set(app, 'rootGraphInternal', new LGraph()) - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve - }) - let releaseNewerLoad!: () => void - const newerLoadBlocked = new Promise((resolve) => { - releaseNewerLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith( - 'beforeConfigureGraph', - expect.anything(), - expect.anything() - ) - .thenReturnOnce(olderLoadBlocked) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('afterConfigureGraph', expect.anything()) - .thenReturnOnce(newerLoadBlocked) + .thenReturnOnce(firstBlocked) - const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'beforeConfigureGraph', - expect.anything(), - expect.anything() - ) - ) - const newerLoad = app.loadGraphData(createWorkflowGraphData(), true) + const first = app.loadGraphData(createWorkflowGraphData(), true) await vi.waitFor(() => expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'afterConfigureGraph', - expect.anything() + 'beforeLoadGraph' ) ) + const second = app.loadGraphData(createWorkflowGraphData(), true) - releaseOlderLoad() - await olderLoad - - expect(ChangeTracker.isLoadingGraph).toBe(true) - - releaseNewerLoad() - await newerLoad - }) - - it('does not add a superseded API JSON import’s nodes to the newer graph', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - Reflect.set(singletonApp, 'rootGraphInternal', graph) - vi.spyOn(app, 'clean').mockImplementation(() => {}) - let releaseReplacements!: () => void - const replacementsBlocked = new Promise((resolve) => { - releaseReplacements = resolve - }) - vi.spyOn(useNodeReplacementStore(), 'load').mockReturnValueOnce( - replacementsBlocked - ) - - const apiImport = app.loadApiJson( - { '1': { class_type: 'KSampler', inputs: {} } }, - 'superseded.json' - ) - await vi.waitFor(() => - expect(useNodeReplacementStore().load).toHaveBeenCalled() - ) - await app.loadGraphData(createWorkflowGraphData(), true) - releaseReplacements() - await apiImport + expect( + mockExtensionService.invokeExtensionsAsync.mock.calls.filter( + ([hook]) => hook === 'beforeLoadGraph' + ) + ).toHaveLength(1) - expect(graph.nodes).toHaveLength(0) + releaseFirst() + await expect(first).resolves.toBeTruthy() + await expect(second).resolves.toBeTruthy() + expect( + mockExtensionService.invokeExtensionsAsync.mock.calls.filter( + ([hook]) => hook === 'beforeLoadGraph' + ) + ).toHaveLength(2) }) - it('restarts API JSON construction after an older load commits during preparation', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - Reflect.set(singletonApp, 'rootGraphInternal', graph) - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve - }) + it('continues with the next workflow after a failed load', async () => { vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith( 'beforeConfigureGraph', expect.anything(), expect.anything() ) - .thenReturnOnce(olderLoadBlocked) + .thenRejectOnce(new Error('first load failed')) - const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'beforeConfigureGraph', - expect.anything(), - expect.anything() - ) - ) + const first = app.loadGraphData(createWorkflowGraphData(), true) + const second = app.loadGraphData(createWorkflowGraphData(), true) - let releaseReplacements!: () => void - const replacementsBlocked = new Promise((resolve) => { - releaseReplacements = resolve - }) - vi.spyOn(useNodeReplacementStore(), 'load').mockReturnValueOnce( - replacementsBlocked - ) - const apiImport = app.loadApiJson( - { '1': { class_type: 'KSampler', inputs: {} } }, - 'newer.json' + await expect(first).resolves.toBe(false) + await expect(second).resolves.toBeTruthy() + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'onGraphLoadError', + expect.any(Error) ) - await vi.waitFor(() => - expect(useNodeReplacementStore().load).toHaveBeenCalled() + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterLoadGraph' ) - - releaseOlderLoad() - await olderLoad - releaseReplacements() - await apiImport - - expect(graph.nodes).toHaveLength(1) - expect(graph.nodes[0].type).toBe('KSampler') }) - it('does not bind a superseded API JSON import’s workflow to the newer graph', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - Reflect.set(singletonApp, 'rootGraphInternal', graph) - vi.spyOn(app, 'clean').mockImplementation(() => {}) - let releaseImport!: () => void - const importBlocked = new Promise((resolve) => { - releaseImport = resolve + 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('afterConfigureGraph', expect.anything()) - .thenReturnOnce(importBlocked) + .calledWith('beforeLoadGraph') + .thenReturnOnce(workflowBlocked) - const apiImport = app.loadApiJson({}, 'superseded.json') + const workflow = app.loadGraphData(createWorkflowGraphData(), true) await vi.waitFor(() => expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'afterConfigureGraph', - expect.anything() + 'beforeLoadGraph' ) ) - await app.loadGraphData(createWorkflowGraphData(), true) - mockWorkflowService.afterLoadNewGraph.mockClear() - releaseImport() - await apiImport - - expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() - }) - - it('does not attach a superseded API JSON import’s missing nodes to the newer workflow', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - Reflect.set(singletonApp, 'rootGraphInternal', graph) - vi.spyOn(app, 'clean').mockImplementation(() => {}) - const nodeReplacementStore = useNodeReplacementStore() - vi.spyOn(nodeReplacementStore, 'load').mockResolvedValue() - vi.spyOn(nodeReplacementStore, 'getReplacementFor').mockReturnValue(null) - let releaseImport!: () => void - const importBlocked = new Promise((resolve) => { - releaseImport = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('afterLoadGraph') - .thenReturnOnce(importBlocked) - const apiImport = app.loadApiJson( - { '1': { class_type: 'UninstalledScratchNode', inputs: {} } }, - 'superseded.json' - ) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'afterLoadGraph' - ) - ) - await app.loadGraphData(createWorkflowGraphData(), true) - const newerWorkflow = markLoaded( - new ComfyWorkflow({ - path: 'workflows/newer.json', - modified: 0, - size: 0 - }) + { '1': { class_type: 'KSampler', inputs: {} } }, + 'queued.json' ) - useWorkflowStore().activeWorkflow = newerWorkflow - mockWorkflowService.showPendingWarnings.mockClear() - releaseImport() + + expect(useNodeReplacementStore().load).not.toHaveBeenCalled() + releaseWorkflow() + await workflow await apiImport - expect(mockWorkflowService.showPendingWarnings).not.toHaveBeenCalled() - expect(newerWorkflow.pendingWarnings).toBeNull() + expect(app.rootGraph.nodes).toHaveLength(1) + expect(app.rootGraph.nodes[0].type).toBe('KSampler') }) - it('does not let a superseded A1111 import clear the newer load’s missing nodes', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) + it('queues A1111 construction behind an in-flight workflow load', async () => { vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ parameters: 'positive\nNegative prompt: negative\nSteps: 20' }) - let releaseEmbeddings!: () => void - const embeddingsBlocked = new Promise((resolve) => { - releaseEmbeddings = resolve - }) mockImportA1111.mockImplementation( - async (importGraph, _parameters, beforeGraphClear) => { - await embeddingsBlocked + async (_graph, _parameters, beforeGraphClear) => { await beforeGraphClear?.() - importGraph.clear() return 'imported' } ) - - const a1111Import = app.handleFile( - createTestFile('a1111.png', 'image/png') - ) - await vi.waitFor(() => expect(mockImportA1111).toHaveBeenCalled()) - await app.loadGraphData(createWorkflowGraphData(), true) - const missingNodesStore = useMissingNodesErrorStore() - missingNodesStore.setMissingNodeTypes(['NewerLoadMissingNode']) - releaseEmbeddings() - await a1111Import - - expect(missingNodesStore.missingNodesError?.nodeTypes).toEqual([ - 'NewerLoadMissingNode' - ]) - }) - - it('does not let an A1111 import superseded inside beforeLoadGraph clear the newer graph', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ - parameters: 'positive\nNegative prompt: negative\nSteps: 20' - }) - let releaseBeforeLoad!: () => void - const beforeLoadBlocked = new Promise((resolve) => { - releaseBeforeLoad = resolve + let releaseWorkflow!: () => void + const workflowBlocked = new Promise((resolve) => { + releaseWorkflow = resolve }) vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith('beforeLoadGraph') - .thenReturnOnce(beforeLoadBlocked) - mockImportA1111.mockImplementation( - async (importGraph, _parameters, beforeGraphClear) => { - await beforeGraphClear?.() - importGraph.clear() - return 'imported' - } - ) + .thenReturnOnce(workflowBlocked) - const a1111Import = app.handleFile( - createTestFile('a1111.png', 'image/png') - ) + const workflow = app.loadGraphData(createWorkflowGraphData(), true) await vi.waitFor(() => expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( 'beforeLoadGraph' ) ) - await app.loadGraphData(createWorkflowGraphData(), true) - const survivor = markerNode() - graph.add(survivor) - releaseBeforeLoad() - await a1111Import - - expect(graph.getNodeById(survivor.id)).toBe(survivor) - }) - - it('does not let an A1111 import superseded inside beforeLoadGraph clear the newer load’s missing nodes', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ - parameters: 'positive\nNegative prompt: negative\nSteps: 20' - }) - let releaseBeforeLoad!: () => void - const beforeLoadBlocked = new Promise((resolve) => { - releaseBeforeLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('beforeLoadGraph') - .thenReturnOnce(beforeLoadBlocked) - mockImportA1111.mockImplementation( - async (_importGraph, _parameters, beforeGraphClear) => { - await beforeGraphClear?.() - return 'imported' - } - ) - const a1111Import = app.handleFile( - createTestFile('a1111.png', 'image/png') - ) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'beforeLoadGraph' - ) - ) - await app.loadGraphData(createWorkflowGraphData(), true) - const missingNodesStore = useMissingNodesErrorStore() - missingNodesStore.setMissingNodeTypes(['NewerLoadMissingNode']) - releaseBeforeLoad() - await a1111Import - - expect(missingNodesStore.missingNodesError?.nodeTypes).toEqual([ - 'NewerLoadMissingNode' - ]) - }) - - it('does not bind a superseded A1111 import’s workflow to the newer graph', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ - parameters: 'positive\nNegative prompt: negative\nSteps: 20' - }) - let releaseAfterConfigure!: () => void - const afterConfigureBlocked = new Promise((resolve) => { - releaseAfterConfigure = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('afterConfigureGraph', expect.anything()) - .thenReturnOnce(afterConfigureBlocked) - mockImportA1111.mockImplementation( - async (_importGraph, _parameters, beforeGraphClear) => { - await beforeGraphClear?.() - return 'imported' - } + createTestFile('queued-a1111.png', 'image/png') ) - const a1111Import = app.handleFile( - createTestFile('a1111.png', 'image/png') - ) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'afterConfigureGraph', - expect.anything() - ) - ) - await app.loadGraphData(createWorkflowGraphData(), true) - mockWorkflowService.afterLoadNewGraph.mockClear() - releaseAfterConfigure() + expect(mockImportA1111).not.toHaveBeenCalled() + releaseWorkflow() + await workflow await a1111Import - - expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() + expect(mockImportA1111).toHaveBeenCalledOnce() }) - it('does not let a load still awaiting its hooks erase a committed A1111 import', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ - parameters: 'positive\nNegative prompt: negative\nSteps: 20' - }) - const clean = vi.spyOn(app, 'clean').mockImplementation(() => {}) - let releaseOlderLoad!: () => void - const olderLoadBlocked = new Promise((resolve) => { - releaseOlderLoad = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('beforeLoadGraph') - .thenReturnOnce(olderLoadBlocked) - mockImportA1111.mockImplementation( - async (importGraph, _parameters, beforeGraphClear) => { - await beforeGraphClear?.() - importGraph.clear() - return 'imported' + it('finishes terminal hooks before a re-entrant load starts', async () => { + const events: string[] = [] + let reentrantLoad: ReturnType | undefined + let terminalCalls = 0 + mockExtensionService.invokeExtensionsAsync.mockImplementation( + async (hook) => { + if (hook !== 'afterLoadGraph') return + terminalCalls++ + if (terminalCalls === 1) { + events.push('first-terminal-start') + reentrantLoad = app.loadGraphData(createWorkflowGraphData(), true) + await Promise.resolve() + events.push('first-terminal-end') + } else { + events.push('second-terminal') + } } ) - const olderLoad = app.loadGraphData(createWorkflowGraphData(), true) - await app.handleFile(createTestFile('a1111.png', 'image/png')) - vi.mocked(mockCanvas.setGraph).mockClear() - clean.mockClear() - releaseOlderLoad() - await olderLoad + await app.loadGraphData(createWorkflowGraphData(), true) + await reentrantLoad - expect(mockCanvas.setGraph).not.toHaveBeenCalled() - expect(clean).not.toHaveBeenCalled() + expect(events).toEqual([ + 'first-terminal-start', + 'first-terminal-end', + 'second-terminal' + ]) }) - it('does not let a superseded A1111 import clear the newer graph', async () => { - app.canvasElRef.value = document.createElement('canvas') - const graph = new LGraph() - Reflect.set(app, 'rootGraphInternal', graph) - vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ - parameters: 'positive\nNegative prompt: negative\nSteps: 20' - }) - let releaseEmbeddings!: () => void - const embeddingsBlocked = new Promise((resolve) => { - releaseEmbeddings = resolve - }) - mockImportA1111.mockImplementation( - async (importGraph, _parameters, beforeGraphClear) => { - await embeddingsBlocked - await beforeGraphClear?.() - importGraph.clear() - return 'imported' + it('cleans before extensions prepare the incoming workflow', async () => { + const clean = vi.spyOn(app, 'clean') + mockExtensionService.invokeExtensionsAsync.mockImplementation( + async (hook) => { + if (hook !== 'beforeConfigureGraph') return + expect(clean).toHaveBeenCalledOnce() } ) - const a1111Import = app.handleFile( - createTestFile('a1111.png', 'image/png') - ) - await vi.waitFor(() => expect(mockImportA1111).toHaveBeenCalled()) await app.loadGraphData(createWorkflowGraphData(), true) - const survivor = markerNode() - graph.add(survivor) - releaseEmbeddings() - await a1111Import - - expect(graph.getNodeById(survivor.id)).toBe(survivor) - expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() }) }) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 2bd72daaa20..900d1eff62d 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -436,6 +436,7 @@ export class ComfyApp implements IComfyApp { private configuringGraphLevel: number = 0 private graphLoadSequence = 0 + private graphLoadQueue: Promise = Promise.resolve() private committedGraphLoadSequence = 0 private pendingCamera: | { id: number; workflow: string | null | ComfyWorkflow } @@ -1193,12 +1194,33 @@ export class ComfyApp implements IComfyApp { return 'superseded' } + 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, + clean: boolean = true, + restore_view: boolean = true, + workflow: string | null | ComfyWorkflow = null, + options: LoadGraphDataOptions = {} ): Promise { const canvasScheduler = useCanvasScheduler() const loadId = ++this.graphLoadSequence @@ -1222,6 +1244,13 @@ export class ComfyApp implements IComfyApp { try { useExecutionErrorStore().setActiveGraph(null) + if (clean) { + // Cleanup must precede extension preparation. Several extensions attach + // subgraph, preview, media, and colour state in beforeConfigureGraph. + this.canvas.setGraph(this.rootGraph) + withGraphIntentSource('load', () => this.clean()) + } + if (skipAssetScans) { // Only reset candidates; preserve UI state (fileSizes, etc.) // so cached results restored by showPendingWarnings still display sizes. @@ -1435,15 +1464,6 @@ export class ComfyApp implements IComfyApp { try { this.commitGraphLoad(loadId) - 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()) - } - useSubgraphService().loadSubgraphs(graphData) this.rootGraph.configure(graphData as ISerialisedGraph) @@ -2098,7 +2118,6 @@ export class ComfyApp implements IComfyApp { } ) { const fileName = file.name.replace(/\.\w+$/, '') // Strip file extension - const loadId = ++this.graphLoadSequence const workflowData = await getWorkflowDataFromFile(file) const { workflow, prompt, parameters, templates } = workflowData ?? {} @@ -2203,71 +2222,76 @@ export class ComfyApp implements IComfyApp { // Use parameters strictly as the final fallback if (parameters && typeof parameters === 'string') { - let outcome: A1111ImportOutcome - try { - outcome = await importA1111(this.rootGraph, parameters, async () => { - if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() - try { - // false: final destination; no later load republishes the hash. - useWorkflowService().beforeLoadNewGraph(false) - await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') - } finally { - if (this.ownsGraphLoad(loadId)) { - useMissingNodesErrorStore().setMissingNodeTypes([]) + return await this.enqueueGraphLoad(async () => { + const loadId = ++this.graphLoadSequence + let outcome: A1111ImportOutcome + try { + outcome = await importA1111(this.rootGraph, parameters, async () => { + if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() + try { + // false: final destination; no later load republishes the hash. + useWorkflowService().beforeLoadNewGraph(false) + await useExtensionService().invokeExtensionsAsync( + 'beforeLoadGraph' + ) + } finally { + if (this.ownsGraphLoad(loadId)) { + useMissingNodesErrorStore().setMissingNodeTypes([]) + } } + if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() + this.canvas.setGraph(this.rootGraph) + this.commitGraphLoad(loadId) + }) + } catch (error) { + if (!(error instanceof SupersededGraphLoad)) throw error + await this.rejectSupersededGraphLoad() + return + } + 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}` + ) } - if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() - this.canvas.setGraph(this.rootGraph) - this.commitGraphLoad(loadId) - }) - } catch (error) { - if (!(error instanceof SupersededGraphLoad)) throw error - await this.rejectSupersededGraphLoad() - return - } - switch (outcome) { - case 'core-nodes-unavailable': - useToast().warning(t('toastMessages.a1111CoreNodesUnavailable')) + } + // Intentionally no beforeConfigureGraph: A1111 has no mutable + // workflow JSON before graph construction, so there is no payload. + await useExtensionService().invokeExtensionsAsync( + 'afterConfigureGraph', + [] + ) + if (!this.ownsGraphLoad(loadId)) { + await this.rejectSupersededGraphLoad() return - case 'not-a1111': - this.showErrorOnFileLoad(file) + } + const activated = await useWorkflowService().afterLoadNewGraph( + fileName, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, + undefined, + { isCurrent: () => this.ownsGraphLoad(loadId) } + ) + if (!activated) { + await this.rejectSupersededGraphLoad() 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', - [] - ) - if (!this.ownsGraphLoad(loadId)) { - await this.rejectSupersededGraphLoad() + await useExtensionService().invokeExtensionsAsync('afterLoadGraph') return - } - const activated = await useWorkflowService().afterLoadNewGraph( - fileName, - this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, - undefined, - { isCurrent: () => this.ownsGraphLoad(loadId) } - ) - if (!activated) { - await this.rejectSupersededGraphLoad() - return - } - await useExtensionService().invokeExtensionsAsync('afterLoadGraph') - return + }) } this.showErrorOnFileLoad(file) @@ -2399,12 +2423,26 @@ 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 { const loadId = ++this.graphLoadSequence // false: no workflow load follows to republish the hash. useWorkflowService().beforeLoadNewGraph(false) await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + this.canvas.setGraph(this.rootGraph) + withGraphIntentSource('load', () => this.clean()) + this.commitGraphLoad(loadId) + if (!this.ownsGraphLoad(loadId)) { await this.rejectSupersededGraphLoad() return @@ -2437,9 +2475,6 @@ export class ComfyApp implements IComfyApp { await this.rejectSupersededGraphLoad() return } - this.canvas.setGraph(this.rootGraph) - withGraphIntentSource('load', () => this.clean()) - this.commitGraphLoad(loadId) withGraphIntentSource('load', () => { for (const id of ids) { const data = apiData[id] From f416d0b5a3e33512303b313750a1f0537ab92a55 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 14 Oct 2026 09:47:16 +0000 Subject: [PATCH 22/31] test: stabilize focused graph load browser shard --- browser_tests/tests/sidebar/workflows.spec.ts | 3 ++- browser_tests/tests/subgraph/subgraphSeed.spec.ts | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) 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' }, From 8802da2639e6f5f0baec095cc4052784c97d5881 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 14 Oct 2026 09:52:46 +0000 Subject: [PATCH 23/31] test: remove obsolete workflow load guard --- src/platform/workflow/management/stores/workflowStore.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/platform/workflow/management/stores/workflowStore.test.ts b/src/platform/workflow/management/stores/workflowStore.test.ts index c725bc9f782..e3c89d322b9 100644 --- a/src/platform/workflow/management/stores/workflowStore.test.ts +++ b/src/platform/workflow/management/stores/workflowStore.test.ts @@ -441,7 +441,6 @@ describe('useWorkflowStore', () => { const loadedWorkflow = await store.openWorkflow(workflow) expect(loadedWorkflow).toBe(workflow) - if (!loadedWorkflow) throw new Error('workflow did not load') expect(loadedWorkflow.path).toBe('workflows/a.json') expect(store.activeWorkflow?.path).toBe('workflows/a.json') expect(store.isOpen(loadedWorkflow)).toBe(true) From bc2dc7553f2b58803edb5272191eab39042ea8c9 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 14 Oct 2026 10:04:06 +0000 Subject: [PATCH 24/31] test: cover graph load FIFO in browser --- .../agentOverlappingWorkflowLoad.spec.ts | 176 +++++++++++------- 1 file changed, 104 insertions(+), 72 deletions(-) diff --git a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts index d26d17f9c31..6d5efb78967 100644 --- a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts +++ b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts @@ -36,44 +36,59 @@ test.describe( 'Overlapping workflow loads', { tag: ['@cloud', '@vue-nodes'] }, () => { - test('the newer workflow survives an older load resuming', async ({ - comfyPage - }) => { + test('workflow loads finish in FIFO order', async ({ comfyPage }) => { test.setTimeout(60_000) const { page, vueNodes } = comfyPage - await test.step('hold the first load open, then start a second', async () => { - await page.evaluate( - async ([extensionName, older, newer]) => { - let release!: () => void - const held = new Promise((resolve) => { - release = resolve - }) - let holdNext = true - window.app!.registerExtension({ - name: extensionName, - beforeLoadGraph: async () => { - if (!holdNext) return - holdNext = false - await held - } - }) + const order = + await test.step('hold the first load open, then queue a second', async () => + await page.evaluate( + async ([extensionName, 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 + window.app!.registerExtension({ + name: extensionName, + beforeLoadGraph: async () => { + if (!holdNext) return + holdNext = false + entered() + await held + } + }) - const olderLoad = window.app!.loadGraphData(older) - const newerLoad = window.app!.loadGraphData(newer) - await newerLoad - release() - await olderLoad - }, - [ - STALL_EXTENSION, - noteWorkflow('older workflow'), - noteWorkflow('newer workflow') - ] as const - ) + 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 newerFinishedWhileOlderWasHeld = order.includes('newer') + release() + await olderLoad.then(() => order.push('older')) + await newerLoad + return { order, newerFinishedWhileOlderWasHeld } + }, + [ + STALL_EXTENSION, + noteWorkflow('older workflow'), + noteWorkflow('newer workflow') + ] as const + )) + + expect(order).toEqual({ + order: ['older', 'newer'], + newerFinishedWhileOlderWasHeld: false }) - await test.step('the canvas still shows the newer workflow', async () => { + await test.step('the canvas shows the last queued workflow', async () => { await expect(vueNodes.nodes).toHaveCount(1) await expect( vueNodes.getNodeByTitle('newer workflow').first() @@ -82,59 +97,76 @@ test.describe( }) }) - test('the newer workflow survives a superseded API JSON import', async ({ + test('a workflow waits for an earlier API JSON import', async ({ comfyPage }) => { test.setTimeout(60_000) const { page, vueNodes } = comfyPage - await test.step('hold an API JSON import open, then load a workflow', async () => { - await page.evaluate( - async ([extensionName, apiPrompt, newer]) => { - let release!: () => void - const held = new Promise((resolve) => { - release = resolve - }) - let holdNext = true - window.app!.registerExtension({ - name: extensionName, - beforeLoadGraph: async () => { - if (!holdNext) return - holdNext = false - await held - } - }) + const order = + await test.step('hold an API JSON import open, then queue a workflow', async () => + await page.evaluate( + async ([extensionName, apiPrompt, newer]) => { + let release!: () => void + const held = new Promise((resolve) => { + release = resolve + }) + let entered!: () => void + const firstEntered = new Promise((resolve) => { + entered = resolve + }) + let holdNext = true + window.app!.registerExtension({ + name: extensionName, + beforeLoadGraph: async () => { + if (!holdNext) return + holdNext = false + entered() + await held + } + }) - const apiImport = window.app!.loadApiJson( - apiPrompt, - 'superseded-api-prompt.json' - ) - await window.app!.loadGraphData(newer) - release() - await apiImport - }, - [ - `${STALL_EXTENSION}.apiJson`, - { - '1': { - class_type: 'EmptyLatentImage', - inputs: {}, - _meta: { title: 'superseded api import' } - } + const order: string[] = [] + const apiImport = window + .app!.loadApiJson(apiPrompt, 'queued-api-prompt.json') + .then(() => order.push('api')) + await firstEntered + const workflowLoad = window + .app!.loadGraphData(newer) + .then(() => order.push('workflow')) + await Promise.resolve() + const workflowFinishedWhileApiWasHeld = order.includes('workflow') + release() + await apiImport + await workflowLoad + return { order, workflowFinishedWhileApiWasHeld } }, - noteWorkflow('newer workflow') - ] as const - ) + [ + `${STALL_EXTENSION}.apiJson`, + { + '1': { + class_type: 'EmptyLatentImage', + inputs: {}, + _meta: { title: 'queued api import' } + } + }, + noteWorkflow('newer workflow') + ] as const + )) + + expect(order).toEqual({ + order: ['api', 'workflow'], + workflowFinishedWhileApiWasHeld: false }) - await test.step('the canvas still shows the newer workflow', async () => { + 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('superseded api import') - ).toHaveCount(0) + await expect(vueNodes.getNodeByTitle('queued api import')).toHaveCount( + 0 + ) }) }) } From 99dc256803dd44dc8722c93c9eb77fec9e46e314 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 15 Oct 2026 09:23:06 +0000 Subject: [PATCH 25/31] fix(workflow): preserve clipspace override and strengthen FIFO proof --- .../agent/agentOverlappingWorkflowLoad.spec.ts | 8 +++++--- src/scripts/app.test.ts | 16 ++++++++++++++++ src/scripts/app.ts | 2 +- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts index 6d5efb78967..405a9d44767 100644 --- a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts +++ b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts @@ -53,9 +53,11 @@ test.describe( entered = resolve }) let holdNext = true + let beforeLoadGraphCalls = 0 window.app!.registerExtension({ name: extensionName, beforeLoadGraph: async () => { + beforeLoadGraphCalls++ if (!holdNext) return holdNext = false entered() @@ -70,11 +72,11 @@ test.describe( .app!.loadGraphData(newer) .then(() => order.push('newer')) await Promise.resolve() - const newerFinishedWhileOlderWasHeld = order.includes('newer') + const loadsStartedWhileOlderWasHeld = beforeLoadGraphCalls release() await olderLoad.then(() => order.push('older')) await newerLoad - return { order, newerFinishedWhileOlderWasHeld } + return { order, loadsStartedWhileOlderWasHeld } }, [ STALL_EXTENSION, @@ -85,7 +87,7 @@ test.describe( expect(order).toEqual({ order: ['older', 'newer'], - newerFinishedWhileOlderWasHeld: false + loadsStartedWhileOlderWasHeld: 1 }) await test.step('the canvas shows the last queued workflow', async () => { diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 4e1a40811f5..9b6c51f40ff 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -275,6 +275,22 @@ describe('ComfyApp', () => { let app: ComfyApp let mockCanvas: LGraphCanvas + it('applies extension paste overrides when the clipspace editor saves', () => { + const node = new LGraphNode('original') + const previousReturnNode = ComfyApp.clipspace_return_node + onTestFinished(() => { + ComfyApp.clipspace_return_node = previousReturnNode + }) + ComfyApp.clipspace_return_node = node + vi.spyOn(ComfyApp, 'pasteFromClipspace').mockImplementation((target) => { + target.title = 'extension-edited' + }) + + ComfyApp.onClipspaceEditorSave() + + expect(node.title).toBe('extension-edited') + }) + beforeEach(() => { vi.mocked(createNode).mockResolvedValue(null) vi.mocked(executeWidgetsCallback).mockImplementation(() => {}) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 6a5db8e462e..6de60c18783 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -623,7 +623,7 @@ export class ComfyApp implements IComfyApp { static onClipspaceEditorSave() { if (clipspace.returnNode) { - pasteFromClipspace(clipspace.returnNode) + ComfyApp.pasteFromClipspace(clipspace.returnNode) } } From 0ee4f107b85bc631e2efcc645be8715786285103 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 15 Oct 2026 10:01:19 +0000 Subject: [PATCH 26/31] fix(workflow): reject nested lifecycle loads --- .../core/services/workflowService.test.ts | 19 -- .../workflow/core/services/workflowService.ts | 4 - .../composables/useTemplateWorkflows.test.ts | 11 -- .../composables/useTemplateWorkflows.ts | 3 +- src/scripts/app.test.ts | 42 ++--- src/scripts/app.ts | 176 +++++------------- src/types/comfy.ts | 2 +- 7 files changed, 71 insertions(+), 186 deletions(-) diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 03dce8db53d..0cc2bf4eff1 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -531,25 +531,6 @@ describe('useWorkflowService', () => { expect(loading.isLoaded).toBe(false) }) - it('does not restore the retained workflow after a superseded graph load', async () => { - const workflows = useWorkflowStore() - const current = createModeTestWorkflow({ - path: 'workflows/current.json' - }) - const loading = createModeTestWorkflow({ - path: 'workflows/loading.json' - }) - workflows.activeWorkflow = current - vi.mocked(app.loadGraphData).mockResolvedValue('superseded') - - await expect(useWorkflowService().openWorkflow(loading)).resolves.toBe( - false - ) - - expect(app.loadGraphData).toHaveBeenCalledOnce() - expect(workflows.activeWorkflow.path).toBe(current.path) - }) - it('leaves a saved workflow clean after a superseded load applied its draft', async () => { const workflows = useWorkflowStore() const current = createModeTestWorkflow({ diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index 3605c83e859..13346c23f31 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -482,10 +482,6 @@ export const useWorkflowService = () => { await restoreRetainedWorkflow(workflow) return false } - if (loaded === 'superseded') { - useSubgraphNavigationStore().endWorkflowNavigation(navigationIntentId) - return false - } showPendingWarnings(undefined, { silent: !loadFromRemote && !options.force }) diff --git a/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts b/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts index 9229b0d6329..c83ea17a9ac 100644 --- a/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts +++ b/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts @@ -1407,17 +1407,6 @@ describe('useTemplateWorkflows', () => { expect(useFeatureUsageTracker(SURVEY_ID).useCount.value).toBe(0) }) - it('does not count or report a template whose graph load was superseded', async () => { - vi.mocked(app.loadGraphData).mockResolvedValueOnce('superseded') - const { loader } = mountTemplateWorkflows() - - expect(await loader.loadWorkflowTemplate('template1', 'default')).toBe( - 'not-started' - ) - - expect(useFeatureUsageTracker(SURVEY_ID).useCount.value).toBe(0) - }) - it('does not count a custom-node template', async () => { const { loader } = mountTemplateWorkflows() diff --git a/src/platform/workflow/templates/composables/useTemplateWorkflows.ts b/src/platform/workflow/templates/composables/useTemplateWorkflows.ts index 28eed99f9ae..f402206f618 100644 --- a/src/platform/workflow/templates/composables/useTemplateWorkflows.ts +++ b/src/platform/workflow/templates/composables/useTemplateWorkflows.ts @@ -297,8 +297,7 @@ export function useTemplateWorkflows() { { openSource: 'template' } ) if (loadedWorkflow === false) return 'graph-failed' - if (loadedWorkflow === undefined || loadedWorkflow === 'superseded') - return 'not-started' + if (loadedWorkflow === undefined) return 'not-started' updateTemplateEducation(template?.isPartnerNode, loadedWorkflow) await syncCompletedTemplateInputsWithCurrentGraph() diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 9b6c51f40ff..fcaf0be8ac7 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -3109,45 +3109,41 @@ describe('ComfyApp', () => { expect(mockImportA1111).toHaveBeenCalledOnce() }) - it('finishes terminal hooks before a re-entrant load starts', async () => { - const events: string[] = [] - let reentrantLoad: ReturnType | undefined - let terminalCalls = 0 + it('rejects a nested load awaited by a lifecycle hook', async () => { + let beforeLoadGraphCalls = 0 mockExtensionService.invokeExtensionsAsync.mockImplementation( async (hook) => { + if (hook === 'beforeLoadGraph') beforeLoadGraphCalls++ if (hook !== 'afterLoadGraph') return - terminalCalls++ - if (terminalCalls === 1) { - events.push('first-terminal-start') - reentrantLoad = app.loadGraphData(createWorkflowGraphData(), true) - await Promise.resolve() - events.push('first-terminal-end') - } else { - events.push('second-terminal') - } + await expect( + app.loadGraphData(createWorkflowGraphData(), true) + ).rejects.toThrow( + 'A graph-load lifecycle hook cannot start a nested graph load' + ) + expect(beforeLoadGraphCalls).toBe(1) } ) - await app.loadGraphData(createWorkflowGraphData(), true) - await reentrantLoad - - expect(events).toEqual([ - 'first-terminal-start', - 'first-terminal-end', - 'second-terminal' - ]) + await expect( + app.loadGraphData(createWorkflowGraphData(), true) + ).resolves.toBeTruthy() + expect(beforeLoadGraphCalls).toBe(1) }) it('cleans before extensions prepare the incoming workflow', async () => { const clean = vi.spyOn(app, 'clean') + let cleanCallsDuringPreparation: number | undefined mockExtensionService.invokeExtensionsAsync.mockImplementation( async (hook) => { if (hook !== 'beforeConfigureGraph') return - expect(clean).toHaveBeenCalledOnce() + cleanCallsDuringPreparation = clean.mock.calls.length } ) - await app.loadGraphData(createWorkflowGraphData(), true) + await expect( + app.loadGraphData(createWorkflowGraphData(), true) + ).resolves.toBeTruthy() + expect(cleanCallsDuringPreparation).toBe(1) }) }) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 6de60c18783..17d781115bc 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -306,13 +306,6 @@ function createNodeOutputsMutationView( }) } -class SupersededGraphLoad extends Error { - constructor() { - super('Graph load superseded by a newer load') - this.name = 'SupersededGraphLoad' - } -} - export class ComfyApp implements IComfyApp { /** * List of entries to queue @@ -441,7 +434,7 @@ export class ComfyApp implements IComfyApp { private configuringGraphLevel: number = 0 private graphLoadSequence = 0 private graphLoadQueue: Promise = Promise.resolve() - private committedGraphLoadSequence = 0 + private invokingGraphLoadHookSynchronously = false private pendingCamera: | { id: number; workflow: string | null | ComfyWorkflow } | undefined @@ -1190,25 +1183,35 @@ export class ComfyApp implements IComfyApp { reportType: 'loadWorkflowError' }) console.error(error) - await useExtensionService().invokeExtensionsAsync('onGraphLoadError', error) - } - - private ownsGraphLoad(loadId: number): boolean { - return loadId >= this.committedGraphLoadSequence - } - - private commitGraphLoad(loadId: number): void { - this.committedGraphLoadSequence = Math.max( - loadId, - this.committedGraphLoadSequence - ) + await this.invokeGraphLoadHook('onGraphLoadError', error) } - private rejectSupersededGraphLoad(): 'superseded' { - return 'superseded' + private invokeGraphLoadHook( + ...args: Parameters< + ReturnType['invokeExtensionsAsync'] + > + ): ReturnType< + ReturnType['invokeExtensionsAsync'] + > { + this.invokingGraphLoadHookSynchronously = true + try { + return useExtensionService().invokeExtensionsAsync(...args) + } finally { + // Extension callbacks start synchronously. Rejecting a nested load in + // that call stack prevents a hook that awaits it from deadlocking the + // queue, while later user actions still queue normally. + this.invokingGraphLoadHookSynchronously = false + } } private enqueueGraphLoad(operation: () => Promise): Promise { + if (this.invokingGraphLoadHookSynchronously) { + return Promise.reject( + new Error( + 'A graph-load lifecycle hook cannot start a nested graph load' + ) + ) + } const result = this.graphLoadQueue.then(operation) this.graphLoadQueue = result.then( () => undefined, @@ -1223,7 +1226,7 @@ export class ComfyApp implements IComfyApp { restore_view: boolean = true, workflow: string | null | ComfyWorkflow = null, options: LoadGraphDataOptions = {} - ): Promise { + ): Promise { return this.enqueueGraphLoad(() => this.loadGraphDataNow(graphData, clean, restore_view, workflow, options) ) @@ -1235,7 +1238,7 @@ export class ComfyApp implements IComfyApp { restore_view: boolean = true, workflow: string | null | ComfyWorkflow = null, options: LoadGraphDataOptions = {} - ): Promise { + ): Promise { const canvasScheduler = useCanvasScheduler() const loadId = ++this.graphLoadSequence @@ -1249,9 +1252,7 @@ export class ComfyApp implements IComfyApp { workflowNavigationId } = options useWorkflowService().beforeLoadNewGraph(clean) - await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') - - if (!this.ownsGraphLoad(loadId)) return this.rejectSupersededGraphLoad() + await this.invokeGraphLoadHook('beforeLoadGraph') let reset_invalid_values = false const missingNodeTypes: MissingNodeType[] = [] @@ -1300,9 +1301,6 @@ export class ComfyApp implements IComfyApp { // Ideally we should not block users from loading the workflow. graphData = validatedGraphData ?? graphData } - if (!this.ownsGraphLoad(loadId)) { - return this.rejectSupersededGraphLoad() - } const subgraphTypes = useSubgraphService().normalizeSubgraphs(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 @@ -1336,7 +1334,7 @@ export class ComfyApp implements IComfyApp { ) } - await useExtensionService().invokeExtensionsAsync( + await this.invokeGraphLoadHook( 'beforeConfigureGraph', graphData, missingNodeTypes @@ -1425,7 +1423,6 @@ export class ComfyApp implements IComfyApp { // 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. - if (!this.ownsGraphLoad(loadId)) return this.rejectSupersededGraphLoad() await this.reportGraphLoadFailure(error) void useSubgraphNavigationStore().updateHash( 'workflow-load', @@ -1468,16 +1465,12 @@ export class ComfyApp implements IComfyApp { } } - if (!this.ownsGraphLoad(loadId)) return this.rejectSupersededGraphLoad() - const endGraphLoadSuppression = ChangeTracker.beginGraphLoad() let activatedWorkflow: LoadedComfyWorkflow | undefined let reconcileResourceErrors: (() => void) | undefined let resourceScanLoadCompleted = false try { try { - this.commitGraphLoad(loadId) - useSubgraphService().loadSubgraphs(graphData) this.rootGraph.configure(graphData as ISerialisedGraph) @@ -1529,9 +1522,6 @@ export class ComfyApp implements IComfyApp { } } } catch (error) { - if (!this.ownsGraphLoad(loadId)) { - return this.rejectSupersededGraphLoad() - } await this.reportGraphLoadFailure(error) // Resolves rather than throws: the close/replacement guards read this outcome. return false @@ -1596,14 +1586,7 @@ export class ComfyApp implements IComfyApp { }) ) - await useExtensionService().invokeExtensionsAsync( - 'afterConfigureGraph', - missingNodeTypes - ) - - if (!this.ownsGraphLoad(loadId)) { - return await this.rejectSupersededGraphLoad() - } + await this.invokeGraphLoadHook('afterConfigureGraph', missingNodeTypes) const effectiveShareId = shareId ?? @@ -1622,15 +1605,10 @@ export class ComfyApp implements IComfyApp { const activated = await useWorkflowService().afterLoadNewGraph( workflow, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, - effectiveShareId, - { isCurrent: () => this.ownsGraphLoad(loadId) } + effectiveShareId ) - if (!activated) return await this.rejectSupersededGraphLoad() - await useExtensionService().invokeExtensionsAsync('afterLoadGraph') - - if (!this.ownsGraphLoad(loadId)) { - return await this.rejectSupersededGraphLoad() - } + if (!activated) return false + await this.invokeGraphLoadHook('afterLoadGraph') // Capture the workflow this load activated before the asset-scan awaits // below can hand control back and let the user switch to another one. @@ -1682,10 +1660,6 @@ export class ComfyApp implements IComfyApp { }) } - if (!this.ownsGraphLoad(loadId)) { - return await this.rejectSupersededGraphLoad() - } - if (!deferWarnings) { useWorkflowService().showPendingWarnings(undefined, { silent: silentAssetErrors @@ -2237,31 +2211,20 @@ export class ComfyApp implements IComfyApp { // Use parameters strictly as the final fallback if (parameters && typeof parameters === 'string') { return await this.enqueueGraphLoad(async () => { - const loadId = ++this.graphLoadSequence - let outcome: A1111ImportOutcome - try { - outcome = await importA1111(this.rootGraph, parameters, async () => { - if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() + const outcome: A1111ImportOutcome = await importA1111( + this.rootGraph, + parameters, + async () => { try { // false: final destination; no later load republishes the hash. useWorkflowService().beforeLoadNewGraph(false) - await useExtensionService().invokeExtensionsAsync( - 'beforeLoadGraph' - ) + await this.invokeGraphLoadHook('beforeLoadGraph') } finally { - if (this.ownsGraphLoad(loadId)) { - useMissingNodesErrorStore().setMissingNodeTypes([]) - } + useMissingNodesErrorStore().setMissingNodeTypes([]) } - if (!this.ownsGraphLoad(loadId)) throw new SupersededGraphLoad() this.canvas.setGraph(this.rootGraph) - this.commitGraphLoad(loadId) - }) - } catch (error) { - if (!(error instanceof SupersededGraphLoad)) throw error - await this.rejectSupersededGraphLoad() - return - } + } + ) switch (outcome) { case 'core-nodes-unavailable': useToast().warning(t('toastMessages.a1111CoreNodesUnavailable')) @@ -2285,25 +2248,13 @@ export class ComfyApp implements IComfyApp { } // Intentionally no beforeConfigureGraph: A1111 has no mutable // workflow JSON before graph construction, so there is no payload. - await useExtensionService().invokeExtensionsAsync( - 'afterConfigureGraph', - [] - ) - if (!this.ownsGraphLoad(loadId)) { - await this.rejectSupersededGraphLoad() - return - } + await this.invokeGraphLoadHook('afterConfigureGraph', []) const activated = await useWorkflowService().afterLoadNewGraph( fileName, - this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, - undefined, - { isCurrent: () => this.ownsGraphLoad(loadId) } + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON ) - if (!activated) { - await this.rejectSupersededGraphLoad() - return - } - await useExtensionService().invokeExtensionsAsync('afterLoadGraph') + if (!activated) return + await this.invokeGraphLoadHook('afterLoadGraph') return }) } @@ -2448,19 +2399,12 @@ export class ComfyApp implements IComfyApp { fileName: string, options: { deferWarnings?: boolean } = {} ): Promise { - const loadId = ++this.graphLoadSequence // false: no workflow load follows to republish the hash. useWorkflowService().beforeLoadNewGraph(false) - await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + await this.invokeGraphLoadHook('beforeLoadGraph') this.canvas.setGraph(this.rootGraph) withGraphIntentSource('load', () => this.clean()) - this.commitGraphLoad(loadId) - - if (!this.ownsGraphLoad(loadId)) { - await this.rejectSupersededGraphLoad() - return - } const ids = Object.keys(apiData) // Export (API) flattens subgraph nodes to ids like "194:45". At the root // graph a colon reads as an execution-id path: Locate walks into node @@ -2485,10 +2429,6 @@ export class ComfyApp implements IComfyApp { const nodeReplacementStore = useNodeReplacementStore() await nodeReplacementStore.load() - if (!this.ownsGraphLoad(loadId)) { - await this.rejectSupersededGraphLoad() - return - } withGraphIntentSource('load', () => { for (const id of ids) { const data = apiData[id] @@ -2662,30 +2602,14 @@ export class ComfyApp implements IComfyApp { // Intentionally no beforeConfigureGraph: API JSON builds nodes directly // and never passes a ComfyWorkflowJSON through the configure stage. - await useExtensionService().invokeExtensionsAsync( - 'afterConfigureGraph', - missingNodeTypes - ) + await this.invokeGraphLoadHook('afterConfigureGraph', missingNodeTypes) - if (!this.ownsGraphLoad(loadId)) { - await this.rejectSupersededGraphLoad() - return - } const activated = await useWorkflowService().afterLoadNewGraph( fileName, - this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, - undefined, - { isCurrent: () => this.ownsGraphLoad(loadId) } + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON ) - if (!activated) { - await this.rejectSupersededGraphLoad() - return - } - await useExtensionService().invokeExtensionsAsync('afterLoadGraph') - if (!this.ownsGraphLoad(loadId)) { - await this.rejectSupersededGraphLoad() - return - } + if (!activated) return + await this.invokeGraphLoadHook('afterLoadGraph') if (missingNodeTypes.length) { this.showMissingNodesError(missingNodeTypes, options) } diff --git a/src/types/comfy.ts b/src/types/comfy.ts index a874aa94014..ecec8cc77fb 100644 --- a/src/types/comfy.ts +++ b/src/types/comfy.ts @@ -165,7 +165,7 @@ export interface ComfyApp { restore_view?: boolean, workflow?: string | null | ComfyWorkflow, options?: LoadGraphDataOptions - ): Promise + ): Promise refreshMissingModels(options?: { silent?: boolean reloadDefs?: boolean From 88f72b214dd2edaa413a2034b4749048991e82aa Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 15 Oct 2026 10:36:33 +0000 Subject: [PATCH 27/31] fix(workflow): preserve lifecycle context across awaits --- src/scripts/app.test.ts | 21 -------------- src/scripts/app.ts | 18 +----------- src/services/extensionService.test.ts | 20 ++++++++++++++ src/services/extensionService.ts | 40 +++++++++++++++++++++++++-- 4 files changed, 59 insertions(+), 40 deletions(-) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index fcaf0be8ac7..c59e757587b 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -3109,27 +3109,6 @@ describe('ComfyApp', () => { expect(mockImportA1111).toHaveBeenCalledOnce() }) - it('rejects a nested load awaited by a lifecycle hook', async () => { - let beforeLoadGraphCalls = 0 - mockExtensionService.invokeExtensionsAsync.mockImplementation( - async (hook) => { - if (hook === 'beforeLoadGraph') beforeLoadGraphCalls++ - if (hook !== 'afterLoadGraph') return - await expect( - app.loadGraphData(createWorkflowGraphData(), true) - ).rejects.toThrow( - 'A graph-load lifecycle hook cannot start a nested graph load' - ) - expect(beforeLoadGraphCalls).toBe(1) - } - ) - - await expect( - app.loadGraphData(createWorkflowGraphData(), true) - ).resolves.toBeTruthy() - expect(beforeLoadGraphCalls).toBe(1) - }) - it('cleans before extensions prepare the incoming workflow', async () => { const clean = vi.spyOn(app, 'clean') let cleanCallsDuringPreparation: number | undefined diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 17d781115bc..bf208d622ac 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -434,7 +434,6 @@ export class ComfyApp implements IComfyApp { private configuringGraphLevel: number = 0 private graphLoadSequence = 0 private graphLoadQueue: Promise = Promise.resolve() - private invokingGraphLoadHookSynchronously = false private pendingCamera: | { id: number; workflow: string | null | ComfyWorkflow } | undefined @@ -1193,25 +1192,10 @@ export class ComfyApp implements IComfyApp { ): ReturnType< ReturnType['invokeExtensionsAsync'] > { - this.invokingGraphLoadHookSynchronously = true - try { - return useExtensionService().invokeExtensionsAsync(...args) - } finally { - // Extension callbacks start synchronously. Rejecting a nested load in - // that call stack prevents a hook that awaits it from deadlocking the - // queue, while later user actions still queue normally. - this.invokingGraphLoadHookSynchronously = false - } + return useExtensionService().invokeExtensionsAsync(...args) } private enqueueGraphLoad(operation: () => Promise): Promise { - if (this.invokingGraphLoadHookSynchronously) { - return Promise.reject( - new Error( - 'A graph-load lifecycle hook cannot start a nested graph load' - ) - ) - } const result = this.graphLoadQueue.then(operation) this.graphLoadQueue = result.then( () => undefined, diff --git a/src/services/extensionService.test.ts b/src/services/extensionService.test.ts index 4d05f8cf56a..8711771c290 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/appRegistry' import { useExtensionStore } from '@/stores/extensionStore' import { useExtensionService } from './extensionService' @@ -147,6 +148,25 @@ describe('invokeExtensionsAsync', () => { expect(hook.mock.contexts[0]).toBe(useExtensionStore().extensions[0]) }) + it('rejects a graph load requested after an await in a lifecycle hook', async () => { + let hookApp: ReturnType | undefined + register({ + name: 'nested-loader', + beforeLoadGraph: async (app: ReturnType) => { + hookApp = app + await Promise.resolve() + await expect(app.loadGraphData()).rejects.toThrow( + 'A graph-load lifecycle hook cannot start a nested graph load' + ) + } + }) + + await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + + expect(hookApp).not.toBe(useApp()) + expect(hookApp?.loadGraphData).not.toBe(useApp().loadGraphData) + }) + 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..03b07771f76 100644 --- a/src/services/extensionService.ts +++ b/src/services/extensionService.ts @@ -22,6 +22,41 @@ function isPromiseLike(value: unknown): value is PromiseLike { ) } +const graphLoadLifecycleHooks = new Set([ + 'beforeLoadGraph', + 'beforeConfigureGraph', + 'afterConfigureGraph', + 'afterLoadGraph', + 'onGraphLoadError' +]) + +const graphLoadHookApps = new WeakMap() + +function extensionAppForHook(method: string): ComfyApp { + const app = useApp() + if (!graphLoadLifecycleHooks.has(method)) return app + + let hookApp = graphLoadHookApps.get(app) + if (!hookApp) { + hookApp = new Proxy(app, { + get(target, property, receiver) { + if (property === 'loadGraphData') { + return () => + Promise.reject( + new Error( + 'A graph-load lifecycle hook cannot start a nested graph load' + ) + ) + } + const value: unknown = Reflect.get(target, property, receiver) + return typeof value === 'function' ? value.bind(target) : value + } + }) + graphLoadHookApps.set(app, hookApp) + } + return hookApp +} + export const useExtensionService = () => { const extensionStore = useExtensionStore() const settingStore = useSettingStore() @@ -179,6 +214,7 @@ export const useExtensionService = () => { method: T, ...args: Parameters> ) => { + const app = extensionAppForHook(method) const logError = (ext: ComfyExtension, error: unknown) => console.error( `Error calling extension '${ext.name}' method '${method}'`, @@ -203,7 +239,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 +248,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)) From 0e68d580cac02cda35c5fb4020ed9f13e54eefe8 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 15 Oct 2026 11:07:53 +0000 Subject: [PATCH 28/31] fix(workflow): guard all nested load entrypoints --- src/services/extensionService.test.ts | 24 +++++++++++++++++++----- src/services/extensionService.ts | 11 ++++++++++- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/services/extensionService.test.ts b/src/services/extensionService.test.ts index 8711771c290..f21c96069ee 100644 --- a/src/services/extensionService.test.ts +++ b/src/services/extensionService.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { legacyMenuCompat } from '@/lib/litegraph/src/contextMenuCompat' -import { useApp } from '@/scripts/appRegistry' +import type { useApp } from '@/scripts/appRegistry' import { useExtensionStore } from '@/stores/extensionStore' import { useExtensionService } from './extensionService' @@ -149,11 +149,9 @@ describe('invokeExtensionsAsync', () => { }) it('rejects a graph load requested after an await in a lifecycle hook', async () => { - let hookApp: ReturnType | undefined register({ name: 'nested-loader', beforeLoadGraph: async (app: ReturnType) => { - hookApp = app await Promise.resolve() await expect(app.loadGraphData()).rejects.toThrow( 'A graph-load lifecycle hook cannot start a nested graph load' @@ -162,9 +160,25 @@ describe('invokeExtensionsAsync', () => { }) await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + }) + + it('rejects an awaited API import without blocking the next load hook', async () => { + const nestedImportRejected = vi.fn() + register({ + name: 'nested-api-loader', + beforeLoadGraph: async (app: ReturnType) => { + await Promise.resolve() + await expect(app.loadApiJson({}, 'nested.json')).rejects.toThrow( + 'A graph-load lifecycle hook cannot start a nested graph load' + ) + nestedImportRejected() + } + }) + + await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') - expect(hookApp).not.toBe(useApp()) - expect(hookApp?.loadGraphData).not.toBe(useApp().loadGraphData) + expect(nestedImportRejected).toHaveBeenCalledTimes(2) }) it('silently ignores a non-function property of the same name', async () => { diff --git a/src/services/extensionService.ts b/src/services/extensionService.ts index 03b07771f76..f3d7c07689e 100644 --- a/src/services/extensionService.ts +++ b/src/services/extensionService.ts @@ -30,6 +30,12 @@ const graphLoadLifecycleHooks = new Set([ 'onGraphLoadError' ]) +const graphLoadEntrypoints = new Set([ + 'loadGraphData', + 'loadApiJson', + 'handleFile' +]) + const graphLoadHookApps = new WeakMap() function extensionAppForHook(method: string): ComfyApp { @@ -40,7 +46,10 @@ function extensionAppForHook(method: string): ComfyApp { if (!hookApp) { hookApp = new Proxy(app, { get(target, property, receiver) { - if (property === 'loadGraphData') { + if ( + typeof property === 'string' && + graphLoadEntrypoints.has(property) + ) { return () => Promise.reject( new Error( From 86c6d3194405332efce46af6b75017683ab55af7 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Thu, 15 Oct 2026 15:44:36 +0000 Subject: [PATCH 29/31] fix(workflow): keep main's load suppression and replaced-load aborts under the queue Capture suppression starts again right after beforeLoadGraph, so a capture while extensions prepare the incoming workflow cannot write the cleared canvas into the outgoing workflow, and it ends after afterLoadGraph so resource scans no longer block capture. A graph cleared during activation emits onGraphLoadError again. The queue makes the generation counter, the isCurrent option, the boolean afterLoadNewGraph result and the subgraph normalize/load split unnecessary, so those return to main. The #20294 and #11420 tests are restored, adapted to queued loads. --- .../services/__mocks__/workflowService.ts | 2 +- .../core/services/workflowService.test.ts | 111 +--- .../workflow/core/services/workflowService.ts | 43 +- .../composables/useTemplateWorkflows.test.ts | 11 + src/scripts/app.test.ts | 548 +++++++++++++----- src/scripts/app.ts | 148 +++-- src/scripts/changeTracker.test.ts | 19 +- src/scripts/changeTracker.ts | 26 +- src/services/subgraphService.ts | 17 +- 9 files changed, 522 insertions(+), 403 deletions(-) diff --git a/src/platform/workflow/core/services/__mocks__/workflowService.ts b/src/platform/workflow/core/services/__mocks__/workflowService.ts index 6e8bc863d5a..f514e35acb9 100644 --- a/src/platform/workflow/core/services/__mocks__/workflowService.ts +++ b/src/platform/workflow/core/services/__mocks__/workflowService.ts @@ -18,7 +18,7 @@ const workflowService: ReturnType = { loadPreviousOpenedWorkflow: vi.fn(async () => {}), duplicateWorkflow: vi.fn(async () => {}), showPendingWarnings: vi.fn(), - afterLoadNewGraph: vi.fn(async () => true), + afterLoadNewGraph: vi.fn(async () => {}), beforeLoadNewGraph: vi.fn() } diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 0cc2bf4eff1..637e2d3655c 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -494,9 +494,7 @@ describe('useWorkflowService', () => { describe('openWorkflow ordering', () => { it('keeps the current workflow when a remote load is superseded', async () => { const workflows = useWorkflowStore() - const current = createModeTestWorkflow({ - path: 'workflows/current.json' - }) + const current = createModeTestWorkflow({ path: 'workflows/current.json' }) const loading = createModeTestWorkflow({ path: 'workflows/closed.json', loaded: false @@ -533,9 +531,7 @@ describe('useWorkflowService', () => { it('leaves a saved workflow clean after a superseded load applied its draft', async () => { const workflows = useWorkflowStore() - const current = createModeTestWorkflow({ - path: 'workflows/current.json' - }) + const current = createModeTestWorkflow({ path: 'workflows/current.json' }) const saved = createModeTestWorkflow({ path: 'workflows/saved.json', loaded: false @@ -570,9 +566,7 @@ describe('useWorkflowService', () => { it('keeps a temporary workflow openable after a superseded load', async () => { const workflows = useWorkflowStore() - const current = createModeTestWorkflow({ - path: 'workflows/current.json' - }) + const current = createModeTestWorkflow({ path: 'workflows/current.json' }) const draft = new ComfyWorkflowClass({ path: 'workflows/draft.json', modified: Date.now(), @@ -606,9 +600,7 @@ describe('useWorkflowService', () => { it('settles an already superseded opening without waiting for queued loads', async () => { const workflows = useWorkflowStore() - const blocker = createModeTestWorkflow({ - path: 'workflows/blocker.json' - }) + const blocker = createModeTestWorkflow({ path: 'workflows/blocker.json' }) const stale = createModeTestWorkflow({ path: 'workflows/stale.json', loaded: false @@ -638,9 +630,7 @@ describe('useWorkflowService', () => { it('skips an opening superseded while it waits behind another load', async () => { const workflows = useWorkflowStore() - const blocker = createModeTestWorkflow({ - path: 'workflows/blocker.json' - }) + const blocker = createModeTestWorkflow({ path: 'workflows/blocker.json' }) const stale = createModeTestWorkflow({ path: 'workflows/stale.json', loaded: false @@ -2475,97 +2465,6 @@ describe('useWorkflowService', () => { ) }) }) - - describe('when a newer load supersedes this one mid-flight', () => { - const newerCamera = { scale: 1.75, offset: [10, 20] as [number, number] } - const rootGraphId = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' - let releaseOpen: () => void - let setGraph: ReturnType - let originalCanvas: typeof app.canvas - - beforeEach(() => { - originalCanvas = app.canvas - Reflect.set(app, 'isGraphReady', true) - app.rootGraph.id = rootGraphId - - setGraph = vi.fn() - Reflect.set(app, 'canvas', { - ds: { scale: newerCamera.scale, offset: newerCamera.offset }, - setGraph, - bg_tint: undefined - }) - - const tracker = new ChangeTracker(existingWorkflow, makeWorkflowData()) - app.canvas.ds.scale = 0.3 - app.canvas.ds.offset = [-999, -999] - tracker.store() - app.canvas.ds.scale = newerCamera.scale - app.canvas.ds.offset = newerCamera.offset - existingWorkflow.changeTracker = tracker - - const blocked = new Promise((resolve) => { - releaseOpen = resolve - }) - vi.mocked(workflowStore.openWorkflow).mockImplementation(async () => { - await blocked - return existingWorkflow - }) - }) - - afterEach(() => { - Reflect.deleteProperty(app, 'isGraphReady') - Reflect.deleteProperty(app.rootGraph, 'id') - Reflect.set(app, 'canvas', originalCanvas) - }) - - it('does not write the newer graph camera when the predicate says it is stale', async () => { - let isCurrent = true - - const supersededLoad = useWorkflowService().afterLoadNewGraph( - 'repeat', - makeWorkflowData(), - undefined, - { isCurrent: () => isCurrent } - ) - await Promise.resolve() - - expect(app.canvas.ds.scale).toBe(newerCamera.scale) - - isCurrent = false - releaseOpen() - await supersededLoad - - expect(app.canvas.ds.scale).toBe(newerCamera.scale) - expect(app.canvas.ds.offset).toEqual(newerCamera.offset) - expect(setGraph).not.toHaveBeenCalled() - expect(useExecutionErrorStore().setActiveGraph).not.toHaveBeenCalled() - expect( - useNodeOutputStore().restorePreviewsForWorkflow - ).not.toHaveBeenCalled() - }) - - it('still activates normally when the load is not superseded', async () => { - const liveLoad = useWorkflowService().afterLoadNewGraph( - 'repeat', - makeWorkflowData(), - undefined, - { isCurrent: () => true } - ) - await Promise.resolve() - releaseOpen() - await liveLoad - - expect(app.canvas.ds.scale).toBe(0.3) - expect(setGraph).toHaveBeenCalled() - expect(useExecutionErrorStore().setActiveGraph).toHaveBeenCalledWith( - rootGraphId, - existingWorkflow.path - ) - expect( - useNodeOutputStore().restorePreviewsForWorkflow - ).toHaveBeenCalled() - }) - }) }) describe('per-workflow mode switching', () => { diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index 13346c23f31..f3b03d27fb6 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -703,29 +703,21 @@ export const useWorkflowService = () => { const afterLoadNewGraph = async ( value: string | ComfyWorkflow | null, workflowData: ComfyWorkflowJSON, - shareId?: string, - options: { isCurrent?: () => boolean } = {} - ): Promise => { + shareId?: string + ) => { const graphState = useApp().rootGraphOrUndefined?.state - if (!(await activateLoadedWorkflow(value, workflowData, shareId, options))) - return false - if ( - graphState !== useApp().rootGraphOrUndefined?.state || - options.isCurrent?.() === false - ) - return false + await activateLoadedWorkflow(value, workflowData, shareId) + if (graphState !== useApp().rootGraphOrUndefined?.state) return useNodeOutputStore().restorePreviewsForWorkflow( useWorkspaceStore().workflow.activeWorkflow?.path ) - return true } const activateLoadedWorkflow = async ( value: string | ComfyWorkflow | null, workflowData: ComfyWorkflowJSON, - shareId?: string, - options: { isCurrent?: () => boolean } = {} - ): Promise => { + shareId?: string + ) => { const graphState = useApp().rootGraphOrUndefined?.state const workflowStore = useWorkspaceStore().workflow const { isAppMode } = useAppMode() @@ -777,11 +769,7 @@ export const useWorkflowService = () => { ) { const loadedWorkflow = await workflowStore.openWorkflow(existingWorkflow) - if ( - graphState !== useApp().rootGraphOrUndefined?.state || - options.isCurrent?.() === false - ) - return false + if (graphState !== useApp().rootGraphOrUndefined?.state) return activateRunErrors(loadedWorkflow) if (loadedWorkflow.initialMode === undefined) { // Prefer the file's linearMode over the draft's since the file @@ -803,7 +791,7 @@ export const useWorkflowService = () => { ) ) loadedWorkflow.changeTracker.restore() - return true + return } } @@ -817,21 +805,13 @@ export const useWorkflowService = () => { } trackIfEnteringApp(tempWorkflow) const loadedWorkflow = await workflowStore.openWorkflow(tempWorkflow) - if ( - graphState !== useApp().rootGraphOrUndefined?.state || - options.isCurrent?.() === false - ) - return false + if (graphState !== useApp().rootGraphOrUndefined?.state) return activateRunErrors(loadedWorkflow) - return true + return } const loadedWorkflow = await workflowStore.openWorkflow(value) - if ( - graphState !== useApp().rootGraphOrUndefined?.state || - options.isCurrent?.() === false - ) - return false + if (graphState !== useApp().rootGraphOrUndefined?.state) return activateRunErrors(loadedWorkflow) if (shareId) { loadedWorkflow.shareId = shareId @@ -845,7 +825,6 @@ export const useWorkflowService = () => { ensureWorkflowId(workflowData, activeStateFallbackId(loadedWorkflow)) ) loadedWorkflow.changeTracker.restore() - return true } /** diff --git a/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts b/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts index c83ea17a9ac..ae0fbffc7ac 100644 --- a/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts +++ b/src/platform/workflow/templates/composables/useTemplateWorkflows.test.ts @@ -1407,6 +1407,17 @@ describe('useTemplateWorkflows', () => { expect(useFeatureUsageTracker(SURVEY_ID).useCount.value).toBe(0) }) + it('does not count a template whose graph load was superseded', async () => { + vi.mocked(app.loadGraphData).mockResolvedValueOnce(undefined) + const { loader } = mountTemplateWorkflows() + + expect(await loader.loadWorkflowTemplate('template1', 'default')).toBe( + 'not-started' + ) + + expect(useFeatureUsageTracker(SURVEY_ID).useCount.value).toBe(0) + }) + it('does not count a custom-node template', async () => { const { loader } = mountTemplateWorkflows() diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index c59e757587b..142c62f9bae 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -22,7 +22,7 @@ import { onTestFinished, vi } from 'vitest' -import { ref } from 'vue' +import { markRaw, ref } from 'vue' import { useLitegraphService } from '@/services/litegraphService' import { useNodeDefStore } from '@/stores/nodeDefStore' import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration' @@ -55,6 +55,7 @@ import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/ import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import type { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation' import { createMockChangeTracker } from '@/utils/__tests__/litegraphTestUtils' +import { ChangeTracker } from '@/scripts/changeTracker' import { createTestCanvasElement, createTestDragAndScale, @@ -332,7 +333,7 @@ describe('ComfyApp', () => { mockExtensionService.invokeExtensionsAsync.mockResolvedValue(undefined) vi.mocked(extractFilesFromDragEvent).mockResolvedValue([]) mockImportA1111.mockResolvedValue('imported') - mockWorkflowService.afterLoadNewGraph.mockResolvedValue(true) + mockWorkflowService.afterLoadNewGraph.mockResolvedValue() useSettingStore().settingValues['Comfy.RightSidePanel.ShowErrorsTab'] = true mockValidateWorkflow.mockReset().mockResolvedValue({ graphData: null }) vi.mocked(useWorkflowStore().getWorkflowByPath).mockReturnValue(null) @@ -372,7 +373,6 @@ describe('ComfyApp', () => { ]) mockWorkflowService.afterLoadNewGraph.mockImplementation(async () => { store.setActiveGraph(graphId) - return true }) return store } @@ -592,19 +592,41 @@ describe('ComfyApp', () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) const showDialog = vi.spyOn(useDialogStore(), 'showDialog') - mockExtensionService.invokeExtensionsAsync.mockImplementation( - async (hook: string) => { - if (hook === 'beforeConfigureGraph') { - throw new Error('bad extension') - } - } + const error = new Error('bad extension') + let releaseErrorHandling!: () => void + const errorHandling = new Promise((resolve) => { + releaseErrorHandling = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith( + 'beforeConfigureGraph', + expect.anything(), + expect.anything() + ) + .thenRejectOnce(error) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('onGraphLoadError', error) + .thenReturnOnce(errorHandling) + const load = app.loadGraphData( + createWorkflowGraphData(), + false, + true, + null, + { workflowNavigationId: 9 } ) - - await expect( - app.loadGraphData(createWorkflowGraphData(), false, true, null, { - workflowNavigationId: 9 - }) - ).resolves.toBe(false) + try { + await vi.waitFor(() => + expect( + mockExtensionService.invokeExtensionsAsync + ).toHaveBeenCalledWith('onGraphLoadError', error) + ) + expect(ChangeTracker.isLoadingGraph).toBe(true) + } finally { + releaseErrorHandling() + await load + } + await expect(load).resolves.toBe(false) + expect(ChangeTracker.isLoadingGraph).toBe(false) expect(showDialog).toHaveBeenCalledOnce() expect(useSubgraphNavigationStore().updateHash).toHaveBeenCalledWith( @@ -752,62 +774,342 @@ describe('ComfyApp', () => { ]) }) - it('does not report a new subgraph instance as a missing node', 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()) + mockWorkflowService.afterLoadNewGraph.mockImplementation(async () => { + app.clean() + }) + + await expect( + app.loadGraphData(createWorkflowGraphData(), false) + ).resolves.toBeUndefined() + + 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' }) + ) + }) + + it('does not assign a newer workflow graph to an Undo load waiting after configuration', 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 saved = createWorkflowGraphData() + saved.extra = { marker: 'saved' } + const changed = structuredClone(saved) + changed.extra = { marker: 'changed' } + const firstTracker = new ChangeTracker(firstWorkflow, saved) + firstTracker.activeState = changed + firstTracker._restoringState = true + firstWorkflow.changeTracker = firstTracker + const secondWorkflow = new ComfyWorkflow({ + path: 'workflows/other.json', + modified: 0, + size: 0 + }) + const other = createWorkflowGraphData() + other.extra = { marker: 'other' } + const secondTracker = new ChangeTracker(secondWorkflow, other) + secondWorkflow.changeTracker = secondTracker + mockWorkflowService.afterLoadNewGraph.mockImplementation( + async ( + workflow: string | ComfyWorkflow | null, + state: ComfyWorkflowJSON + ) => { + assert(workflow instanceof ComfyWorkflow) + workflow.changeTracker?.reset(state) + } + ) + let releasePending!: () => void + const pending = new Promise((resolve) => { + releasePending = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('afterConfigureGraph', expect.anything()) + .thenReturnOnce(pending) + + const undoLoad = app.loadGraphData(saved, false, false, firstWorkflow, { + skipAssetScans: true + }) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterConfigureGraph', + expect.anything() + ) + ) + const newerLoad = app.loadGraphData(other, false, false, secondWorkflow, { + skipAssetScans: true + }) + releasePending() + await expect(undoLoad).resolves.toBeTruthy() + await expect(newerLoad).resolves.toBeTruthy() + + 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)( + 'finishes an older restore paused during %s before the newer workflow loads', + async (pauseAt) => { + app.canvasElRef.value = document.createElement('canvas') + const graph = new LGraph() + const previousGraph = singletonApp.rootGraphOrUndefined + const previousCanvas = singletonApp.canvas + onTestFinished(() => { + Reflect.set(singletonApp, 'rootGraphInternal', previousGraph) + singletonApp.canvas = previousCanvas + }) + Reflect.set(app, 'rootGraphInternal', graph) + Reflect.set(singletonApp, 'rootGraphInternal', graph) + singletonApp.canvas = mockCanvas + Reflect.set(mockCanvas, 'ds', { scale: 1, offset: [0, 0] }) + await useRealWorkflowService() + const workflowStore = useWorkflowStore() + vi.mocked(workflowStore.openWorkflow).mockRestore() + vi.mocked(workflowStore.isActive).mockRestore() + + const saved = createWorkflowGraphData() + saved.extra = { marker: 'saved' } + const changed = structuredClone(saved) + changed.extra = { marker: 'changed' } + const firstWorkflow = markLoaded( + new ComfyWorkflow({ + path: 'workflows/undo.json', + modified: 0, + size: 0 + }) + ) + const firstTracker = markRaw(new ChangeTracker(firstWorkflow, saved)) + firstTracker.activeState = changed + firstTracker._restoringState = true + firstWorkflow.changeTracker = firstTracker + const other = createWorkflowGraphData() + other.extra = { marker: 'other' } + const secondWorkflow = markLoaded( + new ComfyWorkflow({ + path: 'workflows/other.json', + modified: 0, + size: 0 + }) + ) + const secondTracker = markRaw(new ChangeTracker(secondWorkflow, other)) + secondWorkflow.changeTracker = secondTracker + let releasePause!: () => void + const pause = new Promise((resolve) => { + releasePause = resolve + }) + let reachedPause = false + if (pauseAt === 'activation') { + vi.spyOn(firstWorkflow, 'load').mockImplementationOnce(async () => { + reachedPause = true + await pause + return firstWorkflow + }) + } else if (pauseAt === 'tracker restoration') { + const openWorkflow = vi + .mocked(workflowStore.openWorkflow) + .getMockImplementation() + assert(openWorkflow) + vi.mocked(workflowStore.openWorkflow).mockImplementation( + async (workflow) => { + const loaded = await openWorkflow(workflow) + if (workflow.path === firstWorkflow.path) { + reachedPause = true + await pause + } + return loaded + } + ) + } else { + mockExtensionService.invokeExtensionsAsync.mockImplementation( + async (hook) => { + if (hook === 'afterLoadGraph' && !reachedPause) { + reachedPause = true + await pause + } + } + ) + } + + const olderLoad = app.loadGraphData( + saved, + false, + false, + firstWorkflow, + { + skipAssetScans: true + } + ) + await vi.waitFor(() => expect(reachedPause).toBe(true)) + const newerLoad = app.loadGraphData( + other, + false, + false, + secondWorkflow, + { + skipAssetScans: true + } + ) + releasePause() + await expect(olderLoad).resolves.toBeTruthy() + await expect(newerLoad).resolves.toBeTruthy() + + expect(workflowStore.activeWorkflow?.path).toBe(secondWorkflow.path) + expect(workflowStore.activeWorkflow?.changeTracker).toBe(secondTracker) + expect(secondTracker.activeState.extra).toMatchObject({ + marker: 'other' + }) + expect(secondTracker.initialState.extra).toMatchObject({ + marker: 'other' + }) + expect(firstTracker.initialState).toEqual(saved) + expect(firstTracker.activeState.extra).toMatchObject({ + marker: 'saved' + }) + expect(graph.extra).toMatchObject({ marker: 'other' }) + expect(ChangeTracker.isLoadingGraph).toBe(false) + } + ) + + it('does not assign a cleared canvas to Undo while the newer workflow is still preparing', async () => { app.canvasElRef.value = document.createElement('canvas') const graph = new LGraph() + graph.add(new LGraphNode('outgoing')) + const previousGraph = singletonApp.rootGraphOrUndefined + onTestFinished(() => { + Reflect.set(singletonApp, 'rootGraphInternal', previousGraph) + }) Reflect.set(app, 'rootGraphInternal', graph) Reflect.set(singletonApp, 'rootGraphInternal', graph) - const subgraphId = '00000000-0000-4000-8000-000000000001' - const graphData = { - ...createWorkflowGraphData(), - nodes: [ - { - id: 1, - type: subgraphId, - pos: [0, 0], - size: [100, 100], - flags: {}, - order: 0, - mode: 0, - inputs: [], - outputs: [], - properties: {} - } - ], - definitions: { - subgraphs: [ - { - id: subgraphId, - version: 1, - state: { - lastGroupId: 0, - lastNodeId: 0, - lastLinkId: 0, - lastRerouteId: 0 - }, - revision: 0, - config: {}, - name: 'Review fixture', - inputNode: { id: -10, bounding: [0, 0, 100, 60] }, - outputNode: { id: -20, bounding: [200, 0, 100, 60] }, - inputs: [], - outputs: [], - widgets: [], - nodes: [], - groups: [], - links: [], - extra: {} - } - ] + const outgoing = new ComfyWorkflow({ + path: 'workflows/outgoing.json', + modified: 0, + size: 0 + }) + 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() } - } as ComfyWorkflowJSON + ) - await app.loadGraphData(graphData, true) + await app.loadGraphData(createWorkflowGraphData(), true) - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'afterConfigureGraph', - [] + expect(tracker.activeState).toEqual(outgoingState) + expect(tracker.undoQueue).toHaveLength(0) + }) + + it('allows capture while the loaded workflow resource scans are pending', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + let releaseModels!: () => void + const modelsPending = new Promise((resolve) => { + releaseModels = resolve + }) + vi.mocked(runMissingModelPipeline).mockImplementationOnce(async () => { + await modelsPending + return { missingModels: [], confirmedCandidates: [] } + }) + const load = app.loadGraphData(createWorkflowGraphData(), false, false) + try { + await vi.waitFor(() => + expect(runMissingModelPipeline).toHaveBeenCalledOnce() + ) + + expect(ChangeTracker.isLoadingGraph).toBe(false) + } finally { + releaseModels() + await load + } + }) + + 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() + graph.extra = { marker: 'configured' } + let releaseFirst!: () => void + const firstPending = new Promise((resolve) => { + releaseFirst = resolve + }) + vi.when(mockExtensionService.invokeExtensionsAsync) + .calledWith('afterConfigureGraph', expect.anything()) + .thenReturnOnce(firstPending) + const firstLoad = app.loadGraphData(graph, false, false, null, { + skipAssetScans: true + }) + await vi.waitFor(() => + expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( + 'afterConfigureGraph', + expect.anything() + ) ) + vi.spyOn(app.rootGraph, 'configure').mockImplementationOnce(() => { + throw new Error('Configuration failed before clearing') + }) + const failedLoad = app.loadGraphData( + createWorkflowGraphData(), + false, + false, + null, + { skipAssetScans: true } + ) + releaseFirst() + + 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 queued replacement fails', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + let releaseOlderLoad!: () => void + const olderLoadBlocked = new Promise((resolve) => { + releaseOlderLoad = resolve + }) + 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.objectContaining({ extra: { marker: 'newer' } }), + expect.anything() + ) + .thenReject(new Error('newer load failed')) + + 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', () => { @@ -2985,64 +3287,24 @@ describe('ComfyApp', () => { 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 workflow loads in call order', async () => { - let releaseFirst!: () => void - const firstBlocked = new Promise((resolve) => { - releaseFirst = resolve - }) - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith('beforeLoadGraph') - .thenReturnOnce(firstBlocked) - - const first = app.loadGraphData(createWorkflowGraphData(), true) - await vi.waitFor(() => - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'beforeLoadGraph' - ) + it('runs the next workflow after a load rejects', async () => { + mockWorkflowService.afterLoadNewGraph.mockRejectedValueOnce( + new Error('activation failed') ) - const second = app.loadGraphData(createWorkflowGraphData(), true) - - expect( - mockExtensionService.invokeExtensionsAsync.mock.calls.filter( - ([hook]) => hook === 'beforeLoadGraph' - ) - ).toHaveLength(1) - - releaseFirst() - await expect(first).resolves.toBeTruthy() - await expect(second).resolves.toBeTruthy() - expect( - mockExtensionService.invokeExtensionsAsync.mock.calls.filter( - ([hook]) => hook === 'beforeLoadGraph' - ) - ).toHaveLength(2) - }) - - it('continues with the next workflow after a failed load', async () => { - vi.when(mockExtensionService.invokeExtensionsAsync) - .calledWith( - 'beforeConfigureGraph', - expect.anything(), - expect.anything() - ) - .thenRejectOnce(new Error('first load failed')) const first = app.loadGraphData(createWorkflowGraphData(), true) const second = app.loadGraphData(createWorkflowGraphData(), true) - await expect(first).resolves.toBe(false) + await expect(first).rejects.toThrow('activation failed') await expect(second).resolves.toBeTruthy() - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'onGraphLoadError', - expect.any(Error) - ) - expect(mockExtensionService.invokeExtensionsAsync).toHaveBeenCalledWith( - 'afterLoadGraph' - ) }) it('queues an API JSON import behind an in-flight workflow load', async () => { @@ -3064,8 +3326,6 @@ describe('ComfyApp', () => { { '1': { class_type: 'KSampler', inputs: {} } }, 'queued.json' ) - - expect(useNodeReplacementStore().load).not.toHaveBeenCalled() releaseWorkflow() await workflow await apiImport @@ -3074,23 +3334,27 @@ describe('ComfyApp', () => { expect(app.rootGraph.nodes[0].type).toBe('KSampler') }) - it('queues A1111 construction behind an in-flight workflow load', async () => { - vi.mocked(getWorkflowDataFromFile).mockResolvedValue({ - parameters: 'positive\nNegative prompt: negative\nSteps: 20' - }) - mockImportA1111.mockImplementation( - async (_graph, _parameters, beforeGraphClear) => { - await beforeGraphClear?.() - return 'imported' - } - ) + it('starts an A1111 import only after the in-flight workflow load finishes', async () => { let releaseWorkflow!: () => void - const workflowBlocked = new Promise((resolve) => { - releaseWorkflow = resolve - }) vi.when(mockExtensionService.invokeExtensionsAsync) .calledWith('beforeLoadGraph') - .thenReturnOnce(workflowBlocked) + .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(() => @@ -3098,31 +3362,25 @@ describe('ComfyApp', () => { 'beforeLoadGraph' ) ) - const a1111Import = app.handleFile( - createTestFile('queued-a1111.png', 'image/png') - ) - - expect(mockImportA1111).not.toHaveBeenCalled() - releaseWorkflow() + await app.handleFile(createTestFile('queued-a1111.png', 'image/png')) await workflow - await a1111Import - expect(mockImportA1111).toHaveBeenCalledOnce() + + expect(workflowFinishedBeforeImport).toBe(true) }) it('cleans before extensions prepare the incoming workflow', async () => { - const clean = vi.spyOn(app, 'clean') - let cleanCallsDuringPreparation: number | undefined + app.rootGraph.add(new LGraphNode('outgoing')) + let nodesDuringPreparation: number | undefined mockExtensionService.invokeExtensionsAsync.mockImplementation( async (hook) => { - if (hook !== 'beforeConfigureGraph') return - cleanCallsDuringPreparation = clean.mock.calls.length + if (hook === 'beforeConfigureGraph') + nodesDuringPreparation = app.rootGraph.nodes.length } ) - await expect( - app.loadGraphData(createWorkflowGraphData(), true) - ).resolves.toBeTruthy() - expect(cleanCallsDuringPreparation).toBe(1) + await app.loadGraphData(createWorkflowGraphData(), true) + + expect(nodesDuringPreparation).toBe(0) }) }) @@ -3964,8 +4222,8 @@ describe('ComfyApp', () => { } ) let resolveAfterLoad: (() => void) | undefined - const afterLoad = new Promise((resolve) => { - resolveAfterLoad = () => resolve(true) + const afterLoad = new Promise((resolve) => { + resolveAfterLoad = resolve }) mockWorkflowService.afterLoadNewGraph.mockReturnValue(afterLoad) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index bf208d622ac..ef6136f47cd 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -95,11 +95,11 @@ import type { ComfyNodeDef as ComfyNodeDefV1 } from '@/schemas/nodeDefSchema' import { ComponentWidgetImpl, DOMWidgetImpl } from '@/scripts/domWidget' import type { BaseDOMWidget } from '@/types/domWidget' import { useAccountPreconditionDialog } from '@/platform/cloud/subscription/composables/useAccountPreconditionDialog' -import { useRunButtonTelemetry } from '@/composables/useRunButtonTelemetry' import { resolveAccountPrecondition } from '@/platform/errorCatalog/accountPreconditionRouting' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useDialogService } from '@/services/dialogService' import { useExtensionService } from '@/services/extensionService' +import { useRunButtonTelemetry } from '@/composables/useRunButtonTelemetry' import { useLitegraphService } from '@/services/litegraphService' import { useSubgraphService } from '@/services/subgraphService' import { isDesktopHostSignedIn } from '@/platform/auth/desktopHost/desktopHostSession' @@ -189,7 +189,6 @@ import { PromptExecutionError, api } from './api' import type { ComfyApi } from './api' import { defaultGraph } from './defaultGraph' import { importA1111 } from './pnginfo' -import type { A1111ImportOutcome } from './pnginfo' import { applyPromotedWidgetControl } from '@/core/graph/subgraph/promotedWidgetControl' import { ComfyUI } from './ui' import { $el } from './ui/utils' @@ -1182,17 +1181,7 @@ export class ComfyApp implements IComfyApp { reportType: 'loadWorkflowError' }) console.error(error) - await this.invokeGraphLoadHook('onGraphLoadError', error) - } - - private invokeGraphLoadHook( - ...args: Parameters< - ReturnType['invokeExtensionsAsync'] - > - ): ReturnType< - ReturnType['invokeExtensionsAsync'] - > { - return useExtensionService().invokeExtensionsAsync(...args) + await useExtensionService().invokeExtensionsAsync('onGraphLoadError', error) } private enqueueGraphLoad(operation: () => Promise): Promise { @@ -1217,11 +1206,11 @@ export class ComfyApp implements IComfyApp { } private async loadGraphDataNow( - graphData?: ComfyWorkflowJSON, - clean: boolean = true, - restore_view: boolean = true, - workflow: string | null | ComfyWorkflow = null, - options: LoadGraphDataOptions = {} + graphData: ComfyWorkflowJSON | undefined, + clean: boolean, + restore_view: boolean, + workflow: string | null | ComfyWorkflow, + options: LoadGraphDataOptions ): Promise { const canvasScheduler = useCanvasScheduler() const loadId = ++this.graphLoadSequence @@ -1236,20 +1225,14 @@ export class ComfyApp implements IComfyApp { workflowNavigationId } = options useWorkflowService().beforeLoadNewGraph(clean) - await this.invokeGraphLoadHook('beforeLoadGraph') + await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + ChangeTracker.isLoadingGraph = true let reset_invalid_values = false const missingNodeTypes: MissingNodeType[] = [] try { useExecutionErrorStore().setActiveGraph(null) - if (clean) { - // Cleanup must precede extension preparation. Several extensions attach - // subgraph, preview, media, and colour state in beforeConfigureGraph. - this.canvas.setGraph(this.rootGraph) - withGraphIntentSource('load', () => this.clean()) - } - if (skipAssetScans) { // Only reset candidates; preserve UI state (fileSizes, etc.) // so cached results restored by showPendingWarnings still display sizes. @@ -1264,6 +1247,16 @@ export class ComfyApp implements IComfyApp { useMissingMediaStore().clearMissingMedia() } + 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 ( @@ -1285,7 +1278,6 @@ export class ComfyApp implements IComfyApp { // Ideally we should not block users from loading the workflow. graphData = validatedGraphData ?? graphData } - const subgraphTypes = useSubgraphService().normalizeSubgraphs(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. @@ -1318,7 +1310,9 @@ export class ComfyApp implements IComfyApp { ) } - await this.invokeGraphLoadHook( + useSubgraphService().loadSubgraphs(graphData) + + await useExtensionService().invokeExtensionsAsync( 'beforeConfigureGraph', graphData, missingNodeTypes @@ -1341,10 +1335,7 @@ export class ComfyApp implements IComfyApp { return } for (const n of nodes) { - if ( - !(n.type in LiteGraph.registered_node_types) && - !subgraphTypes.has(n.type) - ) { + 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 = @@ -1407,7 +1398,11 @@ export class ComfyApp implements IComfyApp { // 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. - await this.reportGraphLoadFailure(error) + try { + await this.reportGraphLoadFailure(error) + } finally { + ChangeTracker.isLoadingGraph = false + } void useSubgraphNavigationStore().updateHash( 'workflow-load', workflowNavigationId @@ -1449,13 +1444,11 @@ export class ComfyApp implements IComfyApp { } } - const endGraphLoadSuppression = ChangeTracker.beginGraphLoad() let activatedWorkflow: LoadedComfyWorkflow | undefined let reconcileResourceErrors: (() => void) | undefined let resourceScanLoadCompleted = false try { try { - useSubgraphService().loadSubgraphs(graphData) this.rootGraph.configure(graphData as ISerialisedGraph) // Save original renderer version before scaling (it gets modified during scaling) @@ -1510,6 +1503,14 @@ export class ComfyApp implements IComfyApp { // 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 @@ -1570,7 +1571,14 @@ export class ComfyApp implements IComfyApp { }) ) - await this.invokeGraphLoadHook('afterConfigureGraph', missingNodeTypes) + await useExtensionService().invokeExtensionsAsync( + 'afterConfigureGraph', + missingNodeTypes + ) + if (!isCurrentGraphLoad()) { + await cancelReplacedLoad() + return undefined + } const effectiveShareId = shareId ?? @@ -1586,14 +1594,25 @@ export class ComfyApp implements IComfyApp { } useTelemetry()?.trackWorkflowOpened(telemetryPayload) useTelemetry()?.trackWorkflowImported(telemetryPayload) - const activated = await useWorkflowService().afterLoadNewGraph( - workflow, - this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, - effectiveShareId - ) - if (!activated) return false - await this.invokeGraphLoadHook('afterLoadGraph') - + try { + await useWorkflowService().afterLoadNewGraph( + workflow, + this.rootGraph.serialize() as unknown as ComfyWorkflowJSON, + effectiveShareId + ) + } catch (error) { + if (isCurrentGraphLoad()) throw error + } + if (!isCurrentGraphLoad()) { + await cancelReplacedLoad() + return undefined + } + await useExtensionService().invokeExtensionsAsync('afterLoadGraph') + if (!isCurrentGraphLoad()) { + await cancelReplacedLoad() + 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 @@ -1661,10 +1680,9 @@ export class ComfyApp implements IComfyApp { 'workflow-load', workflowNavigationId ) - endGraphLoadSuppression() - if (!ChangeTracker.isLoadingGraph) { - useExecutionErrorStore().retireResolvedMissingNodePromptError() - } + ChangeTracker.isLoadingGraph = false + // The retirement watcher skips transitions made during the load. + useExecutionErrorStore().retireResolvedMissingNodePromptError() reconcileResourceErrors?.() } } @@ -2195,14 +2213,16 @@ export class ComfyApp implements IComfyApp { // Use parameters strictly as the final fallback if (parameters && typeof parameters === 'string') { return await this.enqueueGraphLoad(async () => { - const outcome: A1111ImportOutcome = await importA1111( + const outcome = await importA1111( this.rootGraph, parameters, async () => { try { // false: final destination; no later load republishes the hash. useWorkflowService().beforeLoadNewGraph(false) - await this.invokeGraphLoadHook('beforeLoadGraph') + await useExtensionService().invokeExtensionsAsync( + 'beforeLoadGraph' + ) } finally { useMissingNodesErrorStore().setMissingNodeTypes([]) } @@ -2232,13 +2252,15 @@ export class ComfyApp implements IComfyApp { } // Intentionally no beforeConfigureGraph: A1111 has no mutable // workflow JSON before graph construction, so there is no payload. - await this.invokeGraphLoadHook('afterConfigureGraph', []) - const activated = await useWorkflowService().afterLoadNewGraph( + await useExtensionService().invokeExtensionsAsync( + 'afterConfigureGraph', + [] + ) + await useWorkflowService().afterLoadNewGraph( fileName, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON ) - if (!activated) return - await this.invokeGraphLoadHook('afterLoadGraph') + await useExtensionService().invokeExtensionsAsync('afterLoadGraph') return }) } @@ -2381,14 +2403,14 @@ export class ComfyApp implements IComfyApp { private async loadApiJsonNow( apiData: ComfyApiWorkflow, fileName: string, - options: { deferWarnings?: boolean } = {} + options: { deferWarnings?: boolean } ): Promise { // false: no workflow load follows to republish the hash. useWorkflowService().beforeLoadNewGraph(false) - await this.invokeGraphLoadHook('beforeLoadGraph') - + await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') this.canvas.setGraph(this.rootGraph) withGraphIntentSource('load', () => this.clean()) + const ids = Object.keys(apiData) // Export (API) flattens subgraph nodes to ids like "194:45". At the root // graph a colon reads as an execution-id path: Locate walks into node @@ -2412,7 +2434,6 @@ export class ComfyApp implements IComfyApp { const missingNodeTypes: MissingNodeType[] = [] const nodeReplacementStore = useNodeReplacementStore() await nodeReplacementStore.load() - withGraphIntentSource('load', () => { for (const id of ids) { const data = apiData[id] @@ -2586,14 +2607,15 @@ export class ComfyApp implements IComfyApp { // Intentionally no beforeConfigureGraph: API JSON builds nodes directly // and never passes a ComfyWorkflowJSON through the configure stage. - await this.invokeGraphLoadHook('afterConfigureGraph', missingNodeTypes) - - const activated = await useWorkflowService().afterLoadNewGraph( + await useExtensionService().invokeExtensionsAsync( + 'afterConfigureGraph', + missingNodeTypes + ) + await useWorkflowService().afterLoadNewGraph( fileName, this.rootGraph.serialize() as unknown as ComfyWorkflowJSON ) - if (!activated) return - await this.invokeGraphLoadHook('afterLoadGraph') + await useExtensionService().invokeExtensionsAsync('afterLoadGraph') if (missingNodeTypes.length) { this.showMissingNodesError(missingNodeTypes, options) } diff --git a/src/scripts/changeTracker.test.ts b/src/scripts/changeTracker.test.ts index 96c4e34a2e1..392388d4fbb 100644 --- a/src/scripts/changeTracker.test.ts +++ b/src/scripts/changeTracker.test.ts @@ -222,13 +222,7 @@ describe('ChangeTracker', () => { calls: 0 }, { key: 'z', shiftKey: true, history: 'redo', selectOnly: true, calls: 0 }, - { - key: 'y', - shiftKey: false, - history: 'redo', - selectOnly: true, - calls: 0 - } + { key: 'y', shiftKey: false, history: 'redo', selectOnly: true, calls: 0 } ] as const)( 'Ctrl+$key shift=$shiftKey with selectOnly=$selectOnly consumes the key and runs $history $calls times', async ({ key, shiftKey, history, selectOnly, calls }) => { @@ -696,17 +690,6 @@ describe('ChangeTracker', () => { } ) - it('lets the newest graph load release suppression without waiting for an older load', () => { - const endOlderLoad = ChangeTracker.beginGraphLoad() - const endNewerLoad = ChangeTracker.beginGraphLoad() - - endNewerLoad() - - expect(ChangeTracker.isLoadingGraph).toBe(false) - endOlderLoad() - expect(ChangeTracker.isLoadingGraph).toBe(false) - }) - it('does not push when state is identical', () => { const state = createState() const tracker = createTracker(state) diff --git a/src/scripts/changeTracker.ts b/src/scripts/changeTracker.ts index fdbbed3c6f0..a35b34602be 100644 --- a/src/scripts/changeTracker.ts +++ b/src/scripts/changeTracker.ts @@ -294,9 +294,6 @@ function reportInactiveTrackerCall(method: string, workflowPath: string) { export class ChangeTracker implements WorkflowChangeTracker { static MAX_HISTORY = 50 - private static graphLoadGeneration = 0 - private static activeGraphLoadGeneration: number | undefined - /** * Guard flag to prevent captureCanvasState from running during loadGraphData. * Between rootGraph.configure() and afterLoadNewGraph(), the rootGraph @@ -304,28 +301,7 @@ export class ChangeTracker implements WorkflowChangeTracker { * the OLD workflow. Any captureCanvasState call in that window would * serialize the wrong graph into the old workflow's activeState, corrupting it. */ - static get isLoadingGraph(): boolean { - return ChangeTracker.activeGraphLoadGeneration !== undefined - } - - static set isLoadingGraph(value: boolean) { - ChangeTracker.activeGraphLoadGeneration = value - ? ++ChangeTracker.graphLoadGeneration - : undefined - } - - static beginGraphLoad(): () => void { - const generation = ++ChangeTracker.graphLoadGeneration - ChangeTracker.activeGraphLoadGeneration = generation - let closed = false - return () => { - if (closed) return - closed = true - if (ChangeTracker.activeGraphLoadGeneration === generation) { - ChangeTracker.activeGraphLoadGeneration = undefined - } - } - } + static isLoadingGraph = false /** * The active state of the workflow. */ diff --git a/src/services/subgraphService.ts b/src/services/subgraphService.ts index 2794ce02d89..a65b0ae510e 100644 --- a/src/services/subgraphService.ts +++ b/src/services/subgraphService.ts @@ -60,10 +60,10 @@ export const useSubgraphService = () => { return nodeDef } - /** Normalizes exported subgraph ids without mutating shared graph state. */ - function normalizeSubgraphs(graphData: ComfyWorkflowJSON) { + /** Loads all exported subgraph definitions from workflow */ + function loadSubgraphs(graphData: ComfyWorkflowJSON) { const subgraphs = graphData.definitions?.subgraphs - if (!subgraphs) return new Set() + if (!subgraphs) return const normalized = normalizeSubgraphDefinitionIds( subgraphs, @@ -71,16 +71,8 @@ export const useSubgraphService = () => { ) graphData.definitions!.subgraphs = normalized.subgraphs if (normalized.rootNodes) graphData.nodes = normalized.rootNodes - return new Set(normalized.subgraphs.map(({ id }) => id)) - } - - /** Loads all normalized exported subgraph definitions from workflow. */ - function loadSubgraphs(graphData: ComfyWorkflowJSON) { - const subgraphs = graphData.definitions?.subgraphs - if (!subgraphs) return - // Assertion: overriding Zod schema - const exportedSubgraphs = subgraphs as ExportedSubgraph[] + const exportedSubgraphs = normalized.subgraphs as ExportedSubgraph[] const missingSubgraphs = exportedSubgraphs.filter( ({ id }) => !useApp().rootGraph.subgraphs.has(id) ) @@ -109,7 +101,6 @@ export const useSubgraphService = () => { } return { - normalizeSubgraphs, loadSubgraphs, registerNewSubgraph } From d9f973db831f145d145df40d31d87eb2dbd3c72b Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Thu, 15 Oct 2026 15:45:10 +0000 Subject: [PATCH 30/31] fix(extensions): limit the graph-load hook app to its own dispatch The app passed to a graph-load lifecycle hook now rejects nested loads only while that hook dispatch is running, so an extension that keeps the argument can load normally later. The hook and entrypoint lists are checked against ComfyExtension and ComfyApp, and the tests assert the rejection outside the hook for all three entrypoints. --- src/services/extensionService.test.ts | 72 +++++++++++++++++---------- src/services/extensionService.ts | 65 ++++++++++++------------ 2 files changed, 80 insertions(+), 57 deletions(-) diff --git a/src/services/extensionService.test.ts b/src/services/extensionService.test.ts index f21c96069ee..6412b55f3d0 100644 --- a/src/services/extensionService.test.ts +++ b/src/services/extensionService.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { legacyMenuCompat } from '@/lib/litegraph/src/contextMenuCompat' -import type { useApp } from '@/scripts/appRegistry' +import { useApp } from '@/scripts/appInstance' import { useExtensionStore } from '@/stores/extensionStore' import { useExtensionService } from './extensionService' @@ -148,37 +148,59 @@ describe('invokeExtensionsAsync', () => { expect(hook.mock.contexts[0]).toBe(useExtensionStore().extensions[0]) }) - it('rejects a graph load requested after an await in a lifecycle hook', async () => { - register({ - name: 'nested-loader', - beforeLoadGraph: async (app: ReturnType) => { - await Promise.resolve() - await expect(app.loadGraphData()).rejects.toThrow( - 'A graph-load lifecycle hook cannot start a nested graph load' - ) - } - }) + 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 useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + + await expect(nested).rejects.toThrow( + 'A graph-load lifecycle hook cannot start a nested graph load' + ) + } + ) - it('rejects an awaited API import without blocking the next load hook', async () => { - const nestedImportRejected = vi.fn() + it('lets a retained hook app load once the hook dispatch has finished', async () => { + let retained: HookApp | undefined register({ - name: 'nested-api-loader', - beforeLoadGraph: async (app: ReturnType) => { - await Promise.resolve() - await expect(app.loadApiJson({}, 'nested.json')).rejects.toThrow( - 'A graph-load lifecycle hook cannot start a nested graph load' - ) - nestedImportRejected() + 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 useExtensionService().invokeExtensionsAsync('beforeLoadGraph') - await useExtensionService().invokeExtensionsAsync('beforeLoadGraph') + await retained?.handleFile(file) - expect(nestedImportRejected).toHaveBeenCalledTimes(2) + expect(handleFile).toHaveBeenCalledWith(file) }) it('silently ignores a non-function property of the same name', async () => { diff --git a/src/services/extensionService.ts b/src/services/extensionService.ts index f3d7c07689e..b76e8c47eec 100644 --- a/src/services/extensionService.ts +++ b/src/services/extensionService.ts @@ -22,48 +22,42 @@ function isPromiseLike(value: unknown): value is PromiseLike { ) } -const graphLoadLifecycleHooks = new Set([ +const graphLoadLifecycleHooks = new Set([ 'beforeLoadGraph', 'beforeConfigureGraph', 'afterConfigureGraph', 'afterLoadGraph', 'onGraphLoadError' -]) +] satisfies (keyof ComfyExtension)[]) -const graphLoadEntrypoints = new Set([ +const graphLoadEntrypoints = new Set([ 'loadGraphData', 'loadApiJson', 'handleFile' -]) +] satisfies (keyof ComfyApp)[]) -const graphLoadHookApps = new WeakMap() - -function extensionAppForHook(method: string): ComfyApp { - const app = useApp() - if (!graphLoadLifecycleHooks.has(method)) return app +function rejectNestedGraphLoad() { + return Promise.reject( + new Error('A graph-load lifecycle hook cannot start a nested graph load') + ) +} - let hookApp = graphLoadHookApps.get(app) - if (!hookApp) { - hookApp = new Proxy(app, { - get(target, property, receiver) { - if ( - typeof property === 'string' && - graphLoadEntrypoints.has(property) - ) { - return () => - Promise.reject( - new Error( - 'A graph-load lifecycle hook cannot start a nested graph load' - ) - ) - } - const value: unknown = Reflect.get(target, property, receiver) - return typeof value === 'function' ? value.bind(target) : value - } - }) - graphLoadHookApps.set(app, hookApp) +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 + } } - return hookApp } export const useExtensionService = () => { @@ -223,7 +217,10 @@ export const useExtensionService = () => { method: T, ...args: Parameters> ) => { - const app = extensionAppForHook(method) + 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}'`, @@ -267,7 +264,11 @@ export const useExtensionService = () => { logError(ext, error) } } - return await Promise.all(pending) + try { + return await Promise.all(pending) + } finally { + graphLoadHook?.endDispatch() + } } return { From 7245b727bfc0e4e42bfab51d3ab67bc4a5c292cc Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Thu, 15 Oct 2026 15:45:34 +0000 Subject: [PATCH 31/31] test: run the workflow load queue spec in the OSS browser project Moves the spec out of tests/agent, drops the API JSON case that the unit suite already covers, and removes the cloud-only tag and timeout override. --- .../agentOverlappingWorkflowLoad.spec.ts | 175 ------------------ .../tests/workflow/workflowLoadQueue.spec.ts | 94 ++++++++++ 2 files changed, 94 insertions(+), 175 deletions(-) delete mode 100644 browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts create mode 100644 browser_tests/tests/workflow/workflowLoadQueue.spec.ts diff --git a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts b/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts deleted file mode 100644 index 405a9d44767..00000000000 --- a/browser_tests/tests/agent/agentOverlappingWorkflowLoad.spec.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { expect } from '@playwright/test' - -import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' - -import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' - -const STALL_EXTENSION = 'e2e.op329.stallBeforeLoadGraph' - -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( - 'Overlapping workflow loads', - { tag: ['@cloud', '@vue-nodes'] }, - () => { - test('workflow loads finish in FIFO order', async ({ comfyPage }) => { - test.setTimeout(60_000) - const { page, vueNodes } = comfyPage - - const order = - await test.step('hold the first load open, then queue a second', async () => - await page.evaluate( - async ([extensionName, 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: extensionName, - 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 } - }, - [ - STALL_EXTENSION, - noteWorkflow('older workflow'), - noteWorkflow('newer workflow') - ] as const - )) - - expect(order).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) - }) - }) - - test('a workflow waits for an earlier API JSON import', async ({ - comfyPage - }) => { - test.setTimeout(60_000) - const { page, vueNodes } = comfyPage - - const order = - await test.step('hold an API JSON import open, then queue a workflow', async () => - await page.evaluate( - async ([extensionName, apiPrompt, newer]) => { - let release!: () => void - const held = new Promise((resolve) => { - release = resolve - }) - let entered!: () => void - const firstEntered = new Promise((resolve) => { - entered = resolve - }) - let holdNext = true - window.app!.registerExtension({ - name: extensionName, - beforeLoadGraph: async () => { - if (!holdNext) return - holdNext = false - entered() - await held - } - }) - - const order: string[] = [] - const apiImport = window - .app!.loadApiJson(apiPrompt, 'queued-api-prompt.json') - .then(() => order.push('api')) - await firstEntered - const workflowLoad = window - .app!.loadGraphData(newer) - .then(() => order.push('workflow')) - await Promise.resolve() - const workflowFinishedWhileApiWasHeld = order.includes('workflow') - release() - await apiImport - await workflowLoad - return { order, workflowFinishedWhileApiWasHeld } - }, - [ - `${STALL_EXTENSION}.apiJson`, - { - '1': { - class_type: 'EmptyLatentImage', - inputs: {}, - _meta: { title: 'queued api import' } - } - }, - noteWorkflow('newer workflow') - ] as const - )) - - expect(order).toEqual({ - order: ['api', 'workflow'], - workflowFinishedWhileApiWasHeld: false - }) - - 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('queued api import')).toHaveCount( - 0 - ) - }) - }) - } -) 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) + }) + }) +})