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): reconcile queue runtime with backend
joshistoast6bffa72345d1
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsxindex 75f0052035..6588e2f5c1 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.tsx@@ -1,4 +1,14 @@-import { createContext, use, useEffect, useMemo, useReducer, useRef, type Dispatch, type ReactNode } from 'react';+import {+ createContext,+ use,+ useEffect,+ useMemo,+ useReducer,+ useRef,+ useState,+ type Dispatch,+ type ReactNode,+} from 'react';import { localStorageWorkbenchPersistence } from './persistence';import type { Project, WorkbenchState } from './types';@@ -8,6 +18,12 @@ interface WorkbenchContextValue {state: WorkbenchState;activeProject: Project;dispatch: Dispatch<WorkbenchAction>;+ /**+ * True once the persisted snapshot has been loaded (or found absent). Side+ * effects that read or mutate the queue must wait for this, or they race the+ * async hydration and act on state that is about to be replaced.+ */+ hasHydrated: boolean;}const WorkbenchContext = createContext<WorkbenchContextValue | null>(null);@@ -26,6 +42,7 @@ const getPersistedStateKey = (state: WorkbenchState): string =>export const WorkbenchProvider = ({ children }: { children: ReactNode }) => {const [state, dispatch] = useReducer(workbenchReducer, undefined, createInitialWorkbenchState);+ const [hasHydrated, setHasHydrated] = useState(false);const hasLoadedPersistenceRef = useRef(false);const latestStateRef = useRef(state);const lastSavedStateKeyRef = useRef(getPersistedStateKey(state));@@ -55,6 +72,10 @@ export const WorkbenchProvider = ({ children }: { children: ReactNode }) => {});} finally {hasLoadedPersistenceRef.current = true;++ if (!isCancelled) {+ setHasHydrated(true);+ }}};@@ -110,8 +131,8 @@ export const WorkbenchProvider = ({ children }: { children: ReactNode }) => {const value = useMemo<WorkbenchContextValue>(() => {const activeProject = state.projects.find((project) => project.id === state.activeProjectId) ?? state.projects[0];- return { state, activeProject, dispatch };- }, [state]);+ return { state, activeProject, dispatch, hasHydrated };+ }, [state, hasHydrated]);return <WorkbenchContext value={value}>{children}</WorkbenchContext>;};diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsxindex 14ba4eb052..f071ecefb3 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx@@ -1,10 +1,16 @@-import { useEffect, useRef } from 'react';+import { useEffect, useRef, useState, type Dispatch } from 'react';-import { cancelQueueItems, enqueueGenerateGraph, waitForQueueItemImages } from './generation/api';+import {+ createQueueCoordinator,+ QueueItemCancelledError,+ type QueueCoordinator,+ type ReconcileInput,+} from './backend/queueCoordinator';import type { GenerateSettings } from './generation/types';import { addImagesToGalleryBoard } from './gallery/api';-import type { QueueItem } from './types';+import type { Project, QueueItem } from './types';import { useWorkbench } from './WorkbenchContext';+import type { WorkbenchAction } from './workbenchState';const isGenerateSettings = (value: unknown): value is GenerateSettings => {if (!value || typeof value !== 'object') {@@ -22,124 +28,276 @@ const isGenerateSettings = (value: unknown): value is GenerateSettings => {);};-const getPendingGenerateQueueItems = (items: QueueItem[]): QueueItem[] =>- items.filter((item) => item.status === 'pending' && item.snapshot.sourceId === 'generate');--const getCancelledQueueItems = (items: QueueItem[]): QueueItem[] => items.filter((item) => item.status === 'cancelled');--const getCancelledBackendQueueItems = (items: QueueItem[]): QueueItem[] =>- items.filter((item) => item.status === 'cancelled' && item.backendItemIds?.length);-const getSnapshotGalleryBoardId = (queueItem: QueueItem): string | null => {const selectedBoardId = queueItem.snapshot.widgetStates.gallery.values.selectedBoardId;return typeof selectedBoardId === 'string' ? selectedBoardId : null;};+const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));++/**+ * Await a tracked run's terminal outcome, route its images to the queue item's+ * destination, and reflect the outcome in workbench state.+ */+const routeRunResults = async (+ coordinator: QueueCoordinator,+ projectId: string,+ queueItem: QueueItem,+ dispatch: Dispatch<WorkbenchAction>+): Promise<void> => {+ try {+ const images = await coordinator.waitForResults(queueItem.id, queueItem.snapshot.submittedAt);++ if (queueItem.snapshot.destination === 'gallery') {+ const selectedBoardId = getSnapshotGalleryBoardId(queueItem);++ if (selectedBoardId && selectedBoardId !== 'none') {+ await addImagesToGalleryBoard(+ selectedBoardId,+ images.map((image) => image.imageName)+ );+ }+ }++ dispatch({ images, projectId, queueItemId: queueItem.id, type: 'routeQueueItemResults' });+ } catch (error) {+ if (error instanceof QueueItemCancelledError) {+ dispatch({ projectId, queueItemId: queueItem.id, status: 'cancelled', type: 'setQueueItemStatus' });+ return;+ }++ dispatch({+ error: toErrorMessage(error),+ projectId,+ queueItemId: queueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });+ }+};++const submitQueueItem = (+ coordinator: QueueCoordinator,+ project: Project,+ queueItem: QueueItem,+ dispatch: Dispatch<WorkbenchAction>+): void => {+ const graph = queueItem.snapshot.graph.backendGraph;+ const generateValues = queueItem.snapshot.widgetStates.generate.values;++ if (!graph || !isGenerateSettings(generateValues)) {+ dispatch({+ error: 'Generate queue item is missing a compiled backend graph.',+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });+ return;+ }++ coordinator+ .submitGenerate(queueItem.id, {+ batchCount: generateValues.batchCount,+ destination: queueItem.snapshot.destination,+ graph,+ negativePrompt: generateValues.negativePrompt,+ negativePromptNodeId: 'negative_prompt',+ positivePrompt: generateValues.positivePrompt,+ positivePromptNodeId: 'positive_prompt',+ seed: generateValues.seed,+ seedNodeId: 'seed',+ sourceQueueItemId: queueItem.id,+ })+ .then(({ batchId, itemIds }) => {+ dispatch({+ backendBatchId: batchId,+ backendItemIds: itemIds,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });++ return routeRunResults(coordinator, project.id, queueItem, dispatch);+ })+ .catch((error: unknown) => {+ dispatch({+ error: toErrorMessage(error),+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });+ });+};++/**+ * Bridges workbench state to the backend queue coordinator: it submits pending+ * queue items, forwards cancellations, and reflects connection status, while+ * the coordinator owns the socket and event-driven settlement. Mounted once+ * inside the WorkbenchProvider; renders nothing.+ */export const WorkbenchRuntime = () => {- const { state, dispatch } = useWorkbench();+ const { state, dispatch, hasHydrated } = useWorkbench();+ const coordinatorRef = useRef<QueueCoordinator | null>(null);const startedQueueItemIdsRef = useRef(new Set<string>());const cancelledQueueItemIdsRef = useRef(new Set<string>());- const backendCancellationQueueItemIdsRef = useRef(new Set<string>());+ const reconcileStateRef = useRef<'idle' | 'running' | 'done'>('idle');+ const [isReconciled, setIsReconciled] = useState(false);useEffect(() => {- for (const project of state.projects) {- for (const queueItem of getCancelledQueueItems(project.queue.items)) {- cancelledQueueItemIdsRef.current.add(queueItem.id);- }+ const coordinator = createQueueCoordinator({+ onConnectionChange: (status, error) => {+ dispatch({ error, status, type: 'setBackendConnectionStatus' });+ },+ onGalleryRefresh: () => {+ dispatch({ type: 'refreshBackendData' });+ },+ });- for (const queueItem of getPendingGenerateQueueItems(project.queue.items)) {- if (startedQueueItemIdsRef.current.has(queueItem.id)) {- continue;- }+ coordinatorRef.current = coordinator;+ coordinator.connect();++ return () => {+ coordinatorRef.current = null;+ coordinator.dispose();+ };+ }, [dispatch]);++ // Reconcile persisted queue items against the live backend queue exactly+ // once, after hydration and first connect. Until this finishes, submission+ // is held back so an item the backend already accepted is not enqueued twice.+ useEffect(() => {+ const coordinator = coordinatorRef.current;++ if (+ !coordinator ||+ !hasHydrated ||+ state.backendConnection.status !== 'connected' ||+ reconcileStateRef.current !== 'idle'+ ) {+ return;+ }- startedQueueItemIdsRef.current.add(queueItem.id);+ reconcileStateRef.current = 'running';- const graph = queueItem.snapshot.graph.backendGraph;- const generateValues = queueItem.snapshot.widgetStates.generate.values;+ const openItems = state.projects.flatMap((project) =>+ project.queue.items+ .filter((queueItem) => queueItem.status === 'pending' || queueItem.status === 'running')+ .map((queueItem) => ({ project, queueItem }))+ );++ for (const { queueItem } of openItems) {+ startedQueueItemIdsRef.current.add(queueItem.id);+ }++ const inputs: ReconcileInput[] = openItems.map(({ queueItem }) => ({+ backendBatchId: queueItem.backendBatchId,+ backendItemIds: queueItem.backendItemIds,+ id: queueItem.id,+ status: queueItem.status === 'running' ? 'running' : 'pending',+ }));++ coordinator+ .reconcile(inputs)+ .then((outcomes) => {+ for (const { project, queueItem } of openItems) {+ const outcome = outcomes.get(queueItem.id);++ switch (outcome?.kind) {+ case 'enqueue': {+ startedQueueItemIdsRef.current.delete(queueItem.id);+ break;+ }+ case 'adopted': {+ dispatch({+ backendBatchId: outcome.backendBatchId,+ backendItemIds: outcome.backendItemIds,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ void routeRunResults(coordinator, project.id, queueItem, dispatch);+ break;+ }+ case 'resumed': {+ void routeRunResults(coordinator, project.id, queueItem, dispatch);+ break;+ }+ case 'missing': {+ dispatch({+ error: 'This run is no longer on the backend queue (it may have been cleared).',+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });+ break;+ }+ }+ }+ })+ .catch((error: unknown) => {+ // Release pending items to the normal submission path; running items+ // cannot be re-attached without backend state, so fail them visibly+ // rather than leaving them stuck as running forever.+ dispatch({ message: `Queue reconciliation failed: ${toErrorMessage(error)}`, type: 'recordError' });++ for (const { project, queueItem } of openItems) {+ if (queueItem.status === 'pending') {+ startedQueueItemIdsRef.current.delete(queueItem.id);+ continue;+ }- if (!graph || !isGenerateSettings(generateValues)) {dispatch({- error: 'Generate queue item is missing a compiled backend graph.',+ error: 'Could not reconcile this run with the backend queue after reload.',projectId: project.id,queueItemId: queueItem.id,status: 'failed',type: 'setQueueItemStatus',});- continue;}+ })+ .finally(() => {+ reconcileStateRef.current = 'done';+ setIsReconciled(true);+ });+ }, [dispatch, hasHydrated, state.backendConnection.status, state.projects]);- const queuedAt = queueItem.snapshot.submittedAt;-- enqueueGenerateGraph({- batchCount: generateValues.batchCount,- destination: queueItem.snapshot.destination,- graph,- negativePrompt: generateValues.negativePrompt,- negativePromptNodeId: 'negative_prompt',- positivePrompt: generateValues.positivePrompt,- positivePromptNodeId: 'positive_prompt',- seed: generateValues.seed,- seedNodeId: 'seed',- sourceQueueItemId: queueItem.id,- })- .then(async ({ itemIds }) => {- dispatch({- backendItemIds: itemIds,- projectId: project.id,- queueItemId: queueItem.id,- type: 'markQueueItemBackendSubmitted',- });-- if (cancelledQueueItemIdsRef.current.has(queueItem.id)) {- return;- }-- const images = (- await Promise.all(itemIds.map((itemId) => waitForQueueItemImages(itemId, queueItem.id, queuedAt)))- ).flat();-- if (cancelledQueueItemIdsRef.current.has(queueItem.id)) {- return;- }+ useEffect(() => {+ const coordinator = coordinatorRef.current;- if (queueItem.snapshot.destination === 'gallery') {- const selectedBoardId = getSnapshotGalleryBoardId(queueItem);+ if (!coordinator || !isReconciled) {+ return;+ }- if (selectedBoardId && selectedBoardId !== 'none') {- await addImagesToGalleryBoard(- selectedBoardId,- images.map((image) => image.imageName)- );- }- }+ for (const project of state.projects) {+ for (const queueItem of project.queue.items) {+ if (+ queueItem.status === 'pending' &&+ queueItem.snapshot.sourceId === 'generate' &&+ !startedQueueItemIdsRef.current.has(queueItem.id)+ ) {+ startedQueueItemIdsRef.current.add(queueItem.id);+ submitQueueItem(coordinator, project, queueItem, dispatch);+ }- dispatch({ images, projectId: project.id, queueItemId: queueItem.id, type: 'routeQueueItemResults' });- })- .catch((error: unknown) => {- dispatch({- error: error instanceof Error ? error.message : String(error),- projectId: project.id,- queueItemId: queueItem.id,- status: 'failed',- type: 'setQueueItemStatus',+ if (+ queueItem.status === 'cancelled' &&+ (queueItem.backendBatchId || queueItem.backendItemIds?.length) &&+ !cancelledQueueItemIdsRef.current.has(queueItem.id)+ ) {+ cancelledQueueItemIdsRef.current.add(queueItem.id);+ coordinator+ .cancelRun({ backendBatchId: queueItem.backendBatchId, backendItemIds: queueItem.backendItemIds })+ .catch((error: unknown) => {+ dispatch({ message: toErrorMessage(error), type: 'recordError' });});- });- }-- for (const queueItem of getCancelledBackendQueueItems(project.queue.items)) {- if (backendCancellationQueueItemIdsRef.current.has(queueItem.id) || !queueItem.backendItemIds?.length) {- continue;}-- backendCancellationQueueItemIdsRef.current.add(queueItem.id);-- cancelQueueItems(queueItem.backendItemIds).catch((error: unknown) => {- dispatch({ message: error instanceof Error ? error.message : String(error), type: 'recordError' });- });}}- }, [dispatch, state.projects]);+ }, [dispatch, isReconciled, state.projects]);return null;};diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex 0d84f65304..7c75f49b7f 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -288,6 +288,7 @@ export interface LayoutPreset {export interface WorkbenchState {projects: Project[];activeProjectId: string;+ backendConnection: BackendConnectionState;errorLog: string[];notifications: WorkbenchNotification[];autosave: AutosaveState;@@ -295,6 +296,15 @@ export interface WorkbenchState {widgetFailures: WidgetFailure[];}+export type BackendConnectionStatus = 'connecting' | 'connected' | 'disconnected';++export interface BackendConnectionState {+ status: BackendConnectionStatus;+ error?: string;+ lastConnectedAt?: string;+ lastDisconnectedAt?: string;+}+export type WorkbenchNotificationKind = 'error' | 'success' | 'info';export interface WorkbenchNotification {@@ -351,6 +361,7 @@ export interface QueueItem {cancellable: boolean;snapshot: QueueSubmissionSnapshot;backendItemIds?: number[];+ backendBatchId?: string;error?: string;resultImages?: GeneratedImageContract[];}diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 98f38df13a..8982a328ff 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -622,3 +622,50 @@ describe('workbench preferences', () => {expect(state.account.preferences.themeId).toBe('dark');});});++describe('workbench backend connection recovery', () => {+ it('tracks backend connection status', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ status: 'disconnected',+ type: 'setBackendConnectionStatus',+ error: 'server down',+ });++ expect(state.backendConnection.status).toBe('disconnected');+ expect(state.backendConnection.error).toBe('server down');+ expect(state.backendConnection.lastDisconnectedAt).toBeDefined();++ state = workbenchReducer(state, { status: 'connected', type: 'setBackendConnectionStatus' });++ expect(state.backendConnection.status).toBe('connected');+ expect(state.backendConnection.error).toBeUndefined();+ expect(state.backendConnection.lastConnectedAt).toBeDefined();+ });++ it('refreshes every project gallery when backend data may have changed', () => {+ const initial = createInitialWorkbenchState();+ const previousTokens = initial.projects.map((project) => project.widgetStates.gallery.values.galleryRefreshToken);+ const state = workbenchReducer(initial, { type: 'refreshBackendData' });++ expect(state.projects).toHaveLength(initial.projects.length);++ for (const [index, project] of state.projects.entries()) {+ expect(project.widgetStates.gallery.values.galleryRefreshToken).toBeDefined();+ expect(project.widgetStates.gallery.values.galleryRefreshToken).not.toBe(previousTokens[index]);+ }+ });++ it('does not hydrate stale persisted backend connection state', () => {+ const initial = createInitialWorkbenchState();+ const persisted = {+ ...initial,+ backendConnection: { lastConnectedAt: '2026-06-10T00:00:00.000Z', status: 'connected' },+ } as WorkbenchState;++ const state = workbenchReducer(initial, { state: persisted, type: 'hydrateWorkbench' });++ expect(state.backendConnection).toEqual({ status: 'connecting' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 2666a6ea28..3631c76593 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -59,7 +59,13 @@ type WorkbenchAction =| { type: 'setGenerateBatchCount'; batchCount: number }| { type: 'submitInvocationSnapshot'; backendSupportsCancellation: boolean }| { type: 'submitResolvedInvocationSnapshot'; backendSupportsCancellation: boolean; route: InvocationRoute }- | { type: 'markQueueItemBackendSubmitted'; projectId: string; queueItemId: string; backendItemIds: number[] }+ | {+ type: 'markQueueItemBackendSubmitted';+ projectId: string;+ queueItemId: string;+ backendItemIds: number[];+ backendBatchId?: string;+ }| { type: 'setQueueItemStatus'; projectId: string; queueItemId: string; status: QueueItemStatus; error?: string }| { type: 'routeQueueItemResults'; projectId: string; queueItemId: string; images: GeneratedImageContract[] }| { type: 'setStagedImageIndex'; imageIndex: number }@@ -96,6 +102,8 @@ type WorkbenchAction =| { type: 'recordWidgetFailure'; failure: WidgetFailure }| { type: 'setPreferences'; preferences: Partial<WorkbenchPreferences> }| { type: 'recordError'; message: string }+ | { type: 'setBackendConnectionStatus'; status: WorkbenchState['backendConnection']['status']; error?: string }+ | { type: 'refreshBackendData' }| { type: 'recordNotice'; kind: WorkbenchNotificationKind; title: string; message?: string };const HISTORY_LIMIT = 40;@@ -610,6 +618,7 @@ const normalizePreferences = (preferences?: Partial<WorkbenchPreferences>): Workconst normalizeWorkbenchState = (state: WorkbenchState): WorkbenchState => ({...state,+ backendConnection: { status: 'connecting' },// Persisted snapshots from before preferences existed (or partially written// ones) are healed by merging in defaults, so hydrate never reads `undefined`.account: {@@ -762,6 +771,20 @@ const updateGalleryValues = (},}));+const refreshProjectBackendData = (project: Project): Project => ({+ ...project,+ widgetStates: {+ ...project.widgetStates,+ gallery: {+ ...project.widgetStates.gallery,+ values: {+ ...project.widgetStates.gallery.values,+ galleryRefreshToken: createId('gallery-refresh'),+ },+ },+ },+});+const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => ({...project,queue: {@@ -896,6 +919,7 @@ export const createInitialWorkbenchState = (): WorkbenchState => ({account: { activeLayoutPresetId: 'canvas-default', preferences: { ...DEFAULT_PREFERENCES } },activeProjectId: 'project-1',autosave: { status: 'idle' },+ backendConnection: { status: 'connecting' },errorLog: [],notifications: [],projects: Array.from({ length: INITIAL_PROJECT_COUNT }, (_value, index) => createProject(index + 1)),@@ -1128,6 +1152,7 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)return updateProjectById(state, action.projectId, (project) =>updateQueueItem(project, action.queueItemId, (item) => ({...item,+ backendBatchId: action.backendBatchId,backendItemIds: action.backendItemIds,status: item.status === 'cancelled' ? 'cancelled' : 'running',}))@@ -1610,6 +1635,22 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)createNotification({ kind: 'error', message: action.message, title: 'Error' }));}+ case 'setBackendConnectionStatus': {+ const timestamp = now();++ return {+ ...state,+ backendConnection: {+ error: action.error,+ lastConnectedAt: action.status === 'connected' ? timestamp : state.backendConnection.lastConnectedAt,+ lastDisconnectedAt: action.status === 'disconnected' ? timestamp : state.backendConnection.lastDisconnectedAt,+ status: action.status,+ },+ };+ }+ case 'refreshBackendData': {+ return { ...state, projects: state.projects.map((project) => refreshProjectBackendData(project)) };+ }case 'recordNotice': {return addNotification(state,