From 2debc89478ee5b89792606516e655a6f7756fc5d Mon Sep 17 00:00:00 2001 From: bymyself Date: Wed, 28 Oct 2026 03:15:10 +0000 Subject: [PATCH 01/10] feat: load the default workflow from core's route (FE-1178) ComfyUI#16956 added `GET /default_workflow` so core owns the workflow new users land on, instead of it being frozen into the frontend bundle. Fetch it at boot and fall back to the bundled `defaultGraph` whenever the backend cannot serve one. This lets core refresh the default in a one-line `server.py` change rather than through a frontend release plus a core version bump, and lets cloud, desktop and platform-specific builds each serve their own. The three places that need a default are synchronous, so resolution is a one-shot prefetch: `ComfyApp.setup` starts the request before `syncWorkflows` and awaits it last, so it overlaps the rest of boot instead of adding to it. Falls back silently on 404, which is how every backend older than that PR answers, and with a warning on a server error, a non-JSON body, a body that fails schema validation, or a failed request. `VITE_USE_LEGACY_DEFAULT_GRAPH` builds skip the request entirely. They run against a real core, so fetching would serve the current default and undo the test pinning hundreds of specs rely on. No user-visible change here: core serves a byte-for-byte copy of the workflow the frontend already bundles. --- ...W-0050-core-serves-the-default-workflow.md | 124 +++++++++++++++ .../services/defaultWorkflowService.test.ts | 141 ++++++++++++++++++ .../core/services/defaultWorkflowService.ts | 88 +++++++++++ .../workflow/core/services/workflowService.ts | 5 +- .../management/stores/workflowStore.ts | 6 +- src/scripts/app.ts | 14 +- 6 files changed, 372 insertions(+), 6 deletions(-) create mode 100644 docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md create mode 100644 src/platform/workflow/core/services/defaultWorkflowService.test.ts create mode 100644 src/platform/workflow/core/services/defaultWorkflowService.ts diff --git a/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md b/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md new file mode 100644 index 00000000000..71b28ac9100 --- /dev/null +++ b/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md @@ -0,0 +1,124 @@ +# ADR-DEFAULT-WORKFLOW-0050: Core Serves the Default Workflow + +Date: 2026-10-28 + +## Status + +Proposed + +## Context + +The workflow a new user lands on has lived in frontend TypeScript +(`src/scripts/defaultGraph.ts`) since it existed. Changing it therefore costs a +frontend release plus a core version bump, which is why it sat on Stable +Diffusion 1.5 for years before ComfyUI_frontend#12804 moved it to Z-Image Turbo. + +Two things want that coupling gone: + +- Core wants to refresh the default on a cadence measured in weeks (the + community-submitted showcase workflow), which a release train cannot serve. +- Each distribution wants a different default. Cloud does not want a workflow + that assumes a local GPU; desktop would rather open one whose model it + already bundles; Apple Silicon wants something that runs there. + +ComfyUI#16956 (CORE-340) landed the backend half: `default_workflow.json` plus +`GET /default_workflow` (and `/api/default_workflow`), documented in +`openapi.yaml` and served with `Cache-Control: no-cache` so an updated file is +not heuristically reused from cache. The file is a byte-for-byte copy of the +frontend's current `prodDefaultGraph`. Cloud implements the same endpoint. + +This ADR covers the frontend half (FE-1178), the last of the four steps planned +for this change. Decoupling the e2e suites from the default workflow was the +other, and it already shipped as the `VITE_USE_LEGACY_DEFAULT_GRAPH` build +variable. + +The frontend constraint that shapes the design: all three places that need a +default are synchronous. `loadGraphData` falls back to it when handed invalid +data, `createNewWorkflow` seeds a new tab with it, and `loadDefaultWorkflow` +loads it on the last tab closing. Making the default async would push +`await` into a store getter and a tab-creation path that are not async today. + +## Decision + +The frontend fetches the default workflow from the backend once per page load +and keeps the bundled graph as the fallback. + +- `defaultWorkflowService` owns resolution. `initDefaultWorkflow()` performs + the request at most once; `getDefaultWorkflow()` returns the fetched workflow + if there is one and the bundled `defaultGraph` otherwise. +- `ComfyApp.setup` starts the request before `syncWorkflows` and awaits it as + its last step, so the request overlaps the rest of boot rather than adding to + it. The startup workflow load runs after `setup` returns, so a resolved + default is already in place by the time anything reads it. +- The three call sites stay synchronous: they call `getDefaultWorkflow()` where + they used to read the `defaultGraph` import. Each already cloned before + mutating, which a shared module-level object also required. +- `initDefaultWorkflow()` never rejects. A 404 (any backend older than + ComfyUI#16956), a server error, a body that is not JSON, a body that fails + `validateComfyWorkflow`, and a failed request all resolve to the bundled + graph. Only a 404 is silent, because that is simply what an older backend + says; the rest warn. +- Builds with `VITE_USE_LEGACY_DEFAULT_GRAPH=true` skip the request entirely. + Those builds run against a real core, so fetching would serve the current + default and undo the test pinning that hundreds of specs depend on. The flag + is read at call time rather than at module load; Vite inlines + `import.meta.env` the same either way, and a call-time read is testable + without resetting the module registry. + +A prefetch was chosen over a fetch per use because the call sites are +synchronous and because core sends `Cache-Control: no-cache` — a reload is the +intended way to pick up a changed default, not a mid-session swap. + +Alternatives considered and rejected: + +- Making the default async end to end. Correct in the abstract, but it turns a + store getter and a tab-creation path async for a value that is known before + the editor opens. +- Mocking the route in the e2e suites instead of skipping the fetch. The + pinning already exists and works; adding a route mock to every spec file + would be a larger change than the feature. +- Serving the default from the workflow templates index, which the frontend + already fetches. It is a different contract with a different owner, and core + wants `server.py` to be the one-line edit. + +## Consequences + +### Positive + +- Core changes the default workflow in a one-line `server.py` edit, with no + frontend release and no core version bump. A CMS can replace the file later + without the frontend noticing. +- Cloud, desktop and platform-specific builds can each serve their own default + from their own backend. +- No user-visible change on this commit: core serves a byte-for-byte copy of + the workflow the frontend already bundles, so the decoupling ships before any + content change does. +- Every backend older than the route keeps working, silently. + +### Negative + +- Boot awaits one more request. It is started early and awaited last, so it + adds nothing unless it outlasts the rest of `setup`; on a slow or hanging + backend it delays the editor opening, because there is no timeout of its own + beyond `fetchApi`'s. +- The default is now a network-dependent value, so two users on the same + frontend build can land on different workflows. That is the point, but it + makes "what did the user see" unanswerable from the frontend version alone. +- A core that serves a workflow this frontend's schema rejects falls back + silently apart from a console warning. Nothing tells core that its workflow + was refused; a server-side contract test, or a telemetry event on fallback, + is the follow-up. +- E2E builds do not exercise the fetch path at all, by construction. The unit + tests cover it; no browser test does. +- `defaultGraph` remains exported and bundled, so the workflow is still shipped + in the frontend bundle even once core always serves one. It cannot be dropped + while it is the fallback. + +## Notes + +The service and its fallback matrix are covered in +`src/platform/workflow/core/services/defaultWorkflowService.test.ts`. + +Backend half: ComfyUI#16956. Tracked as FE-1178 (frontend) and CORE-340 +(core, done). The community-submission program that motivates the cadence is +still in design and is not part of this decision. diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts new file mode 100644 index 00000000000..3a73e7c317b --- /dev/null +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -0,0 +1,141 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' +import { api } from '@/scripts/api' +import { blankGraph, defaultGraph } from '@/scripts/defaultGraph' + +import { + getDefaultWorkflow, + initDefaultWorkflow, + resetDefaultWorkflowForTesting +} from './defaultWorkflowService' + +vi.mock(import('@/scripts/api')) + +const fetchApi = vi.mocked(api.fetchApi) + +/** A valid workflow that is not the bundled default, so the two are telling apart. */ +const servedWorkflow: ComfyWorkflowJSON = { + ...blankGraph, + last_node_id: 42 +} + +const jsonResponse = (body: unknown) => + ({ + ok: true, + status: 200, + json: () => Promise.resolve(body) + }) as unknown as Response + +const errorResponse = (status: number) => + ({ + ok: false, + status, + json: () => Promise.reject(new Error('should not be read')) + }) as unknown as Response + +describe('defaultWorkflowService', () => { + beforeEach(() => { + resetDefaultWorkflowForTesting() + fetchApi.mockReset() + }) + + it('serves the backend workflow once the route has answered', async () => { + fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) + + await initDefaultWorkflow() + + expect(fetchApi).toHaveBeenCalledWith('/default_workflow') + expect(getDefaultWorkflow()).toEqual(servedWorkflow) + }) + + it('serves the bundled default until the route has answered', () => { + fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) + + void initDefaultWorkflow() + + expect(getDefaultWorkflow()).toBe(defaultGraph) + }) + + it('falls back to the bundled default on a backend without the route', async () => { + fetchApi.mockResolvedValue(errorResponse(404)) + + await initDefaultWorkflow() + + expect(getDefaultWorkflow()).toBe(defaultGraph) + }) + + it('does not warn about a 404, which is how older backends answer', async () => { + fetchApi.mockResolvedValue(errorResponse(404)) + + await initDefaultWorkflow() + + expect(console.warn).not.toHaveBeenCalled() + }) + + it('falls back to the bundled default on a server error', async () => { + fetchApi.mockResolvedValue(errorResponse(500)) + + await initDefaultWorkflow() + + expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(console.warn).toHaveBeenCalled() + }) + + it('falls back to the bundled default when the route serves an invalid workflow', async () => { + fetchApi.mockResolvedValue(jsonResponse({ not: 'a workflow' })) + + await initDefaultWorkflow() + + expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(console.warn).toHaveBeenCalled() + }) + + it('falls back to the bundled default when the body is not JSON', async () => { + fetchApi.mockResolvedValue({ + ok: true, + status: 200, + json: () => Promise.reject(new SyntaxError('Unexpected token <')) + } as unknown as Response) + + await initDefaultWorkflow() + + expect(getDefaultWorkflow()).toBe(defaultGraph) + }) + + it('falls back to the bundled default when the request fails outright', async () => { + fetchApi.mockRejectedValue(new TypeError('Failed to fetch')) + + await expect(initDefaultWorkflow()).resolves.toBeUndefined() + expect(getDefaultWorkflow()).toBe(defaultGraph) + }) + + it('requests the workflow at most once per page load', async () => { + fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) + + await Promise.all([ + initDefaultWorkflow(), + initDefaultWorkflow(), + initDefaultWorkflow() + ]) + await initDefaultWorkflow() + + expect(fetchApi).toHaveBeenCalledTimes(1) + }) +}) + +describe('defaultWorkflowService in e2e builds', () => { + beforeEach(() => { + resetDefaultWorkflowForTesting() + vi.stubEnv('VITE_USE_LEGACY_DEFAULT_GRAPH', 'true') + fetchApi.mockReset() + fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) + }) + + it('never requests the route, so the pinned test graph stays pinned', async () => { + await initDefaultWorkflow() + + expect(fetchApi).not.toHaveBeenCalled() + expect(getDefaultWorkflow()).toBe(defaultGraph) + }) +}) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.ts b/src/platform/workflow/core/services/defaultWorkflowService.ts new file mode 100644 index 00000000000..0478acbfb2a --- /dev/null +++ b/src/platform/workflow/core/services/defaultWorkflowService.ts @@ -0,0 +1,88 @@ +import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' +import { validateComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' +import { api } from '@/scripts/api' +import { defaultGraph } from '@/scripts/defaultGraph' + +/** + * Resolves the workflow new users land on. + * + * Core owns the default workflow as of ComfyUI#16956, which serves it from + * `GET /default_workflow`. Fetching it here lets core (and cloud) swap the + * default in a one-line `server.py` change instead of waiting on a frontend + * release, and lets each distribution ship a different one - e.g. a model + * desktop pre-bundles, or something that does not assume a local GPU on cloud. + * + * The bundled `defaultGraph` stays as the fallback, so backends predating that + * route (404), offline loads, and malformed responses all keep working. + * + * Resolution is a one-shot prefetch rather than a fetch per use: the three + * places that need a default are synchronous, and core sends + * `Cache-Control: no-cache`, so a reload is what picks up a changed default. + */ + +/** + * E2E builds pin the default to the bundled legacy graph because hundreds of + * specs assert on its node IDs and positions. Those builds run against a real + * core, so without this the route would serve the current default and undo + * that pinning. See browser_tests/README.md. + */ +const usesLegacyDefaultGraph = () => + import.meta.env.VITE_USE_LEGACY_DEFAULT_GRAPH === 'true' + +let remoteDefaultWorkflow: ComfyWorkflowJSON | null = null +let prefetch: Promise | null = null + +async function fetchDefaultWorkflow(): Promise { + try { + const res = await api.fetchApi('/default_workflow') + if (!res.ok) { + // 404 is the expected answer from a backend older than ComfyUI#16956. + if (res.status !== 404) { + console.warn( + `[defaultWorkflow] /default_workflow returned ${res.status}; using the bundled default` + ) + } + return null + } + const json: unknown = await res.json() + return await validateComfyWorkflow(json, (error) => { + console.warn( + `[defaultWorkflow] /default_workflow failed validation; using the bundled default:\n${error}` + ) + }) + } catch (error) { + console.warn( + '[defaultWorkflow] could not load /default_workflow; using the bundled default', + error + ) + return null + } +} + +/** + * Loads the backend's default workflow, if it serves one. Safe to call more + * than once - the request is made at most once per page load. Never rejects: + * every failure resolves to the bundled default. + */ +export function initDefaultWorkflow(): Promise { + if (usesLegacyDefaultGraph()) return Promise.resolve() + prefetch ??= fetchDefaultWorkflow().then((workflow) => { + remoteDefaultWorkflow = workflow + }) + return prefetch +} + +/** + * The default workflow: the backend's if {@link initDefaultWorkflow} resolved + * one, otherwise the bundled graph. Callers clone before mutating, as they + * already did when this was a plain import. + */ +export function getDefaultWorkflow(): ComfyWorkflowJSON { + return remoteDefaultWorkflow ?? defaultGraph +} + +/** Test seam: drops the prefetched workflow and lets the request run again. */ +export function resetDefaultWorkflowForTesting(): void { + remoteDefaultWorkflow = null + prefetch = null +} diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index 7cf6a4d41dc..502012b1b8c 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -26,7 +26,8 @@ import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/w // oxlint-disable-next-line comfy/no-restricted-paths import { useWorkflowThumbnail } from '@/renderer/core/thumbnail/useWorkflowThumbnail' import { useApp } from '@/scripts/appInstance' -import { blankGraph, defaultGraph } from '@/scripts/defaultGraph' +import { getDefaultWorkflow } from '@/platform/workflow/core/services/defaultWorkflowService' +import { blankGraph } from '@/scripts/defaultGraph' import { useDialogService } from '@/services/dialogService' import { nodeTypesMayStillArrive } from '@/platform/lateCustomNodes/lateNodeTypes' import { showPlaceholdersAsWaiting } from '@/platform/lateCustomNodes/waitingNodes' @@ -399,7 +400,7 @@ export const useWorkflowService = () => { * Load the default workflow */ const loadDefaultWorkflow = () => - queueWorkflowLoad(() => useApp().loadGraphData(defaultGraph)) + queueWorkflowLoad(() => useApp().loadGraphData(getDefaultWorkflow())) /** * Load a blank workflow diff --git a/src/platform/workflow/management/stores/workflowStore.ts b/src/platform/workflow/management/stores/workflowStore.ts index 34a4a6a6b8d..293918dd8c2 100644 --- a/src/platform/workflow/management/stores/workflowStore.ts +++ b/src/platform/workflow/management/stores/workflowStore.ts @@ -23,7 +23,7 @@ import { useWorkflowThumbnail } from '@/renderer/core/thumbnail/useWorkflowThumb import { api } from '@/scripts/api' import { useApp } from '@/scripts/appInstance' import { ChangeTrackerAccess } from '@/scripts/changeTrackerAccess' -import { defaultGraph } from '@/scripts/defaultGraph' +import { getDefaultWorkflow } from '@/platform/workflow/core/services/defaultWorkflowService' import { useDialogService } from '@/services/dialogService' import { useWidgetHistoryStore } from '@/stores/widgetHistoryStore' import { reportError } from '@/platform/telemetry/reportError' @@ -272,7 +272,9 @@ export const useWorkflowStore = defineStore('workflow', () => { }) workflow.legacyId = getLegacyWorkflowId(workflowData?.id) - const initialWorkflowData = ensureWorkflowId(workflowData ?? defaultGraph) + const initialWorkflowData = ensureWorkflowId( + workflowData ?? getDefaultWorkflow() + ) workflow.originalContent = workflow.content = JSON.stringify(initialWorkflowData) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 17f9f709bd3..2687b990e4d 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -66,6 +66,10 @@ import { MIME_ASSET_INFO } from '@/platform/assets/schemas/mediaAssetSchema' import { restoreDynamicGroupInputs } from '@/platform/workflow/core/utils/restoreDynamicGroupInputs' import { updatePendingWarnings } from '@/platform/workflow/core/utils/pendingWarnings' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' +import { + getDefaultWorkflow, + initDefaultWorkflow +} from '@/platform/workflow/core/services/defaultWorkflowService' import { ComfyWorkflow, useWorkflowStore @@ -188,7 +192,6 @@ import { deserialiseAndCreate } from '@/utils/vintageClipboard' import { PromptExecutionError, api } from './api' import type { ComfyApi } from './api' -import { defaultGraph } from './defaultGraph' import { importA1111 } from './pnginfo' import { applyPromotedWidgetControl } from '@/core/graph/subgraph/promotedWidgetControl' import type { ComfyUI } from './ui' @@ -893,6 +896,11 @@ export class ComfyApp implements IComfyApp { this.canvasElRef.value = canvasEl + // Started here and awaited at the end of setup so the request overlaps the + // rest of boot instead of adding to it. The startup workflow load runs + // after setup returns, so the default is resolved before anything needs it. + const defaultWorkflowReady = initDefaultWorkflow() + await bootstrapTracer.settle('bootstrap/sync-workflows', () => useWorkspaceStore().workflow.syncWorkflows() ) @@ -1001,6 +1009,8 @@ export class ComfyApp implements IComfyApp { useExtensionService().invokeExtensionsAsync('setup') ) + await defaultWorkflowReady + this.positionConversion = useCanvasPositionConversion( this.canvasContainer, this.canvas @@ -1255,7 +1265,7 @@ export class ComfyApp implements IComfyApp { typeof graphData !== 'object' || Array.isArray(graphData) ) { - graphData = defaultGraph + graphData = getDefaultWorkflow() reset_invalid_values = true } From 7a467498ebcd2c0fb2883b31d1c326553bbfdac0 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 29 Oct 2026 20:20:15 +0000 Subject: [PATCH 02/10] fix: bound the default workflow prefetch and report its fallbacks Addresses review feedback on the default workflow route. Bound the whole prefetch, body read included. `fetchApi` clears its timeout once the response arrives, so a backend that sends headers and then stalls mid-body left `res.json()` pending and held the editor closed for as long as the socket lived. On expiry the bundled graph is used and `setup` continues. Route failures other than 404 now go through `reportError` with a distinct `errorType` instead of a console warning, so a core that starts serving a workflow this schema rejects is visible. The 404 stays silent, because that is what every backend older than the route says. Drop the explanatory comments per AGENTS.md: the rationale lives in the ADR, which is updated for both changes. Test fixtures build real `Response` objects rather than casting partials, so the not-JSON case exercises a real parse failure. Drop the redundant `mockReset` calls, which `mockReset: true` in the vitest config already does, and settle the interim-fallback test's promise before it ends so it cannot write service state during a later test. --- ...W-0050-core-serves-the-default-workflow.md | 20 +++-- .../services/defaultWorkflowService.test.ts | 76 +++++++++++------ .../core/services/defaultWorkflowService.ts | 85 +++++++++---------- src/scripts/app.ts | 3 - 4 files changed, 103 insertions(+), 81 deletions(-) diff --git a/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md b/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md index 71b28ac9100..328d15da00e 100644 --- a/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md +++ b/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md @@ -57,7 +57,13 @@ and keeps the bundled graph as the fallback. ComfyUI#16956), a server error, a body that is not JSON, a body that fails `validateComfyWorkflow`, and a failed request all resolve to the bundled graph. Only a 404 is silent, because that is simply what an older backend - says; the rest warn. + says. The rest go through `reportError` with a distinct `errorType`, so a + core that starts serving a workflow this schema rejects is visible. +- The whole prefetch is bounded, body read included, not just the request. + `fetchApi` clears its timeout once the response arrives, so a backend that + sends headers and then stalls mid-body would otherwise leave `res.json()` + pending and hold the editor closed for as long as the socket lives. On expiry + the bundled graph is used and `setup` continues. - Builds with `VITE_USE_LEGACY_DEFAULT_GRAPH=true` skip the request entirely. Those builds run against a real core, so fetching would serve the current default and undo the test pinning that hundreds of specs depend on. The flag @@ -98,16 +104,16 @@ Alternatives considered and rejected: ### Negative - Boot awaits one more request. It is started early and awaited last, so it - adds nothing unless it outlasts the rest of `setup`; on a slow or hanging - backend it delays the editor opening, because there is no timeout of its own - beyond `fetchApi`'s. + adds nothing unless it outlasts the rest of `setup`. A slow backend can still + delay the editor opening by up to the prefetch bound. - The default is now a network-dependent value, so two users on the same frontend build can land on different workflows. That is the point, but it makes "what did the user see" unanswerable from the frontend version alone. - A core that serves a workflow this frontend's schema rejects falls back - silently apart from a console warning. Nothing tells core that its workflow - was refused; a server-side contract test, or a telemetry event on fallback, - is the follow-up. + without telling the user. The fallback is reported, so it is visible in + telemetry rather than only in a console, but nothing tells core at publish + time that its workflow would be refused. A server-side contract test against + this schema is the follow-up. - E2E builds do not exercise the fetch path at all, by construction. The unit tests cover it; no browser test does. - `defaultGraph` remains exported and bundled, so the workflow is still shipped diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index 3a73e7c317b..c6253d32def 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { reportError } from '@/platform/telemetry/reportError' import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' import { api } from '@/scripts/api' import { blankGraph, defaultGraph } from '@/scripts/defaultGraph' @@ -11,33 +12,32 @@ import { } from './defaultWorkflowService' vi.mock(import('@/scripts/api')) +vi.mock(import('@/platform/telemetry/reportError')) const fetchApi = vi.mocked(api.fetchApi) -/** A valid workflow that is not the bundled default, so the two are telling apart. */ const servedWorkflow: ComfyWorkflowJSON = { ...blankGraph, last_node_id: 42 } const jsonResponse = (body: unknown) => - ({ - ok: true, + new Response(JSON.stringify(body), { status: 200, - json: () => Promise.resolve(body) - }) as unknown as Response + headers: { 'Content-Type': 'application/json' } + }) + +const errorResponse = (status: number) => new Response('', { status }) -const errorResponse = (status: number) => - ({ - ok: false, - status, - json: () => Promise.reject(new Error('should not be read')) - }) as unknown as Response +const notJsonResponse = () => + new Response('nope', { + status: 200, + headers: { 'Content-Type': 'text/html' } + }) describe('defaultWorkflowService', () => { beforeEach(() => { resetDefaultWorkflowForTesting() - fetchApi.mockReset() }) it('serves the backend workflow once the route has answered', async () => { @@ -49,12 +49,13 @@ describe('defaultWorkflowService', () => { expect(getDefaultWorkflow()).toEqual(servedWorkflow) }) - it('serves the bundled default until the route has answered', () => { + it('serves the bundled default until the route has answered', async () => { fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) - void initDefaultWorkflow() - + const ready = initDefaultWorkflow() expect(getDefaultWorkflow()).toBe(defaultGraph) + + await ready }) it('falls back to the bundled default on a backend without the route', async () => { @@ -65,42 +66,48 @@ describe('defaultWorkflowService', () => { expect(getDefaultWorkflow()).toBe(defaultGraph) }) - it('does not warn about a 404, which is how older backends answer', async () => { + it('does not report a 404, which is how older backends answer', async () => { fetchApi.mockResolvedValue(errorResponse(404)) await initDefaultWorkflow() - expect(console.warn).not.toHaveBeenCalled() + expect(reportError).not.toHaveBeenCalled() }) - it('falls back to the bundled default on a server error', async () => { + it('reports a server error and falls back to the bundled default', async () => { fetchApi.mockResolvedValue(errorResponse(500)) await initDefaultWorkflow() expect(getDefaultWorkflow()).toBe(defaultGraph) - expect(console.warn).toHaveBeenCalled() + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ errorType: 'DefaultWorkflowRouteUnavailable' }) + ) }) - it('falls back to the bundled default when the route serves an invalid workflow', async () => { + it('reports an invalid workflow and falls back to the bundled default', async () => { fetchApi.mockResolvedValue(jsonResponse({ not: 'a workflow' })) await initDefaultWorkflow() expect(getDefaultWorkflow()).toBe(defaultGraph) - expect(console.warn).toHaveBeenCalled() + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ errorType: 'DefaultWorkflowInvalid' }) + ) }) it('falls back to the bundled default when the body is not JSON', async () => { - fetchApi.mockResolvedValue({ - ok: true, - status: 200, - json: () => Promise.reject(new SyntaxError('Unexpected token <')) - } as unknown as Response) + fetchApi.mockResolvedValue(notJsonResponse()) await initDefaultWorkflow() expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ errorType: 'DefaultWorkflowFetchFailed' }) + ) }) it('falls back to the bundled default when the request fails outright', async () => { @@ -122,13 +129,28 @@ describe('defaultWorkflowService', () => { expect(fetchApi).toHaveBeenCalledTimes(1) }) + + it('opens with the bundled default when the body never arrives', async () => { + vi.useFakeTimers() + fetchApi.mockReturnValue(new Promise(() => {})) + + const ready = initDefaultWorkflow() + await vi.advanceTimersByTimeAsync(10_000) + await ready + + expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) + ) + vi.useRealTimers() + }) }) describe('defaultWorkflowService in e2e builds', () => { beforeEach(() => { resetDefaultWorkflowForTesting() vi.stubEnv('VITE_USE_LEGACY_DEFAULT_GRAPH', 'true') - fetchApi.mockReset() fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) }) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.ts b/src/platform/workflow/core/services/defaultWorkflowService.ts index 0478acbfb2a..0872c7510e7 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.ts @@ -1,68 +1,69 @@ +import { reportError } from '@/platform/telemetry/reportError' import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' import { validateComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' import { api } from '@/scripts/api' import { defaultGraph } from '@/scripts/defaultGraph' -/** - * Resolves the workflow new users land on. - * - * Core owns the default workflow as of ComfyUI#16956, which serves it from - * `GET /default_workflow`. Fetching it here lets core (and cloud) swap the - * default in a one-line `server.py` change instead of waiting on a frontend - * release, and lets each distribution ship a different one - e.g. a model - * desktop pre-bundles, or something that does not assume a local GPU on cloud. - * - * The bundled `defaultGraph` stays as the fallback, so backends predating that - * route (404), offline loads, and malformed responses all keep working. - * - * Resolution is a one-shot prefetch rather than a fetch per use: the three - * places that need a default are synchronous, and core sends - * `Cache-Control: no-cache`, so a reload is what picks up a changed default. - */ +const DEFAULT_WORKFLOW_ROUTE = '/default_workflow' +const PREFETCH_TIMEOUT_MS = 10_000 -/** - * E2E builds pin the default to the bundled legacy graph because hundreds of - * specs assert on its node IDs and positions. Those builds run against a real - * core, so without this the route would serve the current default and undo - * that pinning. See browser_tests/README.md. - */ const usesLegacyDefaultGraph = () => import.meta.env.VITE_USE_LEGACY_DEFAULT_GRAPH === 'true' let remoteDefaultWorkflow: ComfyWorkflowJSON | null = null let prefetch: Promise | null = null -async function fetchDefaultWorkflow(): Promise { +function reportFallback(cause: unknown, errorType: string): void { + reportError(cause, { errorType, surface: 'graph', level: 'warning' }) +} + +async function readDefaultWorkflow(): Promise { try { - const res = await api.fetchApi('/default_workflow') + const res = await api.fetchApi(DEFAULT_WORKFLOW_ROUTE) if (!res.ok) { - // 404 is the expected answer from a backend older than ComfyUI#16956. if (res.status !== 404) { - console.warn( - `[defaultWorkflow] /default_workflow returned ${res.status}; using the bundled default` + reportFallback( + new Error(`${DEFAULT_WORKFLOW_ROUTE} responded ${res.status}`), + 'DefaultWorkflowRouteUnavailable' ) } return null } const json: unknown = await res.json() return await validateComfyWorkflow(json, (error) => { - console.warn( - `[defaultWorkflow] /default_workflow failed validation; using the bundled default:\n${error}` - ) + reportFallback(new Error(error), 'DefaultWorkflowInvalid') }) - } catch (error) { - console.warn( - '[defaultWorkflow] could not load /default_workflow; using the bundled default', - error - ) + } catch (cause) { + reportFallback(cause, 'DefaultWorkflowFetchFailed') return null } } +async function fetchDefaultWorkflow(): Promise { + let timer: ReturnType | undefined + const bound = new Promise((resolve) => { + timer = setTimeout(() => { + reportFallback( + new Error( + `${DEFAULT_WORKFLOW_ROUTE} did not settle within ${PREFETCH_TIMEOUT_MS}ms` + ), + 'DefaultWorkflowTimedOut' + ) + resolve(null) + }, PREFETCH_TIMEOUT_MS) + }) + + try { + return await Promise.race([readDefaultWorkflow(), bound]) + } finally { + clearTimeout(timer) + } +} + /** - * Loads the backend's default workflow, if it serves one. Safe to call more - * than once - the request is made at most once per page load. Never rejects: - * every failure resolves to the bundled default. + * Loads the backend's default workflow, if it serves one. Requests it at most + * once per page load and never rejects: every failure resolves to the bundled + * default. */ export function initDefaultWorkflow(): Promise { if (usesLegacyDefaultGraph()) return Promise.resolve() @@ -72,16 +73,12 @@ export function initDefaultWorkflow(): Promise { return prefetch } -/** - * The default workflow: the backend's if {@link initDefaultWorkflow} resolved - * one, otherwise the bundled graph. Callers clone before mutating, as they - * already did when this was a plain import. - */ +/** The backend's default workflow when one loaded, otherwise the bundled graph. */ export function getDefaultWorkflow(): ComfyWorkflowJSON { return remoteDefaultWorkflow ?? defaultGraph } -/** Test seam: drops the prefetched workflow and lets the request run again. */ +/** Drops the prefetched workflow so the request runs again. */ export function resetDefaultWorkflowForTesting(): void { remoteDefaultWorkflow = null prefetch = null diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 2687b990e4d..6f37936c56a 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -896,9 +896,6 @@ export class ComfyApp implements IComfyApp { this.canvasElRef.value = canvasEl - // Started here and awaited at the end of setup so the request overlaps the - // rest of boot instead of adding to it. The startup workflow load runs - // after setup returns, so the default is resolved before anything needs it. const defaultWorkflowReady = initDefaultWorkflow() await bootstrapTracer.settle('bootstrap/sync-workflows', () => From eaf0c0d3e4236a9106411fa3cabd81c2c3774033 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 29 Oct 2026 20:57:10 +0000 Subject: [PATCH 03/10] fix: follow telemetry and graph-model out of src main extracted `reportError` into `@comfyorg/telemetry` and `workflowSchema` into `@comfyorg/graph-model`. The branch still imported both from their old `src/platform/...` paths, which resolve on the branch alone but not against main, so every job that builds the dist failed on the merge ref with UNLOADABLE_DEPENDENCY while the branch built clean in isolation. Also add `default_workflow` to the fetch telemetry route allowlist, so the new route reports under its own name instead of collapsing into `/other`. --- .../workflow/core/services/defaultWorkflowService.test.ts | 6 +++--- .../workflow/core/services/defaultWorkflowService.ts | 6 +++--- src/utils/fetchRouteTemplate.ts | 1 + 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index c6253d32def..8a3fbb0ae76 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { reportError } from '@/platform/telemetry/reportError' -import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' +import { reportError } from '@comfyorg/telemetry/reportError' +import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema' import { api } from '@/scripts/api' import { blankGraph, defaultGraph } from '@/scripts/defaultGraph' @@ -12,7 +12,7 @@ import { } from './defaultWorkflowService' vi.mock(import('@/scripts/api')) -vi.mock(import('@/platform/telemetry/reportError')) +vi.mock(import('@comfyorg/telemetry/reportError')) const fetchApi = vi.mocked(api.fetchApi) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.ts b/src/platform/workflow/core/services/defaultWorkflowService.ts index 0872c7510e7..e4ceae0904c 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.ts @@ -1,6 +1,6 @@ -import { reportError } from '@/platform/telemetry/reportError' -import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' -import { validateComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' +import { reportError } from '@comfyorg/telemetry/reportError' +import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema' +import { validateComfyWorkflow } from '@comfyorg/graph-model/workflowSchema' import { api } from '@/scripts/api' import { defaultGraph } from '@/scripts/defaultGraph' diff --git a/src/utils/fetchRouteTemplate.ts b/src/utils/fetchRouteTemplate.ts index fe1ee49e206..0386a2152af 100644 --- a/src/utils/fetchRouteTemplate.ts +++ b/src/utils/fetchRouteTemplate.ts @@ -2,6 +2,7 @@ const TELEMETRY_SAFE_ROUTE_GROUPS = new Set([ 'assets', 'billing', 'customers', + 'default_workflow', 'embeddings', 'experiment', 'extensions', From af80d3a0dc55a4750a964995901dfc43e2f54fea Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 29 Oct 2026 21:29:03 +0000 Subject: [PATCH 04/10] fix: keep the default workflow free of a document identity Addresses review on PR 22124. A fetched default may carry an exported workflow UUID: the route's contract permits `id`, core serves the selected file without stripping it, and `ensureWorkflowId` preserves a valid existing id on purpose. Every `createTemporary()` then copied that same id into a different new workflow, so normal new tabs shared a root identity and `openWorkflowPathForGraph` could not attribute a polled run to either one. The default is a template, not a document. `getDefaultWorkflow()` now returns it without an `id`, and `createNewWorkflow` mints a fresh identity when it falls back to the default instead of preserving one. Explicitly supplied or opened workflows keep their ids. Also cover the response-body deadline with a real stalled stream. The previous test left `fetchApi` pending, so a regression that stopped applying the deadline to `Response.json()` survived it. The new row serves real headers over a body stream that never closes, and fails under exactly that mutation. --- ...W-0050-core-serves-the-default-workflow.md | 8 ++++ .../services/defaultWorkflowService.test.ts | 37 ++++++++++++++++++- .../core/services/defaultWorkflowService.ts | 7 +++- .../workflow/core/utils/workflowId.ts | 8 ++++ .../management/stores/workflowStore.test.ts | 22 +++++++++++ .../management/stores/workflowStore.ts | 9 +++-- 6 files changed, 85 insertions(+), 6 deletions(-) diff --git a/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md b/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md index 328d15da00e..d997b9057a3 100644 --- a/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md +++ b/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md @@ -59,6 +59,14 @@ and keeps the bundled graph as the fallback. graph. Only a 404 is silent, because that is simply what an older backend says. The rest go through `reportError` with a distinct `errorType`, so a core that starts serving a workflow this schema rejects is visible. +- The default is a template, not a document, so it carries no workflow `id`. + The schema and the route's contract both permit one, and core serves the + selected file as-is, so a replacement default could ship with an exported + UUID. `getDefaultWorkflow()` strips it, and `createNewWorkflow` mints a fresh + identity whenever it falls back to the default rather than preserving one. + Without both, every new tab would share a root graph id and + `openWorkflowPathForGraph` could not attribute a polled run to a single tab. + Explicitly supplied or opened workflows keep their ids as before. - The whole prefetch is bounded, body read included, not just the request. `fetchApi` clears its timeout once the response arrives, so a backend that sends headers and then stalls mid-body would otherwise leave `res.json()` diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index 8a3fbb0ae76..23805a4582e 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -35,6 +35,12 @@ const notJsonResponse = () => headers: { 'Content-Type': 'text/html' } }) +const stalledBodyResponse = () => + new Response(new ReadableStream({ start() {} }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) + describe('defaultWorkflowService', () => { beforeEach(() => { resetDefaultWorkflowForTesting() @@ -130,7 +136,7 @@ describe('defaultWorkflowService', () => { expect(fetchApi).toHaveBeenCalledTimes(1) }) - it('opens with the bundled default when the body never arrives', async () => { + it('opens with the bundled default when the request never answers', async () => { vi.useFakeTimers() fetchApi.mockReturnValue(new Promise(() => {})) @@ -145,6 +151,35 @@ describe('defaultWorkflowService', () => { ) vi.useRealTimers() }) + + it('opens with the bundled default when headers arrive but the body stalls', async () => { + vi.useFakeTimers() + fetchApi.mockResolvedValue(stalledBodyResponse()) + + const ready = initDefaultWorkflow() + await vi.advanceTimersByTimeAsync(10_000) + await ready + + expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) + ) + vi.useRealTimers() + }) + + it('does not hand a served workflow its own document id to new tabs', async () => { + fetchApi.mockResolvedValue( + jsonResponse({ + ...servedWorkflow, + id: '11111111-1111-4111-8111-111111111111' + }) + ) + + await initDefaultWorkflow() + + expect(getDefaultWorkflow()).not.toHaveProperty('id') + }) }) describe('defaultWorkflowService in e2e builds', () => { diff --git a/src/platform/workflow/core/services/defaultWorkflowService.ts b/src/platform/workflow/core/services/defaultWorkflowService.ts index e4ceae0904c..70ccf3d50a2 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.ts @@ -17,6 +17,10 @@ function reportFallback(cause: unknown, errorType: string): void { reportError(cause, { errorType, surface: 'graph', level: 'warning' }) } +function asTemplate({ id: _documentId, ...workflow }: ComfyWorkflowJSON) { + return workflow +} + async function readDefaultWorkflow(): Promise { try { const res = await api.fetchApi(DEFAULT_WORKFLOW_ROUTE) @@ -30,9 +34,10 @@ async function readDefaultWorkflow(): Promise { return null } const json: unknown = await res.json() - return await validateComfyWorkflow(json, (error) => { + const workflow = await validateComfyWorkflow(json, (error) => { reportFallback(new Error(error), 'DefaultWorkflowInvalid') }) + return workflow && asTemplate(workflow) } catch (cause) { reportFallback(cause, 'DefaultWorkflowFetchFailed') return null diff --git a/src/platform/workflow/core/utils/workflowId.ts b/src/platform/workflow/core/utils/workflowId.ts index 47ec18fef77..21d20607ed4 100644 --- a/src/platform/workflow/core/utils/workflowId.ts +++ b/src/platform/workflow/core/utils/workflowId.ts @@ -26,6 +26,14 @@ export function ensureWorkflowId( } } +/** The same workflow with no document identity, so a caller mints a fresh one. */ +export function withoutWorkflowId({ + id: _documentId, + ...workflowData +}: ComfyWorkflowJSON): ComfyWorkflowJSON { + return workflowData +} + export function areWorkflowIdsEquivalent( existingId: string | undefined, incomingId: string | undefined, diff --git a/src/platform/workflow/management/stores/workflowStore.test.ts b/src/platform/workflow/management/stores/workflowStore.test.ts index 84aa0c74707..60350d8bdef 100644 --- a/src/platform/workflow/management/stores/workflowStore.test.ts +++ b/src/platform/workflow/management/stores/workflowStore.test.ts @@ -17,6 +17,7 @@ import { zComfyWorkflow } from '@comfyorg/graph-model/workflowSchema' import { useWorkflowDraftStoreV2 } from '@/platform/workflow/persistence/stores/workflowDraftStoreV2' import { api } from '@/scripts/api' import { app as comfyApp } from '@/scripts/app' +import { getDefaultWorkflow } from '@/platform/workflow/core/services/defaultWorkflowService' import { defaultGraph, defaultGraphJSON } from '@/scripts/defaultGraph' import '@/scripts/changeTracker' import { useWidgetHistoryStore } from '@/stores/widgetHistoryStore' @@ -35,6 +36,9 @@ import { import { createMockCanvas } from '@/utils/__tests__/canvasTestUtils' vi.mock(import('@/scripts/api')) +vi.mock(import('@/platform/workflow/core/services/defaultWorkflowService'), { + spy: true +}) // Mock comfyApp globally for the store setup vi.mock(import('@/scripts/app'), () => ({ @@ -267,6 +271,24 @@ describe('useWorkflowStore', () => { expect(workflow2.path).toBe('workflows/Unsaved Workflow (2).json') }) + it('gives each default-created workflow its own root graph id', () => { + const servedId = '11111111-1111-4111-8111-111111111111' + vi.mocked(getDefaultWorkflow).mockReturnValue({ + ...defaultGraph, + id: servedId + }) + + const first = store.createTemporary() + const second = store.createTemporary() + + const firstId = JSON.parse(first.content!).id + const secondId = JSON.parse(second.content!).id + + expect(firstId).toBeTruthy() + expect(firstId).not.toBe(servedId) + expect(secondId).not.toBe(firstId) + }) + it('assigns each workflow a stable unique session identity', async () => { const workflow = store.createTemporary() const otherWorkflow = store.createTemporary() diff --git a/src/platform/workflow/management/stores/workflowStore.ts b/src/platform/workflow/management/stores/workflowStore.ts index 13b2c62b345..b9c3479c523 100644 --- a/src/platform/workflow/management/stores/workflowStore.ts +++ b/src/platform/workflow/management/stores/workflowStore.ts @@ -13,7 +13,8 @@ import type { import { areWorkflowIdsEquivalent, ensureWorkflowId, - getLegacyWorkflowId + getLegacyWorkflowId, + withoutWorkflowId } from '@/platform/workflow/core/utils/workflowId' import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema' import { useSettingStore } from '@/platform/settings/settingStore' @@ -275,9 +276,9 @@ export const useWorkflowStore = defineStore('workflow', () => { }) workflow.legacyId = getLegacyWorkflowId(workflowData?.id) - const initialWorkflowData = ensureWorkflowId( - workflowData ?? getDefaultWorkflow() - ) + const initialWorkflowData = workflowData + ? ensureWorkflowId(workflowData) + : ensureWorkflowId(withoutWorkflowId(getDefaultWorkflow())) workflow.originalContent = workflow.content = JSON.stringify(initialWorkflowData) From 34e26de83c274274c8792b114bf9316bd352eb54 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 29 Oct 2026 21:52:06 +0000 Subject: [PATCH 05/10] refactor: strip the default's identity at one read, and test it for real Follow-up review on PR 22124. `asTemplate` ran only on the served workflow, so the bundled fallback branch was still free to carry an `id` if `defaultGraph` ever gained one. Move the strip into `getDefaultWorkflow()`, which covers both sources, and drop the second guard at the creation site: with one strip point it is unreachable, and `withoutWorkflowId` goes with it. Both tests asserted things weaker than they looked. `not.toHaveProperty('id')` also held when the id-bearing response was rejected and the bundled graph was returned, so it never showed the served workflow was selected; it now asserts equality with the served workflow. The store test mocked `getDefaultWorkflow` into returning an id-bearing workflow, a state the real service cannot produce, which pinned the redundant guard rather than user behaviour; it now stubs the route and drives the real service. Removing the strip fails both rows, in the service and through the store. --- ...W-0050-core-serves-the-default-workflow.md | 19 ++++++++------- .../services/defaultWorkflowService.test.ts | 24 +++++++++++-------- .../core/services/defaultWorkflowService.ts | 9 ++++--- .../workflow/core/utils/workflowId.ts | 8 ------- .../management/stores/workflowStore.test.ts | 24 ++++++++++++------- .../management/stores/workflowStore.ts | 9 ++++--- 6 files changed, 50 insertions(+), 43 deletions(-) diff --git a/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md b/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md index d997b9057a3..39beb9e95ed 100644 --- a/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md +++ b/docs/adr/DEFAULT-WORKFLOW-0050-core-serves-the-default-workflow.md @@ -59,14 +59,17 @@ and keeps the bundled graph as the fallback. graph. Only a 404 is silent, because that is simply what an older backend says. The rest go through `reportError` with a distinct `errorType`, so a core that starts serving a workflow this schema rejects is visible. -- The default is a template, not a document, so it carries no workflow `id`. - The schema and the route's contract both permit one, and core serves the - selected file as-is, so a replacement default could ship with an exported - UUID. `getDefaultWorkflow()` strips it, and `createNewWorkflow` mints a fresh - identity whenever it falls back to the default rather than preserving one. - Without both, every new tab would share a root graph id and - `openWorkflowPathForGraph` could not attribute a polled run to a single tab. - Explicitly supplied or opened workflows keep their ids as before. +- The default is a template, not a document, so `getDefaultWorkflow()` never + returns a workflow `id`. The schema and the route's contract both permit one, + and core serves the selected file as-is, so a replacement default could ship + with an exported UUID. `ensureWorkflowId` preserves a valid id on purpose, so + without this every `createTemporary()` would copy that one id into a + different new workflow, leaving new tabs sharing a root graph id and + `openWorkflowPathForGraph` unable to attribute a polled run to a single tab. + The strip lives at that one read, covering the bundled fallback as well as a + served workflow; a second guard at the creation site would be unreachable and + only testable through a state the service cannot produce. Explicitly supplied + or opened workflows keep their ids as before. - The whole prefetch is bounded, body read included, not just the request. `fetchApi` clears its timeout once the response arrives, so a backend that sends headers and then stalls mid-body would otherwise leave `res.json()` diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index 23805a4582e..ecd1edcf069 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -59,7 +59,7 @@ describe('defaultWorkflowService', () => { fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) const ready = initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) await ready }) @@ -69,7 +69,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) }) it('does not report a 404, which is how older backends answer', async () => { @@ -85,7 +85,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowRouteUnavailable' }) @@ -97,7 +97,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowInvalid' }) @@ -109,7 +109,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowFetchFailed' }) @@ -120,7 +120,7 @@ describe('defaultWorkflowService', () => { fetchApi.mockRejectedValue(new TypeError('Failed to fetch')) await expect(initDefaultWorkflow()).resolves.toBeUndefined() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) }) it('requests the workflow at most once per page load', async () => { @@ -144,7 +144,7 @@ describe('defaultWorkflowService', () => { await vi.advanceTimersByTimeAsync(10_000) await ready - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) @@ -160,7 +160,7 @@ describe('defaultWorkflowService', () => { await vi.advanceTimersByTimeAsync(10_000) await ready - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) @@ -168,7 +168,7 @@ describe('defaultWorkflowService', () => { vi.useRealTimers() }) - it('does not hand a served workflow its own document id to new tabs', async () => { + it('serves a workflow that arrived with a document id, without that id', async () => { fetchApi.mockResolvedValue( jsonResponse({ ...servedWorkflow, @@ -178,6 +178,10 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() + expect(getDefaultWorkflow()).toEqual(servedWorkflow) + }) + + it('never exposes a document id, so each caller mints its own', () => { expect(getDefaultWorkflow()).not.toHaveProperty('id') }) }) @@ -193,6 +197,6 @@ describe('defaultWorkflowService in e2e builds', () => { await initDefaultWorkflow() expect(fetchApi).not.toHaveBeenCalled() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) }) }) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.ts b/src/platform/workflow/core/services/defaultWorkflowService.ts index 70ccf3d50a2..ad4c821cdca 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.ts @@ -37,7 +37,7 @@ async function readDefaultWorkflow(): Promise { const workflow = await validateComfyWorkflow(json, (error) => { reportFallback(new Error(error), 'DefaultWorkflowInvalid') }) - return workflow && asTemplate(workflow) + return workflow } catch (cause) { reportFallback(cause, 'DefaultWorkflowFetchFailed') return null @@ -78,9 +78,12 @@ export function initDefaultWorkflow(): Promise { return prefetch } -/** The backend's default workflow when one loaded, otherwise the bundled graph. */ +/** + * The backend's default workflow when one loaded, otherwise the bundled graph. + * Always free of a document identity, so each caller mints its own. + */ export function getDefaultWorkflow(): ComfyWorkflowJSON { - return remoteDefaultWorkflow ?? defaultGraph + return asTemplate(remoteDefaultWorkflow ?? defaultGraph) } /** Drops the prefetched workflow so the request runs again. */ diff --git a/src/platform/workflow/core/utils/workflowId.ts b/src/platform/workflow/core/utils/workflowId.ts index 21d20607ed4..47ec18fef77 100644 --- a/src/platform/workflow/core/utils/workflowId.ts +++ b/src/platform/workflow/core/utils/workflowId.ts @@ -26,14 +26,6 @@ export function ensureWorkflowId( } } -/** The same workflow with no document identity, so a caller mints a fresh one. */ -export function withoutWorkflowId({ - id: _documentId, - ...workflowData -}: ComfyWorkflowJSON): ComfyWorkflowJSON { - return workflowData -} - export function areWorkflowIdsEquivalent( existingId: string | undefined, incomingId: string | undefined, diff --git a/src/platform/workflow/management/stores/workflowStore.test.ts b/src/platform/workflow/management/stores/workflowStore.test.ts index 60350d8bdef..c7dc766378c 100644 --- a/src/platform/workflow/management/stores/workflowStore.test.ts +++ b/src/platform/workflow/management/stores/workflowStore.test.ts @@ -17,7 +17,10 @@ import { zComfyWorkflow } from '@comfyorg/graph-model/workflowSchema' import { useWorkflowDraftStoreV2 } from '@/platform/workflow/persistence/stores/workflowDraftStoreV2' import { api } from '@/scripts/api' import { app as comfyApp } from '@/scripts/app' -import { getDefaultWorkflow } from '@/platform/workflow/core/services/defaultWorkflowService' +import { + initDefaultWorkflow, + resetDefaultWorkflowForTesting +} from '@/platform/workflow/core/services/defaultWorkflowService' import { defaultGraph, defaultGraphJSON } from '@/scripts/defaultGraph' import '@/scripts/changeTracker' import { useWidgetHistoryStore } from '@/stores/widgetHistoryStore' @@ -36,9 +39,6 @@ import { import { createMockCanvas } from '@/utils/__tests__/canvasTestUtils' vi.mock(import('@/scripts/api')) -vi.mock(import('@/platform/workflow/core/services/defaultWorkflowService'), { - spy: true -}) // Mock comfyApp globally for the store setup vi.mock(import('@/scripts/app'), () => ({ @@ -271,12 +271,16 @@ describe('useWorkflowStore', () => { expect(workflow2.path).toBe('workflows/Unsaved Workflow (2).json') }) - it('gives each default-created workflow its own root graph id', () => { + it('gives each default-created workflow its own root graph id', async () => { const servedId = '11111111-1111-4111-8111-111111111111' - vi.mocked(getDefaultWorkflow).mockReturnValue({ - ...defaultGraph, - id: servedId - }) + resetDefaultWorkflowForTesting() + vi.mocked(api.fetchApi).mockResolvedValue( + new Response(JSON.stringify({ ...defaultGraph, id: servedId }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) + ) + await initDefaultWorkflow() const first = store.createTemporary() const second = store.createTemporary() @@ -287,6 +291,8 @@ describe('useWorkflowStore', () => { expect(firstId).toBeTruthy() expect(firstId).not.toBe(servedId) expect(secondId).not.toBe(firstId) + + resetDefaultWorkflowForTesting() }) it('assigns each workflow a stable unique session identity', async () => { diff --git a/src/platform/workflow/management/stores/workflowStore.ts b/src/platform/workflow/management/stores/workflowStore.ts index b9c3479c523..13b2c62b345 100644 --- a/src/platform/workflow/management/stores/workflowStore.ts +++ b/src/platform/workflow/management/stores/workflowStore.ts @@ -13,8 +13,7 @@ import type { import { areWorkflowIdsEquivalent, ensureWorkflowId, - getLegacyWorkflowId, - withoutWorkflowId + getLegacyWorkflowId } from '@/platform/workflow/core/utils/workflowId' import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema' import { useSettingStore } from '@/platform/settings/settingStore' @@ -276,9 +275,9 @@ export const useWorkflowStore = defineStore('workflow', () => { }) workflow.legacyId = getLegacyWorkflowId(workflowData?.id) - const initialWorkflowData = workflowData - ? ensureWorkflowId(workflowData) - : ensureWorkflowId(withoutWorkflowId(getDefaultWorkflow())) + const initialWorkflowData = ensureWorkflowId( + workflowData ?? getDefaultWorkflow() + ) workflow.originalContent = workflow.content = JSON.stringify(initialWorkflowData) From a71ca51aabe88809176ea6d5c7aadb9a99dd9dbc Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 29 Oct 2026 22:54:14 +0000 Subject: [PATCH 06/10] fix: strip only the served default, keeping the bundled one's identity Reverts the strip in `getDefaultWorkflow()` from 34e26de83c. Returning `asTemplate(...)` built a new object on every read, and `workflowService.test.ts` keys its `loadGraphData` mock on `data === defaultGraph`, so the fallback workflow was never activated and the user activation assertion failed. The neighbouring `toHaveBeenCalledWith` passed because it compares deeply, which hid the cause. The strip is back on the served workflow only, so the bundled default is returned by reference as before. No production code compares it by identity; that mock is the only reader that does, and it is a reasonable thing to rely on. The bundled branch is covered by pinning the invariant it depends on instead: `defaultGraph` carries no document id. That is an in-repo constant, so a test is the right guard, and it fails loudly if anyone adds one. --- .../services/defaultWorkflowService.test.ts | 21 ++++++++++--------- .../core/services/defaultWorkflowService.ts | 9 +++----- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index ecd1edcf069..65762bd3af6 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -59,7 +59,7 @@ describe('defaultWorkflowService', () => { fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) const ready = initDefaultWorkflow() - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) await ready }) @@ -69,7 +69,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) }) it('does not report a 404, which is how older backends answer', async () => { @@ -85,7 +85,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowRouteUnavailable' }) @@ -97,7 +97,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowInvalid' }) @@ -109,7 +109,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowFetchFailed' }) @@ -120,7 +120,7 @@ describe('defaultWorkflowService', () => { fetchApi.mockRejectedValue(new TypeError('Failed to fetch')) await expect(initDefaultWorkflow()).resolves.toBeUndefined() - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) }) it('requests the workflow at most once per page load', async () => { @@ -144,7 +144,7 @@ describe('defaultWorkflowService', () => { await vi.advanceTimersByTimeAsync(10_000) await ready - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) @@ -160,7 +160,7 @@ describe('defaultWorkflowService', () => { await vi.advanceTimersByTimeAsync(10_000) await ready - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) @@ -181,7 +181,8 @@ describe('defaultWorkflowService', () => { expect(getDefaultWorkflow()).toEqual(servedWorkflow) }) - it('never exposes a document id, so each caller mints its own', () => { + it('ships a bundled default with no document id of its own', () => { + expect(defaultGraph).not.toHaveProperty('id') expect(getDefaultWorkflow()).not.toHaveProperty('id') }) }) @@ -197,6 +198,6 @@ describe('defaultWorkflowService in e2e builds', () => { await initDefaultWorkflow() expect(fetchApi).not.toHaveBeenCalled() - expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(getDefaultWorkflow()).toBe(defaultGraph) }) }) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.ts b/src/platform/workflow/core/services/defaultWorkflowService.ts index ad4c821cdca..70ccf3d50a2 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.ts @@ -37,7 +37,7 @@ async function readDefaultWorkflow(): Promise { const workflow = await validateComfyWorkflow(json, (error) => { reportFallback(new Error(error), 'DefaultWorkflowInvalid') }) - return workflow + return workflow && asTemplate(workflow) } catch (cause) { reportFallback(cause, 'DefaultWorkflowFetchFailed') return null @@ -78,12 +78,9 @@ export function initDefaultWorkflow(): Promise { return prefetch } -/** - * The backend's default workflow when one loaded, otherwise the bundled graph. - * Always free of a document identity, so each caller mints its own. - */ +/** The backend's default workflow when one loaded, otherwise the bundled graph. */ export function getDefaultWorkflow(): ComfyWorkflowJSON { - return asTemplate(remoteDefaultWorkflow ?? defaultGraph) + return remoteDefaultWorkflow ?? defaultGraph } /** Drops the prefetched workflow so the request runs again. */ From 68b1588fb9a23bcd794332aaf7a17ad136cdc33f Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 29 Oct 2026 23:30:16 +0000 Subject: [PATCH 07/10] fix: match the default by content in the close-workflow fixture Reverts a71ca51a and takes the review's approach instead. a71ca51a kept `getDefaultWorkflow()` returning the bundled object by reference so that `workflowService.test.ts`'s `data === defaultGraph` mock kept matching. That preserved a fixture's identity assumption at the cost of the template boundary, and left the bundled branch unstripped. Keep the single strip in `getDefaultWorkflow()` and fix the fixture: the close workflow double now recognises the default by content through `isDefaultWorkflow`, so it no longer depends on the default being one stable object. Every activation assertion in that test is unchanged. Removing the central strip fails both retained regressions, in the service and through the store. --- .../services/defaultWorkflowService.test.ts | 21 +++++++++---------- .../core/services/defaultWorkflowService.ts | 9 +++++--- .../core/services/workflowService.test.ts | 6 +++++- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index 65762bd3af6..ecd1edcf069 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -59,7 +59,7 @@ describe('defaultWorkflowService', () => { fetchApi.mockResolvedValue(jsonResponse(servedWorkflow)) const ready = initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) await ready }) @@ -69,7 +69,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) }) it('does not report a 404, which is how older backends answer', async () => { @@ -85,7 +85,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowRouteUnavailable' }) @@ -97,7 +97,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowInvalid' }) @@ -109,7 +109,7 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowFetchFailed' }) @@ -120,7 +120,7 @@ describe('defaultWorkflowService', () => { fetchApi.mockRejectedValue(new TypeError('Failed to fetch')) await expect(initDefaultWorkflow()).resolves.toBeUndefined() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) }) it('requests the workflow at most once per page load', async () => { @@ -144,7 +144,7 @@ describe('defaultWorkflowService', () => { await vi.advanceTimersByTimeAsync(10_000) await ready - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) @@ -160,7 +160,7 @@ describe('defaultWorkflowService', () => { await vi.advanceTimersByTimeAsync(10_000) await ready - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) @@ -181,8 +181,7 @@ describe('defaultWorkflowService', () => { expect(getDefaultWorkflow()).toEqual(servedWorkflow) }) - it('ships a bundled default with no document id of its own', () => { - expect(defaultGraph).not.toHaveProperty('id') + it('never exposes a document id, so each caller mints its own', () => { expect(getDefaultWorkflow()).not.toHaveProperty('id') }) }) @@ -198,6 +197,6 @@ describe('defaultWorkflowService in e2e builds', () => { await initDefaultWorkflow() expect(fetchApi).not.toHaveBeenCalled() - expect(getDefaultWorkflow()).toBe(defaultGraph) + expect(getDefaultWorkflow()).toEqual(defaultGraph) }) }) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.ts b/src/platform/workflow/core/services/defaultWorkflowService.ts index 70ccf3d50a2..ad4c821cdca 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.ts @@ -37,7 +37,7 @@ async function readDefaultWorkflow(): Promise { const workflow = await validateComfyWorkflow(json, (error) => { reportFallback(new Error(error), 'DefaultWorkflowInvalid') }) - return workflow && asTemplate(workflow) + return workflow } catch (cause) { reportFallback(cause, 'DefaultWorkflowFetchFailed') return null @@ -78,9 +78,12 @@ export function initDefaultWorkflow(): Promise { return prefetch } -/** The backend's default workflow when one loaded, otherwise the bundled graph. */ +/** + * The backend's default workflow when one loaded, otherwise the bundled graph. + * Always free of a document identity, so each caller mints its own. + */ export function getDefaultWorkflow(): ComfyWorkflowJSON { - return remoteDefaultWorkflow ?? defaultGraph + return asTemplate(remoteDefaultWorkflow ?? defaultGraph) } /** Drops the prefetched workflow so the request runs again. */ diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 4c962fd9de3..02874f83069 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -20,6 +20,7 @@ import { } from '@/platform/workflow/management/stores/comfyWorkflow' import { useSettingStore } from '@/platform/settings/settingStore' import { defaultGraph } from '@/scripts/defaultGraph' +import { getDefaultWorkflow } from '@/platform/workflow/core/services/defaultWorkflowService' import { useToast } from '@/components/ui/toast/toastStore' import type { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' @@ -52,6 +53,9 @@ beforeEach(() => { stubFirebaseAuthHarness() }) +const isDefaultWorkflow = (data: unknown) => + JSON.stringify(data) === JSON.stringify(getDefaultWorkflow()) + function createModeTestWorkflow( options: { path?: string @@ -2104,7 +2108,7 @@ describe('useWorkflowService', () => { path: 'Unsaved Workflow.json' }) vi.mocked(app.loadGraphData).mockImplementation(async (data) => { - if (data === defaultGraph) + if (isDefaultWorkflow(data)) useWorkflowStore().activeWorkflow = fallback as LoadedComfyWorkflow return true }) From 4924afeb1f7764df33c3b26c98fe9d5b1fb9d042 Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 30 Oct 2026 01:18:48 +0000 Subject: [PATCH 08/10] fix: snake_case the telemetry slugs and abort a stalled prefetch Addresses the remaining review threads on PR 22124. The four `errorType` values were PascalCase. Every existing slug in the repo is snake_case and they land as the native RUM `error.type`, so these would have been permanent one-offs. Renamed, with their test expectations. The prefetch deadline let setup continue but left the response body pending, because `api.fetchApi` clears its own timeout once headers arrive. The request now carries an `AbortSignal` that the deadline aborts, and a failure we caused that way is not reported as a fetch failure. Removing the abort fails the new regression; it passed all 14 rows before that test existed. Also per the repo's conventions and to stop two tests passing for the wrong reason: `usesLegacyDefaultGraph`, the three response fixtures and `isDefaultWorkflow` are function declarations; the store's served fixture carries a distinguishing `last_node_id` so it cannot pass through the bundled fallback; and the service reset is registered with `onTestFinished` so a failed assertion still restores module state. --- .../services/defaultWorkflowService.test.ts | 55 ++++++++++++++----- .../core/services/defaultWorkflowService.ts | 36 +++++++----- .../core/services/workflowService.test.ts | 5 +- .../management/stores/workflowStore.test.ts | 39 ++++++++----- 4 files changed, 90 insertions(+), 45 deletions(-) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index ecd1edcf069..5ab2e5eabcb 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -16,30 +16,37 @@ vi.mock(import('@comfyorg/telemetry/reportError')) const fetchApi = vi.mocked(api.fetchApi) +const PREFETCH_TIMEOUT_MS = 10_000 + const servedWorkflow: ComfyWorkflowJSON = { ...blankGraph, last_node_id: 42 } -const jsonResponse = (body: unknown) => - new Response(JSON.stringify(body), { +function jsonResponse(body: unknown): Response { + return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } }) +} -const errorResponse = (status: number) => new Response('', { status }) +function errorResponse(status: number): Response { + return new Response('', { status }) +} -const notJsonResponse = () => - new Response('nope', { +function notJsonResponse(): Response { + return new Response('nope', { status: 200, headers: { 'Content-Type': 'text/html' } }) +} -const stalledBodyResponse = () => - new Response(new ReadableStream({ start() {} }), { +function stalledBodyResponse(): Response { + return new Response(new ReadableStream({ start() {} }), { status: 200, headers: { 'Content-Type': 'application/json' } }) +} describe('defaultWorkflowService', () => { beforeEach(() => { @@ -51,7 +58,10 @@ describe('defaultWorkflowService', () => { await initDefaultWorkflow() - expect(fetchApi).toHaveBeenCalledWith('/default_workflow') + expect(fetchApi).toHaveBeenCalledWith( + '/default_workflow', + expect.objectContaining({ signal: expect.any(AbortSignal) }) + ) expect(getDefaultWorkflow()).toEqual(servedWorkflow) }) @@ -88,7 +98,9 @@ describe('defaultWorkflowService', () => { expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), - expect.objectContaining({ errorType: 'DefaultWorkflowRouteUnavailable' }) + expect.objectContaining({ + errorType: 'default_workflow_route_unavailable' + }) ) }) @@ -100,7 +112,7 @@ describe('defaultWorkflowService', () => { expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), - expect.objectContaining({ errorType: 'DefaultWorkflowInvalid' }) + expect.objectContaining({ errorType: 'default_workflow_invalid' }) ) }) @@ -112,7 +124,7 @@ describe('defaultWorkflowService', () => { expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), - expect.objectContaining({ errorType: 'DefaultWorkflowFetchFailed' }) + expect.objectContaining({ errorType: 'default_workflow_fetch_failed' }) ) }) @@ -141,13 +153,13 @@ describe('defaultWorkflowService', () => { fetchApi.mockReturnValue(new Promise(() => {})) const ready = initDefaultWorkflow() - await vi.advanceTimersByTimeAsync(10_000) + await vi.advanceTimersByTimeAsync(PREFETCH_TIMEOUT_MS) await ready expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), - expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) + expect.objectContaining({ errorType: 'default_workflow_timed_out' }) ) vi.useRealTimers() }) @@ -157,17 +169,30 @@ describe('defaultWorkflowService', () => { fetchApi.mockResolvedValue(stalledBodyResponse()) const ready = initDefaultWorkflow() - await vi.advanceTimersByTimeAsync(10_000) + await vi.advanceTimersByTimeAsync(PREFETCH_TIMEOUT_MS) await ready expect(getDefaultWorkflow()).toEqual(defaultGraph) expect(reportError).toHaveBeenCalledWith( expect.any(Error), - expect.objectContaining({ errorType: 'DefaultWorkflowTimedOut' }) + expect.objectContaining({ errorType: 'default_workflow_timed_out' }) ) vi.useRealTimers() }) + it('aborts a stalled request instead of leaving its body pending', async () => { + vi.useFakeTimers() + fetchApi.mockResolvedValue(stalledBodyResponse()) + + const ready = initDefaultWorkflow() + await vi.advanceTimersByTimeAsync(PREFETCH_TIMEOUT_MS) + await ready + + const [, options] = fetchApi.mock.calls[0] ?? [] + expect(options?.signal?.aborted).toBe(true) + vi.useRealTimers() + }) + it('serves a workflow that arrived with a document id, without that id', async () => { fetchApi.mockResolvedValue( jsonResponse({ diff --git a/src/platform/workflow/core/services/defaultWorkflowService.ts b/src/platform/workflow/core/services/defaultWorkflowService.ts index ad4c821cdca..d6427deda7c 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.ts @@ -1,14 +1,16 @@ -import { reportError } from '@comfyorg/telemetry/reportError' import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema' import { validateComfyWorkflow } from '@comfyorg/graph-model/workflowSchema' +import { reportError } from '@comfyorg/telemetry/reportError' + import { api } from '@/scripts/api' import { defaultGraph } from '@/scripts/defaultGraph' const DEFAULT_WORKFLOW_ROUTE = '/default_workflow' const PREFETCH_TIMEOUT_MS = 10_000 -const usesLegacyDefaultGraph = () => - import.meta.env.VITE_USE_LEGACY_DEFAULT_GRAPH === 'true' +function usesLegacyDefaultGraph(): boolean { + return import.meta.env.VITE_USE_LEGACY_DEFAULT_GRAPH === 'true' +} let remoteDefaultWorkflow: ComfyWorkflowJSON | null = null let prefetch: Promise | null = null @@ -17,34 +19,41 @@ function reportFallback(cause: unknown, errorType: string): void { reportError(cause, { errorType, surface: 'graph', level: 'warning' }) } -function asTemplate({ id: _documentId, ...workflow }: ComfyWorkflowJSON) { +function asTemplate({ + id: _documentId, + ...workflow +}: ComfyWorkflowJSON): ComfyWorkflowJSON { return workflow } -async function readDefaultWorkflow(): Promise { +async function readDefaultWorkflow( + signal: AbortSignal +): Promise { try { - const res = await api.fetchApi(DEFAULT_WORKFLOW_ROUTE) + const res = await api.fetchApi(DEFAULT_WORKFLOW_ROUTE, { signal }) if (!res.ok) { if (res.status !== 404) { reportFallback( new Error(`${DEFAULT_WORKFLOW_ROUTE} responded ${res.status}`), - 'DefaultWorkflowRouteUnavailable' + 'default_workflow_route_unavailable' ) } return null } const json: unknown = await res.json() - const workflow = await validateComfyWorkflow(json, (error) => { - reportFallback(new Error(error), 'DefaultWorkflowInvalid') + return await validateComfyWorkflow(json, (error) => { + reportFallback(new Error(error), 'default_workflow_invalid') }) - return workflow } catch (cause) { - reportFallback(cause, 'DefaultWorkflowFetchFailed') + if (!signal.aborted) { + reportFallback(cause, 'default_workflow_fetch_failed') + } return null } } async function fetchDefaultWorkflow(): Promise { + const controller = new AbortController() let timer: ReturnType | undefined const bound = new Promise((resolve) => { timer = setTimeout(() => { @@ -52,14 +61,15 @@ async function fetchDefaultWorkflow(): Promise { new Error( `${DEFAULT_WORKFLOW_ROUTE} did not settle within ${PREFETCH_TIMEOUT_MS}ms` ), - 'DefaultWorkflowTimedOut' + 'default_workflow_timed_out' ) + controller.abort() resolve(null) }, PREFETCH_TIMEOUT_MS) }) try { - return await Promise.race([readDefaultWorkflow(), bound]) + return await Promise.race([readDefaultWorkflow(controller.signal), bound]) } finally { clearTimeout(timer) } diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 02874f83069..ab67120dd2a 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -53,8 +53,9 @@ beforeEach(() => { stubFirebaseAuthHarness() }) -const isDefaultWorkflow = (data: unknown) => - JSON.stringify(data) === JSON.stringify(getDefaultWorkflow()) +function isDefaultWorkflow(data: unknown): boolean { + return JSON.stringify(data) === JSON.stringify(getDefaultWorkflow()) +} function createModeTestWorkflow( options: { diff --git a/src/platform/workflow/management/stores/workflowStore.test.ts b/src/platform/workflow/management/stores/workflowStore.test.ts index c7dc766378c..11e33c44ef8 100644 --- a/src/platform/workflow/management/stores/workflowStore.test.ts +++ b/src/platform/workflow/management/stores/workflowStore.test.ts @@ -1,4 +1,12 @@ -import { assert, beforeEach, describe, expect, it, vi } from 'vitest' +import { + assert, + beforeEach, + describe, + expect, + it, + onTestFinished, + vi +} from 'vitest' import { fromAny, fromPartial } from '@total-typescript/shoehorn' import { nextTick, reactive } from 'vue' @@ -273,26 +281,27 @@ describe('useWorkflowStore', () => { it('gives each default-created workflow its own root graph id', async () => { const servedId = '11111111-1111-4111-8111-111111111111' + onTestFinished(resetDefaultWorkflowForTesting) resetDefaultWorkflowForTesting() vi.mocked(api.fetchApi).mockResolvedValue( - new Response(JSON.stringify({ ...defaultGraph, id: servedId }), { - status: 200, - headers: { 'Content-Type': 'application/json' } - }) + new Response( + JSON.stringify({ + ...defaultGraph, + id: servedId, + last_node_id: 4242 + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ) ) await initDefaultWorkflow() - const first = store.createTemporary() - const second = store.createTemporary() + const first = JSON.parse(store.createTemporary().content!) + const second = JSON.parse(store.createTemporary().content!) - const firstId = JSON.parse(first.content!).id - const secondId = JSON.parse(second.content!).id - - expect(firstId).toBeTruthy() - expect(firstId).not.toBe(servedId) - expect(secondId).not.toBe(firstId) - - resetDefaultWorkflowForTesting() + expect(first.last_node_id).toBe(4242) + expect(first.id).toBeTruthy() + expect(first.id).not.toBe(servedId) + expect(second.id).not.toBe(first.id) }) it('assigns each workflow a stable unique session identity', async () => { From 2f207ec24282e9afb0c8089c97b8a7a1998773ec Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 30 Oct 2026 01:28:44 -0700 Subject: [PATCH 09/10] test: pin the timeout report to one when the abort rejects the body Addresses dante01yoon's non-blocking review suggestion on #22124: the retained cancellation case used a stalled mock that never reacts to cancellation, so the new `if (!signal.aborted)` guard was unpinned. This case errors the response stream on abort, as fetch does, and asserts exactly one report. Red without the guard (a second default_workflow_fetch_failed), green with it. --- .../services/defaultWorkflowService.test.ts | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index 5ab2e5eabcb..4ceaadf34ab 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -48,6 +48,28 @@ function stalledBodyResponse(): Response { }) } +/** A stalled body that errors once the request is aborted, as fetch does. */ +function abortingBodyResponse(signal: AbortSignal): Response { + return new Response( + new ReadableStream({ + start(controller) { + signal.addEventListener('abort', () => { + controller.error( + new DOMException('The operation was aborted.', 'AbortError') + ) + }) + } + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ) +} + +function reportedErrorTypes(): unknown[] { + return vi + .mocked(reportError) + .mock.calls.map(([, context]) => context.errorType) +} + describe('defaultWorkflowService', () => { beforeEach(() => { resetDefaultWorkflowForTesting() @@ -193,6 +215,22 @@ describe('defaultWorkflowService', () => { vi.useRealTimers() }) + it('reports the timeout once when the abort makes the body reject', async () => { + vi.useFakeTimers() + fetchApi.mockImplementation((_route, options) => + Promise.resolve(abortingBodyResponse(options!.signal!)) + ) + + const ready = initDefaultWorkflow() + await vi.advanceTimersByTimeAsync(PREFETCH_TIMEOUT_MS) + await ready + await vi.advanceTimersByTimeAsync(0) + + expect(getDefaultWorkflow()).toEqual(defaultGraph) + expect(reportedErrorTypes()).toEqual(['default_workflow_timed_out']) + vi.useRealTimers() + }) + it('serves a workflow that arrived with a document id, without that id', async () => { fetchApi.mockResolvedValue( jsonResponse({ From cb198bc76752a4e1c43cf450e687c0d3e7e6edca Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 30 Oct 2026 01:57:21 -0700 Subject: [PATCH 10/10] test: drop the comment on the private abort-body helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Repository conformance, per docs/guidance/engineering.md:60 — only curt JSDoc on an exported API is allowed, and abortingBodyResponse is module private, so the rationale belongs here instead. The rationale it carried: abortingBodyResponse returns a real Response over a ReadableStream that errors with an AbortError once the passed signal aborts, which is what fetch does to an in-flight body. The previous stalled mock never reacted to cancellation, so the if (!signal.aborted) guard in readDefaultWorkflow was unpinned — removing the guard left the retained suite green. With this case, removing it fails that row alone with a second default_workflow_fetch_failed report beside the timeout. --- .../workflow/core/services/defaultWorkflowService.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/platform/workflow/core/services/defaultWorkflowService.test.ts b/src/platform/workflow/core/services/defaultWorkflowService.test.ts index 4ceaadf34ab..b958459cec2 100644 --- a/src/platform/workflow/core/services/defaultWorkflowService.test.ts +++ b/src/platform/workflow/core/services/defaultWorkflowService.test.ts @@ -48,7 +48,6 @@ function stalledBodyResponse(): Response { }) } -/** A stalled body that errors once the request is aborted, as fetch does. */ function abortingBodyResponse(signal: AbortSignal): Response { return new Response( new ReadableStream({