From 52cc35e536a453b292e078a104f127aa4c6ba642 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 26 Oct 2026 13:31:15 -0700 Subject: [PATCH 01/13] test(execution): cover the workflow ownership gate belongsToActiveWorkflow arrived in #21666 with no unit test, and the existing executionStore fixtures carry no instanceId, so nothing exercised the instance leg at all. Six cases, one per branch, each verified by mutation: removing the instance comparison fails two, making the activeJobId fallback permissive fails one, inverting the no-prompt_id case fails one, and a gate that rejects everything fails four. Two fixtures deliberately share a graph id, which is what copy-pasting a workflow into a new tab produces, so the suite would catch a gate that tried to separate tabs by workflow id. --- .../executionStore.workflowOwnership.test.ts | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 src/stores/executionStore.workflowOwnership.test.ts diff --git a/src/stores/executionStore.workflowOwnership.test.ts b/src/stores/executionStore.workflowOwnership.test.ts new file mode 100644 index 00000000000..69b76ce2258 --- /dev/null +++ b/src/stores/executionStore.workflowOwnership.test.ts @@ -0,0 +1,106 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' +import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' +import { api } from '@/scripts/api' +import { useExecutionStore } from '@/stores/executionStore' + +vi.mock(import('@/composables/useAppMode')) +vi.mock(import('@/platform/telemetry')) +vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) + +const apiEvents: EventTarget = api + +/** + * `instanceId` is the only identifier unique per open tab. A workflow id is + * shared by every copy of a graph, and a path is shared by a workflow reopened + * in a second tab, so neither can decide which tab a frame belongs to. + */ +function workflow(path: string): LoadedComfyWorkflow { + return fromPartial({ + path, + instanceId: `instance-${path}`, + activeState: { id: 'shared-graph-id' }, + initialState: { id: 'shared-graph-id' } + }) +} + +const workflowA = workflow('workflows/a.json') +const workflowB = workflow('workflows/b.json') + +function promptNode() { + return { inputs: {}, class_type: 'TestNode', _meta: { title: 'Node' } } +} + +describe('executionStore workflow ownership', () => { + let store: ReturnType + + beforeEach(() => { + const workflowStore = useWorkflowStore() + Object.assign(workflowStore, { openWorkflows: [workflowA, workflowB] }) + workflowStore.activeWorkflow = workflowA + store = useExecutionStore() + store.bindExecutionEvents() + }) + + /** Queue a job from `wf`, which is what records its owning tab. */ + function queueJobFrom(jobId: string, wf: LoadedComfyWorkflow) { + store.storeJob({ + nodes: ['1'], + id: jobId, + promptOutput: { '1': promptNode() }, + workflow: wf, + mode: 'graph' + }) + } + + function fire(event: string, detail: Record) { + apiEvents.dispatchEvent(new CustomEvent(event, { detail })) + } + + it('rejects a frame owned by another open tab', () => { + queueJobFrom('job-b', workflowB) + + expect(store.belongsToActiveWorkflow('job-b')).toBe(false) + }) + + it('accepts the visible tab own frame', () => { + queueJobFrom('job-a', workflowA) + + expect(store.belongsToActiveWorkflow('job-a')).toBe(true) + }) + + it('does not separate two tabs by their shared graph id', () => { + // Both fixtures carry 'shared-graph-id', which is what a copy-paste into a + // new tab produces. The gate must still tell them apart. + queueJobFrom('job-a', workflowA) + queueJobFrom('job-b', workflowB) + + expect(store.belongsToActiveWorkflow('job-a')).toBe(true) + expect(store.belongsToActiveWorkflow('job-b')).toBe(false) + }) + + describe('a job whose owning tab is unknown', () => { + it('is accepted while nothing else is running', () => { + expect(store.belongsToActiveWorkflow('job-from-a-previous-page')).toBe( + true + ) + }) + + it('is rejected while another job is active', () => { + queueJobFrom('job-a', workflowA) + fire('execution_start', { prompt_id: 'job-a', timestamp: 1 }) + expect(store.activeJobId).toBe('job-a') + + expect(store.belongsToActiveWorkflow('job-from-a-previous-page')).toBe( + false + ) + }) + }) + + it('accepts a frame that names no job at all', () => { + // `status` frames carry no prompt_id, so there is nothing to attribute. + expect(store.belongsToActiveWorkflow(undefined)).toBe(true) + }) +}) From 896c87d74a6ea12defc1d3b0b2ea823705d3db89 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 26 Oct 2026 13:37:27 -0700 Subject: [PATCH 02/13] feat(execution): send the workflow id and use it to place unmapped jobs ComfyUI#16763 and #16809 shipped a contract the frontend never used: queuePrompt sends no workflow_metadata, so the server has nothing to stamp beyond the id inside extra_pnginfo. This sends it, and reads what comes back. The gate gains two legs below instanceId. The session path places a job whose tab instance is unknown, and the frame's own workflow id places one no per-tab mapping knows about at all: queued before a page reload, or by another client. That last case is what the wire contract buys, and it is the gap instanceId alone cannot close. The graph id stays the weakest leg on purpose. Every copy of a workflow shares it, so copy-paste into a new tab gives two tabs one id, and keying on it first would make each match the other's jobs. The all-zero UUID is discarded rather than compared, on both sides. It is LGraph._id's default and the codebase reads it as 'no id yet', so comparing it as a real id matched nothing and rejected a fresh graph's own frames. Withholding it from the request does not keep it off the wire, because the server falls back to extra_pnginfo. Each leg has its own falsifier: removing the path leg fails two tests, removing the workflow-id leg fails one, removing the sentinel discard fails one. Also wrapped a findLast(belongsToActiveWorkflow) callback, which would otherwise have passed the array index as a workflow id. --- src/scripts/api.ts | 30 +++++++++ src/stores/executionStore.ts | 66 +++++++++++++++++-- .../executionStore.workflowOwnership.test.ts | 59 +++++++++++++++++ 3 files changed, 149 insertions(+), 6 deletions(-) diff --git a/src/scripts/api.ts b/src/scripts/api.ts index a6a42125478..ebf697d09f1 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -84,6 +84,7 @@ import type { import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import type { AuthCredential, AuthScheme } from '@/types/authTypes' import type { NodeExecutionId } from '@/types/nodeIdentification' +import { zeroUuid } from '@/utils/uuid' import { fetchHistory, fetchJobAssets, @@ -97,6 +98,25 @@ interface QueuePromptRequestBody { client_id: string prompt: ComfyApiWorkflow partial_execution_targets?: NodeExecutionId[] + /** + * Echoed back by the server on every WebSocket frame this prompt produces + * that carries a `prompt_id` (ComfyUI#16763 for JSON frames, #16809 for the + * metadata header on binary previews). An older server ignores the field + * rather than rejecting the prompt. + * + * Two limits, since the contract is the server's and not ours. `status` and + * `logs` frames have no `prompt_id`, so they are never stamped. And a value + * the server cannot use is dropped rather than rejected: over 256 characters + * of its own JSON serialisation, with non-ASCII escaped to `\\uXXXX` first. + * The server then falls back to `extra_data.extra_pnginfo.workflow.id`, so + * omitting this field does not keep frames unstamped. + * + * Cloud does not read this field: its gateway stamps `workflow_id` from + * `extra_pnginfo.workflow.id` and assigns the routing ids after the frame's + * own fields, where core lets the frame's fields win. Treat the ids that + * arrive as authoritative either way. + */ + workflow_metadata?: { workflow_id: string } extra_data: { extra_pnginfo: { workflow: ComfyWorkflowJSON @@ -1354,6 +1374,16 @@ export class ComfyApi extends EventTarget { ...(options?.partialExecutionTargets && { partial_execution_targets: options.partialExecutionTargets }), + // `LGraph.serialize()` returns `id` unfiltered and `LGraph._id` defaults + // to the all-zero sentinel, which the codebase reads as "no id yet" and + // replaces on configure and on clear, so it is not a routing key and is + // not sent as one. This does not keep it off the wire: the same graph + // goes out under `extra_pnginfo` and the server falls back to the id + // there, which is why the store also discards the sentinel on the way in. + ...(workflow.id && + workflow.id !== zeroUuid && { + workflow_metadata: { workflow_id: workflow.id } + }), extra_data: { auth_token_comfy_org: this.authToken, api_key_comfy_org: this.apiKey, diff --git a/src/stores/executionStore.ts b/src/stores/executionStore.ts index 3abc84622eb..d0b1d23be33 100644 --- a/src/stores/executionStore.ts +++ b/src/stores/executionStore.ts @@ -40,6 +40,7 @@ import { tryNormalizeNodeExecutionId } from '@/types/nodeIdentification' import type { NodeLocatorId } from '@/types/nodeIdentification' import type { AppMode } from '@/utils/appMode' import { isAppModeValue } from '@/utils/appMode' +import { zeroUuid } from '@/utils/uuid' import { classifyCloudValidationError } from '@/utils/executionErrorUtil' import { executionIdToNodeLocatorId } from '@/utils/graphTraversalUtil' import { createRafCoalescer } from '@/utils/rafBatch' @@ -482,14 +483,63 @@ export const useExecutionStore = defineStore('execution', () => { * Whether frames for this job may paint the active workflow's canvas. * Jobs whose owner is unknown are admitted unless another job is active. */ - function belongsToActiveWorkflow(jobId: JobId | undefined): boolean { + /** + * The all-zero sentinel is `LGraph._id`'s default, which the codebase reads + * as "no id yet" and replaces on configure and on clear. Comparing it as a + * real id matches nothing, which rejected a fresh graph's own frames. It + * reaches the wire regardless, because the server falls back to the id inside + * `extra_pnginfo.workflow`. + */ + function workflowIdOrUndefined(id: string | undefined): string | undefined { + return !id || id === zeroUuid ? undefined : id + } + + /** + * Resolution order, strongest first. `instanceId` is the only identifier + * unique per open tab. The session path is next, since a path identifies one + * open workflow. The frame's own `workflow_id` is weakest, because every copy + * of a graph shares it, so it can only place a job no per-tab mapping knows + * about: one queued before a page reload, or by another client. + * + * @param workflowId The id the server stamped on the frame, where it sends + * one. Absent on a backend without ComfyUI#16763, and on frames with no + * `prompt_id`. + */ + function belongsToActiveWorkflow( + jobId: JobId | undefined, + workflowId?: string + ): boolean { if (!jobId) return true + + const ownedByActiveJob = () => + !activeJobId.value || jobId === activeJobId.value + + const activeWorkflow = workflowStore.activeWorkflow + if (!activeWorkflow) return ownedByActiveJob() + const ownerInstanceId = jobIdToWorkflowInstanceId.get(jobId) - const activeInstanceId = workflowStore.activeWorkflow?.instanceId - if (ownerInstanceId && activeInstanceId) { - return ownerInstanceId === activeInstanceId + if (ownerInstanceId && activeWorkflow.instanceId) { + return ownerInstanceId === activeWorkflow.instanceId } - return !activeJobId.value || jobId === activeJobId.value + + const ownerPath = jobIdToSessionWorkflowPath.value.get(jobId) + if (ownerPath && activeWorkflow.path) { + return ownerPath === activeWorkflow.path + } + + const frameWorkflowId = workflowIdOrUndefined(workflowId) + // Read as ComfyWorkflow, where both states are nullable. LoadedComfyWorkflow + // declares them present and the running store does not always honour that, + // and this is read from a computed, so a missing state must not throw. + const states: ComfyWorkflow = activeWorkflow + const activeGraphId = workflowIdOrUndefined( + states.activeState?.id ?? states.initialState?.id + ) + if (frameWorkflowId && activeGraphId) { + return frameWorkflowId === activeGraphId + } + + return ownedByActiveJob() } function handleExecutionStart(e: CustomEvent) { @@ -1167,7 +1217,11 @@ export const useExecutionStore = defineStore('execution', () => { const startedJobIds = Object.keys(queuedJobs.value).filter( (jobId) => queuedJobs.value[jobId].executionStartedAt !== undefined ) - const ownedJobId = startedJobIds.findLast(belongsToActiveWorkflow) + // Wrapped, not passed directly: findLast would hand the array index to the + // second parameter. + const ownedJobId = startedJobIds.findLast((jobId) => + belongsToActiveWorkflow(jobId) + ) executionIdToLocatorCache.clear() if (!ownedJobId) { nodeProgressStates.value = {} diff --git a/src/stores/executionStore.workflowOwnership.test.ts b/src/stores/executionStore.workflowOwnership.test.ts index 69b76ce2258..b208388fce5 100644 --- a/src/stores/executionStore.workflowOwnership.test.ts +++ b/src/stores/executionStore.workflowOwnership.test.ts @@ -5,6 +5,7 @@ import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/ import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { api } from '@/scripts/api' import { useExecutionStore } from '@/stores/executionStore' +import { zeroUuid } from '@/utils/uuid' vi.mock(import('@/composables/useAppMode')) vi.mock(import('@/platform/telemetry')) @@ -103,4 +104,62 @@ describe('executionStore workflow ownership', () => { // `status` frames carry no prompt_id, so there is nothing to attribute. expect(store.belongsToActiveWorkflow(undefined)).toBe(true) }) + + describe('the session path, when no tab instance is known', () => { + it('places a job by the path it was queued from', () => { + store.ensureSessionWorkflowPath('job-b', workflowB.path) + + expect(store.belongsToActiveWorkflow('job-b')).toBe(false) + useWorkflowStore().activeWorkflow = workflowB + expect(store.belongsToActiveWorkflow('job-b')).toBe(true) + }) + + it('loses to the tab instance when the two disagree', () => { + queueJobFrom('job-a', workflowA) + store.ensureSessionWorkflowPath( + 'job-a', + workflowB.path, + workflowA.instanceId + ) + + useWorkflowStore().activeWorkflow = workflowB + expect( + store.belongsToActiveWorkflow('job-a'), + 'the instance still says A, so B does not own it' + ).toBe(false) + }) + }) + + describe("the frame's own workflow id, when no per-tab mapping exists", () => { + it('places a job queued before this page load', () => { + // No instance and no path: the only thing left is what the server + // stamped on the frame, which is why ComfyUI#16763 exists. + expect( + store.belongsToActiveWorkflow('job-from-a-previous-page', 'other-graph') + ).toBe(false) + expect( + store.belongsToActiveWorkflow( + 'job-from-a-previous-page', + 'shared-graph-id' + ) + ).toBe(true) + }) + + it('ignores the all-zero sentinel rather than comparing it', () => { + // LGraph._id's default. Compared as a real id it matches nothing, so the + // tab's own frames were rejected. + expect( + store.belongsToActiveWorkflow('job-on-a-fresh-graph', zeroUuid) + ).toBe(true) + }) + + it('loses to the session path when the two disagree', () => { + store.ensureSessionWorkflowPath('job-b', workflowB.path) + + expect( + store.belongsToActiveWorkflow('job-b', 'shared-graph-id'), + 'the path says B owns it, even though the graph id matches A' + ).toBe(false) + }) + }) }) From 2ab043d0c17fd819bfa06d6b9715077742d40c2a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 26 Oct 2026 14:13:24 -0700 Subject: [PATCH 03/13] feat(execution): forward the stamped workflow id to the gate The frame types carried no workflow_id, so the leg added in the previous commit was only reachable from tests and could not place a real frame. Every execution frame that carries a prompt_id now carries the optional stamped id, through one StampedWorkflowId mixin rather than five repeated fields, and the handlers pass it: execution_start, progress_state, the executed listener, and the binary preview, whose header has carried the id since ComfyUI#16809 and whose decoder was dropping it. progress_text deliberately passes nothing. Core packs it as a binary frame that send_sync cannot stamp, so it resolves through the job maps alone. Recorded at the call site and tracked as Comfy-Org/ComfyUI#16887, so the omission does not read as an oversight. Pinned by a test that fires a real progress_state frame rather than calling the store API, which fails when the handler stops forwarding. --- .../node/useProgressTextPreviews.ts | 3 +++ .../remote/comfyui/execution/types.ts | 17 +++++++++--- src/scripts/api.ts | 4 ++- src/scripts/app.ts | 12 ++++++--- src/stores/executionStore.ts | 6 ++--- .../executionStore.workflowOwnership.test.ts | 26 +++++++++++++++++++ 6 files changed, 57 insertions(+), 11 deletions(-) diff --git a/src/composables/node/useProgressTextPreviews.ts b/src/composables/node/useProgressTextPreviews.ts index 8ecdc821f5d..ad55e7424a3 100644 --- a/src/composables/node/useProgressTextPreviews.ts +++ b/src/composables/node/useProgressTextPreviews.ts @@ -26,6 +26,9 @@ export function useProgressTextPreviews() { const { nodeId, text, prompt_id } = e.detail if (!text || !nodeId) return + // No workflow id to pass: core packs progress_text as a binary frame that + // send_sync cannot stamp, so this resolves through the job maps alone. + // Tracked as Comfy-Org/ComfyUI#16887. if (!executionStore.belongsToActiveWorkflow(prompt_id)) return const executionId = String(nodeId) diff --git a/src/platform/remote/comfyui/execution/types.ts b/src/platform/remote/comfyui/execution/types.ts index 89c2177b6e1..7955966b1c4 100644 --- a/src/platform/remote/comfyui/execution/types.ts +++ b/src/platform/remote/comfyui/execution/types.ts @@ -1,11 +1,20 @@ import type { PromptInfo } from '@comfyorg/ingest-types' import { z } from 'zod' +import type { WorkflowId } from '@/platform/workflow/validation/schemas/workflowSchema' import { zNodeId } from '@/platform/workflow/validation/schemas/workflowSchema' import type { TaskStatus } from '@/platform/tasks/services/taskSchema' import { resultItemType } from '@/schemas/resultItemTypeSchema' export type JobId = string +/** + * Stamped by the server onto every frame carrying a `prompt_id`, from the + * `workflow_metadata` the client sent or from `extra_pnginfo.workflow.id` + * (ComfyUI#16763). Optional because `status` and `logs` frames have no + * `prompt_id`, and an older server sends it nowhere. + */ +type StampedWorkflowId = { workflow_id?: WorkflowId } + export const zResultItem = z.object({ filename: z.string().optional(), subfolder: z.string().optional(), @@ -39,7 +48,7 @@ export interface StatusWsMessage { status?: StatusWsMessageStatus | null sid?: string | null } -export interface ProgressWsMessage { +export interface ProgressWsMessage extends StampedWorkflowId { value: number max: number prompt_id: JobId @@ -55,11 +64,11 @@ export interface NodeProgressState { parent_node_id?: NodeId real_node_id?: NodeId } -export interface ProgressStateWsMessage { +export interface ProgressStateWsMessage extends StampedWorkflowId { prompt_id: JobId nodes: Record } -export interface ExecutingWsMessage { +export interface ExecutingWsMessage extends StampedWorkflowId { node: NodeId | null display_node?: NodeId prompt_id: JobId @@ -70,7 +79,7 @@ export interface ExecutedWsMessage extends ExecutingWsMessage { output: NodeExecutionOutput merge?: boolean } -interface ExecutionWsMessageBase { +interface ExecutionWsMessageBase extends StampedWorkflowId { prompt_id: JobId timestamp: number } diff --git a/src/scripts/api.ts b/src/scripts/api.ts index ebf697d09f1..51298ea1ba6 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -285,6 +285,7 @@ interface BackendApiCalls { displayNodeId: string realNodeId: string jobId: string + workflowId?: string } progress_text: ProgressTextWsMessage progress_state: ProgressStateWsMessage @@ -1135,7 +1136,8 @@ export class ComfyApi extends EventTarget { displayNodeId: metadata.display_node_id, parentNodeId: metadata.parent_node_id, realNodeId: metadata.real_node_id, - jobId: metadata.prompt_id + jobId: metadata.prompt_id, + workflowId: metadata.workflow_id }) this.dispatchCustomEvent('b_preview', imageBlob4) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 935cd13940d..e49075c92f7 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -788,7 +788,13 @@ export class ComfyApp implements IComfyApp { }) api.addEventListener('executed', ({ detail }) => { - if (!useExecutionStore().belongsToActiveWorkflow(detail.prompt_id)) return + if ( + !useExecutionStore().belongsToActiveWorkflow( + detail.prompt_id, + detail.workflow_id + ) + ) + return const nodeOutputStore = useNodeOutputStore() const executionId = tryNormalizeNodeExecutionId( detail.display_node || detail.node @@ -823,14 +829,14 @@ export class ComfyApp implements IComfyApp { }) api.addEventListener('b_preview_with_metadata', ({ detail }) => { - const { blob, displayNodeId, jobId } = detail + const { blob, displayNodeId, jobId, workflowId } = detail const { setNodePreviewsByExecutionId, revokePreviewsByExecutionId } = useNodeOutputStore() const displayNodeExecutionId = tryNormalizeNodeExecutionId(displayNodeId) if (!displayNodeExecutionId) return const blobUrl = createSharedObjectUrl(blob) useJobPreviewStore().setPreviewUrl(jobId, blobUrl, displayNodeId) - if (!useExecutionStore().belongsToActiveWorkflow(jobId)) { + if (!useExecutionStore().belongsToActiveWorkflow(jobId, workflowId)) { releaseSharedObjectUrl(blobUrl) return } diff --git a/src/stores/executionStore.ts b/src/stores/executionStore.ts index d0b1d23be33..197b64d6d91 100644 --- a/src/stores/executionStore.ts +++ b/src/stores/executionStore.ts @@ -559,7 +559,7 @@ export const useExecutionStore = defineStore('execution', () => { executionStartedAt: queuedJobs.value[jobId].executionStartedAt }) - if (!belongsToActiveWorkflow(jobId)) { + if (!belongsToActiveWorkflow(jobId, e.detail.workflow_id)) { reportAmbiguousExecutionStartRejection(jobId) return } @@ -714,8 +714,8 @@ export const useExecutionStore = defineStore('execution', () => { } function applyProgressState(detail: ProgressStateWsMessage) { - const { nodes, prompt_id: jobId } = detail - const isOwned = belongsToActiveWorkflow(jobId) + const { nodes, prompt_id: jobId, workflow_id: workflowId } = detail + const isOwned = belongsToActiveWorkflow(jobId, workflowId) if (isOwned) { revokeStartedNodePreviews( diff --git a/src/stores/executionStore.workflowOwnership.test.ts b/src/stores/executionStore.workflowOwnership.test.ts index b208388fce5..af725429a3e 100644 --- a/src/stores/executionStore.workflowOwnership.test.ts +++ b/src/stores/executionStore.workflowOwnership.test.ts @@ -153,6 +153,32 @@ describe('executionStore workflow ownership', () => { ).toBe(true) }) + it('reaches the gate from a real progress_state frame', async () => { + // The store API is not the only caller: the handlers must forward the + // stamped id, or the leg is only reachable from tests. + fire('progress_state', { + prompt_id: 'job-elsewhere', + workflow_id: 'other-graph', + nodes: { + '1': { + value: 3, + max: 10, + state: 'running', + node_id: '1', + prompt_id: 'job-elsewhere' + } + } + }) + await vi.waitFor(() => + expect(store.nodeProgressStatesByJob['job-elsewhere']).toBeDefined() + ) + + expect( + store.nodeProgressStates['1'], + "a frame stamped with another graph's id does not reach the visible tab" + ).toBeUndefined() + }) + it('loses to the session path when the two disagree', () => { store.ensureSessionWorkflowPath('job-b', workflowB.path) From 60010c67435bd7767557a0decbdbe016ed92bb0b Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 26 Oct 2026 14:16:29 -0700 Subject: [PATCH 04/13] fix(execution): release the tab badge when a job is forgotten forgetFinishedJobs drops a job that ended without a terminal frame, but not the workflow status handleExecutionStart set. Only a terminal frame clears that, so the tab kept claiming it was running for the rest of the session, which is the visible half of a dropped frame. Scoped to this path rather than forgetJob, which also runs on a normal completion and has a 'completed' status worth keeping. Ordered before forgetJob, which deletes the jobId-to-workflow entry the release needs. Three cases, each verified by mutation: the release itself, a job the server still reports as running being left alone, and a second tab not being disturbed. Both new suites register tabs through workflowStore.attachWorkflow rather than assigning openWorkflows, because applyWorkflowStatus refuses to record a status for a workflow the real isOpen does not consider open. Assigning the computed made the premise silently false and all three tests failed before they could test anything. --- .../executionStore.terminalRecovery.test.ts | 126 ++++++++++++++++++ src/stores/executionStore.ts | 7 + .../executionStore.workflowOwnership.test.ts | 19 ++- 3 files changed, 149 insertions(+), 3 deletions(-) create mode 100644 src/stores/executionStore.terminalRecovery.test.ts diff --git a/src/stores/executionStore.terminalRecovery.test.ts b/src/stores/executionStore.terminalRecovery.test.ts new file mode 100644 index 00000000000..b9184843b5b --- /dev/null +++ b/src/stores/executionStore.terminalRecovery.test.ts @@ -0,0 +1,126 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' +import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' +import { api } from '@/scripts/api' +import { useExecutionStore } from '@/stores/executionStore' + +vi.mock(import('@/composables/useAppMode')) +vi.mock(import('@/platform/telemetry')) +vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) + +const apiEvents: EventTarget = api + +function workflow(path: string): LoadedComfyWorkflow { + return fromPartial({ + path, + instanceId: `instance-${path}`, + activeState: { id: `graph-${path}` }, + initialState: { id: `graph-${path}` } + }) +} + +const workflowA = workflow('workflows/a.json') +const workflowB = workflow('workflows/b.json') + +/** + * Register tabs through the real store, so `isOpen` and `openWorkflows` are the + * production implementations. A hand-built double would keep passing if + * `isOpen` changed what it keys on, and `applyWorkflowStatus` refuses to record + * a status for a workflow the store does not consider open. + */ +function openTabs(...workflows: LoadedComfyWorkflow[]) { + const workflowStore = useWorkflowStore() + for (const wf of workflows) { + if (workflowStore.isOpen(wf)) continue + workflowStore.attachWorkflow(wf, workflowStore.openWorkflows.length) + } +} + +describe('executionStore terminal-frame recovery', () => { + let store: ReturnType + + beforeEach(() => { + openTabs(workflowA, workflowB) + useWorkflowStore().activeWorkflow = workflowA + store = useExecutionStore() + store.bindExecutionEvents() + }) + + /** + * A job that started and then never reported a terminal frame: the frame was + * dropped, or the socket went away before it arrived. + */ + function startedJobWithNoTerminalFrame( + jobId: string, + wf: LoadedComfyWorkflow + ) { + store.storeJob({ + nodes: ['1'], + id: jobId, + promptOutput: { '1': { inputs: {}, class_type: 'TestNode' } }, + workflow: wf, + mode: 'graph' + }) + apiEvents.dispatchEvent( + new CustomEvent('execution_start', { + detail: { prompt_id: jobId, timestamp: 1 } + }) + ) + apiEvents.dispatchEvent( + new CustomEvent('progress_state', { + detail: { + prompt_id: jobId, + nodes: { + '1': { + value: 3, + max: 10, + state: 'running', + node_id: '1', + prompt_id: jobId + } + } + } + }) + ) + return jobId + } + + it('releases the tab status of a job it forgets', () => { + const jobId = startedJobWithNoTerminalFrame('job-b', workflowB) + expect(store.getWorkflowStatus(workflowB)).toBe('running') + + store.forgetFinishedJobs([jobId]) + + expect( + store.getWorkflowStatus(workflowB), + 'the badge must not keep claiming the tab is running' + ).toBeUndefined() + }) + + it('leaves a job the server still reports as running alone', async () => { + const jobId = startedJobWithNoTerminalFrame('job-b', workflowB) + // progress_state is RAF-coalesced, so the per-job record lands a frame later. + await vi.waitFor(() => + expect(store.nodeProgressStatesByJob[jobId]).toBeDefined() + ) + + store.forgetFinishedJobs([]) + + expect(store.getWorkflowStatus(workflowB)).toBe('running') + expect(store.nodeProgressStatesByJob[jobId]).toBeDefined() + }) + + it('does not disturb a second tab while forgetting one job', () => { + startedJobWithNoTerminalFrame('job-a', workflowA) + const jobB = startedJobWithNoTerminalFrame('job-b', workflowB) + + store.forgetFinishedJobs([jobB]) + + expect( + store.getWorkflowStatus(workflowA), + 'A never went terminal, so forgetting B must not release it' + ).toBe('running') + }) +}) diff --git a/src/stores/executionStore.ts b/src/stores/executionStore.ts index 197b64d6d91..b2bc6f4959e 100644 --- a/src/stores/executionStore.ts +++ b/src/stores/executionStore.ts @@ -1008,6 +1008,13 @@ export const useExecutionStore = defineStore('execution', () => { function forgetFinishedJobs(jobIds: Iterable) { for (const jobId of jobIds) { if (jobId === activeJobId.value || !(jobId in queuedJobs.value)) continue + // Before forgetJob, which drops the jobId→workflow entry this needs. + // handleExecutionStart set the tab to running and only a terminal frame + // clears it, so without this the badge claims the tab is still running + // for the rest of the session. Not inside forgetJob: that also runs on a + // normal completion, which has a 'completed' status to keep. + const workflow = jobIdToWorkflow.get(jobId) + if (workflow) clearWorkflowStatus(workflow) forgetJob(jobId) } } diff --git a/src/stores/executionStore.workflowOwnership.test.ts b/src/stores/executionStore.workflowOwnership.test.ts index af725429a3e..f3be7485520 100644 --- a/src/stores/executionStore.workflowOwnership.test.ts +++ b/src/stores/executionStore.workflowOwnership.test.ts @@ -34,13 +34,26 @@ function promptNode() { return { inputs: {}, class_type: 'TestNode', _meta: { title: 'Node' } } } +/** + * Register tabs through the real store, so `isOpen` and `openWorkflows` are the + * production implementations. A hand-built double would keep passing if + * `isOpen` changed what it keys on, and `applyWorkflowStatus` refuses to record + * a status for a workflow the store does not consider open. + */ +function openTabs(...workflows: LoadedComfyWorkflow[]) { + const workflowStore = useWorkflowStore() + for (const wf of workflows) { + if (workflowStore.isOpen(wf)) continue + workflowStore.attachWorkflow(wf, workflowStore.openWorkflows.length) + } +} + describe('executionStore workflow ownership', () => { let store: ReturnType beforeEach(() => { - const workflowStore = useWorkflowStore() - Object.assign(workflowStore, { openWorkflows: [workflowA, workflowB] }) - workflowStore.activeWorkflow = workflowA + openTabs(workflowA, workflowB) + useWorkflowStore().activeWorkflow = workflowA store = useExecutionStore() store.bindExecutionEvents() }) From a3c1a297563d710dd4b3b96da58cb7e8dfdbff0a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 26 Oct 2026 14:17:25 -0700 Subject: [PATCH 05/13] docs(adr): record workflow ownership for execution frames #21666 landed the instance-keyed gate without an ADR, and this PR adds two legs below it plus the wire contract, so the resolution order is now worth writing down. The part that needed recording most is the boundary: ADR-GRAPH-DOCUMENT-0026 D2 says an unresolvable frame goes to an unattributed bucket and that misdelivery is not the fallback, and this applies it to the active job instead. The ADR states why (quarantining would stop a single-tab user's own run updating after a reload, and no surfacing UI for the bucket exists), and the condition for removing the exception. Also records why the graph id is the weakest leg rather than the strongest, which is the mistake #20045 made and the one most likely to be repeated, since the id looks like the obvious key. --- ...workflow-ownership-for-websocket-frames.md | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md diff --git a/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md b/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md new file mode 100644 index 00000000000..8fcaed0c8e9 --- /dev/null +++ b/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md @@ -0,0 +1,47 @@ +# ADR-EXECUTION-ROUTING-0049: Workflow ownership for execution websocket frames + +Date: 2026-10-26 + +## Status + +Proposed + +## Context + +One `LGraph` and one `LGraphCanvas` serve every open workflow tab, so execution state written by node id is shared state. A run started in one tab painted its progress and outputs onto whichever tab was in front. Reported on #1293, #2660, #6730 and Comfy-Org/ComfyUI#6581, under the umbrella #3377. + +[ADR-GRAPH-DOCUMENT-0026](GRAPH-DOCUMENT-0026-frontend-document-model.md) D2 states the rule: a frame arriving on a push channel resolves its target document at ingress via the job map, never via the active pointer. It also states what to do at the boundary — "events with no job→uid resolution (page reloaded mid-run, jobs queued by another client) go to an explicit _unattributed_ bucket rather than being applied to the active document by default … misdelivery is not the fallback." + +`#21666` implemented D2's addressing rule for the Agent, keying `belongsToActiveWorkflow` on `jobIdToWorkflowInstanceId` and gating the node-output and preview paths. That shipped without unit coverage, and without the wire contract Comfy-Org/ComfyUI#16763 and #16809 were merged to provide: the frontend sent no `workflow_metadata`, so the only id the server could stamp came from `extra_pnginfo`. + +This ADR records what the resolution order is, why the graph id is its weakest signal, and that the boundary departs from D2. + +## Decision + +**Resolution order, strongest first.** The open tab's `instanceId`, then the session path, then the workflow id stamped on the frame. When none resolves, the `activeJobId` guard decides. + +`instanceId` is the only identifier unique per open tab. A path identifies one open workflow, so it is next. The frame's own workflow id is weakest, because every copy of a graph shares it: `ensureWorkflowId` keeps the id already present in a pasted graph, so copy a workflow, open a tab and paste gives two tabs carrying one id. Keying on it first would make each tab match the other's jobs. Its value is placing a job that no per-tab mapping knows about at all — one queued before a page reload, or by another client — which is the gap `instanceId` alone cannot close and the reason the wire contract exists. + +**The all-zero UUID is not an id.** `LGraph._id` defaults to it and the codebase reads it as "no id yet", replacing it on configure and on clear. It is not sent as a routing key, and an incoming one is discarded rather than compared, because comparing it as a real id matches nothing and rejected a fresh graph's own frames. Withholding it from the request does not keep it off the wire: the same graph goes out under `extra_pnginfo` and the server falls back to the id there. + +**Unresolvable frames fall back to the active job.** This is the documented exception to D2's boundary rule. Such a frame is delivered to the tab in front when no job is active or the frame belongs to `activeJobId`, rather than quarantined. A frame with no `prompt_id` is always delivered. + +**What is gated is decided by the consumer's key, not by the frame being foreign.** Node-keyed writes are gated, because the visible graph may hold the same node ids. Job-keyed writes are not: `useJobPreviewStore().setPreviewUrl` feeds the queue panel thumbnail for a background run. Account-level signals are not, because a sign-in or credit precondition belongs to the account rather than to one workflow. + +## Alternatives considered + +**Quarantine unresolvable frames, as D2 prescribes.** Rejected. The common unresolvable case is a page reloaded mid-run, where the mappings are gone and the only open tab is the one being looked at. Quarantining would stop a single-tab user's own run updating after a refresh, a regression for the common case in service of a rule written for the multi-tab case. D2's boundary also assumes a surfacing UI for the unattributed bucket, which does not exist. + +**Gate on the workflow id alone.** This was tried on #20045 and was wrong, for the copy-paste reason above. Recorded because the id looks like the obvious key. + +**A `contextvars` owner on the backend.** Rejected on a mechanism error: `prompt_worker` is a daemon thread and `send_json` runs on the event loop, so a ContextVar set in the worker is unset at send time. The attribute merged in the body of `send_sync` is what shipped. + +## Consequences + +**The `activeJobId` fallback is load-bearing and is the weakest point.** Single-tab behaviour after a reload is preserved, and it is narrower than a blanket permissive rule, since a foreign job's unresolvable frame is dropped while another job is active. What remains is that with two tabs open and a frame unresolvable, it can land on the wrong one. + +**`status` and `progress_text` stay unattributable.** `status` carries no `prompt_id`, because one server-wide socket serves every workflow. `progress_text` is a packed binary frame that `send_sync` cannot stamp, and the frontend already reads a `supports_progress_text_metadata` server flag that no core version sets. Tracked as Comfy-Org/ComfyUI#16887. Until it lands, the text-preview gate resolves through the job maps alone, without the frame's own id. + +**The two backends merge in opposite orders.** Core merges `{**workflow_metadata, **data}`, so a frame's own fields win. The Cloud gateway assigns `prompt_id` and `workflow_id` after the fact, so the backend wins, and it does not read `workflow_metadata` at all. Neither order should be relied on; the routing ids that arrive are authoritative whichever side set them. + +**Revisit if** an unattributed-frame surface is built, at which point D2's boundary becomes implementable and this exception should be removed rather than inherited. From 3c1c42b3fdcad1c2f9ffb6eae8ee11660a5e96d7 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 08:15:21 -0700 Subject: [PATCH 06/13] fix(execution): complete the main merge and implement the review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completes the resolution of the preceding `-X ours` merge and implements the two findings from jaeone94's review of #22013. `-X ours` kept this branch's side of the three import-block conflicts, which main's `@comfyorg/*` package extraction had moved, so those imports pointed at modules main deleted. It also discarded main's additions that sat inside the conflict regions. Both are repaired here: imports repointed onto `@comfyorg/graph-model/{nodeIdentification,appMode,workflowSchema,uuid}`, and main's `retryingSend`/`NO_RETRY_POLICY`/`RetryPolicy` imports in `api.ts` restored. Finding 1 — a workflow-id rejection was reported as an ambiguous one. `handleExecutionStart` called `reportAmbiguousExecutionStartRejection` on any rejection, so a definite id mismatch raised `warning_rejecting_unowned_execution_start`. Under Cloud's per-user fan-out every open tab sees every other tab's job starts, so that was one warning per foreign job on ordinary traffic. `resolveWorkflowOwnership` now returns which leg decided and only the `active-job` guess reports. Finding 2 — the stamped workflow id was checked per frame, never remembered, so the three callers that hold no frame (`replayOutputs`'s hand-built `executed` events, `adoptActiveWorkflowJob`, `progress_text`) fell through to the `activeJobId` fallback and a reconnect replay could paint a foreign job's output onto the visible graph. A `jobIdToStampedWorkflowId` map records a job's first stamp at the single `belongsToActiveWorkflow` chokepoint and the workflow-id leg reads it when the caller passes none. First stamp wins: core merges `workflow_metadata` at `send_sync` enqueue time, so a frame already queued cannot be relabelled. Ownership order is unchanged and pinned by tests: instance, path, stamped workflow id, then active-job fallback. The stamp is deliberately not filed in `jobIdToWorkflowId`, which backs `runErrorKeyForJob` and would attribute a foreign job's errors to a local tab sharing a graph id; that map is fed only from local workflow objects and queue polling, never from the wire. Also repoints `zeroUuid` to `@comfyorg/graph-model/uuid`. The branch added `@/utils/uuid` imports to `executionStore.ts` and `api.ts`, which cross the `execution/application` -> `graph-model/infrastructure` boundary and were two new blocking fallow findings when measured against main — the base `ci-fallow` actually uses. The constant moves to the module that already owns the `UUID` type, and `@/utils/uuid` re-exports it so existing consumers are untouched. Tests: 26 cases across the two ownership suites, each repair reverted and confirmed red (4/2/1/1/3 failures). Both suites had also mocked a module main deleted — `@/platform/telemetry` has no index, so `vi.mock` silently no-opped and `reportError` was unmocked, making finding 1 untestable; repointed to `@comfyorg/telemetry`. Added `afterEach` unbinding because `api` is a module singleton and listeners accumulated across cases. --- ...workflow-ownership-for-websocket-frames.md | 8 +- packages/graph-model/src/uuid.ts | 3 + .../node/useProgressTextPreviews.ts | 5 +- .../remote/comfyui/execution/types.ts | 4 +- src/scripts/api.ts | 7 +- .../executionStore.terminalRecovery.test.ts | 11 +- src/stores/executionStore.ts | 190 ++++++++++++++---- .../executionStore.workflowOwnership.test.ts | 169 +++++++++++++++- src/utils/uuid.ts | 5 +- 9 files changed, 346 insertions(+), 56 deletions(-) diff --git a/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md b/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md index 8fcaed0c8e9..39d04eed97f 100644 --- a/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md +++ b/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md @@ -24,6 +24,12 @@ This ADR records what the resolution order is, why the graph id is its weakest s **The all-zero UUID is not an id.** `LGraph._id` defaults to it and the codebase reads it as "no id yet", replacing it on configure and on clear. It is not sent as a routing key, and an incoming one is discarded rather than compared, because comparing it as a real id matches nothing and rejected a fresh graph's own frames. Withholding it from the request does not keep it off the wire: the same graph goes out under `extra_pnginfo` and the server falls back to the id there. +**The stamp is remembered per job, not re-read per frame.** The first stamped frame of a job records `jobId → workflow_id`, and the workflow-id leg reads it when the caller holds no frame. Three callers hold none: `adoptActiveWorkflowJob` on a tab switch, the `executed` events `useReconnectQueueRefresh` rebuilds by hand on reconnect, and `progress_text`. Without it those three skipped the leg and reached the `activeJobId` fallback, so a reconnect replay could paint a foreign job's output onto the visible graph — `handleExecutionStart` enrols a job in `queuedJobs` before the gate runs, and the replay follows every job in that map, so a rejected foreign job was still replayed unstamped. + +First stamp wins: core merges `workflow_metadata` at `send_sync` enqueue time rather than at publication, so a frame already queued for a job cannot be relabelled by the next prompt, and a later disagreeing stamp belongs to a different job. The map is separate from `jobIdToWorkflowId` on purpose — that one is reactive, exported, and backs `runErrorKeyForJob`, so recording a foreign job's stamp there would file that job's errors against a local tab whenever the two share a graph id, which is the copy-paste case the resolution order exists to handle. Being populated for foreign jobs, it carries its own FIFO bound rather than relying on the local-job eviction paths. + +**A rejection by a real identifier is not a diagnostic.** Only a rejection decided by the `activeJobId` fallback is reported, because that is the one leg that guesses. The resolver returns which leg decided; a mismatched instance, path or workflow id is a definite answer. Reporting every rejection raised one `warning_rejecting_unowned_execution_start` per foreign job start on ordinary traffic, since Cloud's per-user fan-out shows every open tab every other tab's job starts. + **Unresolvable frames fall back to the active job.** This is the documented exception to D2's boundary rule. Such a frame is delivered to the tab in front when no job is active or the frame belongs to `activeJobId`, rather than quarantined. A frame with no `prompt_id` is always delivered. **What is gated is decided by the consumer's key, not by the frame being foreign.** Node-keyed writes are gated, because the visible graph may hold the same node ids. Job-keyed writes are not: `useJobPreviewStore().setPreviewUrl` feeds the queue panel thumbnail for a background run. Account-level signals are not, because a sign-in or credit precondition belongs to the account rather than to one workflow. @@ -40,7 +46,7 @@ This ADR records what the resolution order is, why the graph id is its weakest s **The `activeJobId` fallback is load-bearing and is the weakest point.** Single-tab behaviour after a reload is preserved, and it is narrower than a blanket permissive rule, since a foreign job's unresolvable frame is dropped while another job is active. What remains is that with two tabs open and a frame unresolvable, it can land on the wrong one. -**`status` and `progress_text` stay unattributable.** `status` carries no `prompt_id`, because one server-wide socket serves every workflow. `progress_text` is a packed binary frame that `send_sync` cannot stamp, and the frontend already reads a `supports_progress_text_metadata` server flag that no core version sets. Tracked as Comfy-Org/ComfyUI#16887. Until it lands, the text-preview gate resolves through the job maps alone, without the frame's own id. +**`status` stays unattributable; `progress_text` no longer is.** `status` carries no `prompt_id`, because one server-wide socket serves every workflow. `progress_text` is a packed binary frame that `send_sync` cannot stamp, and the frontend already reads a `supports_progress_text_metadata` server flag that no core version sets — tracked as Comfy-Org/ComfyUI#16887. Its gate now resolves by workflow id anyway, through the stamp remembered from an earlier stamped frame of the same job, so #16887 would improve the first-frame case rather than unblock the leg. **The two backends merge in opposite orders.** Core merges `{**workflow_metadata, **data}`, so a frame's own fields win. The Cloud gateway assigns `prompt_id` and `workflow_id` after the fact, so the backend wins, and it does not read `workflow_metadata` at all. Neither order should be relied on; the routing ids that arrive are authoritative whichever side set them. diff --git a/packages/graph-model/src/uuid.ts b/packages/graph-model/src/uuid.ts index 77587cd4b30..c9500127464 100644 --- a/packages/graph-model/src/uuid.ts +++ b/packages/graph-model/src/uuid.ts @@ -1 +1,4 @@ export type UUID = string + +/** Special-case zero-UUID, consisting entirely of zeros. Used as a default value. */ +export const zeroUuid = '00000000-0000-0000-0000-000000000000' diff --git a/src/composables/node/useProgressTextPreviews.ts b/src/composables/node/useProgressTextPreviews.ts index 79be7d9eada..96d522fadde 100644 --- a/src/composables/node/useProgressTextPreviews.ts +++ b/src/composables/node/useProgressTextPreviews.ts @@ -27,8 +27,9 @@ export function useProgressTextPreviews() { if (!text || !nodeId) return // No workflow id to pass: core packs progress_text as a binary frame that - // send_sync cannot stamp, so this resolves through the job maps alone. - // Tracked as Comfy-Org/ComfyUI#16887. + // send_sync cannot stamp (Comfy-Org/ComfyUI#16887). It still resolves by + // workflow id, through the stamp the store remembered from an earlier + // stamped frame of the same job. if (!executionStore.belongsToActiveWorkflow(prompt_id)) return const executionId = String(nodeId) diff --git a/src/platform/remote/comfyui/execution/types.ts b/src/platform/remote/comfyui/execution/types.ts index 7955966b1c4..e23d55da357 100644 --- a/src/platform/remote/comfyui/execution/types.ts +++ b/src/platform/remote/comfyui/execution/types.ts @@ -1,7 +1,7 @@ import type { PromptInfo } from '@comfyorg/ingest-types' import { z } from 'zod' -import type { WorkflowId } from '@/platform/workflow/validation/schemas/workflowSchema' -import { zNodeId } from '@/platform/workflow/validation/schemas/workflowSchema' +import type { WorkflowId } from '@comfyorg/graph-model/workflowSchema' +import { zNodeId } from '@comfyorg/graph-model/workflowSchema' import type { TaskStatus } from '@/platform/tasks/services/taskSchema' import { resultItemType } from '@/schemas/resultItemTypeSchema' diff --git a/src/scripts/api.ts b/src/scripts/api.ts index c38d199ff87..8211a424bab 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -83,8 +83,11 @@ import type { } from '@/platform/remote/comfyui/jobs/jobTypes' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import type { AuthCredential, AuthScheme } from '@/types/authTypes' -import type { NodeExecutionId } from '@/types/nodeIdentification' -import { zeroUuid } from '@/utils/uuid' +import type { NodeExecutionId } from '@comfyorg/graph-model/nodeIdentification' +import { retryingSend } from '@/utils/fetchWithRetry' +import { NO_RETRY_POLICY } from '@/utils/retryPolicy' +import type { RetryPolicy } from '@/utils/retryPolicy' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { fetchHistory, fetchJobAssets, diff --git a/src/stores/executionStore.terminalRecovery.test.ts b/src/stores/executionStore.terminalRecovery.test.ts index b9184843b5b..267f9f18df4 100644 --- a/src/stores/executionStore.terminalRecovery.test.ts +++ b/src/stores/executionStore.terminalRecovery.test.ts @@ -1,5 +1,5 @@ import { fromPartial } from '@total-typescript/shoehorn' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' @@ -7,7 +7,8 @@ import { api } from '@/scripts/api' import { useExecutionStore } from '@/stores/executionStore' vi.mock(import('@/composables/useAppMode')) -vi.mock(import('@/platform/telemetry')) +vi.mock(import('@comfyorg/telemetry')) +vi.mock(import('@comfyorg/telemetry/reportError')) vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) const apiEvents: EventTarget = api @@ -48,6 +49,12 @@ describe('executionStore terminal-frame recovery', () => { store.bindExecutionEvents() }) + // `api` is a module singleton, so without this each test's listeners + // accumulate and later tests re-run earlier handlers against disposed stores. + afterEach(() => { + store.unbindExecutionEvents() + }) + /** * A job that started and then never reported a terminal frame: the frame was * dropped, or the socket went away before it arrived. diff --git a/src/stores/executionStore.ts b/src/stores/executionStore.ts index b077d2ac609..179f6498893 100644 --- a/src/stores/executionStore.ts +++ b/src/stores/executionStore.ts @@ -36,11 +36,11 @@ import { useApp } from '@/scripts/appInstance' import { useNodeOutputStore } from '@/stores/nodeOutputStore' import { useJobPreviewStore } from '@/stores/jobPreviewStore' import { useExecutionErrorStore } from '@/stores/executionErrorStore' -import { tryNormalizeNodeExecutionId } from '@/types/nodeIdentification' -import type { NodeLocatorId } from '@/types/nodeIdentification' -import type { AppMode } from '@/utils/appMode' -import { isAppModeValue } from '@/utils/appMode' -import { zeroUuid } from '@/utils/uuid' +import { tryNormalizeNodeExecutionId } from '@comfyorg/graph-model/nodeIdentification' +import type { NodeLocatorId } from '@comfyorg/graph-model/nodeIdentification' +import type { AppMode } from '@comfyorg/graph-model/appMode' +import { isAppModeValue } from '@comfyorg/graph-model/appMode' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { classifyCloudValidationError } from '@/utils/executionErrorUtil' import { executionIdToNodeLocatorId } from '@/utils/graphTraversalUtil' import { createRafCoalescer } from '@/utils/rafBatch' @@ -168,6 +168,25 @@ export const useExecutionStore = defineStore('execution', () => { const jobIdToSessionWorkflowPath = shallowRef>(new Map()) const jobIdToWorkflowInstanceId = new Map() + /** + * The `workflow_id` the server stamped on this job's first stamped frame + * (ComfyUI#16763), remembered so the callers that hold no frame can still + * place the job: `adoptActiveWorkflowJob` on a tab switch, the `executed` + * frames `useReconnectQueueRefresh` rebuilds by hand on reconnect, and + * `progress_text`, which core packs as a binary frame `send_sync` cannot + * stamp (ComfyUI#16887). + * + * Deliberately **not** `jobIdToWorkflowId`: that map is reactive, exported, + * and backs `runErrorKeyForJob`, so filing a foreign job's stamp there would + * attribute that job's errors to a local tab whenever the two share a graph + * id — exactly the copy-paste case the resolution order exists to handle. + * This map is populated for foreign jobs on purpose, and those never reach + * `ensureSessionWorkflowPath`'s eviction, so it carries its own bound. + */ + const jobIdToStampedWorkflowId = new Map() + // ~0.27 MB at capacity (32 char GUID key + 36 char UUID value) + const MAX_STAMPED_WORKFLOW_ID_ENTRIES = 4000 + const initializingJobIds = ref>(new Set()) const workflowStatus = shallowRef< @@ -475,14 +494,11 @@ export const useExecutionStore = defineStore('execution', () => { pendingWorkflowStatusByJobId.clear() pendingExecutionErrorsByJobId.clear() jobIdToWorkflow.clear() + jobIdToStampedWorkflowId.clear() cancelPendingProgressUpdates() } - /** - * Whether frames for this job may paint the active workflow's canvas. - * Jobs whose owner is unknown are admitted unless another job is active. - */ /** * The all-zero sentinel is `LGraph._id`'s default, which the codebase reads * as "no id yet" and replaces on configure and on clear. Comparing it as a @@ -495,51 +511,132 @@ export const useExecutionStore = defineStore('execution', () => { } /** - * Resolution order, strongest first. `instanceId` is the only identifier - * unique per open tab. The session path is next, since a path identifies one - * open workflow. The frame's own `workflow_id` is weakest, because every copy - * of a graph shares it, so it can only place a job no per-tab mapping knows - * about: one queued before a page reload, or by another client. - * - * @param workflowId The id the server stamped on the frame, where it sends - * one. Absent on a backend without ComfyUI#16763, and on frames with no - * `prompt_id`. + * First stamp wins. Core merges `workflow_metadata` into a frame at + * `send_sync` enqueue time rather than at publication, so a frame queued for + * this job cannot be relabelled by whatever the next prompt sets — meaning + * the first stamp seen is this job's, and a later one disagreeing would be a + * frame belonging to a different job. */ - function belongsToActiveWorkflow( - jobId: JobId | undefined, - workflowId?: string - ): boolean { - if (!jobId) return true + function rememberStampedWorkflowId( + jobId: JobId, + workflowId: string | undefined + ): void { + const stamped = workflowIdOrUndefined(workflowId) + if (!stamped || jobIdToStampedWorkflowId.has(jobId)) return + jobIdToStampedWorkflowId.set(jobId, stamped) + while (jobIdToStampedWorkflowId.size > MAX_STAMPED_WORKFLOW_ID_ENTRIES) { + const oldest = jobIdToStampedWorkflowId.keys().next().value + if (oldest === undefined) break + jobIdToStampedWorkflowId.delete(oldest) + } + } - const ownedByActiveJob = () => - !activeJobId.value || jobId === activeJobId.value + /** Which leg of the resolution order decided. Only `active-job` is a guess. */ + type OwnershipLeg = 'instance' | 'path' | 'workflow-id' | 'active-job' - const activeWorkflow = workflowStore.activeWorkflow - if (!activeWorkflow) return ownedByActiveJob() + interface WorkflowOwnership { + owned: boolean + leg: OwnershipLeg + } + /** + * `instanceId` is the only identifier unique per open tab, so it is the + * strongest leg. `undefined` means this leg cannot decide. + */ + function ownershipByInstance( + jobId: JobId, + activeWorkflow: ComfyWorkflow + ): WorkflowOwnership | undefined { const ownerInstanceId = jobIdToWorkflowInstanceId.get(jobId) - if (ownerInstanceId && activeWorkflow.instanceId) { - return ownerInstanceId === activeWorkflow.instanceId + if (!ownerInstanceId || !activeWorkflow.instanceId) return + return { + owned: ownerInstanceId === activeWorkflow.instanceId, + leg: 'instance' } + } + /** A path identifies one open workflow, so it is next after the instance. */ + function ownershipByPath( + jobId: JobId, + activeWorkflow: ComfyWorkflow + ): WorkflowOwnership | undefined { const ownerPath = jobIdToSessionWorkflowPath.value.get(jobId) - if (ownerPath && activeWorkflow.path) { - return ownerPath === activeWorkflow.path - } + if (!ownerPath || !activeWorkflow.path) return + return { owned: ownerPath === activeWorkflow.path, leg: 'path' } + } - const frameWorkflowId = workflowIdOrUndefined(workflowId) + /** + * Weakest leg: every copy of a graph shares its workflow id, so this can only + * place a job no per-tab mapping knows about — one queued before a page + * reload, or by another client. Reads the frame's own stamp where the caller + * has a frame, and otherwise the stamp remembered from an earlier frame of the + * same job. + */ + function ownershipByWorkflowId( + jobId: JobId, + activeWorkflow: ComfyWorkflow, + workflowId: string | undefined + ): WorkflowOwnership | undefined { // Read as ComfyWorkflow, where both states are nullable. LoadedComfyWorkflow // declares them present and the running store does not always honour that, - // and this is read from a computed, so a missing state must not throw. - const states: ComfyWorkflow = activeWorkflow + // so a missing state must not throw. const activeGraphId = workflowIdOrUndefined( - states.activeState?.id ?? states.initialState?.id + activeWorkflow.activeState?.id ?? activeWorkflow.initialState?.id ) - if (frameWorkflowId && activeGraphId) { - return frameWorkflowId === activeGraphId - } + const frameWorkflowId = + workflowIdOrUndefined(workflowId) ?? jobIdToStampedWorkflowId.get(jobId) + if (!frameWorkflowId || !activeGraphId) return + return { owned: frameWorkflowId === activeGraphId, leg: 'workflow-id' } + } + + /** + * Resolution order, strongest first, kept as an explicit chain of single-leg + * predicates so the order is readable at one glance and each leg stays small. + * + * Returns which leg decided, because a rejection by a real identifier is a + * definite answer and only the `active-job` fallback is a guess worth + * reporting. + * + * @param workflowId The id the server stamped on the frame, where the caller + * has a frame in hand. Absent on a backend without ComfyUI#16763, on frames + * with no `prompt_id`, and for the callers holding no frame at all. + */ + function resolveWorkflowOwnership( + jobId: JobId, + workflowId?: string + ): WorkflowOwnership { + const ownedByActiveJob = (): WorkflowOwnership => ({ + owned: !activeJobId.value || jobId === activeJobId.value, + leg: 'active-job' + }) + + const activeWorkflow = workflowStore.activeWorkflow + if (!activeWorkflow) return ownedByActiveJob() - return ownedByActiveJob() + return ( + ownershipByInstance(jobId, activeWorkflow) ?? + ownershipByPath(jobId, activeWorkflow) ?? + ownershipByWorkflowId(jobId, activeWorkflow, workflowId) ?? + ownedByActiveJob() + ) + } + + /** + * Whether frames for this job may paint the active workflow's canvas. + * Jobs whose owner is unknown are admitted unless another job is active. + * + * Recording the stamp here rather than at each frame handler is deliberate: + * this is the one chokepoint every stamped frame path already passes through + * (`execution_start`, `progress_state`, `executed`, `b_preview_with_metadata`), + * so a future frame path cannot acquire the stamp and forget to remember it. + */ + function belongsToActiveWorkflow( + jobId: JobId | undefined, + workflowId?: string + ): boolean { + if (!jobId) return true + rememberStampedWorkflowId(jobId, workflowId) + return resolveWorkflowOwnership(jobId, workflowId).owned } function handleExecutionStart(e: CustomEvent) { @@ -559,8 +656,16 @@ export const useExecutionStore = defineStore('execution', () => { executionStartedAt: queuedJobs.value[jobId].executionStartedAt }) - if (!belongsToActiveWorkflow(jobId, e.detail.workflow_id)) { - reportAmbiguousExecutionStartRejection(jobId) + rememberStampedWorkflowId(jobId, e.detail.workflow_id) + const ownership = resolveWorkflowOwnership(jobId, e.detail.workflow_id) + if (!ownership.owned) { + // A mismatch on a real identifier is a definite answer, not a diagnostic. + // Under Cloud's per-user fan-out every open tab sees every other tab's + // job starts, so reporting those raised one warning per foreign job on + // ordinary traffic. + if (ownership.leg === 'active-job') { + reportAmbiguousExecutionStartRejection(jobId) + } return } executionIdToLocatorCache.clear() @@ -1025,6 +1130,7 @@ export const useExecutionStore = defineStore('execution', () => { nodeProgressStatesByJob.value = progress useJobPreviewStore().clearPreview(jobId) jobIdToWorkflow.delete(jobId) + jobIdToStampedWorkflowId.delete(jobId) if (jobId in queuedJobs.value) void jobReset.trigger(queuedJobs.value[jobId]) delete queuedJobs.value[jobId] diff --git a/src/stores/executionStore.workflowOwnership.test.ts b/src/stores/executionStore.workflowOwnership.test.ts index f3be7485520..c07c077f35b 100644 --- a/src/stores/executionStore.workflowOwnership.test.ts +++ b/src/stores/executionStore.workflowOwnership.test.ts @@ -1,5 +1,7 @@ +import { reportError } from '@comfyorg/telemetry/reportError' import { fromPartial } from '@total-typescript/shoehorn' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { nextTick } from 'vue' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' @@ -8,7 +10,8 @@ import { useExecutionStore } from '@/stores/executionStore' import { zeroUuid } from '@/utils/uuid' vi.mock(import('@/composables/useAppMode')) -vi.mock(import('@/platform/telemetry')) +vi.mock(import('@comfyorg/telemetry')) +vi.mock(import('@comfyorg/telemetry/reportError')) vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) const apiEvents: EventTarget = api @@ -58,6 +61,13 @@ describe('executionStore workflow ownership', () => { store.bindExecutionEvents() }) + // `api` is a module singleton, so without this the listeners bound by each + // test accumulate and later tests run every earlier test's handler against a + // disposed store. Harmless for a boolean assertion, fatal for a counting one. + afterEach(() => { + store.unbindExecutionEvents() + }) + /** Queue a job from `wf`, which is what records its owning tab. */ function queueJobFrom(jobId: string, wf: LoadedComfyWorkflow) { store.storeJob({ @@ -201,4 +211,159 @@ describe('executionStore workflow ownership', () => { ).toBe(false) }) }) + + describe('the stamp remembered from an earlier frame of the same job', () => { + /** + * A job this tab never queued, reaching the tab through Cloud's per-user + * fan-out. `handleExecutionStart` enrols it in `queuedJobs` before the gate + * runs, which is what makes it eligible for a reconnect replay. + */ + function foreignJobStarted(jobId: string, workflowId?: string) { + fire('execution_start', { + prompt_id: jobId, + workflow_id: workflowId, + timestamp: 1 + }) + return jobId + } + + it('places a job for a caller that holds no frame', () => { + foreignJobStarted('job-elsewhere', 'other-graph') + + expect( + store.belongsToActiveWorkflow('job-elsewhere'), + 'the stamp seen on execution_start still decides when no id is passed' + ).toBe(false) + }) + + it('blocks a reconnect replay of a foreign job output', () => { + // `useReconnectQueueRefresh.replayOutputs` rebuilds `executed` by hand + // with no `workflow_id` field, and replays every job in `queuedJobs` — + // which includes the foreign jobs `handleExecutionStart` enrolled. This is + // the call `app.ts` then makes, with `detail.workflow_id` undefined. + foreignJobStarted('job-elsewhere', 'other-graph') + + expect(store.belongsToActiveWorkflow('job-elsewhere', undefined)).toBe( + false + ) + }) + + it('is not consulted for a job this tab owns', () => { + queueJobFrom('job-a', workflowA) + foreignJobStarted('job-a', 'shared-graph-id') + + expect(store.belongsToActiveWorkflow('job-a')).toBe(true) + }) + + it('keeps the first stamp when a later frame disagrees', () => { + // Core merges workflow_metadata at send_sync enqueue time, so a frame + // carrying a different id belongs to a different job, not a relabelling. + foreignJobStarted('job-elsewhere', 'other-graph') + + // The call app.ts makes for an `executed` frame, carrying a second, + // disagreeing stamp for the same job. + store.belongsToActiveWorkflow('job-elsewhere', 'shared-graph-id') + + expect( + store.belongsToActiveWorkflow('job-elsewhere'), + 'the later stamp must not relabel the job onto the visible tab' + ).toBe(false) + }) + + it('loses to the tab instance, which is still the strongest leg', () => { + queueJobFrom('job-a', workflowA) + // A foreign stamp naming B's graph arrives for a job A owns by instance. + store.belongsToActiveWorkflow('job-a', 'other-graph') + + useWorkflowStore().activeWorkflow = workflowB + expect( + store.belongsToActiveWorkflow('job-a'), + 'the instance says A, so the remembered stamp must not outrank it' + ).toBe(false) + useWorkflowStore().activeWorkflow = workflowA + expect(store.belongsToActiveWorkflow('job-a')).toBe(true) + }) + + it('loses to the session path', () => { + store.ensureSessionWorkflowPath('job-b', workflowB.path) + store.belongsToActiveWorkflow('job-b', 'shared-graph-id') + + expect( + store.belongsToActiveWorkflow('job-b'), + 'the path says B owns it, even though the remembered stamp matches A' + ).toBe(false) + }) + + it('stops a tab switch from adopting a foreign job', async () => { + // adoptActiveWorkflowJob passes no id at all, so before the stamp was + // remembered a foreign job fell through to the active-job fallback. + foreignJobStarted('job-elsewhere', 'other-graph') + expect(store.queuedJobs['job-elsewhere']).toBeDefined() + + useWorkflowStore().activeWorkflow = workflowB + await nextTick() + + expect(store.activeJobId).toBeNull() + }) + + it('is forgotten with the job', () => { + foreignJobStarted('job-elsewhere', 'other-graph') + + store.forgetFinishedJobs(['job-elsewhere']) + + expect( + store.belongsToActiveWorkflow('job-elsewhere'), + 'nothing is left to place the job, so the fallback admits it again' + ).toBe(true) + }) + }) + + describe('reporting a rejected execution_start', () => { + function rejectionWarnings() { + return vi + .mocked(reportError) + .mock.calls.filter( + ([, options]) => + options.errorType === 'warning_rejecting_unowned_execution_start' + ) + } + + it('does not report a rejection decided by the frame workflow id', () => { + // Under Cloud's per-user fan-out every tab sees every other tab's job + // starts, so reporting these was one warning per foreign job on ordinary + // traffic. A mismatched id is a definite answer, not an ambiguous one. + fire('execution_start', { + prompt_id: 'job-elsewhere', + workflow_id: 'other-graph', + timestamp: 1 + }) + + expect(store.activeJobId, 'the frame was still rejected').toBeNull() + expect(rejectionWarnings()).toHaveLength(0) + }) + + it('does not report a rejection decided by the session path', () => { + store.ensureSessionWorkflowPath('job-b', workflowB.path) + + fire('execution_start', { prompt_id: 'job-b', timestamp: 1 }) + + expect(store.activeJobId).toBeNull() + expect(rejectionWarnings()).toHaveLength(0) + }) + + it('still reports a rejection that is only a guess', () => { + // No instance, no path, no stamp: the active-job fallback is the one leg + // that guesses, so this is the rejection worth knowing about. + queueJobFrom('job-a', workflowA) + fire('execution_start', { prompt_id: 'job-a', timestamp: 1 }) + expect(store.activeJobId).toBe('job-a') + + fire('execution_start', { + prompt_id: 'job-from-a-previous-page', + timestamp: 2 + }) + + expect(rejectionWarnings()).toHaveLength(1) + }) + }) }) diff --git a/src/utils/uuid.ts b/src/utils/uuid.ts index f44552ca9a7..6346c3f23c2 100644 --- a/src/utils/uuid.ts +++ b/src/utils/uuid.ts @@ -1,9 +1,8 @@ // Using a template string for this is resulting in complex type workarounds. No current benefit beyond dev reading. import type { UUID } from '@comfyorg/graph-model/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' export type { UUID } from '@comfyorg/graph-model/uuid' - -/** Special-case zero-UUID, consisting entirely of zeros. Used as a default value. */ -export const zeroUuid = '00000000-0000-0000-0000-000000000000' +export { zeroUuid } from '@comfyorg/graph-model/uuid' /** Pre-allocated storage for uuid random values. */ const randomStorage = new Uint32Array(31) From d7c0105248cedeb550b6117124136808543ae457 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 09:32:32 -0700 Subject: [PATCH 07/13] fix: preserve running status for overlapping jobs --- .../tests/wsReconnectStaleJob.spec.ts | 83 ++++++++++++++++ .../node/useProgressTextPreviews.ts | 4 - .../remote/comfyui/execution/types.ts | 6 -- src/scripts/api.ts | 24 ----- .../executionStore.terminalRecovery.test.ts | 24 +++-- src/stores/executionStore.ts | 99 +++---------------- .../executionStore.workflowOwnership.test.ts | 45 --------- 7 files changed, 109 insertions(+), 176 deletions(-) diff --git a/browser_tests/tests/wsReconnectStaleJob.spec.ts b/browser_tests/tests/wsReconnectStaleJob.spec.ts index 26fc95ddca2..0878b557c32 100644 --- a/browser_tests/tests/wsReconnectStaleJob.spec.ts +++ b/browser_tests/tests/wsReconnectStaleJob.spec.ts @@ -99,6 +99,89 @@ async function triggerReconnect( } test.describe('WebSocket reconnect with stale job', { tag: '@ui' }, () => { + test('keeps the visible workflow running status when cleanup forgets one job', async ({ + comfyPage, + getWebSocket, + nextWebSocket + }) => { + const ws = await getWebSocket() + const exec = new ExecutionHelper(comfyPage, ws) + const topbar = comfyPage.menu.topbar + + await comfyPage.workflow.waitForActiveWorkflow() + await comfyPage.workflow.waitForWorkflowIdle() + + const finishedJobId = await exec.run() + const runningJobId = await exec.run() + exec.executionStart(finishedJobId) + exec.executionStart(runningJobId) + + await topbar.newWorkflowButton.click() + await comfyPage.workflow.waitForWorkflowIdle() + await expect(topbar.getActiveTab()).toContainText('(2)') + + const backgroundTab = topbar.getTab(0) + const runningIndicator = backgroundTab.getByRole('img', { + name: 'Running' + }) + await expect(runningIndicator).toBeVisible() + + const remainingJobScenario: Scenario = { + name: 'preserves the remaining same-workflow job', + queueBody: () => + JSON.stringify( + jobsResponse([ + { + id: runningJobId, + status: 'in_progress', + create_time: Date.now() + } + ]) + ), + expectsActiveAfter: true + } + const finishedJobReads = await mockJobsRoute( + comfyPage, + new RegExp(`/api/jobs/${finishedJobId}$`), + '{}', + 404 + ) + + const secondSocketPromise = nextWebSocket() + await triggerReconnect(comfyPage, ws, remainingJobScenario, runningJobId) + await expect.poll(finishedJobReads).toBeGreaterThanOrEqual(2) + const secondSocket = await secondSocketPromise + + const thirdSocketPromise = nextWebSocket() + await triggerReconnect( + comfyPage, + secondSocket, + remainingJobScenario, + runningJobId + ) + await expect.poll(finishedJobReads).toBeGreaterThanOrEqual(4) + const thirdSocket = await thirdSocketPromise + + const fourthSocketPromise = nextWebSocket() + await triggerReconnect( + comfyPage, + thirdSocket, + remainingJobScenario, + runningJobId + ) + await expect.poll(finishedJobReads).toBeGreaterThanOrEqual(6) + const fourthSocket = await fourthSocketPromise + + await triggerReconnect( + comfyPage, + fourthSocket, + remainingJobScenario, + runningJobId + ) + + await expect(runningIndicator).toBeVisible() + }) + test.describe('app mode skeleton', () => { test.beforeEach(async ({ comfyPage }) => { await comfyPage.appMode.enterAppModeWithInputs([[KSAMPLER_NODE, 'seed']]) diff --git a/src/composables/node/useProgressTextPreviews.ts b/src/composables/node/useProgressTextPreviews.ts index 96d522fadde..9f5343453e9 100644 --- a/src/composables/node/useProgressTextPreviews.ts +++ b/src/composables/node/useProgressTextPreviews.ts @@ -26,10 +26,6 @@ export function useProgressTextPreviews() { const { nodeId, text, prompt_id } = e.detail if (!text || !nodeId) return - // No workflow id to pass: core packs progress_text as a binary frame that - // send_sync cannot stamp (Comfy-Org/ComfyUI#16887). It still resolves by - // workflow id, through the stamp the store remembered from an earlier - // stamped frame of the same job. if (!executionStore.belongsToActiveWorkflow(prompt_id)) return const executionId = String(nodeId) diff --git a/src/platform/remote/comfyui/execution/types.ts b/src/platform/remote/comfyui/execution/types.ts index e23d55da357..298e734ccb7 100644 --- a/src/platform/remote/comfyui/execution/types.ts +++ b/src/platform/remote/comfyui/execution/types.ts @@ -7,12 +7,6 @@ import { resultItemType } from '@/schemas/resultItemTypeSchema' export type JobId = string -/** - * Stamped by the server onto every frame carrying a `prompt_id`, from the - * `workflow_metadata` the client sent or from `extra_pnginfo.workflow.id` - * (ComfyUI#16763). Optional because `status` and `logs` frames have no - * `prompt_id`, and an older server sends it nowhere. - */ type StampedWorkflowId = { workflow_id?: WorkflowId } export const zResultItem = z.object({ diff --git a/src/scripts/api.ts b/src/scripts/api.ts index 8211a424bab..f6706c90588 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -101,24 +101,6 @@ interface QueuePromptRequestBody { client_id: string prompt: ComfyApiWorkflow partial_execution_targets?: NodeExecutionId[] - /** - * Echoed back by the server on every WebSocket frame this prompt produces - * that carries a `prompt_id` (ComfyUI#16763 for JSON frames, #16809 for the - * metadata header on binary previews). An older server ignores the field - * rather than rejecting the prompt. - * - * Two limits, since the contract is the server's and not ours. `status` and - * `logs` frames have no `prompt_id`, so they are never stamped. And a value - * the server cannot use is dropped rather than rejected: over 256 characters - * of its own JSON serialisation, with non-ASCII escaped to `\\uXXXX` first. - * The server then falls back to `extra_data.extra_pnginfo.workflow.id`, so - * omitting this field does not keep frames unstamped. - * - * Cloud does not read this field: its gateway stamps `workflow_id` from - * `extra_pnginfo.workflow.id` and assigns the routing ids after the frame's - * own fields, where core lets the frame's fields win. Treat the ids that - * arrive as authoritative either way. - */ workflow_metadata?: { workflow_id: string } extra_data: { extra_pnginfo: { @@ -1400,12 +1382,6 @@ export class ComfyApi extends EventTarget { ...(options?.partialExecutionTargets && { partial_execution_targets: options.partialExecutionTargets }), - // `LGraph.serialize()` returns `id` unfiltered and `LGraph._id` defaults - // to the all-zero sentinel, which the codebase reads as "no id yet" and - // replaces on configure and on clear, so it is not a routing key and is - // not sent as one. This does not keep it off the wire: the same graph - // goes out under `extra_pnginfo` and the server falls back to the id - // there, which is why the store also discards the sentinel on the way in. ...(workflow.id && workflow.id !== zeroUuid && { workflow_metadata: { workflow_id: workflow.id } diff --git a/src/stores/executionStore.terminalRecovery.test.ts b/src/stores/executionStore.terminalRecovery.test.ts index 267f9f18df4..23850cfce06 100644 --- a/src/stores/executionStore.terminalRecovery.test.ts +++ b/src/stores/executionStore.terminalRecovery.test.ts @@ -25,12 +25,6 @@ function workflow(path: string): LoadedComfyWorkflow { const workflowA = workflow('workflows/a.json') const workflowB = workflow('workflows/b.json') -/** - * Register tabs through the real store, so `isOpen` and `openWorkflows` are the - * production implementations. A hand-built double would keep passing if - * `isOpen` changed what it keys on, and `applyWorkflowStatus` refuses to record - * a status for a workflow the store does not consider open. - */ function openTabs(...workflows: LoadedComfyWorkflow[]) { const workflowStore = useWorkflowStore() for (const wf of workflows) { @@ -49,16 +43,10 @@ describe('executionStore terminal-frame recovery', () => { store.bindExecutionEvents() }) - // `api` is a module singleton, so without this each test's listeners - // accumulate and later tests re-run earlier handlers against disposed stores. afterEach(() => { store.unbindExecutionEvents() }) - /** - * A job that started and then never reported a terminal frame: the frame was - * dropped, or the socket went away before it arrived. - */ function startedJobWithNoTerminalFrame( jobId: string, wf: LoadedComfyWorkflow @@ -108,7 +96,6 @@ describe('executionStore terminal-frame recovery', () => { it('leaves a job the server still reports as running alone', async () => { const jobId = startedJobWithNoTerminalFrame('job-b', workflowB) - // progress_state is RAF-coalesced, so the per-job record lands a frame later. await vi.waitFor(() => expect(store.nodeProgressStatesByJob[jobId]).toBeDefined() ) @@ -130,4 +117,15 @@ describe('executionStore terminal-frame recovery', () => { 'A never went terminal, so forgetting B must not release it' ).toBe('running') }) + + it('keeps a tab running while another started job uses it', () => { + const firstJob = startedJobWithNoTerminalFrame('job-b-1', workflowB) + startedJobWithNoTerminalFrame('job-b-2', workflowB) + + store.forgetFinishedJobs([firstJob]) + + expect(store.getWorkflowStatus(workflowB)).toBe('running') + expect(store.queuedJobs[firstJob]).toBeUndefined() + expect(store.queuedJobs['job-b-2']).toBeDefined() + }) }) diff --git a/src/stores/executionStore.ts b/src/stores/executionStore.ts index 179f6498893..424b16d841e 100644 --- a/src/stores/executionStore.ts +++ b/src/stores/executionStore.ts @@ -168,23 +168,7 @@ export const useExecutionStore = defineStore('execution', () => { const jobIdToSessionWorkflowPath = shallowRef>(new Map()) const jobIdToWorkflowInstanceId = new Map() - /** - * The `workflow_id` the server stamped on this job's first stamped frame - * (ComfyUI#16763), remembered so the callers that hold no frame can still - * place the job: `adoptActiveWorkflowJob` on a tab switch, the `executed` - * frames `useReconnectQueueRefresh` rebuilds by hand on reconnect, and - * `progress_text`, which core packs as a binary frame `send_sync` cannot - * stamp (ComfyUI#16887). - * - * Deliberately **not** `jobIdToWorkflowId`: that map is reactive, exported, - * and backs `runErrorKeyForJob`, so filing a foreign job's stamp there would - * attribute that job's errors to a local tab whenever the two share a graph - * id — exactly the copy-paste case the resolution order exists to handle. - * This map is populated for foreign jobs on purpose, and those never reach - * `ensureSessionWorkflowPath`'s eviction, so it carries its own bound. - */ const jobIdToStampedWorkflowId = new Map() - // ~0.27 MB at capacity (32 char GUID key + 36 char UUID value) const MAX_STAMPED_WORKFLOW_ID_ENTRIES = 4000 const initializingJobIds = ref>(new Set()) @@ -499,29 +483,15 @@ export const useExecutionStore = defineStore('execution', () => { cancelPendingProgressUpdates() } - /** - * The all-zero sentinel is `LGraph._id`'s default, which the codebase reads - * as "no id yet" and replaces on configure and on clear. Comparing it as a - * real id matches nothing, which rejected a fresh graph's own frames. It - * reaches the wire regardless, because the server falls back to the id inside - * `extra_pnginfo.workflow`. - */ - function workflowIdOrUndefined(id: string | undefined): string | undefined { + function routableWorkflowId(id: string | undefined): string | undefined { return !id || id === zeroUuid ? undefined : id } - /** - * First stamp wins. Core merges `workflow_metadata` into a frame at - * `send_sync` enqueue time rather than at publication, so a frame queued for - * this job cannot be relabelled by whatever the next prompt sets — meaning - * the first stamp seen is this job's, and a later one disagreeing would be a - * frame belonging to a different job. - */ function rememberStampedWorkflowId( jobId: JobId, workflowId: string | undefined ): void { - const stamped = workflowIdOrUndefined(workflowId) + const stamped = routableWorkflowId(workflowId) if (!stamped || jobIdToStampedWorkflowId.has(jobId)) return jobIdToStampedWorkflowId.set(jobId, stamped) while (jobIdToStampedWorkflowId.size > MAX_STAMPED_WORKFLOW_ID_ENTRIES) { @@ -531,7 +501,6 @@ export const useExecutionStore = defineStore('execution', () => { } } - /** Which leg of the resolution order decided. Only `active-job` is a guess. */ type OwnershipLeg = 'instance' | 'path' | 'workflow-id' | 'active-job' interface WorkflowOwnership { @@ -539,10 +508,6 @@ export const useExecutionStore = defineStore('execution', () => { leg: OwnershipLeg } - /** - * `instanceId` is the only identifier unique per open tab, so it is the - * strongest leg. `undefined` means this leg cannot decide. - */ function ownershipByInstance( jobId: JobId, activeWorkflow: ComfyWorkflow @@ -555,7 +520,6 @@ export const useExecutionStore = defineStore('execution', () => { } } - /** A path identifies one open workflow, so it is next after the instance. */ function ownershipByPath( jobId: JobId, activeWorkflow: ComfyWorkflow @@ -565,42 +529,20 @@ export const useExecutionStore = defineStore('execution', () => { return { owned: ownerPath === activeWorkflow.path, leg: 'path' } } - /** - * Weakest leg: every copy of a graph shares its workflow id, so this can only - * place a job no per-tab mapping knows about — one queued before a page - * reload, or by another client. Reads the frame's own stamp where the caller - * has a frame, and otherwise the stamp remembered from an earlier frame of the - * same job. - */ function ownershipByWorkflowId( jobId: JobId, activeWorkflow: ComfyWorkflow, workflowId: string | undefined ): WorkflowOwnership | undefined { - // Read as ComfyWorkflow, where both states are nullable. LoadedComfyWorkflow - // declares them present and the running store does not always honour that, - // so a missing state must not throw. - const activeGraphId = workflowIdOrUndefined( + const activeGraphId = routableWorkflowId( activeWorkflow.activeState?.id ?? activeWorkflow.initialState?.id ) const frameWorkflowId = - workflowIdOrUndefined(workflowId) ?? jobIdToStampedWorkflowId.get(jobId) + routableWorkflowId(workflowId) ?? jobIdToStampedWorkflowId.get(jobId) if (!frameWorkflowId || !activeGraphId) return return { owned: frameWorkflowId === activeGraphId, leg: 'workflow-id' } } - /** - * Resolution order, strongest first, kept as an explicit chain of single-leg - * predicates so the order is readable at one glance and each leg stays small. - * - * Returns which leg decided, because a rejection by a real identifier is a - * definite answer and only the `active-job` fallback is a guess worth - * reporting. - * - * @param workflowId The id the server stamped on the frame, where the caller - * has a frame in hand. Absent on a backend without ComfyUI#16763, on frames - * with no `prompt_id`, and for the callers holding no frame at all. - */ function resolveWorkflowOwnership( jobId: JobId, workflowId?: string @@ -621,15 +563,6 @@ export const useExecutionStore = defineStore('execution', () => { ) } - /** - * Whether frames for this job may paint the active workflow's canvas. - * Jobs whose owner is unknown are admitted unless another job is active. - * - * Recording the stamp here rather than at each frame handler is deliberate: - * this is the one chokepoint every stamped frame path already passes through - * (`execution_start`, `progress_state`, `executed`, `b_preview_with_metadata`), - * so a future frame path cannot acquire the stamp and forget to remember it. - */ function belongsToActiveWorkflow( jobId: JobId | undefined, workflowId?: string @@ -659,10 +592,6 @@ export const useExecutionStore = defineStore('execution', () => { rememberStampedWorkflowId(jobId, e.detail.workflow_id) const ownership = resolveWorkflowOwnership(jobId, e.detail.workflow_id) if (!ownership.owned) { - // A mismatch on a real identifier is a definite answer, not a diagnostic. - // Under Cloud's per-user fan-out every open tab sees every other tab's - // job starts, so reporting those raised one warning per foreign job on - // ordinary traffic. if (ownership.leg === 'active-job') { reportAmbiguousExecutionStartRejection(jobId) } @@ -1109,21 +1038,25 @@ export const useExecutionStore = defineStore('execution', () => { if (id && !activeJobIds.has(id)) resetExecutionState(id) } - /** Stops following queued jobs that ended without a terminal frame. */ function forgetFinishedJobs(jobIds: Iterable) { for (const jobId of jobIds) { if (jobId === activeJobId.value || !(jobId in queuedJobs.value)) continue - // Before forgetJob, which drops the jobId→workflow entry this needs. - // handleExecutionStart set the tab to running and only a terminal frame - // clears it, so without this the badge claims the tab is still running - // for the rest of the session. Not inside forgetJob: that also runs on a - // normal completion, which has a 'completed' status to keep. const workflow = jobIdToWorkflow.get(jobId) - if (workflow) clearWorkflowStatus(workflow) forgetJob(jobId) + if (workflow && !hasStartedJobForWorkflow(workflow)) { + clearWorkflowStatus(workflow) + } } } + function hasStartedJobForWorkflow(workflow: ComfyWorkflow): boolean { + return Object.entries(queuedJobs.value).some( + ([jobId, job]) => + job.executionStartedAt !== undefined && + jobIdToWorkflow.get(jobId) === workflow + ) + } + function forgetJob(jobId: JobId) { const progress = { ...nodeProgressStatesByJob.value } delete progress[jobId] @@ -1330,8 +1263,6 @@ export const useExecutionStore = defineStore('execution', () => { const startedJobIds = Object.keys(queuedJobs.value).filter( (jobId) => queuedJobs.value[jobId].executionStartedAt !== undefined ) - // Wrapped, not passed directly: findLast would hand the array index to the - // second parameter. const ownedJobId = startedJobIds.findLast((jobId) => belongsToActiveWorkflow(jobId) ) diff --git a/src/stores/executionStore.workflowOwnership.test.ts b/src/stores/executionStore.workflowOwnership.test.ts index c07c077f35b..be7aff92c5c 100644 --- a/src/stores/executionStore.workflowOwnership.test.ts +++ b/src/stores/executionStore.workflowOwnership.test.ts @@ -16,11 +16,6 @@ vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) const apiEvents: EventTarget = api -/** - * `instanceId` is the only identifier unique per open tab. A workflow id is - * shared by every copy of a graph, and a path is shared by a workflow reopened - * in a second tab, so neither can decide which tab a frame belongs to. - */ function workflow(path: string): LoadedComfyWorkflow { return fromPartial({ path, @@ -37,12 +32,6 @@ function promptNode() { return { inputs: {}, class_type: 'TestNode', _meta: { title: 'Node' } } } -/** - * Register tabs through the real store, so `isOpen` and `openWorkflows` are the - * production implementations. A hand-built double would keep passing if - * `isOpen` changed what it keys on, and `applyWorkflowStatus` refuses to record - * a status for a workflow the store does not consider open. - */ function openTabs(...workflows: LoadedComfyWorkflow[]) { const workflowStore = useWorkflowStore() for (const wf of workflows) { @@ -61,14 +50,10 @@ describe('executionStore workflow ownership', () => { store.bindExecutionEvents() }) - // `api` is a module singleton, so without this the listeners bound by each - // test accumulate and later tests run every earlier test's handler against a - // disposed store. Harmless for a boolean assertion, fatal for a counting one. afterEach(() => { store.unbindExecutionEvents() }) - /** Queue a job from `wf`, which is what records its owning tab. */ function queueJobFrom(jobId: string, wf: LoadedComfyWorkflow) { store.storeJob({ nodes: ['1'], @@ -96,8 +81,6 @@ describe('executionStore workflow ownership', () => { }) it('does not separate two tabs by their shared graph id', () => { - // Both fixtures carry 'shared-graph-id', which is what a copy-paste into a - // new tab produces. The gate must still tell them apart. queueJobFrom('job-a', workflowA) queueJobFrom('job-b', workflowB) @@ -124,7 +107,6 @@ describe('executionStore workflow ownership', () => { }) it('accepts a frame that names no job at all', () => { - // `status` frames carry no prompt_id, so there is nothing to attribute. expect(store.belongsToActiveWorkflow(undefined)).toBe(true) }) @@ -155,8 +137,6 @@ describe('executionStore workflow ownership', () => { describe("the frame's own workflow id, when no per-tab mapping exists", () => { it('places a job queued before this page load', () => { - // No instance and no path: the only thing left is what the server - // stamped on the frame, which is why ComfyUI#16763 exists. expect( store.belongsToActiveWorkflow('job-from-a-previous-page', 'other-graph') ).toBe(false) @@ -169,16 +149,12 @@ describe('executionStore workflow ownership', () => { }) it('ignores the all-zero sentinel rather than comparing it', () => { - // LGraph._id's default. Compared as a real id it matches nothing, so the - // tab's own frames were rejected. expect( store.belongsToActiveWorkflow('job-on-a-fresh-graph', zeroUuid) ).toBe(true) }) it('reaches the gate from a real progress_state frame', async () => { - // The store API is not the only caller: the handlers must forward the - // stamped id, or the leg is only reachable from tests. fire('progress_state', { prompt_id: 'job-elsewhere', workflow_id: 'other-graph', @@ -213,11 +189,6 @@ describe('executionStore workflow ownership', () => { }) describe('the stamp remembered from an earlier frame of the same job', () => { - /** - * A job this tab never queued, reaching the tab through Cloud's per-user - * fan-out. `handleExecutionStart` enrols it in `queuedJobs` before the gate - * runs, which is what makes it eligible for a reconnect replay. - */ function foreignJobStarted(jobId: string, workflowId?: string) { fire('execution_start', { prompt_id: jobId, @@ -237,10 +208,6 @@ describe('executionStore workflow ownership', () => { }) it('blocks a reconnect replay of a foreign job output', () => { - // `useReconnectQueueRefresh.replayOutputs` rebuilds `executed` by hand - // with no `workflow_id` field, and replays every job in `queuedJobs` — - // which includes the foreign jobs `handleExecutionStart` enrolled. This is - // the call `app.ts` then makes, with `detail.workflow_id` undefined. foreignJobStarted('job-elsewhere', 'other-graph') expect(store.belongsToActiveWorkflow('job-elsewhere', undefined)).toBe( @@ -256,12 +223,8 @@ describe('executionStore workflow ownership', () => { }) it('keeps the first stamp when a later frame disagrees', () => { - // Core merges workflow_metadata at send_sync enqueue time, so a frame - // carrying a different id belongs to a different job, not a relabelling. foreignJobStarted('job-elsewhere', 'other-graph') - // The call app.ts makes for an `executed` frame, carrying a second, - // disagreeing stamp for the same job. store.belongsToActiveWorkflow('job-elsewhere', 'shared-graph-id') expect( @@ -272,7 +235,6 @@ describe('executionStore workflow ownership', () => { it('loses to the tab instance, which is still the strongest leg', () => { queueJobFrom('job-a', workflowA) - // A foreign stamp naming B's graph arrives for a job A owns by instance. store.belongsToActiveWorkflow('job-a', 'other-graph') useWorkflowStore().activeWorkflow = workflowB @@ -295,8 +257,6 @@ describe('executionStore workflow ownership', () => { }) it('stops a tab switch from adopting a foreign job', async () => { - // adoptActiveWorkflowJob passes no id at all, so before the stamp was - // remembered a foreign job fell through to the active-job fallback. foreignJobStarted('job-elsewhere', 'other-graph') expect(store.queuedJobs['job-elsewhere']).toBeDefined() @@ -329,9 +289,6 @@ describe('executionStore workflow ownership', () => { } it('does not report a rejection decided by the frame workflow id', () => { - // Under Cloud's per-user fan-out every tab sees every other tab's job - // starts, so reporting these was one warning per foreign job on ordinary - // traffic. A mismatched id is a definite answer, not an ambiguous one. fire('execution_start', { prompt_id: 'job-elsewhere', workflow_id: 'other-graph', @@ -352,8 +309,6 @@ describe('executionStore workflow ownership', () => { }) it('still reports a rejection that is only a guess', () => { - // No instance, no path, no stamp: the active-job fallback is the one leg - // that guesses, so this is the rejection worth knowing about. queueJobFrom('job-a', workflowA) fire('execution_start', { prompt_id: 'job-a', timestamp: 1 }) expect(store.activeJobId).toBe('job-a') From e9270bdd58bf6e0104450f5543ac979e992b7913 Mon Sep 17 00:00:00 2001 From: bymyself Date: Thu, 29 Oct 2026 12:46:18 -0700 Subject: [PATCH 08/13] fix(execution): keep a newer terminal badge through stale-job cleanup Repairs the mrseek-reviews findings at d7c0105248. Correctness: forgetFinishedJobs released a workflow's status whenever no started job remained, so forgetting an older job that never got a terminal frame erased a newer job's Completed or Failed badge. Only an orphaned Running badge is released now. Coverage: the request body, the type-4 preview decoder and both app forwarding arguments each survived removal with every suite green. They now have independent falsifiers in api.queuePrompt, api.previewMetadata and an app case routed by the frame stamp alone. The reconnect spec asserted a badge that was already visible, so it could pass before cleanup ran. It now strands one job per workflow and waits for the orphaned badge to clear, which only happens inside the same cleanup batch that forgets the shared workflow's stale job. Also: name the ownership action for the stamp it remembers, finish the zeroUuid migration onto the defining package and drop the compatibility re-export, reuse createMockLoadedWorkflow, drop cases that repeat existing protection, and correct the ADR's progress_text attribution claim. --- .../tests/wsReconnectStaleJob.spec.ts | 160 ++++++++++-------- ...workflow-ownership-for-websocket-frames.md | 8 +- .../node/useProgressTextPreviews.ts | 2 +- .../graph/nodeShell/nodeShellState.test.ts | 3 +- src/core/graph/nodeShell/nodeShellState.ts | 2 +- src/lib/litegraph/src/LGraph.test.ts | 3 +- src/lib/litegraph/src/LGraph.ts | 3 +- src/lib/litegraph/src/LGraphNode.ts | 2 +- src/lib/litegraph/src/LLink.ts | 2 +- src/lib/litegraph/src/Reroute.ts | 2 +- .../src/subgraph/EmptySubgraphInput.ts | 2 +- .../src/subgraph/EmptySubgraphOutput.ts | 2 +- .../core/services/workflowService.test.ts | 2 +- .../workflow/core/services/workflowService.ts | 3 +- .../vueNodes/components/LGraphNodePreview.vue | 2 +- src/scripts/api.previewMetadata.test.ts | 91 ++++++++++ src/scripts/api.queuePrompt.test.ts | 69 ++++++++ src/scripts/app.test.ts | 75 +++++++- src/scripts/app.ts | 9 +- src/stores/executionErrorStore.ts | 2 +- .../executionStore.terminalRecovery.test.ts | 89 +++++++--- src/stores/executionStore.ts | 14 +- .../executionStore.workflowOwnership.test.ts | 111 ++++-------- src/utils/__tests__/litegraphTestUtils.ts | 2 +- src/utils/uuid.ts | 1 - 25 files changed, 460 insertions(+), 201 deletions(-) create mode 100644 src/scripts/api.previewMetadata.test.ts create mode 100644 src/scripts/api.queuePrompt.test.ts diff --git a/browser_tests/tests/wsReconnectStaleJob.spec.ts b/browser_tests/tests/wsReconnectStaleJob.spec.ts index 0878b557c32..6fcc87e3dd3 100644 --- a/browser_tests/tests/wsReconnectStaleJob.spec.ts +++ b/browser_tests/tests/wsReconnectStaleJob.spec.ts @@ -108,78 +108,100 @@ test.describe('WebSocket reconnect with stale job', { tag: '@ui' }, () => { const exec = new ExecutionHelper(comfyPage, ws) const topbar = comfyPage.menu.topbar - await comfyPage.workflow.waitForActiveWorkflow() - await comfyPage.workflow.waitForWorkflowIdle() - - const finishedJobId = await exec.run() - const runningJobId = await exec.run() - exec.executionStart(finishedJobId) - exec.executionStart(runningJobId) + // Two workflows, each with an unreadable job. The orphaned one is the + // completion barrier: its badge can only clear from inside the same + // `forgetFinishedJobs` batch that forgets the shared workflow's stale + // job, so observing it gone is what proves cleanup ran. Counting detail + // requests cannot — the counter moves before the response is fulfilled. + const { orphanedIndicator, sharedIndicator, staleJobIds, runningJobId } = + await test.step('Strand one job per workflow behind a live sibling', async () => { + await comfyPage.workflow.waitForActiveWorkflow() + await comfyPage.workflow.waitForWorkflowIdle() + + const orphanedJobId = await exec.run() + exec.executionStart(orphanedJobId) + + await comfyPage.workflow.loadWorkflow('default') + await comfyPage.workflow.waitForWorkflowIdle() + + const sharedStaleJobId = await exec.run() + const runningJobId = await exec.run() + exec.executionStart(sharedStaleJobId) + exec.executionStart(runningJobId) + + await comfyPage.workflow.newBlankWorkflow() + await comfyPage.workflow.waitForWorkflowIdle() + await expect.poll(() => topbar.getTabNames()).toHaveLength(3) + + const orphanedIndicator = topbar + .getTab(0) + .getByRole('img', { name: 'Running' }) + const sharedIndicator = topbar + .getTab(1) + .getByRole('img', { name: 'Running' }) + await expect(orphanedIndicator).toBeVisible() + await expect(sharedIndicator).toBeVisible() + + return { + orphanedIndicator, + sharedIndicator, + staleJobIds: [orphanedJobId, sharedStaleJobId], + runningJobId + } + }) - await topbar.newWorkflowButton.click() - await comfyPage.workflow.waitForWorkflowIdle() - await expect(topbar.getActiveTab()).toContainText('(2)') + await test.step('Recover the remaining job after stale-job cleanup', async () => { + const remainingJobScenario: Scenario = { + name: 'preserves the remaining same-workflow job', + queueBody: () => + JSON.stringify( + jobsResponse([ + { id: runningJobId, status: 'in_progress', create_time: 0 } + ]) + ), + expectsActiveAfter: true + } + const staleJobReads = await Promise.all( + staleJobIds.map((staleJobId) => + mockJobsRoute( + comfyPage, + new RegExp(`/api/jobs/${staleJobId}$`), + '{}', + 404 + ) + ) + ) - const backgroundTab = topbar.getTab(0) - const runningIndicator = backgroundTab.getByRole('img', { - name: 'Running' + // MAX_UNREADABLE_REFRESHES is 3, so three refresh passes reach the + // give-up boundary that calls forgetFinishedJobs. Each pass reads a + // stale job twice (the initial read and the retry), and a reconnect + // arriving mid-pass is absorbed into the in-flight refresh — so gate + // each reconnect on the previous pass having issued both of its reads, + // or two reconnects collapse into one pass and the boundary is missed. + let socket = ws + for (let pass = 1; pass <= 3; pass++) { + const nextSocketPromise = nextWebSocket() + await triggerReconnect( + comfyPage, + socket, + remainingJobScenario, + runningJobId + ) + for (const reads of staleJobReads) { + await expect.poll(reads).toBeGreaterThanOrEqual(2 * pass) + } + socket = await nextSocketPromise + } + + await expect( + orphanedIndicator, + 'the workflow whose only job went unreadable must release its badge' + ).toBeHidden() + await expect( + sharedIndicator, + 'the same cleanup batch must leave the still-running sibling alone' + ).toBeVisible() }) - await expect(runningIndicator).toBeVisible() - - const remainingJobScenario: Scenario = { - name: 'preserves the remaining same-workflow job', - queueBody: () => - JSON.stringify( - jobsResponse([ - { - id: runningJobId, - status: 'in_progress', - create_time: Date.now() - } - ]) - ), - expectsActiveAfter: true - } - const finishedJobReads = await mockJobsRoute( - comfyPage, - new RegExp(`/api/jobs/${finishedJobId}$`), - '{}', - 404 - ) - - const secondSocketPromise = nextWebSocket() - await triggerReconnect(comfyPage, ws, remainingJobScenario, runningJobId) - await expect.poll(finishedJobReads).toBeGreaterThanOrEqual(2) - const secondSocket = await secondSocketPromise - - const thirdSocketPromise = nextWebSocket() - await triggerReconnect( - comfyPage, - secondSocket, - remainingJobScenario, - runningJobId - ) - await expect.poll(finishedJobReads).toBeGreaterThanOrEqual(4) - const thirdSocket = await thirdSocketPromise - - const fourthSocketPromise = nextWebSocket() - await triggerReconnect( - comfyPage, - thirdSocket, - remainingJobScenario, - runningJobId - ) - await expect.poll(finishedJobReads).toBeGreaterThanOrEqual(6) - const fourthSocket = await fourthSocketPromise - - await triggerReconnect( - comfyPage, - fourthSocket, - remainingJobScenario, - runningJobId - ) - - await expect(runningIndicator).toBeVisible() }) test.describe('app mode skeleton', () => { diff --git a/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md b/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md index 39d04eed97f..efabcea5595 100644 --- a/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md +++ b/docs/adr/EXECUTION-ROUTING-0049-workflow-ownership-for-websocket-frames.md @@ -12,7 +12,7 @@ One `LGraph` and one `LGraphCanvas` serve every open workflow tab, so execution [ADR-GRAPH-DOCUMENT-0026](GRAPH-DOCUMENT-0026-frontend-document-model.md) D2 states the rule: a frame arriving on a push channel resolves its target document at ingress via the job map, never via the active pointer. It also states what to do at the boundary — "events with no job→uid resolution (page reloaded mid-run, jobs queued by another client) go to an explicit _unattributed_ bucket rather than being applied to the active document by default … misdelivery is not the fallback." -`#21666` implemented D2's addressing rule for the Agent, keying `belongsToActiveWorkflow` on `jobIdToWorkflowInstanceId` and gating the node-output and preview paths. That shipped without unit coverage, and without the wire contract Comfy-Org/ComfyUI#16763 and #16809 were merged to provide: the frontend sent no `workflow_metadata`, so the only id the server could stamp came from `extra_pnginfo`. +`#21666` implemented D2's addressing rule for the Agent, keying the ownership gate on `jobIdToWorkflowInstanceId` and gating the node-output and preview paths. That shipped without unit coverage, and without the wire contract Comfy-Org/ComfyUI#16763 and #16809 were merged to provide: the frontend sent no `workflow_metadata`, so the only id the server could stamp came from `extra_pnginfo`. This ADR records what the resolution order is, why the graph id is its weakest signal, and that the boundary departs from D2. @@ -24,7 +24,7 @@ This ADR records what the resolution order is, why the graph id is its weakest s **The all-zero UUID is not an id.** `LGraph._id` defaults to it and the codebase reads it as "no id yet", replacing it on configure and on clear. It is not sent as a routing key, and an incoming one is discarded rather than compared, because comparing it as a real id matches nothing and rejected a fresh graph's own frames. Withholding it from the request does not keep it off the wire: the same graph goes out under `extra_pnginfo` and the server falls back to the id there. -**The stamp is remembered per job, not re-read per frame.** The first stamped frame of a job records `jobId → workflow_id`, and the workflow-id leg reads it when the caller holds no frame. Three callers hold none: `adoptActiveWorkflowJob` on a tab switch, the `executed` events `useReconnectQueueRefresh` rebuilds by hand on reconnect, and `progress_text`. Without it those three skipped the leg and reached the `activeJobId` fallback, so a reconnect replay could paint a foreign job's output onto the visible graph — `handleExecutionStart` enrols a job in `queuedJobs` before the gate runs, and the replay follows every job in that map, so a rejected foreign job was still replayed unstamped. +**The stamp is remembered per job, not re-read per frame.** The first stamped frame of a job records `jobId → workflow_id`, and the workflow-id leg reads it when the caller holds no frame. Three callers hold none: `adoptActiveWorkflowJob` on a tab switch, the `executed` events `useReconnectQueueRefresh` rebuilds by hand on reconnect, and `progress_text` when its backend supplies `prompt_id`. Without it those three skipped the leg and reached the `activeJobId` fallback, so a reconnect replay could paint a foreign job's output onto the visible graph — `handleExecutionStart` enrols a job in `queuedJobs` before the gate runs, and the replay follows every job in that map, so a rejected foreign job was still replayed unstamped. First stamp wins: core merges `workflow_metadata` at `send_sync` enqueue time rather than at publication, so a frame already queued for a job cannot be relabelled by the next prompt, and a later disagreeing stamp belongs to a different job. The map is separate from `jobIdToWorkflowId` on purpose — that one is reactive, exported, and backs `runErrorKeyForJob`, so recording a foreign job's stamp there would file that job's errors against a local tab whenever the two share a graph id, which is the copy-paste case the resolution order exists to handle. Being populated for foreign jobs, it carries its own FIFO bound rather than relying on the local-job eviction paths. @@ -40,13 +40,15 @@ First stamp wins: core merges `workflow_metadata` at `send_sync` enqueue time ra **Gate on the workflow id alone.** This was tried on #20045 and was wrong, for the copy-paste reason above. Recorded because the id looks like the obvious key. +The same id-first shape is still open on #11951, which proposes a `messageMatchesActiveWorkflow` resolver consulting the frame's workflow id ahead of session ownership, and it is the inverse of the order decided here. Two tabs holding one copied graph id would match each other's jobs under it, which is exactly what the instance and path legs exist to prevent. Its resolver is therefore superseded by this ADR; remaining work on that branch should be carried onto this gate rather than restoring the competing policy during integration. #20982 overlaps the same seam and is covered by the same ruling. Whichever of #22186's move of the API and execution contracts into `packages/api-client` lands second has to carry this PR's request field, preview decoding and stamped types into that package. + **A `contextvars` owner on the backend.** Rejected on a mechanism error: `prompt_worker` is a daemon thread and `send_json` runs on the event loop, so a ContextVar set in the worker is unset at send time. The attribute merged in the body of `send_sync` is what shipped. ## Consequences **The `activeJobId` fallback is load-bearing and is the weakest point.** Single-tab behaviour after a reload is preserved, and it is narrower than a blanket permissive rule, since a foreign job's unresolvable frame is dropped while another job is active. What remains is that with two tabs open and a frame unresolvable, it can land on the wrong one. -**`status` stays unattributable; `progress_text` no longer is.** `status` carries no `prompt_id`, because one server-wide socket serves every workflow. `progress_text` is a packed binary frame that `send_sync` cannot stamp, and the frontend already reads a `supports_progress_text_metadata` server flag that no core version sets — tracked as Comfy-Org/ComfyUI#16887. Its gate now resolves by workflow id anyway, through the stamp remembered from an earlier stamped frame of the same job, so #16887 would improve the first-frame case rather than unblock the leg. +**`status` and current core `progress_text` both stay unattributable.** Neither supplies a `prompt_id` to the gate. `status` carries none because one server-wide socket serves every workflow. `progress_text` is a packed binary frame that `send_sync` cannot stamp, and the frontend decodes a job id out of it only when the server sets `supports_progress_text_metadata`, which no core version does — tracked as Comfy-Org/ComfyUI#16887. With the flag absent the gate is called with no job id at all, so it returns before any remembered-stamp lookup, and #16887 is what unblocks the leg rather than merely improving its first frame. A backend that does supply `prompt_id` gets the remembered workflow stamp without having to add `workflow_id` to every text frame. **The two backends merge in opposite orders.** Core merges `{**workflow_metadata, **data}`, so a frame's own fields win. The Cloud gateway assigns `prompt_id` and `workflow_id` after the fact, so the backend wins, and it does not read `workflow_metadata` at all. Neither order should be relied on; the routing ids that arrive are authoritative whichever side set them. diff --git a/src/composables/node/useProgressTextPreviews.ts b/src/composables/node/useProgressTextPreviews.ts index 9f5343453e9..92c028007bb 100644 --- a/src/composables/node/useProgressTextPreviews.ts +++ b/src/composables/node/useProgressTextPreviews.ts @@ -26,7 +26,7 @@ export function useProgressTextPreviews() { const { nodeId, text, prompt_id } = e.detail if (!text || !nodeId) return - if (!executionStore.belongsToActiveWorkflow(prompt_id)) return + if (!executionStore.rememberStampAndCheckActiveWorkflow(prompt_id)) return const executionId = String(nodeId) const currentId = executionId.includes(':') diff --git a/src/core/graph/nodeShell/nodeShellState.test.ts b/src/core/graph/nodeShell/nodeShellState.test.ts index 5a358effcdd..aa65ec95cc8 100644 --- a/src/core/graph/nodeShell/nodeShellState.test.ts +++ b/src/core/graph/nodeShell/nodeShellState.test.ts @@ -11,7 +11,8 @@ import { useNodeDataStore } from '@/stores/nodeDataStore' import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId' import { UNASSIGNED_NODE_ID } from '@comfyorg/graph-model/nodeId' import type { NodeState } from '@comfyorg/graph-model/nodeState' -import { createUuidv4, zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' +import { createUuidv4 } from '@/utils/uuid' import { createNodeShellState, unregisterNodeState } from './nodeShellState' diff --git a/src/core/graph/nodeShell/nodeShellState.ts b/src/core/graph/nodeShell/nodeShellState.ts index c84db7a4302..281242b04c1 100644 --- a/src/core/graph/nodeShell/nodeShellState.ts +++ b/src/core/graph/nodeShell/nodeShellState.ts @@ -10,7 +10,7 @@ import { useNodeDataStore } from '@/stores/nodeDataStore' import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId' import { UNASSIGNED_NODE_ID } from '@comfyorg/graph-model/nodeId' import { LGraphEventMode } from '@comfyorg/graph-model/globalEnums' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import type { INodeInputSlot, diff --git a/src/lib/litegraph/src/LGraph.test.ts b/src/lib/litegraph/src/LGraph.test.ts index db3b04ed193..f447e649331 100644 --- a/src/lib/litegraph/src/LGraph.test.ts +++ b/src/lib/litegraph/src/LGraph.test.ts @@ -28,7 +28,8 @@ import { registerDocBoundRootGraphProbe } from '@/lib/litegraph/src/docBoundGraphs' import type { UUID } from '@/utils/uuid' -import { createUuidv4, zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' +import { createUuidv4 } from '@/utils/uuid' import { useEntityIdStore } from '@/stores/entityIdStore' import { useLinkStore } from '@/stores/linkStore' import { useExecutionOrderStore } from '@/stores/executionOrderStore' diff --git a/src/lib/litegraph/src/LGraph.ts b/src/lib/litegraph/src/LGraph.ts index c7024409b5f..7fe17eb045e 100644 --- a/src/lib/litegraph/src/LGraph.ts +++ b/src/lib/litegraph/src/LGraph.ts @@ -19,7 +19,8 @@ import { detachNodeFromStores } from '@/core/graph/nodeShell/nodeShellLifecycle' import type { UUID } from '@/utils/uuid' -import { createUuidv4, zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' +import { createUuidv4 } from '@/utils/uuid' import { reportError } from '@comfyorg/telemetry/reportError' import { attachGroupLayout, diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index fd4a0f3acc1..1e4dc13855a 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -69,7 +69,7 @@ import { } from '@/types/widgetVisibility' import { adjustColor } from '@comfyorg/shared-frontend-utils/colorUtil' import type { ColorAdjustOptions } from '@comfyorg/shared-frontend-utils/colorUtil' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { commonType, isNodeBindable, diff --git a/src/lib/litegraph/src/LLink.ts b/src/lib/litegraph/src/LLink.ts index 872a72d80ad..217c742930e 100644 --- a/src/lib/litegraph/src/LLink.ts +++ b/src/lib/litegraph/src/LLink.ts @@ -18,7 +18,7 @@ import { toOwningGraphId } from '@comfyorg/graph-model/graphScopeId' import type { GraphScope } from '@comfyorg/graph-model/graphScopeId' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { toLinkId } from '@comfyorg/graph-model/linkId' import { UNASSIGNED_NODE_ID, diff --git a/src/lib/litegraph/src/Reroute.ts b/src/lib/litegraph/src/Reroute.ts index 15b25c6d91b..1a6bcdc8557 100644 --- a/src/lib/litegraph/src/Reroute.ts +++ b/src/lib/litegraph/src/Reroute.ts @@ -12,7 +12,7 @@ import { toOwningGraphId } from '@comfyorg/graph-model/graphScopeId' import type { GraphScope } from '@comfyorg/graph-model/graphScopeId' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import type { FloatingRerouteSlot, RerouteChain diff --git a/src/lib/litegraph/src/subgraph/EmptySubgraphInput.ts b/src/lib/litegraph/src/subgraph/EmptySubgraphInput.ts index 0988164df7c..bca6edd1970 100644 --- a/src/lib/litegraph/src/subgraph/EmptySubgraphInput.ts +++ b/src/lib/litegraph/src/subgraph/EmptySubgraphInput.ts @@ -8,7 +8,7 @@ import type { RerouteId } from '@comfyorg/graph-model/rerouteId' import type { PointTuple as Point } from '@comfyorg/shared-frontend-utils/geometry' import type { INodeInputSlot } from '@comfyorg/graph-model/slots' import { nextUniqueName } from '@/lib/litegraph/src/strings' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { SubgraphInput } from './SubgraphInput' diff --git a/src/lib/litegraph/src/subgraph/EmptySubgraphOutput.ts b/src/lib/litegraph/src/subgraph/EmptySubgraphOutput.ts index 9890a13e6e4..27e15abe73d 100644 --- a/src/lib/litegraph/src/subgraph/EmptySubgraphOutput.ts +++ b/src/lib/litegraph/src/subgraph/EmptySubgraphOutput.ts @@ -8,7 +8,7 @@ import type { RerouteId } from '@comfyorg/graph-model/rerouteId' import type { PointTuple as Point } from '@comfyorg/shared-frontend-utils/geometry' import type { INodeOutputSlot } from '@comfyorg/graph-model/slots' import { nextUniqueName } from '@/lib/litegraph/src/strings' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { SubgraphOutput } from './SubgraphOutput' diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index 2fce348199b..6c01122e653 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -42,7 +42,7 @@ import { createTestSubgraph } from '@/lib/litegraph/src/subgraph/__fixtures__/su import { createMockChangeTracker } from '@/utils/__tests__/litegraphTestUtils' import type { AppMode } from '@comfyorg/graph-model/appMode' import { isValidUuid } from '@/utils/formatUtil' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { t } from '@/i18n' import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index 821df1759ad..0b80712001d 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -52,7 +52,8 @@ import { } from '@/utils/formatUtil' import type { AppMode } from '@comfyorg/graph-model/appMode' import type { UUID } from '@/utils/uuid' -import { ensureNonZeroUuid, zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' +import { ensureNonZeroUuid } from '@/utils/uuid' export function readWorkflowDraftLineage(path: string) { return useWorkflowDraftStoreV2().getDraft(path)?.lineage ?? null diff --git a/src/renderer/extensions/vueNodes/components/LGraphNodePreview.vue b/src/renderer/extensions/vueNodes/components/LGraphNodePreview.vue index c456908c3b7..2ea3ab4374d 100644 --- a/src/renderer/extensions/vueNodes/components/LGraphNodePreview.vue +++ b/src/renderer/extensions/vueNodes/components/LGraphNodePreview.vue @@ -51,7 +51,7 @@ import { useWidgetStore } from '@/stores/widgetStore' import { toNodeId } from '@comfyorg/graph-model/nodeId' import type { NodeState } from '@comfyorg/graph-model/nodeState' import type { WidgetValue } from '@/types/simplifiedWidget' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { matchesWidgetName } from '@/utils/widgetBinding' import type { WidgetValueBinding } from '@/utils/widgetBinding' import { cn } from '@comfyorg/tailwind-utils' diff --git a/src/scripts/api.previewMetadata.test.ts b/src/scripts/api.previewMetadata.test.ts new file mode 100644 index 00000000000..d888a356947 --- /dev/null +++ b/src/scripts/api.previewMetadata.test.ts @@ -0,0 +1,91 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { ComfyApi } from '@/scripts/api' + +/** Minimal socket double; the decoder only needs the `message` handler. */ +class FakeWebSocket { + static readonly OPEN = 1 + static instances: FakeWebSocket[] = [] + + readyState = FakeWebSocket.OPEN + binaryType = '' + send = vi.fn() + removeEventListener = vi.fn() + handlers: Record void> = {} + addEventListener = vi.fn( + (event: string, handler: (event: unknown) => void) => { + this.handlers[event] = handler + } + ) + close = vi.fn() + + constructor(readonly url: string) { + FakeWebSocket.instances.push(this) + } + + receiveBinary(data: ArrayBuffer) { + this.handlers['message']?.({ data }) + } +} + +/** Encode the type-4 preview frame: tag, metadata length, JSON, image bytes. */ +function previewFrame( + metadata: Record, + imageBytes: number[] +): ArrayBuffer { + const json = new TextEncoder().encode(JSON.stringify(metadata)) + const buffer = new ArrayBuffer(8 + json.byteLength + imageBytes.length) + const view = new DataView(buffer) + view.setUint32(0, 4) + view.setUint32(4, json.byteLength) + const bytes = new Uint8Array(buffer) + bytes.set(json, 8) + bytes.set(imageBytes, 8 + json.byteLength) + return buffer +} + +describe('ComfyApi type-4 preview metadata', () => { + let api: ComfyApi + + beforeEach(async () => { + FakeWebSocket.instances = [] + vi.stubGlobal('WebSocket', FakeWebSocket) + api = new ComfyApi() + await api.init() + }) + + afterEach(() => { + api.socket = null + }) + + function dispatchedPreview(metadata: Record) { + const detail = vi.fn() + api.addEventListener('b_preview_with_metadata', (event) => { + detail(event.detail) + }) + FakeWebSocket.instances[0].receiveBinary(previewFrame(metadata, [1, 2, 3])) + return detail.mock.calls[0]?.[0] + } + + const baseMetadata = { + node_id: '1', + display_node_id: '1', + parent_node_id: '1', + real_node_id: '1', + prompt_id: 'job-1', + image_type: 'image/png' + } + + it('decodes the stamped workflow id onto the preview event', () => { + expect( + dispatchedPreview({ ...baseMetadata, workflow_id: 'graph-7' }) + ).toMatchObject({ jobId: 'job-1', workflowId: 'graph-7' }) + }) + + it('leaves the workflow id undefined when the frame carries none', () => { + const detail = dispatchedPreview(baseMetadata) + + expect(detail).toMatchObject({ jobId: 'job-1' }) + expect(detail.workflowId).toBeUndefined() + }) +}) diff --git a/src/scripts/api.queuePrompt.test.ts b/src/scripts/api.queuePrompt.test.ts new file mode 100644 index 00000000000..71a2534e0c2 --- /dev/null +++ b/src/scripts/api.queuePrompt.test.ts @@ -0,0 +1,69 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema' +import { zeroUuid } from '@comfyorg/graph-model/uuid' +import { api } from '@/scripts/api' + +const promptResponse = () => + ({ + status: 200, + json: () => Promise.resolve({ prompt_id: 'job-1', node_errors: {} }) + }) as unknown as Response + +function workflowWithId(id: string | undefined): ComfyWorkflowJSON { + return fromPartial({ + id, + revision: 0, + last_node_id: 0, + last_link_id: 0, + nodes: [], + links: [], + groups: [], + extra: {}, + version: 0.4 + }) +} + +describe('api queuePrompt workflow_metadata', () => { + let fetchApiSpy: ReturnType + + beforeEach(() => { + fetchApiSpy = vi.spyOn(api, 'fetchApi').mockResolvedValue(promptResponse()) + }) + + async function postedBody(id: string | undefined) { + await api.queuePrompt(0, { + output: {}, + workflow: workflowWithId(id) + }) + const [, init] = fetchApiSpy.mock.calls[0] as [string, RequestInit] + return JSON.parse(init.body as string) + } + + it.for([ + { + name: 'a routable workflow id', + id: '11111111-2222-3333-4444-555555555555' + }, + { name: 'an id the server did not normalise', id: 'graph-7' } + ])('sends $name as workflow_metadata', async ({ id }) => { + expect(await postedBody(id)).toMatchObject({ + workflow_metadata: { workflow_id: id } + }) + }) + + it.for([ + { name: 'the all-zero sentinel', id: zeroUuid }, + { name: 'an absent id', id: undefined }, + { name: 'an empty id', id: '' } + ])('omits workflow_metadata for $name', async ({ id }) => { + expect(await postedBody(id)).not.toHaveProperty('workflow_metadata') + }) + + it('still carries the graph under extra_pnginfo when the id is withheld', async () => { + const body = await postedBody(zeroUuid) + + expect(body.extra_data.extra_pnginfo.workflow.id).toBe(zeroUuid) + }) +}) diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 67600e4160c..a0bd512319e 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -118,7 +118,7 @@ import { extractFilesFromDragEvent } from '@/utils/eventUtils' import { MIME_ASSET_INFO } from '@/platform/assets/schemas/mediaAssetSchema' import { reportError } from '@comfyorg/telemetry/reportError' import { useCanvasScheduler } from '@/renderer/core/canvas/useCanvasScheduler' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import type { importA1111 } from './pnginfo' type WorkflowService = ReturnType @@ -3636,6 +3636,79 @@ describe('ComfyApp', () => { ).toEqual(['blob:1']) }) + it('routes unmapped outputs and previews by the frame workflow id alone', () => { + Reflect.set(app, 'rootGraphInternal', new LGraph()) + const workflowA = markLoaded( + new ComfyWorkflow({ path: 'workflows/a.json', modified: 0, size: 0 }) + ) + workflowA.changeTracker.activeState = workflowGraphData(workflowAId) + useWorkflowStore().activeWorkflow = workflowA + // No storeJob for any of these ids: with no instance or session-path + // mapping and no active job, the fallback would admit every frame, so + // the stamp forwarded from the wire is the only thing that can reject + // the foreign ones. + + vi.spyOn(URL, 'createObjectURL').mockImplementation( + (blob) => `blob:${blob instanceof Blob ? blob.size : 0}` + ) + const addEventListener = vi.spyOn(api, 'addEventListener') + Reflect.apply(Reflect.get(app, 'addApiUpdateHandlers'), app, []) + function handlerFor(event: string) { + return addEventListener.mock.calls.find( + ([name]) => name === event + )?.[1] as EventListener | undefined + } + function executedEvent(jobId: string, workflowId: string) { + return new CustomEvent('executed', { + detail: { + node: '1', + display_node: '1', + prompt_id: jobId, + workflow_id: workflowId, + output: { text: [jobId] } + } + }) + } + function previewEvent( + jobId: string, + blobText: string, + workflowId: string + ) { + return new CustomEvent('b_preview_with_metadata', { + detail: { + blob: new Blob([blobText]), + nodeId: '1', + parentNodeId: '1', + displayNodeId: '1', + realNodeId: '1', + jobId, + workflowId + } + }) + } + + // A fresh job id per ingress, so a stamp remembered on one path cannot + // stand in for missing wiring on another. + handlerFor('executed')?.(executedEvent('job-own-output', workflowAId)) + handlerFor('b_preview_with_metadata')?.( + previewEvent('job-own-preview', 'a', workflowAId) + ) + handlerFor('executed')?.(executedEvent('job-foreign-output', workflowBId)) + handlerFor('b_preview_with_metadata')?.( + previewEvent('job-foreign-preview', 'bb', workflowBId) + ) + + const nodeOutputStore = useNodeOutputStore() + const executionId = createNodeExecutionId([1]) + expect( + nodeOutputStore.getNodeOutputByExecutionId(executionId), + "the later foreign output must not overwrite the visible tab's" + ).toEqual({ text: ['job-own-output'] }) + expect( + nodeOutputStore.getNodePreviewImagesByExecutionId(executionId) + ).toEqual(['blob:1']) + }) + it('restores the failed run state when returning to a workflow tab', async () => { const workflowService = await useRealWorkflowService() const graph = new LGraph() diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 564e27d3f49..4de1b7753ed 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -786,7 +786,7 @@ export class ComfyApp implements IComfyApp { api.addEventListener('executed', ({ detail }) => { if ( - !useExecutionStore().belongsToActiveWorkflow( + !useExecutionStore().rememberStampAndCheckActiveWorkflow( detail.prompt_id, detail.workflow_id ) @@ -833,7 +833,12 @@ export class ComfyApp implements IComfyApp { if (!displayNodeExecutionId) return const blobUrl = createSharedObjectUrl(blob) useJobPreviewStore().setPreviewUrl(jobId, blobUrl, displayNodeId) - if (!useExecutionStore().belongsToActiveWorkflow(jobId, workflowId)) { + if ( + !useExecutionStore().rememberStampAndCheckActiveWorkflow( + jobId, + workflowId + ) + ) { releaseSharedObjectUrl(blobUrl) return } diff --git a/src/stores/executionErrorStore.ts b/src/stores/executionErrorStore.ts index fed60c7393d..06e928e5411 100644 --- a/src/stores/executionErrorStore.ts +++ b/src/stores/executionErrorStore.ts @@ -39,7 +39,7 @@ import { getNodeByExecutionId } from '@/utils/graphTraversalUtil' import type { UUID } from '@/utils/uuid' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' import { SIMPLE_ERROR_TYPES, errorsForSlot, diff --git a/src/stores/executionStore.terminalRecovery.test.ts b/src/stores/executionStore.terminalRecovery.test.ts index 23850cfce06..3f70d6c44d3 100644 --- a/src/stores/executionStore.terminalRecovery.test.ts +++ b/src/stores/executionStore.terminalRecovery.test.ts @@ -1,10 +1,10 @@ -import { fromPartial } from '@total-typescript/shoehorn' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { api } from '@/scripts/api' import { useExecutionStore } from '@/stores/executionStore' +import { createMockLoadedWorkflow } from '@/utils/__tests__/litegraphTestUtils' vi.mock(import('@/composables/useAppMode')) vi.mock(import('@comfyorg/telemetry')) @@ -14,7 +14,7 @@ vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) const apiEvents: EventTarget = api function workflow(path: string): LoadedComfyWorkflow { - return fromPartial({ + return createMockLoadedWorkflow({ path, instanceId: `instance-${path}`, activeState: { id: `graph-${path}` }, @@ -47,10 +47,7 @@ describe('executionStore terminal-frame recovery', () => { store.unbindExecutionEvents() }) - function startedJobWithNoTerminalFrame( - jobId: string, - wf: LoadedComfyWorkflow - ) { + function queueJob(jobId: string, wf: LoadedComfyWorkflow) { store.storeJob({ nodes: ['1'], id: jobId, @@ -58,6 +55,14 @@ describe('executionStore terminal-frame recovery', () => { workflow: wf, mode: 'graph' }) + return jobId + } + + function startedJobWithNoTerminalFrame( + jobId: string, + wf: LoadedComfyWorkflow + ) { + queueJob(jobId, wf) apiEvents.dispatchEvent( new CustomEvent('execution_start', { detail: { prompt_id: jobId, timestamp: 1 } @@ -94,18 +99,6 @@ describe('executionStore terminal-frame recovery', () => { ).toBeUndefined() }) - it('leaves a job the server still reports as running alone', async () => { - const jobId = startedJobWithNoTerminalFrame('job-b', workflowB) - await vi.waitFor(() => - expect(store.nodeProgressStatesByJob[jobId]).toBeDefined() - ) - - store.forgetFinishedJobs([]) - - expect(store.getWorkflowStatus(workflowB)).toBe('running') - expect(store.nodeProgressStatesByJob[jobId]).toBeDefined() - }) - it('does not disturb a second tab while forgetting one job', () => { startedJobWithNoTerminalFrame('job-a', workflowA) const jobB = startedJobWithNoTerminalFrame('job-b', workflowB) @@ -118,14 +111,60 @@ describe('executionStore terminal-frame recovery', () => { ).toBe('running') }) - it('keeps a tab running while another started job uses it', () => { - const firstJob = startedJobWithNoTerminalFrame('job-b-1', workflowB) - startedJobWithNoTerminalFrame('job-b-2', workflowB) + const siblingCases: { + name: string + registerSibling: () => string + expectedStatus: 'running' | undefined + }[] = [ + { + name: 'started', + registerSibling: () => + startedJobWithNoTerminalFrame('job-b-2', workflowB), + expectedStatus: 'running' + }, + { + name: 'pending', + registerSibling: () => queueJob('job-b-2', workflowB), + expectedStatus: undefined + } + ] + + it.for(siblingCases)( + 'keeps the tab running only while a $name sibling holds it', + ({ registerSibling, expectedStatus }) => { + const firstJob = startedJobWithNoTerminalFrame('job-b-1', workflowB) + registerSibling() + + store.forgetFinishedJobs([firstJob]) + + expect(store.getWorkflowStatus(workflowB)).toBe(expectedStatus) + expect(store.queuedJobs[firstJob]).toBeUndefined() + expect(store.queuedJobs['job-b-2']).toBeDefined() + } + ) + + it('keeps a newer terminal badge when an older unreadable job is forgotten', () => { + const staleJob = startedJobWithNoTerminalFrame('job-b-stale', workflowB) + const completedJob = startedJobWithNoTerminalFrame( + 'job-b-completed', + workflowB + ) + apiEvents.dispatchEvent( + new CustomEvent('execution_success', { + detail: { prompt_id: completedJob, timestamp: 2 } + }) + ) + expect(store.getWorkflowStatus(workflowB)).toBe('completed') + expect( + store.queuedJobs[completedJob], + 'the completed job is already forgotten, so it cannot hold the badge' + ).toBeUndefined() - store.forgetFinishedJobs([firstJob]) + store.forgetFinishedJobs([staleJob]) - expect(store.getWorkflowStatus(workflowB)).toBe('running') - expect(store.queuedJobs[firstJob]).toBeUndefined() - expect(store.queuedJobs['job-b-2']).toBeDefined() + expect( + store.getWorkflowStatus(workflowB), + 'only an orphaned running badge may be released' + ).toBe('completed') }) }) diff --git a/src/stores/executionStore.ts b/src/stores/executionStore.ts index 424b16d841e..0f891bb13a4 100644 --- a/src/stores/executionStore.ts +++ b/src/stores/executionStore.ts @@ -563,7 +563,7 @@ export const useExecutionStore = defineStore('execution', () => { ) } - function belongsToActiveWorkflow( + function rememberStampAndCheckActiveWorkflow( jobId: JobId | undefined, workflowId?: string ): boolean { @@ -749,7 +749,7 @@ export const useExecutionStore = defineStore('execution', () => { function applyProgressState(detail: ProgressStateWsMessage) { const { nodes, prompt_id: jobId, workflow_id: workflowId } = detail - const isOwned = belongsToActiveWorkflow(jobId, workflowId) + const isOwned = rememberStampAndCheckActiveWorkflow(jobId, workflowId) if (isOwned) { revokeStartedNodePreviews( @@ -1043,7 +1043,11 @@ export const useExecutionStore = defineStore('execution', () => { if (jobId === activeJobId.value || !(jobId in queuedJobs.value)) continue const workflow = jobIdToWorkflow.get(jobId) forgetJob(jobId) - if (workflow && !hasStartedJobForWorkflow(workflow)) { + if ( + workflow && + getWorkflowStatus(workflow) === 'running' && + !hasStartedJobForWorkflow(workflow) + ) { clearWorkflowStatus(workflow) } } @@ -1264,7 +1268,7 @@ export const useExecutionStore = defineStore('execution', () => { (jobId) => queuedJobs.value[jobId].executionStartedAt !== undefined ) const ownedJobId = startedJobIds.findLast((jobId) => - belongsToActiveWorkflow(jobId) + rememberStampAndCheckActiveWorkflow(jobId) ) executionIdToLocatorCache.clear() if (!ownedJobId) { @@ -1306,7 +1310,7 @@ export const useExecutionStore = defineStore('execution', () => { runningJobIds, runningWorkflowCount, initializingJobIds, - belongsToActiveWorkflow, + rememberStampAndCheckActiveWorkflow, isActiveWorkflowRunning, isJobInitializing, clearInitializationByJobId, diff --git a/src/stores/executionStore.workflowOwnership.test.ts b/src/stores/executionStore.workflowOwnership.test.ts index be7aff92c5c..336382622f5 100644 --- a/src/stores/executionStore.workflowOwnership.test.ts +++ b/src/stores/executionStore.workflowOwnership.test.ts @@ -1,5 +1,4 @@ import { reportError } from '@comfyorg/telemetry/reportError' -import { fromPartial } from '@total-typescript/shoehorn' import { nextTick } from 'vue' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -7,7 +6,8 @@ import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/ import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { api } from '@/scripts/api' import { useExecutionStore } from '@/stores/executionStore' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' +import { createMockLoadedWorkflow } from '@/utils/__tests__/litegraphTestUtils' vi.mock(import('@/composables/useAppMode')) vi.mock(import('@comfyorg/telemetry')) @@ -17,7 +17,7 @@ vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) const apiEvents: EventTarget = api function workflow(path: string): LoadedComfyWorkflow { - return fromPartial({ + return createMockLoadedWorkflow({ path, instanceId: `instance-${path}`, activeState: { id: 'shared-graph-id' }, @@ -68,55 +68,25 @@ describe('executionStore workflow ownership', () => { apiEvents.dispatchEvent(new CustomEvent(event, { detail })) } - it('rejects a frame owned by another open tab', () => { - queueJobFrom('job-b', workflowB) - - expect(store.belongsToActiveWorkflow('job-b')).toBe(false) - }) - - it('accepts the visible tab own frame', () => { - queueJobFrom('job-a', workflowA) - - expect(store.belongsToActiveWorkflow('job-a')).toBe(true) - }) - it('does not separate two tabs by their shared graph id', () => { queueJobFrom('job-a', workflowA) queueJobFrom('job-b', workflowB) - expect(store.belongsToActiveWorkflow('job-a')).toBe(true) - expect(store.belongsToActiveWorkflow('job-b')).toBe(false) - }) - - describe('a job whose owning tab is unknown', () => { - it('is accepted while nothing else is running', () => { - expect(store.belongsToActiveWorkflow('job-from-a-previous-page')).toBe( - true - ) - }) - - it('is rejected while another job is active', () => { - queueJobFrom('job-a', workflowA) - fire('execution_start', { prompt_id: 'job-a', timestamp: 1 }) - expect(store.activeJobId).toBe('job-a') - - expect(store.belongsToActiveWorkflow('job-from-a-previous-page')).toBe( - false - ) - }) + expect(store.rememberStampAndCheckActiveWorkflow('job-a')).toBe(true) + expect(store.rememberStampAndCheckActiveWorkflow('job-b')).toBe(false) }) it('accepts a frame that names no job at all', () => { - expect(store.belongsToActiveWorkflow(undefined)).toBe(true) + expect(store.rememberStampAndCheckActiveWorkflow(undefined)).toBe(true) }) describe('the session path, when no tab instance is known', () => { it('places a job by the path it was queued from', () => { store.ensureSessionWorkflowPath('job-b', workflowB.path) - expect(store.belongsToActiveWorkflow('job-b')).toBe(false) + expect(store.rememberStampAndCheckActiveWorkflow('job-b')).toBe(false) useWorkflowStore().activeWorkflow = workflowB - expect(store.belongsToActiveWorkflow('job-b')).toBe(true) + expect(store.rememberStampAndCheckActiveWorkflow('job-b')).toBe(true) }) it('loses to the tab instance when the two disagree', () => { @@ -129,7 +99,7 @@ describe('executionStore workflow ownership', () => { useWorkflowStore().activeWorkflow = workflowB expect( - store.belongsToActiveWorkflow('job-a'), + store.rememberStampAndCheckActiveWorkflow('job-a'), 'the instance still says A, so B does not own it' ).toBe(false) }) @@ -138,10 +108,13 @@ describe('executionStore workflow ownership', () => { describe("the frame's own workflow id, when no per-tab mapping exists", () => { it('places a job queued before this page load', () => { expect( - store.belongsToActiveWorkflow('job-from-a-previous-page', 'other-graph') + store.rememberStampAndCheckActiveWorkflow( + 'job-from-a-previous-page', + 'other-graph' + ) ).toBe(false) expect( - store.belongsToActiveWorkflow( + store.rememberStampAndCheckActiveWorkflow( 'job-from-a-previous-page', 'shared-graph-id' ) @@ -150,7 +123,10 @@ describe('executionStore workflow ownership', () => { it('ignores the all-zero sentinel rather than comparing it', () => { expect( - store.belongsToActiveWorkflow('job-on-a-fresh-graph', zeroUuid) + store.rememberStampAndCheckActiveWorkflow( + 'job-on-a-fresh-graph', + zeroUuid + ) ).toBe(true) }) @@ -182,7 +158,7 @@ describe('executionStore workflow ownership', () => { store.ensureSessionWorkflowPath('job-b', workflowB.path) expect( - store.belongsToActiveWorkflow('job-b', 'shared-graph-id'), + store.rememberStampAndCheckActiveWorkflow('job-b', 'shared-graph-id'), 'the path says B owns it, even though the graph id matches A' ).toBe(false) }) @@ -202,56 +178,44 @@ describe('executionStore workflow ownership', () => { foreignJobStarted('job-elsewhere', 'other-graph') expect( - store.belongsToActiveWorkflow('job-elsewhere'), + store.rememberStampAndCheckActiveWorkflow('job-elsewhere'), 'the stamp seen on execution_start still decides when no id is passed' ).toBe(false) }) - it('blocks a reconnect replay of a foreign job output', () => { - foreignJobStarted('job-elsewhere', 'other-graph') - - expect(store.belongsToActiveWorkflow('job-elsewhere', undefined)).toBe( - false - ) - }) - - it('is not consulted for a job this tab owns', () => { - queueJobFrom('job-a', workflowA) - foreignJobStarted('job-a', 'shared-graph-id') - - expect(store.belongsToActiveWorkflow('job-a')).toBe(true) - }) - it('keeps the first stamp when a later frame disagrees', () => { foreignJobStarted('job-elsewhere', 'other-graph') - store.belongsToActiveWorkflow('job-elsewhere', 'shared-graph-id') + store.rememberStampAndCheckActiveWorkflow( + 'job-elsewhere', + 'shared-graph-id' + ) expect( - store.belongsToActiveWorkflow('job-elsewhere'), + store.rememberStampAndCheckActiveWorkflow('job-elsewhere'), 'the later stamp must not relabel the job onto the visible tab' ).toBe(false) }) it('loses to the tab instance, which is still the strongest leg', () => { queueJobFrom('job-a', workflowA) - store.belongsToActiveWorkflow('job-a', 'other-graph') + store.rememberStampAndCheckActiveWorkflow('job-a', 'other-graph') useWorkflowStore().activeWorkflow = workflowB expect( - store.belongsToActiveWorkflow('job-a'), + store.rememberStampAndCheckActiveWorkflow('job-a'), 'the instance says A, so the remembered stamp must not outrank it' ).toBe(false) useWorkflowStore().activeWorkflow = workflowA - expect(store.belongsToActiveWorkflow('job-a')).toBe(true) + expect(store.rememberStampAndCheckActiveWorkflow('job-a')).toBe(true) }) it('loses to the session path', () => { store.ensureSessionWorkflowPath('job-b', workflowB.path) - store.belongsToActiveWorkflow('job-b', 'shared-graph-id') + store.rememberStampAndCheckActiveWorkflow('job-b', 'shared-graph-id') expect( - store.belongsToActiveWorkflow('job-b'), + store.rememberStampAndCheckActiveWorkflow('job-b'), 'the path says B owns it, even though the remembered stamp matches A' ).toBe(false) }) @@ -272,7 +236,7 @@ describe('executionStore workflow ownership', () => { store.forgetFinishedJobs(['job-elsewhere']) expect( - store.belongsToActiveWorkflow('job-elsewhere'), + store.rememberStampAndCheckActiveWorkflow('job-elsewhere'), 'nothing is left to place the job, so the fallback admits it again' ).toBe(true) }) @@ -307,18 +271,5 @@ describe('executionStore workflow ownership', () => { expect(store.activeJobId).toBeNull() expect(rejectionWarnings()).toHaveLength(0) }) - - it('still reports a rejection that is only a guess', () => { - queueJobFrom('job-a', workflowA) - fire('execution_start', { prompt_id: 'job-a', timestamp: 1 }) - expect(store.activeJobId).toBe('job-a') - - fire('execution_start', { - prompt_id: 'job-from-a-previous-page', - timestamp: 2 - }) - - expect(rejectionWarnings()).toHaveLength(1) - }) }) }) diff --git a/src/utils/__tests__/litegraphTestUtils.ts b/src/utils/__tests__/litegraphTestUtils.ts index 0bc82e8a950..6f8208a19a1 100644 --- a/src/utils/__tests__/litegraphTestUtils.ts +++ b/src/utils/__tests__/litegraphTestUtils.ts @@ -30,7 +30,7 @@ import { toNodeId } from '@comfyorg/graph-model/nodeId' import type { NodeState } from '@comfyorg/graph-model/nodeState' import { usePreviewExposureStore } from '@/stores/previewExposureStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' -import { zeroUuid } from '@/utils/uuid' +import { zeroUuid } from '@comfyorg/graph-model/uuid' /** Creates a node shell state with minimal required fields. */ export function createNodeState(overrides: Partial = {}): NodeState { diff --git a/src/utils/uuid.ts b/src/utils/uuid.ts index 6346c3f23c2..e8bb8c41420 100644 --- a/src/utils/uuid.ts +++ b/src/utils/uuid.ts @@ -2,7 +2,6 @@ import type { UUID } from '@comfyorg/graph-model/uuid' import { zeroUuid } from '@comfyorg/graph-model/uuid' export type { UUID } from '@comfyorg/graph-model/uuid' -export { zeroUuid } from '@comfyorg/graph-model/uuid' /** Pre-allocated storage for uuid random values. */ const randomStorage = new Uint32Array(31) From a8e2594384cb3e425d55268959feb6966c8c024f Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 16:20:48 -0700 Subject: [PATCH 09/13] test(execution): implement the review findings on the ownership tests Rationale that used to sit in test comments, which repository guidance keeps out of test bodies: The e2e case uses two workflows, each with an unreadable job. The orphaned one is the completion barrier: its badge can only clear from inside the same `forgetFinishedJobs` batch that forgets the shared workflow's stale job, so observing it gone is what proves cleanup ran. Counting job-detail requests cannot, because the counter increments before the response is fulfilled. `MAX_UNREADABLE_REFRESHES` is 3, so three refresh passes reach the give-up boundary that calls `forgetFinishedJobs`. Each pass reads a stale job twice, the initial read and the retry, and a reconnect arriving mid-pass is absorbed into the in-flight refresh. Each reconnect is therefore gated on the previous pass having issued both of its reads, or two reconnects collapse into one pass and the boundary is never crossed. The app-level case stores no job for any of the ids it dispatches: with no instance and no session-path mapping, and no active job, the fallback would admit every frame, so the id forwarded from the wire is the only thing that can reject the foreign ones. It uses a fresh job id per ingress so that an id remembered on one path cannot stand in for missing wiring on another. Also in this change: the unit cases take the real request and response types instead of asserting partial doubles, intercept listener registration rather than leaving callbacks on the shared API singleton, and stub `api.init` so installing the handlers does not start socket and feature-flag work the case never awaits. --- .../tests/wsReconnectStaleJob.spec.ts | 21 ++++---------- src/scripts/api.previewMetadata.test.ts | 10 +++---- src/scripts/api.queuePrompt.test.ts | 22 +++++++-------- src/scripts/app.test.ts | 28 +++++++++---------- 4 files changed, 35 insertions(+), 46 deletions(-) diff --git a/browser_tests/tests/wsReconnectStaleJob.spec.ts b/browser_tests/tests/wsReconnectStaleJob.spec.ts index 6fcc87e3dd3..a91ae703eaf 100644 --- a/browser_tests/tests/wsReconnectStaleJob.spec.ts +++ b/browser_tests/tests/wsReconnectStaleJob.spec.ts @@ -108,11 +108,6 @@ test.describe('WebSocket reconnect with stale job', { tag: '@ui' }, () => { const exec = new ExecutionHelper(comfyPage, ws) const topbar = comfyPage.menu.topbar - // Two workflows, each with an unreadable job. The orphaned one is the - // completion barrier: its badge can only clear from inside the same - // `forgetFinishedJobs` batch that forgets the shared workflow's stale - // job, so observing it gone is what proves cleanup ran. Counting detail - // requests cannot — the counter moves before the response is fulfilled. const { orphanedIndicator, sharedIndicator, staleJobIds, runningJobId } = await test.step('Strand one job per workflow behind a live sibling', async () => { await comfyPage.workflow.waitForActiveWorkflow() @@ -121,7 +116,7 @@ test.describe('WebSocket reconnect with stale job', { tag: '@ui' }, () => { const orphanedJobId = await exec.run() exec.executionStart(orphanedJobId) - await comfyPage.workflow.loadWorkflow('default') + await comfyPage.workflow.loadWorkflow('nodes/single_save_image_node') await comfyPage.workflow.waitForWorkflowIdle() const sharedStaleJobId = await exec.run() @@ -131,7 +126,7 @@ test.describe('WebSocket reconnect with stale job', { tag: '@ui' }, () => { await comfyPage.workflow.newBlankWorkflow() await comfyPage.workflow.waitForWorkflowIdle() - await expect.poll(() => topbar.getTabNames()).toHaveLength(3) + await expect(topbar.tabs).toHaveCount(3) const orphanedIndicator = topbar .getTab(0) @@ -172,12 +167,6 @@ test.describe('WebSocket reconnect with stale job', { tag: '@ui' }, () => { ) ) - // MAX_UNREADABLE_REFRESHES is 3, so three refresh passes reach the - // give-up boundary that calls forgetFinishedJobs. Each pass reads a - // stale job twice (the initial read and the retry), and a reconnect - // arriving mid-pass is absorbed into the in-flight refresh — so gate - // each reconnect on the previous pass having issued both of its reads, - // or two reconnects collapse into one pass and the boundary is missed. let socket = ws for (let pass = 1; pass <= 3; pass++) { const nextSocketPromise = nextWebSocket() @@ -187,9 +176,9 @@ test.describe('WebSocket reconnect with stale job', { tag: '@ui' }, () => { remainingJobScenario, runningJobId ) - for (const reads of staleJobReads) { - await expect.poll(reads).toBeGreaterThanOrEqual(2 * pass) - } + await expect + .poll(() => staleJobReads.map((reads) => reads() >= 2 * pass)) + .toEqual([true, true]) socket = await nextSocketPromise } diff --git a/src/scripts/api.previewMetadata.test.ts b/src/scripts/api.previewMetadata.test.ts index d888a356947..a96bd12b49f 100644 --- a/src/scripts/api.previewMetadata.test.ts +++ b/src/scripts/api.previewMetadata.test.ts @@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ComfyApi } from '@/scripts/api' -/** Minimal socket double; the decoder only needs the `message` handler. */ class FakeWebSocket { static readonly OPEN = 1 static instances: FakeWebSocket[] = [] @@ -28,7 +27,6 @@ class FakeWebSocket { } } -/** Encode the type-4 preview frame: tag, metadata length, JSON, image bytes. */ function previewFrame( metadata: Record, imageBytes: number[] @@ -59,12 +57,14 @@ describe('ComfyApi type-4 preview metadata', () => { }) function dispatchedPreview(metadata: Record) { - const detail = vi.fn() + const details: NonNullable< + Parameters>[1] + >[] = [] api.addEventListener('b_preview_with_metadata', (event) => { - detail(event.detail) + details.push(event.detail) }) FakeWebSocket.instances[0].receiveBinary(previewFrame(metadata, [1, 2, 3])) - return detail.mock.calls[0]?.[0] + return details[0] } const baseMetadata = { diff --git a/src/scripts/api.queuePrompt.test.ts b/src/scripts/api.queuePrompt.test.ts index 71a2534e0c2..056fc37c590 100644 --- a/src/scripts/api.queuePrompt.test.ts +++ b/src/scripts/api.queuePrompt.test.ts @@ -1,18 +1,16 @@ -import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { MockInstance } from 'vitest' import type { ComfyWorkflowJSON } from '@comfyorg/graph-model/workflowSchema' import { zeroUuid } from '@comfyorg/graph-model/uuid' import { api } from '@/scripts/api' -const promptResponse = () => - ({ - status: 200, - json: () => Promise.resolve({ prompt_id: 'job-1', node_errors: {} }) - }) as unknown as Response +function promptResponse() { + return Response.json({ prompt_id: 'job-1', node_errors: {} }) +} function workflowWithId(id: string | undefined): ComfyWorkflowJSON { - return fromPartial({ + return { id, revision: 0, last_node_id: 0, @@ -22,11 +20,11 @@ function workflowWithId(id: string | undefined): ComfyWorkflowJSON { groups: [], extra: {}, version: 0.4 - }) + } } describe('api queuePrompt workflow_metadata', () => { - let fetchApiSpy: ReturnType + let fetchApiSpy: MockInstance beforeEach(() => { fetchApiSpy = vi.spyOn(api, 'fetchApi').mockResolvedValue(promptResponse()) @@ -37,8 +35,10 @@ describe('api queuePrompt workflow_metadata', () => { output: {}, workflow: workflowWithId(id) }) - const [, init] = fetchApiSpy.mock.calls[0] as [string, RequestInit] - return JSON.parse(init.body as string) + const [, init] = fetchApiSpy.mock.calls[0] + if (typeof init?.body !== 'string') + throw new Error('Expected JSON request body') + return JSON.parse(init.body) } it.for([ diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index a0bd512319e..57f2a7a0fbf 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -3643,20 +3643,22 @@ describe('ComfyApp', () => { ) workflowA.changeTracker.activeState = workflowGraphData(workflowAId) useWorkflowStore().activeWorkflow = workflowA - // No storeJob for any of these ids: with no instance or session-path - // mapping and no active job, the fallback would admit every frame, so - // the stamp forwarded from the wire is the only thing that can reject - // the foreign ones. vi.spyOn(URL, 'createObjectURL').mockImplementation( (blob) => `blob:${blob instanceof Blob ? blob.size : 0}` ) - const addEventListener = vi.spyOn(api, 'addEventListener') + const addEventListener = vi + .spyOn(api, 'addEventListener') + .mockImplementation(() => {}) + vi.spyOn(api, 'init').mockResolvedValue() Reflect.apply(Reflect.get(app, 'addApiUpdateHandlers'), app, []) - function handlerFor(event: string) { - return addEventListener.mock.calls.find( + function handlerFor(event: Parameters[0]) { + const handler = addEventListener.mock.calls.find( ([name]) => name === event - )?.[1] as EventListener | undefined + )?.[1] + if (typeof handler !== 'function') + throw new Error('Expected registered function handler') + return handler } function executedEvent(jobId: string, workflowId: string) { return new CustomEvent('executed', { @@ -3687,14 +3689,12 @@ describe('ComfyApp', () => { }) } - // A fresh job id per ingress, so a stamp remembered on one path cannot - // stand in for missing wiring on another. - handlerFor('executed')?.(executedEvent('job-own-output', workflowAId)) - handlerFor('b_preview_with_metadata')?.( + handlerFor('executed')(executedEvent('job-own-output', workflowAId)) + handlerFor('b_preview_with_metadata')( previewEvent('job-own-preview', 'a', workflowAId) ) - handlerFor('executed')?.(executedEvent('job-foreign-output', workflowBId)) - handlerFor('b_preview_with_metadata')?.( + handlerFor('executed')(executedEvent('job-foreign-output', workflowBId)) + handlerFor('b_preview_with_metadata')( previewEvent('job-foreign-preview', 'bb', workflowBId) ) From 0cf7350c91298495bc87c7a4fc613933b3f3b732 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 31 Oct 2026 05:42:23 -0700 Subject: [PATCH 10/13] chore(architecture): refresh the domain catalog for this PR's new test files The merge of `main` at 24b64d62 brought in #22356's domain catalog, which claims every source file for a domain. This PR's four new test files were not in it, so `pnpm architecture:check` failed with `docs/architecture/domains/boundaries.json is out of date`. That is the sole error in `lint-pr / lint`; `test`, `preflight`, `lint-and-format` and `e2e-status` are gated on lint and so never ran on 24b64d62. Regenerated with `pnpm architecture:update`, which adds exactly the four files to their existing domains' file lists and changes nothing else. Reported by dante01yoon in https://github.com/Comfy-Org/ComfyUI_frontend/pull/22013#discussion_r4429740143 --- docs/architecture/domains/boundaries.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/architecture/domains/boundaries.json b/docs/architecture/domains/boundaries.json index 33083ce3ebe..16a046f741b 100644 --- a/docs/architecture/domains/boundaries.json +++ b/docs/architecture/domains/boundaries.json @@ -1266,7 +1266,9 @@ "src/stores/executionErrorStore.ts", "src/stores/executionErrorStore.test.ts", "src/stores/executionStore.ts", + "src/stores/executionStore.terminalRecovery.test.ts", "src/stores/executionStore.test.ts", + "src/stores/executionStore.workflowOwnership.test.ts", "src/stores/jobPreviewStore.ts", "src/stores/jobPreviewStore.test.ts", "src/stores/nodeOutputStore.ts", @@ -1360,6 +1362,8 @@ "src/scripts/api.getSettings.test.ts", "src/scripts/api.getShareableAssets.test.ts", "src/scripts/api.logs.test.ts", + "src/scripts/api.previewMetadata.test.ts", + "src/scripts/api.queuePrompt.test.ts", "src/scripts/api.responses.test.ts", "src/scripts/api.sessionOverride.test.ts", "src/scripts/api.socketReset.test.ts", From eb29b672d3fffa9678caca3f4148325d466b43a9 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 4 Nov 2026 09:48:27 -0800 Subject: [PATCH 11/13] refactor(api-client): derive the workflow_metadata wire types from core's spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both the request member and the websocket frame field were hand-declared, so a server-side rename or retype of `workflow_metadata` could not fail anything here. They now come from `@comfyorg/comfyui-api-types`, which generates `PromptRequest` from core's `openapi.yaml` pinned at 4281eb0a14. `QueuePromptRequestBody.workflow_metadata` is `Pick` — the spec's map narrowed to the one key this client sends, rather than the whole arbitrary map. `StampedWorkflowId.workflow_id` is `PromptWorkflowMetadata[string]`. Core's spec defines no websocket frame schemas; it documents that `workflow_metadata` is echoed onto every JSON frame carrying a `prompt_id`, so the frame field is that same request contract read back. What transfers is the map's VALUE type, not the map: the frame carries the map's contents merged into the frame object, so a `Pick` or `Partial` of the map would describe the wrong shape here even though it would compile. The dependency sits on `packages/api-client` rather than on the app, since `ComfyApi` is where the request body is built. Verified the derivation is load-bearing, not decorative. Deleting the member from the pinned spec and regenerating fails `pnpm typecheck` with `TS2339: Property 'workflow_metadata' does not exist on type 'PromptRequest'`; restoring the spec passes. That error surfaces at the package's own alias, which masks whether consumers are themselves tied to the spec, so a second pass retyped the spec's value to `integer` with the package's `Record` constraint relaxed. The retype then propagates into real call sites — `src/stores/executionStore.ts` and `src/scripts/app.ts` fail with `TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'string | undefined'` — which is the evidence that the frame-side derivation gates actual usage. --- packages/api-client/package.json | 1 + packages/api-client/src/ComfyApi.ts | 3 ++- packages/api-client/src/executionTypes.ts | 14 ++++++++++++-- pnpm-lock.yaml | 3 +++ 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/api-client/package.json b/packages/api-client/package.json index 636c7e5f288..20132bccbb7 100644 --- a/packages/api-client/package.json +++ b/packages/api-client/package.json @@ -19,6 +19,7 @@ }, "dependencies": { "@comfyorg/account-core": "workspace:*", + "@comfyorg/comfyui-api-types": "workspace:*", "@comfyorg/graph-model": "workspace:*", "@comfyorg/ingest-types": "workspace:*", "@comfyorg/object-info-parser": "workspace:*", diff --git a/packages/api-client/src/ComfyApi.ts b/packages/api-client/src/ComfyApi.ts index 6b29dc3cb52..1cd0dedda99 100644 --- a/packages/api-client/src/ComfyApi.ts +++ b/packages/api-client/src/ComfyApi.ts @@ -11,6 +11,7 @@ import { zGetExtensionsResponse, zPostAssetsFromWorkflowResponse } from '@comfyorg/ingest-types/zod' +import type { PromptWorkflowMetadata } from '@comfyorg/comfyui-api-types' import axios from 'axios' import { get } from 'es-toolkit/compat' import { trimEnd } from 'es-toolkit' @@ -90,7 +91,7 @@ interface QueuePromptRequestBody { client_id: string prompt: ComfyApiWorkflow partial_execution_targets?: NodeExecutionId[] - workflow_metadata?: { workflow_id: string } + workflow_metadata?: Pick extra_data: { extra_pnginfo: { workflow: ComfyWorkflowJSON diff --git a/packages/api-client/src/executionTypes.ts b/packages/api-client/src/executionTypes.ts index 221640eb121..ecd094c3ca1 100644 --- a/packages/api-client/src/executionTypes.ts +++ b/packages/api-client/src/executionTypes.ts @@ -1,13 +1,23 @@ +import type { PromptWorkflowMetadata } from '@comfyorg/comfyui-api-types' import type { PromptInfo } from '@comfyorg/ingest-types' import { z } from 'zod' -import type { WorkflowId } from '@comfyorg/graph-model/workflowSchema' import { zNodeId } from '@comfyorg/graph-model/workflowSchema' import type { TaskStatus } from './taskSchema' import { resultItemType } from './resultItemTypeSchema' export type JobId = string -type StampedWorkflowId = { workflow_id?: WorkflowId } +/** + * Core's OpenAPI defines no websocket frame schemas. It documents that + * `workflow_metadata` is echoed onto every JSON frame carrying a `prompt_id`, + * so this field is the request contract read back rather than a separate one. + * + * What transfers from the spec is the map's VALUE type, not the map: core types + * `workflow_metadata` as an arbitrary string map, and the frame carries that + * map's contents merged into the frame object. So a `Pick` or `Partial` of the + * map would describe the wrong shape here even though it would compile. + */ +type StampedWorkflowId = { workflow_id?: PromptWorkflowMetadata[string] } export const zResultItem = z.object({ filename: z.string().optional(), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f68d58f1c0d..69b5ef5bf92 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1121,6 +1121,9 @@ importers: '@comfyorg/account-core': specifier: workspace:* version: link:../account-core + '@comfyorg/comfyui-api-types': + specifier: workspace:* + version: link:../comfyui-api-types '@comfyorg/graph-model': specifier: workspace:* version: link:../graph-model From 5f192238f1a2e478e278f81daccd47dc9257948d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 4 Nov 2026 10:27:33 -0800 Subject: [PATCH 12/13] fix(api-client): keep the generated types out of the published declarations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two integration gates failed on eb29b672, both caused by the new dependency rather than by the derivation itself. `check:types-consumer` typechecks an external consumer against the bundled `dist/index.d.ts`, and the frame interfaces are re-exported from `@comfyorg/comfyui-frontend-types`. Writing `workflow_id?: PromptWorkflowMetadata[string]` put `import { PromptWorkflowMetadata } from '@comfyorg/comfyui-api-types'` into that bundle, and the generated package is `private: true`, so a consumer cannot resolve it — `TS2307: Cannot find module`. Routing it through a local constrained alias does not help; the alias is emitted too, and the reference survives. So the frame member is plain `string` and the tie to the spec moved to `workflowMetadataContract.ts`, which nothing in the published graph imports. The published contract is unchanged (`workflow_id?: string`) and now resolves: 0 references to the private package in `dist/index.d.ts`. The request member keeps the real derivation. `QueuePromptRequestBody` is not part of the published surface, and it gates at the assignment site: with the spec's values retyped it fails at `ComfyApi.ts:1346` where `workflow.id` is assigned, not merely at a type alias. `validate-licenses` runs `license-checker-rseidelsohn` over production dependencies, which reports any `private: true` package as `UNLICENSED` regardless of its `license` field — the workflow says so, and excludes all twenty-odd internal `@comfyorg/*` packages for exactly that reason. `@comfyorg/comfyui-api-types` was missing from that list because nothing took it as a production dependency until now. Added. Controls, with the spec's `additionalProperties.type` set to `integer` and the generated package's own `Record` constraint relaxed so the consumers are the only thing that can fail: packages/api-client/src/ComfyApi.ts(1346,11) error TS2322 packages/api-client/src/workflowMetadataContract.ts(21,3) error TS2344 Both restored afterwards; spec back at 8f0da854, `check:generated` clean. --- .../workflows/ci-oss-assets-validation.yaml | 2 +- packages/api-client/src/executionTypes.ts | 9 ++++++-- .../src/workflowMetadataContract.ts | 22 +++++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 packages/api-client/src/workflowMetadataContract.ts diff --git a/.github/workflows/ci-oss-assets-validation.yaml b/.github/workflows/ci-oss-assets-validation.yaml index 9abb6f8f139..466c2d96d9c 100644 --- a/.github/workflows/ci-oss-assets-validation.yaml +++ b/.github/workflows/ci-oss-assets-validation.yaml @@ -117,7 +117,7 @@ jobs: if pnpx license-checker-rseidelsohn@4 \ --production \ --summary \ - --excludePackages '@comfyorg/comfyui-frontend;@comfyorg/account-core;@comfyorg/account-ui;@comfyorg/api-client;@comfyorg/billing-contract;@comfyorg/billing-core;@comfyorg/design-system;@comfyorg/graph-model;@comfyorg/ingest-types;@comfyorg/keybindings;@comfyorg/layer-editor;@comfyorg/mask-editor;@comfyorg/registry-types;@comfyorg/settings-core;@comfyorg/shared-frontend-utils;@comfyorg/tailwind-utils;@comfyorg/telemetry;@comfyorg/test-utils;@comfyorg/viewport3d;@comfyorg/comfyui-electron-types;@comfyorg/comfy-multi-player' \ + --excludePackages '@comfyorg/comfyui-frontend;@comfyorg/account-core;@comfyorg/comfyui-api-types;@comfyorg/account-ui;@comfyorg/api-client;@comfyorg/billing-contract;@comfyorg/billing-core;@comfyorg/design-system;@comfyorg/graph-model;@comfyorg/ingest-types;@comfyorg/keybindings;@comfyorg/layer-editor;@comfyorg/mask-editor;@comfyorg/registry-types;@comfyorg/settings-core;@comfyorg/shared-frontend-utils;@comfyorg/tailwind-utils;@comfyorg/telemetry;@comfyorg/test-utils;@comfyorg/viewport3d;@comfyorg/comfyui-electron-types;@comfyorg/comfy-multi-player' \ --clarificationsFile .github/license-clarifications.json \ --onlyAllow 'MIT;MIT*;Apache-2.0;BSD-2-Clause;BSD-3-Clause;ISC;0BSD;BlueOak-1.0.0;Python-2.0;CC0-1.0;Unlicense;(MIT OR Apache-2.0);(MIT OR GPL-3.0);(Apache-2.0 OR MIT);(MPL-2.0 OR Apache-2.0);MPL-2.0;CC-BY-4.0;CC-BY-3.0;GPL-3.0-only'; then echo '' diff --git a/packages/api-client/src/executionTypes.ts b/packages/api-client/src/executionTypes.ts index ecd094c3ca1..38753d66597 100644 --- a/packages/api-client/src/executionTypes.ts +++ b/packages/api-client/src/executionTypes.ts @@ -1,4 +1,3 @@ -import type { PromptWorkflowMetadata } from '@comfyorg/comfyui-api-types' import type { PromptInfo } from '@comfyorg/ingest-types' import { z } from 'zod' import { zNodeId } from '@comfyorg/graph-model/workflowSchema' @@ -16,8 +15,14 @@ export type JobId = string * `workflow_metadata` as an arbitrary string map, and the frame carries that * map's contents merged into the frame object. So a `Pick` or `Partial` of the * map would describe the wrong shape here even though it would compile. + * + * The member is `string` rather than `PromptWorkflowMetadata[string]` because + * these frame interfaces are re-exported from the published + * `@comfyorg/comfyui-frontend-types`, and the generated package is private — an + * external consumer could not resolve the reference. The tie to the spec lives + * in `./workflowMetadataContract`, outside the published graph. */ -type StampedWorkflowId = { workflow_id?: PromptWorkflowMetadata[string] } +type StampedWorkflowId = { workflow_id?: string } export const zResultItem = z.object({ filename: z.string().optional(), diff --git a/packages/api-client/src/workflowMetadataContract.ts b/packages/api-client/src/workflowMetadataContract.ts new file mode 100644 index 00000000000..6786c9c2d88 --- /dev/null +++ b/packages/api-client/src/workflowMetadataContract.ts @@ -0,0 +1,22 @@ +import type { PromptWorkflowMetadata } from '@comfyorg/comfyui-api-types' + +type AssertTrue = T + +/** + * Ties the hand-written `workflow_metadata` wire members to core's OpenAPI + * without putting the generated type in this package's published surface. + * + * `StampedWorkflowId.workflow_id` in `./executionTypes` cannot reference + * `PromptWorkflowMetadata` directly: those frame interfaces are re-exported + * from `@comfyorg/comfyui-frontend-types`, and `@comfyorg/comfyui-api-types` is + * a private workspace package that an external consumer of the published + * declarations cannot resolve (`pnpm check:types-consumer`). Declaring the + * member as `string` keeps the published contract resolvable; this assertion + * keeps it honest, failing the build if core ever retypes the map's values away + * from `string` instead of letting the frontend adopt the change silently. + * + * Deleting the member from the spec fails earlier, in this package's own alias. + */ +export type WorkflowMetadataValuesAreStrings = AssertTrue< + [PromptWorkflowMetadata[string]] extends [string] ? true : false +> From feca33185b2a60ce47f79ec17615c45f5d1418c7 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 4 Nov 2026 10:34:51 -0800 Subject: [PATCH 13/13] fix(types): bundle the generated package into the published declarations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Makes the published declarations self-contained instead of weakening the derivation, replacing the previous commit's approach. `tsconfig.types.json` bundles each workspace package it needs via a `paths` entry plus an `include` glob; the generated package had neither, so the reference to `PromptWorkflowMetadata` was emitted as an import of a `private: true` package and no external consumer could resolve it. With both added, the alias is inlined into `dist/index.d.ts` and the frame member keeps the real derivation: declare type PromptWorkflowMetadata = StringMap>; workflow_id?: PromptWorkflowMetadata[string]; 0 imports of the private package remain in the bundle, and `pnpm check:types-consumer` passes. `workflowMetadataContract.ts` is gone with it — the structural member it existed to constrain is no longer structural. For the licence gate, the package now carries `license: MIT` and a LICENSE file, matching `@comfyorg/ingest-types`, the closest analogue. That metadata alone does not satisfy the gate: `license-checker-rseidelsohn` reports any `private: true` package as UNLICENSED regardless of its `license` field, and `--clarificationsFile` does not override that either — both measured. The package therefore stays in `--excludePackages`, which is the pattern the workflow already documents for the other twenty internal packages and for `@comfyorg/account-core` specifically, whose comment describes licence metadata being added ahead of publish work while the exclusion remains. The alternative that satisfies the gate directly is unsetting `private`, and that is deliberately not done here: `publish-package.yaml` calls the flag "the latch that prevents an accidental publish". Trading it away as a side effect of a licence check would be the wrong order of operations for a package nobody intends to publish yet. --- packages/api-client/src/executionTypes.ts | 11 +++++----- .../src/workflowMetadataContract.ts | 22 ------------------- packages/comfyui-api-types/LICENSE | 21 ++++++++++++++++++ packages/comfyui-api-types/package.json | 1 + tsconfig.types.json | 4 ++++ 5 files changed, 31 insertions(+), 28 deletions(-) delete mode 100644 packages/api-client/src/workflowMetadataContract.ts create mode 100644 packages/comfyui-api-types/LICENSE diff --git a/packages/api-client/src/executionTypes.ts b/packages/api-client/src/executionTypes.ts index 38753d66597..22639644394 100644 --- a/packages/api-client/src/executionTypes.ts +++ b/packages/api-client/src/executionTypes.ts @@ -1,3 +1,4 @@ +import type { PromptWorkflowMetadata } from '@comfyorg/comfyui-api-types' import type { PromptInfo } from '@comfyorg/ingest-types' import { z } from 'zod' import { zNodeId } from '@comfyorg/graph-model/workflowSchema' @@ -16,13 +17,11 @@ export type JobId = string * map's contents merged into the frame object. So a `Pick` or `Partial` of the * map would describe the wrong shape here even though it would compile. * - * The member is `string` rather than `PromptWorkflowMetadata[string]` because - * these frame interfaces are re-exported from the published - * `@comfyorg/comfyui-frontend-types`, and the generated package is private — an - * external consumer could not resolve the reference. The tie to the spec lives - * in `./workflowMetadataContract`, outside the published graph. + * The generated package is bundled into the published declarations by + * `tsconfig.types.json`, so this reference is inlined rather than emitted as an + * import of a private package that an external consumer could not resolve. */ -type StampedWorkflowId = { workflow_id?: string } +type StampedWorkflowId = { workflow_id?: PromptWorkflowMetadata[string] } export const zResultItem = z.object({ filename: z.string().optional(), diff --git a/packages/api-client/src/workflowMetadataContract.ts b/packages/api-client/src/workflowMetadataContract.ts deleted file mode 100644 index 6786c9c2d88..00000000000 --- a/packages/api-client/src/workflowMetadataContract.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { PromptWorkflowMetadata } from '@comfyorg/comfyui-api-types' - -type AssertTrue = T - -/** - * Ties the hand-written `workflow_metadata` wire members to core's OpenAPI - * without putting the generated type in this package's published surface. - * - * `StampedWorkflowId.workflow_id` in `./executionTypes` cannot reference - * `PromptWorkflowMetadata` directly: those frame interfaces are re-exported - * from `@comfyorg/comfyui-frontend-types`, and `@comfyorg/comfyui-api-types` is - * a private workspace package that an external consumer of the published - * declarations cannot resolve (`pnpm check:types-consumer`). Declaring the - * member as `string` keeps the published contract resolvable; this assertion - * keeps it honest, failing the build if core ever retypes the map's values away - * from `string` instead of letting the frontend adopt the change silently. - * - * Deleting the member from the spec fails earlier, in this package's own alias. - */ -export type WorkflowMetadataValuesAreStrings = AssertTrue< - [PromptWorkflowMetadata[string]] extends [string] ? true : false -> diff --git a/packages/comfyui-api-types/LICENSE b/packages/comfyui-api-types/LICENSE new file mode 100644 index 00000000000..7ceb934bd26 --- /dev/null +++ b/packages/comfyui-api-types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Comfy Org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/comfyui-api-types/package.json b/packages/comfyui-api-types/package.json index 4d9cf869566..4c67043fcd5 100644 --- a/packages/comfyui-api-types/package.json +++ b/packages/comfyui-api-types/package.json @@ -3,6 +3,7 @@ "version": "1.0.0", "private": true, "description": "ComfyUI server API TypeScript types, generated from a pinned core OpenAPI spec", + "license": "MIT", "type": "module", "exports": { ".": { diff --git a/tsconfig.types.json b/tsconfig.types.json index 422f4f3c256..914224ad83c 100644 --- a/tsconfig.types.json +++ b/tsconfig.types.json @@ -21,6 +21,9 @@ "@comfyorg/graph-model/*": ["./packages/graph-model/src/*"], "@comfyorg/keybindings/*": ["./packages/keybindings/src/*"], "@comfyorg/api-client/*": ["./packages/api-client/src/*"], + "@comfyorg/comfyui-api-types": [ + "./packages/comfyui-api-types/src/index.ts" + ], "@comfyorg/settings-core/*": ["./packages/settings-core/src/*"], "@comfyorg/telemetry/*": ["./packages/telemetry/src/*"], "@comfyorg/shared-frontend-utils/geometry": [ @@ -33,6 +36,7 @@ "packages/graph-model/src/**/*.ts", "packages/keybindings/src/**/*.ts", "packages/api-client/src/**/*.ts", + "packages/comfyui-api-types/src/**/*.ts", "packages/settings-core/src/**/*.ts", "packages/telemetry/src/types.ts", "packages/shared-frontend-utils/src/geometry.ts",