Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): add socket queue coordinator
joshistoast4c09a3adeae4
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.jsonindex 720aadb5cd..b8e3bb80ed 100644--- a/invokeai/frontend/webv2/package.json+++ b/invokeai/frontend/webv2/package.json@@ -25,7 +25,8 @@"lucide-react": "^1.17.0","react": "^19.1.0","react-dom": "^19.1.0",- "react-icons": "^5.5.0"+ "react-icons": "^5.5.0",+ "socket.io-client": "^4.8.3"},"devDependencies": {"@types/node": "^22.15.1",diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yamlindex 68ae859b71..106cc73c3f 100644--- a/invokeai/frontend/webv2/pnpm-lock.yaml+++ b/invokeai/frontend/webv2/pnpm-lock.yaml@@ -32,6 +32,9 @@ importers:react-icons:specifier: ^5.5.0version: 5.6.0([email protected])+ socket.io-client:+ specifier: ^4.8.3+ version: 4.8.3devDependencies:'@types/node':specifier: ^22.15.1@@ -712,6 +715,9 @@ packages:cpu: [x64]os: [win32]+ '@socket.io/[email protected]':+ resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==}+'@standard-schema/[email protected]':resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}@@ -1143,6 +1149,13 @@ packages:supports-color:optional: true+ resolution: {integrity: sha512-QCwxUDULPlXv8F6tqMMKx5dNkTe6OaBYRMPYeXKBlyOoKvAmE0ac6pW7fFhSscJ/5SI7666/U/B+MElbsrJlIg==}++ resolution: {integrity: sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==}+ engines: {node: '>=10.0.0'}+resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==}@@ -1342,6 +1355,14 @@ packages:resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}+ resolution: {integrity: sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==}+ engines: {node: '>=10.0.0'}++ resolution: {integrity: sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==}+ engines: {node: '>=10.0.0'}+resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}engines: {node: '>=0.10.0'}@@ -1482,6 +1503,22 @@ packages:engines: {node: '>=8'}hasBin: true+ resolution: {integrity: sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true++ resolution: {integrity: sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==}+ engines: {node: '>=0.4.0'}+resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==}engines: {node: '>= 6'}@@ -2003,6 +2040,8 @@ snapshots:'@rollup/[email protected]':optional: true+ '@socket.io/[email protected]': {}+'@standard-schema/[email protected]': {}'@swc/[email protected]':@@ -2747,6 +2786,20 @@ snapshots:dependencies:ms: 2.1.3+ dependencies:+ '@socket.io/component-emitter': 3.1.2+ debug: 4.4.3+ engine.io-parser: 5.2.3+ ws: 8.20.1+ xmlhttprequest-ssl: 2.1.2+ transitivePeerDependencies:+ - bufferutil+ - supports-color+ - utf-8-validate++ [email protected]: {}+dependencies:is-arrayish: 0.2.1@@ -2982,6 +3035,24 @@ snapshots:+ dependencies:+ '@socket.io/component-emitter': 3.1.2+ debug: 4.4.3+ engine.io-client: 6.6.5+ socket.io-parser: 4.2.6+ transitivePeerDependencies:+ - bufferutil+ - supports-color+ - utf-8-validate++ dependencies:+ '@socket.io/component-emitter': 3.1.2+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color+@@ -3059,4 +3130,8 @@ snapshots:siginfo: 2.0.0stackback: 0.0.2+ [email protected]: {}++ [email protected]: {}+diff --git a/invokeai/frontend/webv2/src/workbench/backend/events.ts b/invokeai/frontend/webv2/src/workbench/backend/events.tsnew file mode 100644index 0000000000..91cd95fb75--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/backend/events.ts@@ -0,0 +1,57 @@+/**+ * Typed contracts for the backend Socket.IO events webv2 consumes. Payload+ * shapes mirror the pydantic models in+ * `invokeai/app/services/events/events_common.py` (serialized as snake_case).+ */++/** Backend queue item lifecycle status. Note the backend spells it `canceled`. */+export type BackendQueueItemStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'canceled';++export type TerminalBackendQueueItemStatus = Extract<BackendQueueItemStatus, 'completed' | 'failed' | 'canceled'>;++export interface QueueItemEventBase {+ queue_id: string;+ item_id: number;+ batch_id: string;+ origin: string | null;+ destination: string | null;+}++export interface QueueItemStatusChangedEvent extends QueueItemEventBase {+ status: BackendQueueItemStatus;+ error_type: string | null;+ error_message: string | null;+ created_at: string;+ updated_at: string;+ started_at: string | null;+ completed_at: string | null;+ session_id: string;+}++export interface InvocationProgressEvent extends QueueItemEventBase {+ session_id: string;+ message: string;+ /** 0..1, or null for indeterminate progress. */+ percentage: number | null;+}++export interface BackendSocketEvents {+ queue_item_status_changed: QueueItemStatusChangedEvent;+ invocation_progress: InvocationProgressEvent;+}++export const isTerminalBackendStatus = (status: BackendQueueItemStatus): status is TerminalBackendQueueItemStatus =>+ status === 'completed' || status === 'failed' || status === 'canceled';++/**+ * Queue items enqueued by webv2 carry the local queue item id in their origin+ * so that submissions survive a reload: on startup the backend queue is listed+ * and items are re-adopted by decoding their origin.+ */+const QUEUE_ITEM_ORIGIN_PREFIX = 'webv2:';++export const buildQueueItemOrigin = (localQueueItemId: string): string =>+ `${QUEUE_ITEM_ORIGIN_PREFIX}${localQueueItemId}`;++export const parseQueueItemOrigin = (origin: string | null | undefined): string | null =>+ origin?.startsWith(QUEUE_ITEM_ORIGIN_PREFIX) ? origin.slice(QUEUE_ITEM_ORIGIN_PREFIX.length) : null;diff --git a/invokeai/frontend/webv2/src/workbench/backend/progressStore.ts b/invokeai/frontend/webv2/src/workbench/backend/progressStore.tsnew file mode 100644index 0000000000..1fe47ecb28--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/backend/progressStore.ts@@ -0,0 +1,53 @@+import { useSyncExternalStore } from 'react';++/**+ * Ephemeral live-progress store for in-flight queue items, keyed by the local+ * queue item id. Progress is high-frequency transient data, so it deliberately+ * lives outside the workbench reducer: routing it through dispatch would+ * re-render every consumer of workbench state and churn autosave on each step+ * of every generation. Any widget can subscribe to a single item via+ * `useQueueItemProgress` and only re-renders when that item's progress moves.+ */++export interface QueueItemProgress {+ message: string;+ /** 0..1, or null while indeterminate. */+ percentage: number | null;+}++export interface QueueItemProgressSink {+ set(queueItemId: string, progress: QueueItemProgress): void;+ clear(queueItemId: string): void;+}++const progressByQueueItemId = new Map<string, QueueItemProgress>();+const listeners = new Set<() => void>();++const emit = (): void => {+ for (const listener of listeners) {+ listener();+ }+};++const subscribe = (listener: () => void): (() => void) => {+ listeners.add(listener);++ return () => {+ listeners.delete(listener);+ };+};++export const queueItemProgressStore: QueueItemProgressSink = {+ clear(queueItemId) {+ if (progressByQueueItemId.delete(queueItemId)) {+ emit();+ }+ },+ set(queueItemId, progress) {+ progressByQueueItemId.set(queueItemId, progress);+ emit();+ },+};++export const useQueueItemProgress = (queueItemId: string): QueueItemProgress | null =>+ useSyncExternalStore(subscribe, () => progressByQueueItemId.get(queueItemId) ?? null);diff --git a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.tsnew file mode 100644index 0000000000..66f96e65f2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts@@ -0,0 +1,355 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { EnqueueGenerateRequest, ImageDTO, QueueItemDTO } from '../generation/types';+import { buildQueueItemOrigin, type QueueItemStatusChangedEvent } from './events';+import { ApiError } from './http';+import type { QueueItemProgress, QueueItemProgressSink } from './progressStore';+import {+ createQueueCoordinator,+ QueueItemCancelledError,+ type BackendSocket,+ type QueueCoordinator,+ type QueueCoordinatorApi,+ type QueueCoordinatorCallbacks,+} from './queueCoordinator';++class FakeSocket implements BackendSocket {+ readonly emitted: { event: string; payload: unknown }[] = [];+ private readonly handlers = new Map<string, ((payload: never) => void)[]>();++ on(event: string, handler: (payload: never) => void): void {+ this.handlers.set(event, [...(this.handlers.get(event) ?? []), handler]);+ }++ emit(event: string, payload: unknown): void {+ this.emitted.push({ event, payload });+ }++ connect(): void {+ this.fire('connect', undefined);+ }++ disconnect(): void {+ this.fire('disconnect', 'io client disconnect');+ }++ fire(event: string, payload: unknown): void {+ for (const handler of this.handlers.get(event) ?? []) {+ (handler as (value: unknown) => void)(payload);+ }+ }+}++const createStatusEvent = (overrides: Partial<QueueItemStatusChangedEvent>): QueueItemStatusChangedEvent => ({+ batch_id: 'batch-1',+ completed_at: null,+ created_at: '2026-06-10T00:00:00Z',+ destination: 'gallery',+ error_message: null,+ error_type: null,+ item_id: 1,+ origin: null,+ queue_id: 'default',+ session_id: 'session-1',+ started_at: null,+ status: 'completed',+ updated_at: '2026-06-10T00:00:00Z',+ ...overrides,+});++const createQueueItemDTO = (overrides: Partial<QueueItemDTO>): QueueItemDTO => ({+ item_id: 1,+ session: { results: {} },+ status: 'in_progress',+ ...overrides,+});++const createImage = (imageName: string, sourceQueueItemId: string): ImageDTO => ({+ height: 64,+ imageName,+ imageUrl: `https://example.test/${imageName}`,+ isIntermediate: false,+ queuedAt: '2026-06-10T00:00:00Z',+ sourceQueueItemId,+ thumbnailUrl: `https://example.test/${imageName}/thumb`,+ width: 64,+});++const generateRequest: EnqueueGenerateRequest = {+ batchCount: 1,+ destination: 'gallery',+ graph: { edges: [], id: 'graph-1', nodes: {} },+ negativePrompt: '',+ negativePromptNodeId: 'negative_prompt',+ positivePrompt: 'a fjord at dawn',+ positivePromptNodeId: 'positive_prompt',+ seed: 1,+ seedNodeId: 'seed',+ sourceQueueItemId: 'local-1',+};++interface Harness {+ api: { [Key in keyof QueueCoordinatorApi]: ReturnType<typeof vi.fn> };+ callbacks: { [Key in keyof QueueCoordinatorCallbacks]: ReturnType<typeof vi.fn> };+ coordinator: QueueCoordinator;+ progressEntries: Map<string, QueueItemProgress>;+ socket: FakeSocket;+}++const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Harness => {+ const socket = new FakeSocket();+ const progressEntries = new Map<string, QueueItemProgress>();+ const progress: QueueItemProgressSink = {+ clear: (queueItemId) => {+ progressEntries.delete(queueItemId);+ },+ set: (queueItemId, value) => {+ progressEntries.set(queueItemId, value);+ },+ };+ const api = {+ cancelQueueItems: vi.fn(() => Promise.resolve()),+ cancelQueueItemsByBatchIds: vi.fn(() => Promise.resolve()),+ enqueueGenerateGraph: vi.fn(() => Promise.resolve({ batchId: 'batch-1', itemIds: [1] })),+ getQueueItem: vi.fn((itemId: number) => Promise.resolve(createQueueItemDTO({ item_id: itemId }))),+ getQueueItemResultImages: vi.fn((itemId: number, sourceQueueItemId: string) =>+ Promise.resolve([createImage(`image-${itemId}.png`, sourceQueueItemId)])+ ),+ listAllQueueItems: vi.fn((): Promise<QueueItemDTO[]> => Promise.resolve([])),+ };+ const callbacks = {+ onConnectionChange: vi.fn(),+ onGalleryRefresh: vi.fn(),+ };+ const coordinator = createQueueCoordinator(callbacks, {+ api,+ createSocket: () => socket,+ galleryRefreshCoalesceMs: options.galleryRefreshCoalesceMs ?? 1,+ progress,+ });++ return { api, callbacks, coordinator, progressEntries, socket };+};++describe('queueCoordinator', () => {+ let harness: Harness;++ beforeEach(() => {+ harness = createHarness();+ });++ afterEach(() => {+ harness.coordinator.dispose();+ vi.useRealTimers();+ });++ it('reports connection lifecycle and subscribes to the queue', () => {+ harness.coordinator.connect();++ expect(harness.callbacks.onConnectionChange).toHaveBeenNthCalledWith(1, 'connecting', undefined);+ expect(harness.callbacks.onConnectionChange).toHaveBeenNthCalledWith(2, 'connected', undefined);+ expect(harness.socket.emitted).toContainEqual({ event: 'subscribe_queue', payload: { queue_id: 'default' } });+ });++ it('settles submitted runs from terminal socket events without polling', async () => {+ harness.api.enqueueGenerateGraph.mockResolvedValue({ batchId: 'batch-1', itemIds: [1, 2] });+ harness.coordinator.connect();++ await harness.coordinator.submitGenerate('local-1', generateRequest);+ const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1 }));+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 2 }));++ const images = await resultsPromise;++ expect(images.map((image) => image.imageName)).toEqual(['image-1.png', 'image-2.png']);+ expect(harness.api.getQueueItem).not.toHaveBeenCalled();+ });++ it('rejects with the backend error message when a run fails', async () => {+ harness.coordinator.connect();++ await harness.coordinator.submitGenerate('local-1', generateRequest);+ const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ harness.socket.fire(+ 'queue_item_status_changed',+ createStatusEvent({ error_message: 'CUDA out of memory', item_id: 1, status: 'failed' })+ );++ await expect(resultsPromise).rejects.toThrow('CUDA out of memory');+ });++ it('rejects with QueueItemCancelledError when the backend cancels a run', async () => {+ harness.coordinator.connect();++ await harness.coordinator.submitGenerate('local-1', generateRequest);+ const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1, status: 'canceled' }));++ await expect(resultsPromise).rejects.toBeInstanceOf(QueueItemCancelledError);+ });++ it('settles runs whose terminal event arrived before tracking began', async () => {+ harness.coordinator.connect();++ // The event for item 1 lands while enqueue_batch is still resolving.+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1 }));++ await harness.coordinator.submitGenerate('local-1', generateRequest);++ const images = await harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ expect(images.map((image) => image.imageName)).toEqual(['image-1.png']);+ });++ it('coalesces gallery refreshes across a burst of completions', async () => {+ vi.useFakeTimers();+ harness = createHarness({ galleryRefreshCoalesceMs: 400 });+ harness.coordinator.connect();+ await vi.advanceTimersByTimeAsync(500); // flush the on-connect refresh+ harness.callbacks.onGalleryRefresh.mockClear();++ for (let itemId = 1; itemId <= 10; itemId += 1) {+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: itemId }));+ }++ await vi.advanceTimersByTimeAsync(500);++ expect(harness.callbacks.onGalleryRefresh).toHaveBeenCalledTimes(1);+ });++ it('does not refresh the gallery for failed or canceled items', async () => {+ vi.useFakeTimers();+ harness = createHarness({ galleryRefreshCoalesceMs: 400 });+ harness.coordinator.connect();+ await vi.advanceTimersByTimeAsync(500); // flush the on-connect refresh+ harness.callbacks.onGalleryRefresh.mockClear();++ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1, status: 'failed' }));+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 2, status: 'canceled' }));++ await vi.advanceTimersByTimeAsync(500);++ expect(harness.callbacks.onGalleryRefresh).not.toHaveBeenCalled();+ });++ it('routes progress events to the tracked item and clears them on completion', async () => {+ harness.coordinator.connect();++ await harness.coordinator.submitGenerate('local-1', generateRequest);++ harness.socket.fire('invocation_progress', {+ ...createStatusEvent({ item_id: 1 }),+ message: 'Denoising',+ percentage: 0.5,+ });++ expect(harness.progressEntries.get('local-1')).toEqual({ message: 'Denoising', percentage: 0.5 });++ const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1 }));+ await resultsPromise;++ expect(harness.progressEntries.has('local-1')).toBe(false);+ });++ describe('reconcile', () => {+ it('adopts pending items the backend already accepted, by origin', async () => {+ harness.api.listAllQueueItems.mockResolvedValue([+ createQueueItemDTO({ batch_id: 'batch-9', item_id: 7, origin: buildQueueItemOrigin('local-1') }),+ ]);++ const outcomes = await harness.coordinator.reconcile([{ id: 'local-1', status: 'pending' }]);++ expect(outcomes.get('local-1')).toEqual({ backendBatchId: 'batch-9', backendItemIds: [7], kind: 'adopted' });+ expect(harness.api.enqueueGenerateGraph).not.toHaveBeenCalled();+ });++ it('resumes running items and settles them from their listed terminal status', async () => {+ harness.api.listAllQueueItems.mockResolvedValue([createQueueItemDTO({ item_id: 7, status: 'completed' })]);++ const outcomes = await harness.coordinator.reconcile([{ backendItemIds: [7], id: 'local-1', status: 'running' }]);++ expect(outcomes.get('local-1')).toEqual({ kind: 'resumed' });++ const images = await harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ expect(images.map((image) => image.imageName)).toEqual(['image-7.png']);+ });++ it('marks running items missing when their backend items vanished', async () => {+ harness.api.listAllQueueItems.mockResolvedValue([]);++ const outcomes = await harness.coordinator.reconcile([{ backendItemIds: [7], id: 'local-1', status: 'running' }]);++ expect(outcomes.get('local-1')).toEqual({ kind: 'missing' });+ });++ it('asks for a fresh enqueue when a pending item left no backend trace', async () => {+ harness.api.listAllQueueItems.mockResolvedValue([]);++ const outcomes = await harness.coordinator.reconcile([{ id: 'local-1', status: 'pending' }]);++ expect(outcomes.get('local-1')).toEqual({ kind: 'enqueue' });+ });++ it('skips the backend round-trip when there is nothing to reconcile', async () => {+ const outcomes = await harness.coordinator.reconcile([]);++ expect(outcomes.size).toBe(0);+ expect(harness.api.listAllQueueItems).not.toHaveBeenCalled();+ });+ });++ it('settles missed events through the safety sweep on reconnect', async () => {+ harness.coordinator.connect();++ await harness.coordinator.submitGenerate('local-1', generateRequest);+ const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ // The completion event was lost to a disconnect; the reconnect sweep+ // re-checks every outstanding item.+ harness.api.getQueueItem.mockResolvedValue(createQueueItemDTO({ item_id: 1, status: 'completed' }));+ harness.socket.fire('connect', undefined);++ const images = await resultsPromise;++ expect(images.map((image) => image.imageName)).toEqual(['image-1.png']);+ });++ it('fails runs whose backend items were pruned (404) during a sweep', async () => {+ harness.coordinator.connect();++ await harness.coordinator.submitGenerate('local-1', generateRequest);+ const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ harness.api.getQueueItem.mockRejectedValue(new ApiError('not found', 404));+ harness.socket.fire('connect', undefined);++ await expect(resultsPromise).rejects.toThrow('no longer on the backend queue');+ });++ it('cancels by batch id when available, falling back to item ids', async () => {+ await harness.coordinator.cancelRun({ backendBatchId: 'batch-1', backendItemIds: [1, 2] });++ expect(harness.api.cancelQueueItemsByBatchIds).toHaveBeenCalledWith(['batch-1']);+ expect(harness.api.cancelQueueItems).not.toHaveBeenCalled();++ await harness.coordinator.cancelRun({ backendItemIds: [1, 2] });++ expect(harness.api.cancelQueueItems).toHaveBeenCalledWith([1, 2]);+ });++ it('stops notifying after dispose', () => {+ harness.coordinator.connect();+ harness.callbacks.onConnectionChange.mockClear();++ harness.coordinator.dispose();++ expect(harness.callbacks.onConnectionChange).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.tsnew file mode 100644index 0000000000..adef549b12--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts@@ -0,0 +1,462 @@+import { io } from 'socket.io-client';++import {+ cancelQueueItems,+ cancelQueueItemsByBatchIds,+ enqueueGenerateGraph,+ getQueueItem,+ getQueueItemResultImages,+ listAllQueueItems,+} from '../generation/api';+import type { EnqueueGenerateRequest, EnqueueGenerateResult, ImageDTO, QueueItemDTO } from '../generation/types';+import type { BackendConnectionStatus } from '../types';+import {+ isTerminalBackendStatus,+ parseQueueItemOrigin,+ type InvocationProgressEvent,+ type QueueItemStatusChangedEvent,+ type TerminalBackendQueueItemStatus,+} from './events';+import { ApiError, getAuthToken, getBackendSocketUrl } from './http';+import { queueItemProgressStore, type QueueItemProgressSink } from './progressStore';++const SOCKET_PATH = '/ws/socket.io';+const GALLERY_REFRESH_COALESCE_MS = 400;+const SAFETY_SWEEP_INTERVAL_MS = 30_000;+const TERMINAL_EVENT_BUFFER_LIMIT = 256;++/**+ * The minimal Socket.IO surface the coordinator uses; tests substitute a fake.+ */+export interface BackendSocket {+ on(event: string, handler: (payload: never) => void): unknown;+ emit(event: string, payload: unknown): unknown;+ connect(): unknown;+ disconnect(): unknown;+}++export interface QueueCoordinatorApi {+ cancelQueueItems: typeof cancelQueueItems;+ cancelQueueItemsByBatchIds: typeof cancelQueueItemsByBatchIds;+ enqueueGenerateGraph: typeof enqueueGenerateGraph;+ getQueueItem: typeof getQueueItem;+ getQueueItemResultImages: typeof getQueueItemResultImages;+ listAllQueueItems: typeof listAllQueueItems;+}++export interface QueueCoordinatorCallbacks {+ onConnectionChange(status: BackendConnectionStatus, error?: string): void;+ /** Coalesced signal that completed generations may have added gallery images. */+ onGalleryRefresh(): void;+}++type TerminalOutcome = { status: 'completed' } | { status: 'failed'; error: string } | { status: 'canceled' };++/** Thrown by `waitForResults` when the backend reports the run was canceled. */+export class QueueItemCancelledError extends Error {+ constructor(localQueueItemId: string) {+ super(`Queue item ${localQueueItemId} was canceled.`);+ this.name = 'QueueItemCancelledError';+ }+}++export interface ReconcileInput {+ id: string;+ status: 'pending' | 'running';+ backendItemIds?: number[];+ backendBatchId?: string;+}++export type ReconcileOutcome =+ /** A pending item the backend already accepted before the reload; do not re-enqueue. */+ | { kind: 'adopted'; backendItemIds: number[]; backendBatchId?: string }+ /** A running item whose backend items were found again; its results are awaitable. */+ | { kind: 'resumed' }+ /** A running item whose backend items no longer exist (queue cleared or pruned). */+ | { kind: 'missing' }+ /** A pending item the backend has never seen; submit it normally. */+ | { kind: 'enqueue' };++export interface CancelRunRequest {+ backendBatchId?: string;+ backendItemIds?: number[];+}++export interface QueueCoordinator {+ connect(): void;+ dispose(): void;+ /**+ * Match persisted pending/running queue items against the live backend queue+ * so a reload neither double-submits nor orphans work. Adopted and resumed+ * items are tracked and can be awaited with `waitForResults`.+ */+ reconcile(items: ReconcileInput[]): Promise<Map<string, ReconcileOutcome>>;+ /** Enqueue a generate batch and track its backend items for event-driven settlement. */+ submitGenerate(localQueueItemId: string, request: EnqueueGenerateRequest): Promise<EnqueueGenerateResult>;+ /**+ * Resolve once every backend item of the run reaches a terminal status —+ * driven by socket events, with a slow safety sweep as the only polling.+ * Resolves with the result images, throws on failure, and throws+ * `QueueItemCancelledError` on backend-side cancellation.+ */+ waitForResults(localQueueItemId: string, queuedAt: string): Promise<ImageDTO[]>;+ cancelRun(request: CancelRunRequest): Promise<void>;+}++interface RunState {+ backendItemIds: number[];+ backendBatchId?: string;+ outcomePromises: Promise<TerminalOutcome>[];+}++interface WaitState {+ localQueueItemId: string;+ settle: (outcome: TerminalOutcome) => void;+}++const defaultApi: QueueCoordinatorApi = {+ cancelQueueItems,+ cancelQueueItemsByBatchIds,+ enqueueGenerateGraph,+ getQueueItem,+ getQueueItemResultImages,+ listAllQueueItems,+};++const createDefaultSocket = (): BackendSocket => {+ const token = getAuthToken();++ return io(getBackendSocketUrl(), {+ auth: token ? { token } : undefined,+ autoConnect: false,+ extraHeaders: token ? { Authorization: `Bearer ${token}` } : undefined,+ path: SOCKET_PATH,+ timeout: 60000,+ });+};++const toTerminalOutcome = (+ status: TerminalBackendQueueItemStatus,+ error?: string | null,+ errorType?: string | null+): TerminalOutcome => {+ if (status === 'completed') {+ return { status: 'completed' };+ }++ if (status === 'failed') {+ return { error: error ?? errorType ?? 'Generation failed.', status: 'failed' };+ }++ return { status: 'canceled' };+};++export const createQueueCoordinator = (+ callbacks: QueueCoordinatorCallbacks,+ options: {+ api?: Partial<QueueCoordinatorApi>;+ createSocket?: () => BackendSocket;+ galleryRefreshCoalesceMs?: number;+ progress?: QueueItemProgressSink;+ sweepIntervalMs?: number;+ } = {}+): QueueCoordinator => {+ const api: QueueCoordinatorApi = { ...defaultApi, ...options.api };+ const createSocket = options.createSocket ?? createDefaultSocket;+ const progress = options.progress ?? queueItemProgressStore;+ const galleryRefreshCoalesceMs = options.galleryRefreshCoalesceMs ?? GALLERY_REFRESH_COALESCE_MS;+ const sweepIntervalMs = options.sweepIntervalMs ?? SAFETY_SWEEP_INTERVAL_MS;++ const runs = new Map<string, RunState>();+ const waits = new Map<number, WaitState>();+ /**+ * Terminal events that arrived for items nobody tracks yet. Closes the race+ * where a very fast generation finishes between `enqueue_batch` resolving+ * and the run being registered.+ */+ const recentTerminalOutcomes = new Map<number, TerminalOutcome>();++ let socket: BackendSocket | null = null;+ let isDisposed = false;+ let galleryRefreshTimer: ReturnType<typeof setTimeout> | null = null;+ let sweepTimer: ReturnType<typeof setInterval> | null = null;+ let isSweeping = false;++ const scheduleGalleryRefresh = (): void => {+ if (isDisposed || galleryRefreshTimer !== null) {+ return;+ }++ galleryRefreshTimer = setTimeout(() => {+ galleryRefreshTimer = null;+ callbacks.onGalleryRefresh();+ }, galleryRefreshCoalesceMs);+ };++ const bufferTerminalOutcome = (backendItemId: number, outcome: TerminalOutcome): void => {+ recentTerminalOutcomes.delete(backendItemId);+ recentTerminalOutcomes.set(backendItemId, outcome);++ while (recentTerminalOutcomes.size > TERMINAL_EVENT_BUFFER_LIMIT) {+ const oldestId = recentTerminalOutcomes.keys().next().value;++ if (oldestId === undefined) {+ return;+ }++ recentTerminalOutcomes.delete(oldestId);+ }+ };++ const settleWait = (backendItemId: number, outcome: TerminalOutcome): void => {+ const wait = waits.get(backendItemId);++ if (!wait) {+ bufferTerminalOutcome(backendItemId, outcome);+ return;+ }++ waits.delete(backendItemId);+ progress.clear(wait.localQueueItemId);+ wait.settle(outcome);+ };++ const settleFromQueueItem = (queueItem: QueueItemDTO): void => {+ if (queueItem.status !== 'pending' && queueItem.status !== 'in_progress') {+ settleWait(queueItem.item_id, toTerminalOutcome(queueItem.status, queueItem.error_message, queueItem.error_type));+ }+ };++ const trackBackendItem = (localQueueItemId: string, backendItemId: number): Promise<TerminalOutcome> => {+ const bufferedOutcome = recentTerminalOutcomes.get(backendItemId);++ if (bufferedOutcome) {+ recentTerminalOutcomes.delete(backendItemId);++ return Promise.resolve(bufferedOutcome);+ }++ return new Promise<TerminalOutcome>((settle) => {+ waits.set(backendItemId, { localQueueItemId, settle });+ });+ };++ const beginRun = (localQueueItemId: string, backendItemIds: number[], backendBatchId?: string): void => {+ runs.set(localQueueItemId, {+ backendBatchId,+ backendItemIds,+ outcomePromises: backendItemIds.map((backendItemId) => trackBackendItem(localQueueItemId, backendItemId)),+ });+ };++ /** Slow safety net for events lost to disconnects; runs on reconnect and on a long interval. */+ const sweep = async (): Promise<void> => {+ if (isSweeping || waits.size === 0) {+ return;+ }++ isSweeping = true;++ try {+ await Promise.all(+ [...waits.keys()].map(async (backendItemId) => {+ try {+ settleFromQueueItem(await api.getQueueItem(backendItemId));+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) {+ settleWait(backendItemId, {+ error: `Queue item ${backendItemId} is no longer on the backend queue.`,+ status: 'failed',+ });+ }+ }+ })+ );+ } finally {+ isSweeping = false;+ }+ };++ const handleStatusChanged = (event: QueueItemStatusChangedEvent): void => {+ if (!isTerminalBackendStatus(event.status)) {+ return;+ }++ settleWait(event.item_id, toTerminalOutcome(event.status, event.error_message, event.error_type));++ if (event.status === 'completed') {+ scheduleGalleryRefresh();+ }+ };++ const handleProgress = (event: InvocationProgressEvent): void => {+ const wait = waits.get(event.item_id);++ if (wait) {+ progress.set(wait.localQueueItemId, { message: event.message, percentage: event.percentage });+ }+ };++ /** Dropped after dispose so socket teardown does not dispatch into unmounted React. */+ const notifyConnection = (status: BackendConnectionStatus, error?: string): void => {+ if (!isDisposed) {+ callbacks.onConnectionChange(status, error);+ }+ };++ const connect = (): void => {+ if (isDisposed || socket) {+ return;+ }++ socket = createSocket();+ notifyConnection('connecting');++ socket.on('connect', () => {+ notifyConnection('connected');+ socket?.emit('subscribe_queue', { queue_id: 'default' });+ scheduleGalleryRefresh();+ void sweep();+ });+ socket.on('connect_error', (error: { message: string }) => {+ notifyConnection('disconnected', error.message);+ });+ socket.on('disconnect', (reason: string) => {+ notifyConnection('disconnected', reason);+ });+ socket.on('queue_item_status_changed', handleStatusChanged);+ socket.on('invocation_progress', handleProgress);+ socket.connect();++ sweepTimer = setInterval(() => {+ void sweep();+ }, sweepIntervalMs);+ };++ const dispose = (): void => {+ isDisposed = true;++ if (galleryRefreshTimer !== null) {+ clearTimeout(galleryRefreshTimer);+ galleryRefreshTimer = null;+ }++ if (sweepTimer !== null) {+ clearInterval(sweepTimer);+ sweepTimer = null;+ }++ socket?.disconnect();+ socket = null;+ };++ const reconcile = async (items: ReconcileInput[]): Promise<Map<string, ReconcileOutcome>> => {+ const outcomes = new Map<string, ReconcileOutcome>();++ if (items.length === 0) {+ return outcomes;+ }++ const backendItems = await api.listAllQueueItems();+ const backendItemsById = new Map(backendItems.map((item) => [item.item_id, item]));+ const backendItemsByLocalId = new Map<string, QueueItemDTO[]>();++ for (const backendItem of backendItems) {+ const localQueueItemId = parseQueueItemOrigin(backendItem.origin);++ if (localQueueItemId) {+ backendItemsByLocalId.set(localQueueItemId, [+ ...(backendItemsByLocalId.get(localQueueItemId) ?? []),+ backendItem,+ ]);+ }+ }++ for (const item of items) {+ const knownBackendItems = item.backendItemIds?.length+ ? item.backendItemIds.map((backendItemId) => backendItemsById.get(backendItemId))+ : (backendItemsByLocalId.get(item.id) ?? []);+ const foundBackendItems = knownBackendItems.filter((backendItem) => backendItem !== undefined);++ if (foundBackendItems.length !== knownBackendItems.length || foundBackendItems.length === 0) {+ // A pending item with no backend trace was never accepted and is safe+ // to submit; a running item with (partially) vanished backend items is+ // unrecoverable.+ outcomes.set(item.id, item.status === 'pending' ? { kind: 'enqueue' } : { kind: 'missing' });+ continue;+ }++ const backendItemIds = foundBackendItems.map((backendItem) => backendItem.item_id);+ const backendBatchId = item.backendBatchId ?? foundBackendItems[0]?.batch_id;++ beginRun(item.id, backendItemIds, backendBatchId);++ for (const backendItem of foundBackendItems) {+ settleFromQueueItem(backendItem);+ }++ outcomes.set(+ item.id,+ item.status === 'running' ? { kind: 'resumed' } : { backendBatchId, backendItemIds, kind: 'adopted' }+ );+ }++ return outcomes;+ };++ const submitGenerate = async (+ localQueueItemId: string,+ request: EnqueueGenerateRequest+ ): Promise<EnqueueGenerateResult> => {+ const result = await api.enqueueGenerateGraph(request);++ beginRun(localQueueItemId, result.itemIds, result.batchId);++ return result;+ };++ const waitForResults = async (localQueueItemId: string, queuedAt: string): Promise<ImageDTO[]> => {+ const run = runs.get(localQueueItemId);++ if (!run) {+ throw new Error(`Queue item ${localQueueItemId} has no tracked backend run.`);+ }++ try {+ const outcomes = await Promise.all(run.outcomePromises);+ const failure = outcomes.find((outcome) => outcome.status === 'failed');++ if (failure) {+ throw new Error(failure.error);+ }++ if (outcomes.some((outcome) => outcome.status === 'canceled')) {+ throw new QueueItemCancelledError(localQueueItemId);+ }++ const imagesPerItem = await Promise.all(+ run.backendItemIds.map((backendItemId) =>+ api.getQueueItemResultImages(backendItemId, localQueueItemId, queuedAt)+ )+ );++ return imagesPerItem.flat();+ } finally {+ runs.delete(localQueueItemId);+ progress.clear(localQueueItemId);+ }+ };++ const cancelRun = async ({ backendBatchId, backendItemIds }: CancelRunRequest): Promise<void> => {+ if (backendBatchId) {+ await api.cancelQueueItemsByBatchIds([backendBatchId]);+ return;+ }++ if (backendItemIds?.length) {+ await api.cancelQueueItems(backendItemIds);+ }+ };++ return { cancelRun, connect, dispose, reconcile, submitGenerate, waitForResults };+};