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(workbench): complete durable queue recovery and recall
Josh Corbett2446de579e42
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex b23eee3022..9ba516a33f 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -2,15 +2,15 @@"build": {"launchpad": {"baseline": {- "brotliBytes": 843612,+ "brotliBytes": 845320,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 842578,+ "gzipBytes": 844360,"imageRawBytes": 156376,- "initialRawBytes": 1967072,+ "initialRawBytes": 1971501,"largestAssetRawBytes": 746400,"otherAssetRawBytes": 0,- "ownedRawBytes": 70904,+ "ownedRawBytes": 71161,"requestCount": 42,"scriptRequestCount": 26,"sourceOwners": [@@ -291,15 +291,15 @@]},"limits": {- "brotliBytes": 852049,+ "brotliBytes": 853774,"cssRawBytes": 2181,"fontRawBytes": 221675,- "gzipBytes": 851004,+ "gzipBytes": 852804,"imageRawBytes": 157940,- "initialRawBytes": 1986743,+ "initialRawBytes": 1991217,"largestAssetRawBytes": 753864,"otherAssetRawBytes": 0,- "ownedRawBytes": 70904,+ "ownedRawBytes": 71161,"requestCount": 42,"scriptRequestCount": 26},@@ -309,17 +309,17 @@},"editor": {"baseline": {- "brotliBytes": 1125389,+ "brotliBytes": 1140605,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 1120482,+ "gzipBytes": 1135208,"imageRawBytes": 156376,- "initialRawBytes": 2828584,+ "initialRawBytes": 2869631,"largestAssetRawBytes": 746400,"otherAssetRawBytes": 0,- "ownedRawBytes": 124074,- "requestCount": 97,- "scriptRequestCount": 81,+ "ownedRawBytes": 127188,+ "requestCount": 103,+ "scriptRequestCount": 87,"sourceOwners": ["package:@ark-ui/react","package:@chakra-ui/react",@@ -590,6 +590,7 @@"source:src/features/queue/reveal.ts","source:src/features/queue/runtime.ts","source:src/features/queue/runtime/coordinator.ts",+ "source:src/features/queue/runtime/receiptAcknowledgements.ts","source:src/features/queue/ui/QueueUiContext.tsx","source:src/features/queue/ui/currentBatchItems.ts","source:src/features/queue/ui/queueConfirmationStore.ts",@@ -815,6 +816,7 @@"source:src/workbench/performanceMarks.ts","source:src/workbench/persistenceRuntime.ts","source:src/workbench/projectCanvasGate.ts",+ "source:src/workbench/projectEvents.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",@@ -836,6 +838,7 @@"source:src/workbench/projects/projectFileToasts.ts","source:src/workbench/projects/projectFlush.ts","source:src/workbench/projects/projectHydration.ts",+ "source:src/workbench/projects/projectLifecycleLocks.ts","source:src/workbench/projects/projectLoadRefusal.ts","source:src/workbench/projects/projectTabsA11y.ts","source:src/workbench/projects/session.ts",@@ -845,8 +848,16 @@"source:src/workbench/projects/useProjectFileActions.ts","source:src/workbench/projects/workbenchDatabase.ts","source:src/workbench/queue-integration/QueueProgressRail.tsx",+ "source:src/workbench/queue-integration/QueueRecoveryNotice.tsx",+ "source:src/workbench/queue-integration/activeQueueRuns.ts",+ "source:src/workbench/queue-integration/queueRecallCache.ts",+ "source:src/workbench/queue-integration/queueRecovery.ts",+ "source:src/workbench/queue-integration/queueRunJournal.ts",+ "source:src/workbench/queue-integration/queueRunLocks.ts",+ "source:src/workbench/queue-integration/queueRunPersistence.ts",+ "source:src/workbench/queue-integration/queueRunRestoration.ts","source:src/workbench/queue-integration/useActiveQueueProgress.ts",- "source:src/workbench/queueHistoryNormalization.ts",+ "source:src/workbench/queue-integration/useQueueRecoveryProjectIds.ts","source:src/workbench/settings/SettingsButton.tsx","source:src/workbench/settings/SettingsDialogHost.tsx","source:src/workbench/settings/clearWorkspaceData.ts",@@ -857,6 +868,7 @@"source:src/workbench/shell/DocumentTitleProgress.tsx","source:src/workbench/shell/Panels.tsx","source:src/workbench/shell/ProjectConflictBanner.tsx",+ "source:src/workbench/shell/QueueRecoveryBanner.tsx","source:src/workbench/shell/StatusBar.tsx","source:src/workbench/shell/WorkbenchShell.tsx","source:src/workbench/shell/documentTitle.ts",@@ -946,17 +958,17 @@]},"limits": {- "brotliBytes": 1136643,+ "brotliBytes": 1152012,"cssRawBytes": 2181,"fontRawBytes": 221675,- "gzipBytes": 1131687,+ "gzipBytes": 1146561,"imageRawBytes": 157940,- "initialRawBytes": 2856870,+ "initialRawBytes": 2898328,"largestAssetRawBytes": 753864,"otherAssetRawBytes": 0,- "ownedRawBytes": 124074,- "requestCount": 97,- "scriptRequestCount": 81+ "ownedRawBytes": 127188,+ "requestCount": 103,+ "scriptRequestCount": 87},"owner": "workbench","remediationTicket": "deepen-widget-registry-loading",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex d8b5179456..05593e4b24 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -413,6 +413,7 @@},"projects": {"allSavedAlreadyOpen": "All saved projects are already open.",+ "activeRunsMustFinish": "Wait for active queue runs to finish first.","closeProjectLabel": "Close {{name}}","closeBlocked": "Project not closed","couldNotOpen": "Could not open project",@@ -1523,6 +1524,25 @@"useServer": "Use server version","useServerConfirmBody": "Replace the local draft with the current server version? Local changes will be discarded."},+ "queueRecovery": {+ "actionFailed": "The queue recovery action failed.",+ "description": "Project {{projectId}} has locally saved queue run recovery data.",+ "discard": "Discard recovery",+ "discardConfirmBody": "Permanently discard this project's local queue recovery data? This does not cancel work that may still be running on the server.",+ "discardConfirmTitle": "Discard queue recovery?",+ "export": "Export recovery",+ "loading": "Looking for queue recovery data…",+ "lockContended": "This project's queue recovery is active in another tab. Close that tab or wait for its runs to finish.",+ "lockUnavailable": "Queue recovery cannot be discarded because cross-tab coordination is unavailable.",+ "next": "Next",+ "open": "Open project",+ "openFailed": "The project could not be opened. Its local queue recovery data is still available.",+ "position": "Recovery {{number}} of {{count}}.",+ "previous": "Previous",+ "storageUnavailable": "Browser queue recovery storage may contain data, but it cannot be inspected in this browser session.",+ "storageUnavailableTitle": "Queue recovery storage is unavailable",+ "title": "Queue run recovery available"+ },"deleteLayoutPreset": "Delete preset","deleteLayoutPresetBody": "Delete \"{{name}}\"? This only removes the saved preset.","deleteLayoutPresetQuestion": "Delete layout preset?",@@ -2133,26 +2153,18 @@},"project": {"copyId": "Copy project id",- "deleteRecovery": "Delete recovery",- "deleteRecoveryAria": "Delete {{name}}",- "deleteRecoveryBody": "Delete \"{{name}}\"? The recovery copy is removed permanently.",- "deleteRecoveryTitle": "Delete recovery?",+ "activeRuns": "Active runs",+ "activeRunCounts": "{{running}} running · {{queued}} queued","events": "Events","graphNodes": "Graph nodes","idCopied": "Project id copied","nameHelp": "Saved with the project.","nameLabel": "Project name",- "openOriginal": "Open original \"{{name}}\"",- "openRecovery": "Open {{name}}",- "queueItems": "Queue items",- "recoveries": "Recoveries",- "recoveryCopy": "Recovery copy",- "recoveryForkedDescription": "Forked {{time}} after this project was changed elsewhere.","sync": "Sync",- "syncOffline": "Offline — saved in this browser",+ "syncOffline": "Offline — awaiting sync","syncSynced": "Synced (revision {{revision}})","syncConflict": "Needs conflict resolution",- "syncUpdateClient": "Update Invoke to sync — saved in this browser",+ "syncUpdateClient": "Update Invoke to sync","syncWaiting": "Waiting to sync"},"preview": {diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsxindex 6e6a105603..5d5cab78ce 100644--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx@@ -1,12 +1,24 @@import { invalidateGallery } from '@features/gallery/queries';import { modelLoadActivitySink } from '@features/models';import { nodeExecutionStore } from '@features/nodes';-import { createProductionQueueRuntime } from '@features/queue';+import { createProductionQueueRuntime, createProductionQueueReceiptAcknowledgements } from '@features/queue';import { createWorkflowRunCaptureSink } from '@features/workflow/queries';import { ensureInvocationTemplatesLoaded } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';-import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';import { useQueryClient } from '@tanstack/react-query';+import { getOpenProject, getProjectSyncSnapshot } from '@workbench/projects/syncStore';+import {+ createAccountOwnedQueueRecallCache,+ type QueueRecallCache,+} from '@workbench/queue-integration/queueRecallCache';+import { createAccountOwnedQueueRunJournal, type QueueRunJournal } from '@workbench/queue-integration/queueRunJournal';+import { createQueueRunLockPort } from '@workbench/queue-integration/queueRunLocks';+import { withQueueRecallCache } from '@workbench/queue-integration/queueRunPersistence';import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSubscription } from '@workbench/WorkbenchContext';/** App-owned production composition of Queue, Workbench, Gallery, Workflow, Nodes, and Models adapters. */@@ -18,71 +30,162 @@ export const QueueRuntimeAdapter = () => {useMountEffect(() => {const owner = captureAccountScope();- const runtime = createProductionQueueRuntime({- destinations: {- addImagesToGalleryBoard: async (boardId, imageNames) => {- assertAccountScopeCurrent(owner);- const { galleryOrganization } = await import('@features/gallery');+ let isDisposed = false;+ let journal: QueueRunJournal | undefined;+ let recallCache: QueueRecallCache | undefined;+ let runtime: ReturnType<typeof createProductionQueueRuntime> | undefined;+ let receiptAcknowledgements: ReturnType<typeof createProductionQueueReceiptAcknowledgements> | undefined;+ const startRuntime = async (runJournal?: QueueRunJournal) => {+ const cache = await createAccountOwnedQueueRecallCache(owner).catch(() => undefined);+ if (isDisposed || !isAccountScopeCurrent(owner)) {+ runJournal?.close();+ cache?.close();+ return;+ }+ journal = runJournal;+ recallCache = cache;+ if (runJournal && cache) {+ runJournal = withQueueRecallCache(runJournal, cache, (projectId, queueItemId) =>+ queries+ .getSnapshot()+ .projects.find((project) => project.id === projectId)+ ?.queue.items.find((item) => item.id === queueItemId)+ );+ }+ if (runJournal) {+ receiptAcknowledgements = createProductionQueueReceiptAcknowledgements(+ runJournal,+ () => !isDisposed && isAccountScopeCurrent(owner)+ );+ void receiptAcknowledgements.flush();+ }+ runtime = createProductionQueueRuntime({+ destinations: {+ addImagesToGalleryBoard: async (boardId, imageNames) => {+ assertAccountScopeCurrent(owner);+ const { galleryOrganization } = await import('@features/gallery');- assertAccountScopeCurrent(owner);- await galleryOrganization.addToBoard(boardId, imageNames, owner.signal);- assertAccountScopeCurrent(owner);- },- addVideosToGalleryBoard: async (boardId, videoNames) => {- assertAccountScopeCurrent(owner);- const { galleryItemOrganization, isGalleryBoardAttachable } = await import('@features/gallery');+ assertAccountScopeCurrent(owner);+ await galleryOrganization.addToBoard(boardId, imageNames, owner.signal);+ assertAccountScopeCurrent(owner);+ },+ addVideosToGalleryBoard: async (boardId, videoNames) => {+ assertAccountScopeCurrent(owner);+ const { galleryItemOrganization, isGalleryBoardAttachable } = await import('@features/gallery');- // Virtual destinations (date buckets, `generated`/`assets`) cannot hold- // attachments: the transport no-ops for them, which would otherwise read- // back as every video failing. The image path ignores this the same way.- if (!isGalleryBoardAttachable(boardId)) {- return;- }+ // Virtual destinations (date buckets, `generated`/`assets`) cannot hold+ // attachments: the transport no-ops for them, which would otherwise read+ // back as every video failing. The image path ignores this the same way.+ if (!isGalleryBoardAttachable(boardId)) {+ return;+ }- assertAccountScopeCurrent(owner);- const result = await galleryItemOrganization.moveToBoard(- videoNames.map((name) => ({ kind: 'video' as const, name })),- boardId,- owner.signal- );- assertAccountScopeCurrent(owner);- // The video transport confirms per item and never throws on non-fatal errors;- // surface unconfirmed refs so the queue runtime can record the failure instead- // of leaving the videos silently in Uncategorized (e.g. board deleted mid-run).- if (result.failed.length > 0) {- throw new Error(- `${result.failed.length} of ${videoNames.length} video(s) could not be added to the board.`+ assertAccountScopeCurrent(owner);+ const result = await galleryItemOrganization.moveToBoard(+ videoNames.map((name) => ({ kind: 'video' as const, name })),+ boardId,+ owner.signal);- }+ assertAccountScopeCurrent(owner);+ // The video transport confirms per item and never throws on non-fatal errors;+ // surface unconfirmed refs so the queue runtime can record the failure instead+ // of leaving the videos silently in Uncategorized (e.g. board deleted mid-run).+ if (result.failed.length > 0) {+ throw new Error(+ `${result.failed.length} of ${videoNames.length} video(s) could not be added to the board.`+ );+ }+ },},- },- ensureTemplatesLoaded: ensureInvocationTemplatesLoaded,- history: {- commands: {- ...queue,- recordError: notifications.reportError,- refreshBackendData: () => void invalidateGallery(queryClient),+ async ensureProjectPersisted(projectId) {+ assertAccountScopeCurrent(owner);+ const sync = getProjectSyncSnapshot().projects[projectId];+ if (sync?.conflict?.kind === 'deleted') {+ return 'refused';+ }+ if (sync?.revision && sync.revision > 0) {+ return 'ready';+ }+ if (sync?.conflict || sync?.schemaRefusal) {+ return 'refused';+ }+ const project = getOpenProject(projectId);+ if (!project) {+ return 'retry';+ }+ const outcome = await project.flush();+ assertAccountScopeCurrent(owner);+ return outcome.kind === 'acknowledged' ? 'ready' : outcome.kind === 'unsynced' ? 'retry' : 'refused';},- getSnapshot: () => {- const snapshot = queries.getSnapshot();+ ensureTemplatesLoaded: ensureInvocationTemplatesLoaded,+ history: {+ commands: {+ ...queue,+ recordError: notifications.reportError,+ refreshBackendData: () => void invalidateGallery(queryClient),+ },+ getSnapshot: () => {+ const snapshot = queries.getSnapshot();- return {- connectionStatus: snapshot.backendConnection.status,- isHydrated: snapshot.hasHydrated,- projects: snapshot.projects,- };+ return {+ connectionStatus: snapshot.backendConnection.status,+ isHydrated: snapshot.hasHydrated,+ projects: snapshot.projects,+ };+ },+ subscribe,},- subscribe,- },- modelLoads: modelLoadActivitySink,- nodeExecution: nodeExecutionStore,- // Closes the loop on a library-bound run: its final output becomes the- // workflow's cover image and stamps `last_run_at` on the record.- workflowRuns: createWorkflowRunCaptureSink(),- });+ journal: runJournal+ ? {+ ...runJournal,+ async record(projectId, item) {+ const result = await runJournal.record(projectId, item);+ void receiptAcknowledgements?.flush();+ return result;+ },+ async settle(projectId, queueItemId) {+ const result = await runJournal.settle(projectId, queueItemId);+ void receiptAcknowledgements?.flush();+ return result;+ },+ }+ : undefined,+ locks: createQueueRunLockPort(owner.storageSuffix),+ modelLoads: modelLoadActivitySink,+ nodeExecution: nodeExecutionStore,+ // Closes the loop on a library-bound run: its final output becomes the+ // workflow's cover image and stamps `last_run_at` on the record.+ workflowRuns: createWorkflowRunCaptureSink(),+ });+ runtime.start();+ };++ void createAccountOwnedQueueRunJournal(owner)+ .then(startRuntime)+ .catch((error: unknown) => {+ if (!isDisposed && isAccountScopeCurrent(owner)) {+ notifications.reportError({+ area: 'queue-recovery',+ message: error instanceof Error ? error.message : String(error),+ namespace: 'queue',+ });+ startRuntime();+ }+ });- runtime.start();- return () => runtime.dispose();+ return () => {+ isDisposed = true;+ receiptAcknowledgements?.dispose();+ if (runtime) {+ void runtime.dispose().finally(() => {+ journal?.close();+ recallCache?.close();+ });+ } else {+ journal?.close();+ recallCache?.close();+ }+ };});return null;diff --git a/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts b/invokeai/frontend/webv2/src/features/queue/core/historyTypes.tsindex 645385cce3..a3157c14e2 100644--- a/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts@@ -26,6 +26,9 @@ export interface QueueSubmissionSnapshot {export interface QueueItem {id: string;status: QueueHistoryItemStatus;+ /** Whether this run can still exist in durable browser recovery storage. */+ localRecoveryState?: 'durable' | 'local-only' | 'uncertain';+ cancellationPending?: boolean;cancellable: boolean;snapshot: QueueSubmissionSnapshot;backendItemIds?: number[];diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.tsindex 88e2e90eee..0450321231 100644--- a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts@@ -13,6 +13,7 @@*/const SEED_MAX = 4_294_967_295;+export const MAX_QUEUE_BATCH_ITEMS = 10_000;export type QueuePromptSeedBehaviour = 'per-iteration' | 'per-image';@@ -20,7 +21,9 @@ export const isQueuePromptSeedBehaviour = (value: unknown): value is QueuePromptvalue === 'per-iteration' || value === 'per-image';export const sanitizeBatchCount = (value: unknown): number =>- typeof value === 'number' && Number.isFinite(value) ? Math.max(1, Math.round(value)) : 1;+ typeof value === 'number' && Number.isFinite(value)+ ? Math.min(MAX_QUEUE_BATCH_ITEMS, Math.max(1, Math.round(value)))+ : 1;export const generateSeedSequence = (start: number, count: number): number[] =>Array.from({ length: sanitizeBatchCount(count) }, (_, index) => (start + index) % SEED_MAX);diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.tsindex a8a6352975..8196697b20 100644--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts@@ -263,6 +263,8 @@ export interface QueueFeatureCommands {* events so runtimes never assemble HTTP calls and socket subscriptions.*/export interface QueueBackendPort extends QueueFeatureCommands {+ acknowledgeEnqueue?(projectId: string, sourceQueueItemId: string): Promise<void>;+ getEnqueueReceipt?(projectId: string, sourceQueueItemId: string): Promise<QueueEnqueueResult | null>;cancelQueueItems(itemIds: number[]): Promise<void>;cancelQueueItemsByBatchIds(batchIds: string[]): Promise<void>;enqueueGenerate(request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult>;diff --git a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.tsindex 4b78f441d8..42681df21b 100644--- a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts@@ -22,10 +22,18 @@ import {retryItemsById,resumeQueueProcessor,} from './serverApi';-import { enqueueGenerate, enqueueWorkflow, getResultImages, getResultVideoNames } from './submissionApi';+import {+ acknowledgeQueueEnqueue,+ enqueueGenerate,+ enqueueWorkflow,+ getQueueEnqueueReceipt,+ getResultImages,+ getResultVideoNames,+} from './submissionApi';/** Production adapter for the queue backend port. */export const queueBackend: QueueBackendPort = {+ acknowledgeEnqueue: acknowledgeQueueEnqueue,cancelCurrentItem: cancelCurrentQueueItem,cancelQueueItems,cancelQueueItemsByBatchIds: async (batchIds) => {@@ -40,6 +48,7 @@ export const queueBackend: QueueBackendPort = {emit: socketHub.emit,enqueueGenerate,enqueueWorkflow,+ getEnqueueReceipt: getQueueEnqueueReceipt,getItem: async (itemId) => mapQueueBackendItemDTO(await getQueueItem(itemId)),getResultImages,getResultVideoNames,diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts b/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.tsindex 8aec76ab08..66f1c79f92 100644--- a/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts@@ -7,7 +7,13 @@ const transport = vi.hoisted(() => ({vi.mock('@platform/transport/http', () => transport);-import { cancelCurrentQueueItem, cancelScopedQueueItems, clearFailedQueueItems, clearScopedQueue } from './serverApi';+import {+ cancelCurrentQueueItem,+ cancelQueueItems,+ cancelScopedQueueItems,+ clearFailedQueueItems,+ clearScopedQueue,+} from './serverApi';describe('queue command account ownership', () => {beforeEach(() => {@@ -56,4 +62,22 @@ describe('queue command account ownership', () => {expect(signal?.aborted).toBe(true);expect(transport.apiFetchJson).toHaveBeenCalledTimes(1);});++ it('bounds fallback item cancellation concurrency', async () => {+ let active = 0;+ let maximum = 0;+ transport.apiFetchJson.mockImplementation(async () => {+ active += 1;+ maximum = Math.max(maximum, active);+ await new Promise((resolve) => {+ setTimeout(resolve, 1);+ });+ active -= 1;+ });++ await cancelQueueItems(Array.from({ length: 40 }, (_, index) => index + 1));++ expect(transport.apiFetchJson).toHaveBeenCalledTimes(40);+ expect(maximum).toBeLessThanOrEqual(8);+ });});diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts b/invokeai/frontend/webv2/src/features/queue/data/serverApi.tsindex a5e21be0fe..46a29ff8fd 100644--- a/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts@@ -9,6 +9,7 @@ import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/import { apiFetchJson } from '@platform/transport/http';const QUEUE_ID = 'default';+const QUEUE_MUTATION_CONCURRENCY = 8;const buildQueueUrl = (path = ''): string => `/api/v1/queue/${QUEUE_ID}/${path}`;const buildQueryString = (params: Record<string, string | undefined>): string => {@@ -25,6 +26,20 @@ const buildQueryString = (params: Record<string, string | undefined>): string =>return queryString ? `?${queryString}` : '';};+const runConcurrent = async <T>(items: readonly T[], visit: (item: T) => Promise<unknown>): Promise<void> => {+ let nextIndex = 0;+ const worker = async (): Promise<void> => {+ while (nextIndex < items.length) {+ const item = items[nextIndex];+ nextIndex += 1;+ if (item !== undefined) {+ await visit(item);+ }+ }+ };+ await Promise.all(Array.from({ length: Math.min(QUEUE_MUTATION_CONCURRENCY, items.length) }, worker));+};+export const getQueueStatus = (scope: QueueQueryScope = {},signal?: AbortSignal@@ -92,11 +107,11 @@ export const deleteQueueItem = (itemId: number, signal?: AbortSignal): Promise<uapiFetchJson(buildQueueUrl(`i/${itemId}`), { method: 'DELETE', signal });export const deleteQueueItems = async (itemIds: number[], signal?: AbortSignal): Promise<void> => {- await Promise.all(itemIds.map((itemId) => deleteQueueItem(itemId, signal)));+ await runConcurrent(itemIds, (itemId) => deleteQueueItem(itemId, signal));};export const cancelQueueItems = async (itemIds: number[], signal?: AbortSignal): Promise<void> => {- await Promise.all(itemIds.map((itemId) => cancelQueueItem(itemId, signal)));+ await runConcurrent(itemIds, (itemId) => cancelQueueItem(itemId, signal));};export const clearFailedQueueItems = async (scope: QueueQueryScope = {}): Promise<void> => {diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.tsindex 3fe0ec864d..301713dadd 100644--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts@@ -4,6 +4,7 @@ import { accountLifecycle } from '@platform/state/accountLifecycle';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({+ apiFetch: vi.fn(),apiFetchJson: vi.fn(),}));@@ -12,14 +13,69 @@ vi.mock('@platform/transport/http', () => ({ApiError: class ApiError extends Error {status: number;- constructor(status: number) {- super('API error');+ constructor(message: string, status: number) {+ super(message);this.status = status;}},+ apiFetch: mocks.apiFetch,apiFetchJson: mocks.apiFetchJson,}));+describe('acknowledgeQueueEnqueue', () => {+ it('releases the exact enqueue receipt', async () => {+ const { acknowledgeQueueEnqueue } = await import('./submissionApi');++ await acknowledgeQueueEnqueue('project-1', 'local-1');++ expect(mocks.apiFetch).toHaveBeenCalledWith('/api/v1/queue/default/enqueue_batch/acknowledge', {+ body: JSON.stringify({ idempotency_key: 'webv2:project-1:local-1' }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });+ });+});++describe('getQueueEnqueueReceipt', () => {+ it.each([+ { batch_id: 'batch-1', enqueued: 1, item_ids: [], requested: 1 },+ { batch_id: 'batch-1', enqueued: 2, item_ids: [11, 11], requested: 2 },+ { batch_id: '', enqueued: 1, item_ids: [11], requested: 1 },+ { batch_id: 'batch-1', enqueued: 1, item_ids: [-1], requested: 1 },+ { batch_id: 'batch-1', enqueued: 2, item_ids: [11, 12], requested: 1 },+ { batch_id: 'batch-1', enqueued: 0, item_ids: [], requested: 1 },+ ])('rejects malformed accepted receipts: %j', async (receipt) => {+ const { getQueueEnqueueReceipt } = await import('./submissionApi');+ mocks.apiFetchJson.mockResolvedValueOnce(receipt);+ await expect(getQueueEnqueueReceipt('project-1', 'local-1')).rejects.toThrow('Invalid queue enqueue response');+ });++ it('loads only the caller-owned receipt and maps its accepted ids', async () => {+ const { getQueueEnqueueReceipt } = await import('./submissionApi');+ mocks.apiFetchJson.mockResolvedValueOnce({ batch_id: 'batch-1', enqueued: 2, item_ids: [11, 12], requested: 3 });++ await expect(getQueueEnqueueReceipt('project-1', 'local-1')).resolves.toEqual({+ batchId: 'batch-1',+ enqueued: 2,+ itemIds: [11, 12],+ requested: 3,+ });+ expect(mocks.apiFetchJson).toHaveBeenLastCalledWith(+ '/api/v1/queue/default/enqueue_batch/receipt?idempotency_key=webv2%3Aproject-1%3Alocal-1'+ );+ });++ it('treats only 404 as an absent receipt', async () => {+ const { getQueueEnqueueReceipt } = await import('./submissionApi');+ const { ApiError } = await import('@platform/transport/http');+ mocks.apiFetchJson.mockRejectedValueOnce(new ApiError('not found', 404));+ await expect(getQueueEnqueueReceipt('project-1', 'local-1')).resolves.toBeNull();+ const offline = new Error('offline');+ mocks.apiFetchJson.mockRejectedValueOnce(offline);+ await expect(getQueueEnqueueReceipt('project-1', 'local-1')).rejects.toBe(offline);+ });+});+const createRequest = (overrides: Partial<QueueEnqueueGenerateRequest> = {}): QueueEnqueueGenerateRequest => ({batchCount: 3,destination: 'gallery',@@ -52,7 +108,9 @@ const getSubmittedBody = () => {return JSON.parse(init?.body as string) as {batch: {+ batch_id?: string;data: { field_name: string; items: unknown[]; node_path: string }[][];+ idempotency_key: string;origin: string;runs: number;};@@ -110,6 +168,8 @@ describe('enqueueGenerate', () => {await enqueueGenerate(createRequest());expect(getSubmittedBody().batch.origin).toBe('webv2:p:project-1:q:local-1');+ expect(getSubmittedBody().batch.idempotency_key).toBe('webv2:project-1:local-1');+ expect(getSubmittedBody().batch.batch_id).toBeUndefined();});describe('expanded prompts', () => {@@ -184,12 +244,37 @@ describe('enqueueWorkflow', () => {});});+ it('rejects ambiguous accepted ids but accepts an explicit zero-capacity result', async () => {+ const { enqueueWorkflow } = await import('./submissionApi');+ mocks.apiFetchJson.mockResolvedValueOnce({+ batch: { batch_id: 'batch-1' },+ enqueued: 1,+ item_ids: [],+ requested: 2,+ });+ await expect(enqueueWorkflow(createWorkflowRequest())).rejects.toThrow('Invalid queue enqueue response');+ mocks.apiFetchJson.mockResolvedValueOnce({+ batch: { batch_id: 'batch-1' },+ enqueued: 0,+ item_ids: [],+ requested: 2,+ });+ await expect(enqueueWorkflow(createWorkflowRequest())).resolves.toEqual({+ batchId: 'batch-1',+ enqueued: 0,+ itemIds: [],+ requested: 2,+ });+ });+it('submits workflow runs for the requested batch count', async () => {const { enqueueWorkflow } = await import('./submissionApi');await enqueueWorkflow(createWorkflowRequest());expect(getSubmittedBody().batch.runs).toBe(2);+ expect(getSubmittedBody().batch.idempotency_key).toBe('webv2:project-1:local-1');+ expect(getSubmittedBody().batch.batch_id).toBeUndefined();});it('does not cap workflow runs', async () => {@@ -207,6 +292,50 @@ describe('getResultImages', () => {mocks.apiFetchJson.mockReset();});+ it.each(['image', 'video'] as const)('bounds %s metadata requests for collection-sized results', async (kind) => {+ let active = 0;+ let peak = 0;+ mocks.apiFetchJson.mockImplementation(async (url: string) => {+ if (url === '/api/v1/queue/default/i/1') {+ return {+ item_id: 1,+ status: 'completed',+ session: {+ results: Object.fromEntries(+ Array.from({ length: 20 }, (_, index) => [+ String(index),+ {+ [kind]: { [`${kind}_name`]: `asset-${index}` },+ },+ ])+ ),+ },+ };+ }+ active += 1;+ peak = Math.max(peak, active);+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 1);+ });+ active -= 1;+ return {+ image_name: url.split('/').at(-1),+ image_url: url,+ thumbnail_url: url,+ height: 512,+ width: 512,+ is_intermediate: false,+ };+ });+ const { getResultImages, getResultVideoNames } = await import('./submissionApi');+ const result =+ kind === 'image'+ ? await getResultImages(1, 'source-1', '2026-09-04T00:00:00Z')+ : await getResultVideoNames(1, { excludeIntermediate: true });+ expect(result).toHaveLength(20);+ expect(peak).toBeLessThanOrEqual(8);+ });+it('can restrict image extraction to explicit result node ids', async () => {mocks.apiFetchJson.mockImplementation((url: string) => {if (url === '/api/v1/queue/default/i/1') {diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.tsindex 847fc96e98..585fd48ff1 100644--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts@@ -8,26 +8,67 @@ import type {} from '@features/queue/core/types';import { buildGeneratePromptBatchPlan, sanitizeBatchCount } from '@features/queue/core/promptBatch';+import { mapWithConcurrency } from '@platform/core/concurrency';import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';-import { absolutizeApiUrl, ApiError, apiFetchJson } from '@platform/transport/http';+import { absolutizeApiUrl, ApiError, apiFetch, apiFetchJson } from '@platform/transport/http';import type { QueueImageDTO, QueueServerItemDTO } from './serverTypes';import { buildQueueItemOrigin } from './events';import { getQueueItem } from './serverApi';-const mapEnqueueResult = (result: {- batch?: { batch_id?: string };- enqueued?: number;- item_ids?: number[];- requested?: number;-}): QueueEnqueueResult => ({- batchId: result.batch?.batch_id,- enqueued: result.enqueued ?? 0,- itemIds: result.item_ids ?? [],- requested: result.requested ?? 0,-});+const getQueueIdempotencyKey = (projectId: string, sourceQueueItemId: string): string =>+ `webv2:${projectId}:${sourceQueueItemId}`;++export const acknowledgeQueueEnqueue = async (projectId: string, sourceQueueItemId: string): Promise<void> => {+ await apiFetch('/api/v1/queue/default/enqueue_batch/acknowledge', {+ body: JSON.stringify({ idempotency_key: getQueueIdempotencyKey(projectId, sourceQueueItemId) }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });+};++export const getQueueEnqueueReceipt = async (+ projectId: string,+ sourceQueueItemId: string+): Promise<QueueEnqueueResult | null> => {+ const query = new URLSearchParams({ idempotency_key: getQueueIdempotencyKey(projectId, sourceQueueItemId) });+ try {+ const result = await apiFetchJson<unknown>(`/api/v1/queue/default/enqueue_batch/receipt?${query}`);+ return mapEnqueueResult(result, true);+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) {+ return null;+ }+ throw error;+ }+};++const mapEnqueueResult = (value: unknown, isReceipt = false): QueueEnqueueResult => {+ const result = value && typeof value === 'object' ? (value as Record<string, unknown>) : {};+ const batch = result.batch && typeof result.batch === 'object' ? (result.batch as Record<string, unknown>) : {};+ const batchId = isReceipt ? result.batch_id : batch.batch_id;+ const { enqueued, item_ids: itemIds, requested } = result;+ if (+ typeof batchId !== 'string' ||+ batchId.length === 0 ||+ typeof requested !== 'number' ||+ !Number.isSafeInteger(requested) ||+ requested < 1 ||+ typeof enqueued !== 'number' ||+ !Number.isSafeInteger(enqueued) ||+ enqueued < (isReceipt ? 1 : 0) ||+ enqueued > requested ||+ !Array.isArray(itemIds) ||+ itemIds.length !== enqueued ||+ new Set(itemIds).size !== itemIds.length ||+ itemIds.some((id) => !Number.isSafeInteger(id) || id <= 0)+ ) {+ throw new Error('Invalid queue enqueue response');+ }+ return { batchId, enqueued, itemIds, requested };+};export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult> => {const plan = buildGeneratePromptBatchPlan({@@ -41,17 +82,14 @@ export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): ProseedNodeId: request.seedNodeId,shouldRandomizeSeed: request.shouldRandomizeSeed,});- const result = await apiFetchJson<{- batch?: { batch_id?: string };- enqueued?: number;- item_ids?: number[];- requested?: number;- }>('/api/v1/queue/default/enqueue_batch', {+ const result = await apiFetchJson<unknown>('/api/v1/queue/default/enqueue_batch', {body: JSON.stringify({batch: {data: plan.data,destination: request.destination,graph: request.graph,+ idempotency_key: getQueueIdempotencyKey(request.projectId, request.sourceQueueItemId),+ project_id: request.projectId,origin: buildQueueItemOrigin(request.sourceQueueItemId, request.projectId),runs: plan.runs,},@@ -64,16 +102,13 @@ export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Pro};export const enqueueWorkflow = async (request: QueueEnqueueWorkflowRequest): Promise<QueueEnqueueResult> => {- const result = await apiFetchJson<{- batch?: { batch_id?: string };- enqueued?: number;- item_ids?: number[];- requested?: number;- }>('/api/v1/queue/default/enqueue_batch', {+ const result = await apiFetchJson<unknown>('/api/v1/queue/default/enqueue_batch', {body: JSON.stringify({batch: {destination: request.destination,graph: request.graph,+ idempotency_key: getQueueIdempotencyKey(request.projectId, request.sourceQueueItemId),+ project_id: request.projectId,origin: buildQueueItemOrigin(request.sourceQueueItemId, request.projectId),runs: sanitizeBatchCount(request.batchCount),},@@ -170,10 +205,11 @@ export const getResultImages = async (const item = await getQueueItem(itemId, owner.signal);assertAccountScopeCurrent(owner);- const images = await Promise.all(- getResultImageNames(item, options).map((imageName) =>- getResultImage(imageName, queuedAt, sourceQueueItemId, owner.signal)- )+ const images = await mapWithConcurrency(+ getResultImageNames(item, options),+ 8,+ (imageName) => getResultImage(imageName, queuedAt, sourceQueueItemId, owner.signal),+ { signal: owner.signal });assertAccountScopeCurrent(owner);@@ -244,7 +280,9 @@ export const getResultVideoNames = async (itemId: number, options?: QueueResultVreturn videoNames;}- const intermediateFlags = await Promise.all(videoNames.map((name) => isIntermediateVideo(name, owner.signal)));+ const intermediateFlags = await mapWithConcurrency(videoNames, 8, (name) => isIntermediateVideo(name, owner.signal), {+ signal: owner.signal,+ });assertAccountScopeCurrent(owner);return videoNames.filter((_, index) => !intermediateFlags[index]);diff --git a/invokeai/frontend/webv2/src/features/queue/index.ts b/invokeai/frontend/webv2/src/features/queue/index.tsindex f421c8ffc0..77dd39b0d6 100644--- a/invokeai/frontend/webv2/src/features/queue/index.ts+++ b/invokeai/frontend/webv2/src/features/queue/index.ts@@ -43,6 +43,7 @@ export {isBackendSubmittableSourceId,shouldSubmitPendingQueueItem,} from './core/submissionRules';+export { MAX_QUEUE_BATCH_ITEMS } from './core/promptBatch';export {buildProjectQueueItemOriginPrefix,buildQueueItemOrigin,@@ -58,5 +59,11 @@ export {type InvocationStartedEvent,type QueueItemStatusChangedEvent,} from './data/events';-export { createProductionQueueRuntime, getQueueReadModelOptions, queueCommands } from './publicApi';+export {+ createProductionQueueRuntime,+ createProductionQueueReceiptAcknowledgements,+ getQueueReadModelOptions,+ queueCommands,+} from './publicApi';+export type { QueueRunLockPort } from './runtime';export { hasPendingWorkflowQueueItem } from './ui/queueViewModel';diff --git a/invokeai/frontend/webv2/src/features/queue/publicApi.ts b/invokeai/frontend/webv2/src/features/queue/publicApi.tsindex b3faac5a5a..fe1cee9592 100644--- a/invokeai/frontend/webv2/src/features/queue/publicApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/publicApi.ts@@ -1,12 +1,26 @@import type { QueueFeatureCommands, QueueQueryScope, QueueReadModel, QueueWorkflowRunSink } from './core/types';import type { QueueItemProgressPort, QueueRealtimeRuntime } from './data/realtimeRuntime';-import type { QueueHistoryPort, QueueResultDestinationPort, QueueRuntime } from './runtime';+import type {+ QueueHistoryPort,+ QueueResultDestinationPort,+ QueueRunJournalPort,+ QueueRunLockPort,+ QueueRuntime,+} from './runtime';import type { QueueModelLoadPort, QueueNodeExecutionPort } from './runtime/coordinator';import { queueBackend } from './data/httpRealtimeQueueBackend';import { queueReadModelOptions } from './data/queries';import { createQueueRealtimeRuntime } from './data/realtimeRuntime';import { createQueueRuntime } from './runtime';+import { createQueueReceiptAcknowledgements, type QueueReceiptStorePort } from './runtime/receiptAcknowledgements';++export const createProductionQueueReceiptAcknowledgements = (store: QueueReceiptStorePort, isActive: () => boolean) =>+ createQueueReceiptAcknowledgements({+ acknowledge: (projectId, queueItemId) => queueBackend.acknowledgeEnqueue!(projectId, queueItemId),+ isActive,+ store,+ });export const queueCommands: QueueFeatureCommands = {cancelCurrentItem: queueBackend.cancelCurrentItem,@@ -42,15 +56,21 @@ export const createProductionQueueRealtimeRuntime = ({export const createProductionQueueRuntime = ({destinations,+ ensureProjectPersisted,ensureTemplatesLoaded,history,+ journal,+ locks,modelLoads,nodeExecution,workflowRuns,}: {destinations: QueueResultDestinationPort;+ ensureProjectPersisted?(projectId: string): Promise<'ready' | 'refused' | 'retry'>;ensureTemplatesLoaded: () => void;history: QueueHistoryPort;+ journal?: QueueRunJournalPort;+ locks?: QueueRunLockPort;modelLoads: QueueModelLoadPort;nodeExecution: QueueNodeExecutionPort;workflowRuns?: QueueWorkflowRunSink;@@ -58,8 +78,11 @@ export const createProductionQueueRuntime = ({createQueueRuntime({backend: queueBackend,destinations,+ ensureProjectPersisted,ensureTemplatesLoaded,history,+ journal,+ locks,modelLoads,nodeExecution,workflowRuns,diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.tsindex 473151909b..9ff4b1de2e 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts@@ -5,11 +5,20 @@ import type {QueueResultImage,QueueWorkflowRunSink,} from '@features/queue/core/types';+import type { BackendConnectionStatus } from '@platform/transport/types';import { buildQueueItemOrigin } from '@features/queue/data/events';+import { ApiError } from '@platform/transport/http';import { describe, expect, it, vi } from 'vitest';-import { createQueueItemBackendSubmission, createQueueRuntime, type QueueHistoryCommands } from './runtime';+import {+ createQueueItemBackendSubmission,+ createQueueRuntime,+ type QueueHistoryCommands,+ type QueueRunJournalPort,+ type QueueRunLock,+ type QueueRunLockPort,+} from './runtime';const createPendingQueueItem = (): QueueItem => ({cancellable: true,@@ -39,21 +48,1604 @@ const createPendingQueueItem = (): QueueItem => ({status: 'pending',});+const createTestBackend = (overrides: Partial<QueueBackendPort> = {}): QueueBackendPort => ({+ cancelCurrentItem: vi.fn(),+ cancelItem: vi.fn(),+ cancelQueueItems: vi.fn(),+ cancelQueueItemsByBatchIds: vi.fn(),+ cancelScopedItems: vi.fn(),+ clearFailedItems: vi.fn(),+ clearItems: vi.fn(),+ emit: vi.fn(),+ enqueueGenerate: vi.fn(),+ enqueueWorkflow: vi.fn(),+ getItem: vi.fn(),+ getResultImages: vi.fn().mockResolvedValue([]),+ getResultVideoNames: vi.fn().mockResolvedValue([]),+ listItems: vi.fn().mockResolvedValue([]),+ on: vi.fn(() => vi.fn()),+ onConnectionChange: vi.fn((listener) => {+ listener('connected');+ return vi.fn();+ }),+ pauseProcessor: vi.fn(),+ readCurrent: vi.fn(),+ readItemIds: vi.fn(),+ readItemsById: vi.fn(),+ readNext: vi.fn(),+ readStatus: vi.fn(),+ resumeProcessor: vi.fn(),+ retryItems: vi.fn(),+ ...overrides,+});++const createTestCommands = (overrides: Partial<QueueHistoryCommands> = {}): QueueHistoryCommands => ({+ markBackendCancelled: vi.fn(),+ markBackendSubmitted: vi.fn(),+ setCancellationPending: vi.fn(),+ setLocalRecoveryState: vi.fn(),+ recordError: vi.fn(),+ refreshBackendData: vi.fn(),+ restoreFromJournal: vi.fn(),+ routePartialResults: vi.fn(),+ routeResults: vi.fn(),+ setConnectionStatus: vi.fn(),+ setStatus: vi.fn(),+ ...overrides,+});++const createTestJournal = (overrides: Partial<QueueRunJournalPort> = {}): QueueRunJournalPort => ({+ listForProject: vi.fn().mockResolvedValue({ entries: [], kind: 'available' }),+ record: vi.fn().mockResolvedValue({ kind: 'stored' }),+ settle: vi.fn().mockResolvedValue({ kind: 'removed' }),+ ...overrides,+});++const runtimeServices = {+ destinations: { addImagesToGalleryBoard: vi.fn(), addVideosToGalleryBoard: vi.fn() },+ ensureTemplatesLoaded: vi.fn(),+ modelLoads: { completed: vi.fn(), reset: vi.fn(), started: vi.fn() },+ nodeExecution: {+ clearAll: vi.fn(),+ completed: vi.fn(),+ failed: vi.fn(),+ progress: vi.fn(),+ settleRunning: vi.fn(),+ started: vi.fn(),+ },+};+describe('queue runtime', () => {it('turns a malformed legacy submission into a failed request instead of throwing', () => {const queueItem = createPendingQueueItem();- delete (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;+ delete (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;++ expect(createQueueItemBackendSubmission({ id: 'project-1' }, queueItem)).toEqual({+ error: 'Queue item is missing a compiled backend submission.',+ kind: 'invalid',+ });+ });++ it('adopts a persisted backend run before submission so reload cannot duplicate it', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const enqueueGenerate = vi.fn();+ const listItems = vi.fn().mockResolvedValue([+ {+ batchId: 'backend-batch',+ id: 77,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'in_progress',+ },+ ]);+ const backend: QueueBackendPort = {+ cancelCurrentItem: vi.fn(),+ cancelItem: vi.fn(),+ cancelQueueItems: vi.fn(),+ cancelQueueItemsByBatchIds: vi.fn(),+ cancelScopedItems: vi.fn(),+ clearFailedItems: vi.fn(),+ clearItems: vi.fn(),+ emit: vi.fn(),+ enqueueGenerate,+ enqueueWorkflow: vi.fn(),+ getItem: vi.fn(),+ getResultImages: vi.fn(),+ getResultVideoNames: vi.fn().mockResolvedValue([]),+ listItems,+ on: vi.fn(() => vi.fn()),+ onConnectionChange: vi.fn((listener) => {+ listener('connected');+ return vi.fn();+ }),+ pauseProcessor: vi.fn(),+ readCurrent: vi.fn(),+ readItemIds: vi.fn(),+ readItemsById: vi.fn(),+ readNext: vi.fn(),+ readStatus: vi.fn(),+ resumeProcessor: vi.fn(),+ retryItems: vi.fn(),+ };+ const commands: QueueHistoryCommands = {+ markBackendCancelled: vi.fn(),+ markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {+ queueItem.backendBatchId = backendBatchId;+ queueItem.backendItemIds = backendItemIds;+ queueItem.status = 'running';+ },+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ },+ setLocalRecoveryState: vi.fn(),+ recordError: vi.fn(),+ refreshBackendData: vi.fn(),+ restoreFromJournal: vi.fn(),+ routePartialResults: vi.fn(),+ routeResults: vi.fn(),+ setConnectionStatus: vi.fn(),+ setStatus: vi.fn(),+ };+ const runtime = createQueueRuntime({+ backend,+ destinations: { addImagesToGalleryBoard: vi.fn(), addVideosToGalleryBoard: vi.fn() },+ ensureTemplatesLoaded: vi.fn(),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ modelLoads: {+ completed: vi.fn(),+ reset: vi.fn(),+ started: vi.fn(),+ },+ nodeExecution: {+ clearAll: vi.fn(),+ completed: vi.fn(),+ failed: vi.fn(),+ progress: vi.fn(),+ settleRunning: vi.fn(),+ started: vi.fn(),+ },+ });++ runtime.start();++ await vi.waitFor(() => {+ expect(queueItem).toMatchObject({+ backendBatchId: 'backend-batch',+ backendItemIds: [77],+ status: 'running',+ });+ });+ expect(listItems).toHaveBeenCalledTimes(1);+ expect(enqueueGenerate).not.toHaveBeenCalled();++ runtime.dispose();+ });++ it('durably records a new run before enqueueing it', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ let finishRecord: (result: { kind: 'stored' }) => void = () => undefined;+ const record = vi.fn(+ () =>+ new Promise<{ kind: 'stored' }>((resolve) => {+ finishRecord = resolve;+ })+ );+ const journal = createTestJournal({ record });+ const enqueueGenerate = vi.fn().mockResolvedValue({ enqueued: 1, itemIds: [77], requested: 1 });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate }),+ history: {+ commands: createTestCommands(),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal,+ });++ runtime.start();++ await vi.waitFor(() => expect(record).toHaveBeenCalledWith(project.id, queueItem));+ expect(enqueueGenerate).not.toHaveBeenCalled();++ finishRecord({ kind: 'stored' });+ await vi.waitFor(() => expect(enqueueGenerate).toHaveBeenCalledTimes(1));++ runtime.dispose();+ });++ it('checks that a project is durable after journaling and before enqueueing', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const order: string[] = [];+ const journal = createTestJournal({+ record: vi.fn(() => {+ order.push('journal');+ return Promise.resolve({ kind: 'stored' as const });+ }),+ });+ const ensureProjectPersisted = vi.fn(() => {+ order.push('project');+ return Promise.resolve('ready' as const);+ });+ const enqueueGenerate = vi.fn(() => {+ order.push('enqueue');+ return Promise.resolve({ enqueued: 1, itemIds: [77], requested: 1 });+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate }),+ ensureProjectPersisted,+ history: {+ commands: createTestCommands(),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal,+ });++ runtime.start();++ await vi.waitFor(() => expect(enqueueGenerate).toHaveBeenCalledTimes(1));+ expect(ensureProjectPersisted).toHaveBeenCalledWith(project.id);+ expect(order.slice(0, 3)).toEqual(['journal', 'project', 'enqueue']);+ await runtime.dispose();+ });++ it.each([+ ['retry', false],+ ['refused', true],+ ] as const)('does not enqueue when project persistence returns %s', async (outcome, shouldFail) => {+ vi.useFakeTimers();+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const enqueueGenerate = vi.fn();+ const commands = createTestCommands();+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate }),+ ensureProjectPersisted: vi.fn().mockResolvedValue(outcome),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal(),+ });++ runtime.start();+ await vi.advanceTimersByTimeAsync(1);++ expect(enqueueGenerate).not.toHaveBeenCalled();+ if (shouldFail) {+ expect(commands.setStatus).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: project.id, queueItemId: queueItem.id, status: 'failed' })+ );+ } else {+ expect(commands.setStatus).not.toHaveBeenCalled();+ }+ await runtime.dispose();+ vi.useRealTimers();+ });++ it('leaves durable enqueue receipt acknowledgement to the durable acknowledgement worker', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ let finishAcceptanceRecord: (result: { kind: 'stored' }) => void = () => undefined;+ const acceptanceRecord = new Promise<{ kind: 'stored' }>((resolve) => {+ finishAcceptanceRecord = resolve;+ });+ const record = vi+ .fn<QueueRunJournalPort['record']>()+ .mockResolvedValueOnce({ kind: 'stored' })+ .mockReturnValueOnce(acceptanceRecord);+ const acknowledgeEnqueue = vi.fn().mockResolvedValue(undefined);+ const commands = createTestCommands({+ markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {+ queueItem.backendBatchId = backendBatchId;+ queueItem.backendItemIds = backendItemIds;+ queueItem.status = 'running';+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ acknowledgeEnqueue,+ enqueueGenerate: vi.fn().mockResolvedValue({ batchId: 'batch-1', enqueued: 1, itemIds: [77], requested: 1 }),+ }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal({ record }),+ });++ runtime.start();++ await vi.waitFor(() => expect(record).toHaveBeenCalledTimes(2));+ expect(acknowledgeEnqueue).not.toHaveBeenCalled();+ finishAcceptanceRecord({ kind: 'stored' });+ await Promise.resolve();+ expect(acknowledgeEnqueue).not.toHaveBeenCalled();++ await runtime.dispose();+ });++ it('acknowledges a terminal receipt in memory when the run was proven never durable', async () => {+ const queueItem: QueueItem = { ...createPendingQueueItem(), localRecoveryState: 'local-only' };+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ const acknowledgeEnqueue = vi.fn().mockResolvedValue(undefined);+ const commands = createTestCommands({+ markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {+ queueItem.backendBatchId = backendBatchId;+ queueItem.backendItemIds = backendItemIds;+ queueItem.status = 'running';+ },+ routeResults: () => {+ queueItem.status = 'completed';+ listeners.forEach((listener) => listener());+ },+ setLocalRecoveryState: ({ state }) => {+ queueItem.localRecoveryState = state;+ listeners.forEach((listener) => listener());+ },+ setStatus: ({ status }) => {+ queueItem.status = status;+ listeners.forEach((listener) => listener());+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ acknowledgeEnqueue,+ getEnqueueReceipt: vi.fn().mockResolvedValue({+ batchId: 'batch-1',+ enqueued: 1,+ itemIds: [77],+ requested: 1,+ }),+ getItem: vi.fn().mockRejectedValue(new ApiError('not found', 404)),+ }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({ record: vi.fn().mockResolvedValue({ kind: 'quota' }) }),+ });++ runtime.start();++ await vi.waitFor(() => expect(acknowledgeEnqueue).toHaveBeenCalledWith(project.id, queueItem.id));+ await runtime.dispose();+ });++ it.each(['durable', 'uncertain'] as const)(+ 'never fallback-acknowledges a receipt when recovery state is %s',+ async (localRecoveryState) => {+ const queueItem: QueueItem = {+ ...createPendingQueueItem(),+ backendItemIds: [77],+ localRecoveryState,+ status: 'running',+ };+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ const acknowledgeEnqueue = vi.fn().mockResolvedValue(undefined);+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ acknowledgeEnqueue,+ getItem: vi.fn().mockResolvedValue({+ id: 77,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'completed',+ }),+ }),+ history: {+ commands: createTestCommands({+ routeResults: () => {+ queueItem.status = 'completed';+ listeners.forEach((listener) => listener());+ },+ setLocalRecoveryState: ({ state }) => {+ queueItem.localRecoveryState = state;+ },+ }),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({ record: vi.fn().mockResolvedValue({ kind: 'unavailable' }) }),+ });++ runtime.start();++ await vi.waitFor(() => expect(queueItem.status).toBe('completed'));+ expect(acknowledgeEnqueue).not.toHaveBeenCalled();+ await runtime.dispose();+ }+ );++ it('discovers a committed row after a runtime replacement before allowing fallback acknowledgement', async () => {+ const queueItem: QueueItem = {+ ...createPendingQueueItem(),+ backendItemIds: [77],+ localRecoveryState: 'local-only',+ status: 'running',+ };+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ let finishRecord: (result: { kind: 'stored' }) => void = () => undefined;+ const record = vi.fn(+ () =>+ new Promise<{ kind: 'stored' }>((resolve) => {+ finishRecord = resolve;+ })+ );+ const firstRuntime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend(),+ history: {+ commands: createTestCommands({+ setLocalRecoveryState: ({ state }) => {+ queueItem.localRecoveryState = state;+ },+ }),+ getSnapshot: () => ({ connectionStatus: 'disconnected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal({ record }),+ });++ firstRuntime.start();+ await vi.waitFor(() => expect(queueItem.localRecoveryState).toBe('uncertain'));+ const disposeFirst = firstRuntime.dispose();+ finishRecord({ kind: 'stored' });+ await disposeFirst;+ expect(queueItem.localRecoveryState).toBe('uncertain');++ const listeners = new Set<() => void>();+ const acknowledgeEnqueue = vi.fn().mockResolvedValue(undefined);+ const secondRuntime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ acknowledgeEnqueue,+ getItem: vi.fn().mockResolvedValue({+ id: 77,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'completed',+ }),+ }),+ history: {+ commands: createTestCommands({+ restoreFromJournal: () => {+ queueItem.localRecoveryState = 'durable';+ },+ routeResults: () => {+ queueItem.status = 'completed';+ listeners.forEach((listener) => listener());+ },+ setLocalRecoveryState: ({ state }) => {+ queueItem.localRecoveryState = state;+ },+ }),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: structuredClone(queueItem), projectId: project.id, queueItemId: queueItem.id }],+ kind: 'available',+ }),+ record: vi.fn().mockResolvedValue({ kind: 'unavailable' }),+ }),+ });++ secondRuntime.start();+ await vi.waitFor(() => expect(queueItem.status).toBe('completed'));+ expect(queueItem.localRecoveryState).toBe('durable');+ expect(acknowledgeEnqueue).not.toHaveBeenCalled();+ await secondRuntime.dispose();+ });++ it('does not retry a fallback acknowledgement after account disposal', async () => {+ const queueItem: QueueItem = {+ ...createPendingQueueItem(),+ backendItemIds: [77],+ localRecoveryState: 'local-only',+ status: 'running',+ };+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ let rejectAcknowledgement: (error: Error) => void = () => undefined;+ const acknowledgeEnqueue = vi.fn(+ () =>+ new Promise<void>((_resolve, reject) => {+ rejectAcknowledgement = reject;+ })+ );+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ acknowledgeEnqueue,+ getItem: vi.fn().mockResolvedValue({+ id: 77,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'completed',+ }),+ }),+ history: {+ commands: createTestCommands({+ routeResults: () => {+ queueItem.status = 'completed';+ listeners.forEach((listener) => listener());+ },+ setLocalRecoveryState: ({ state }) => {+ queueItem.localRecoveryState = state;+ },+ }),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({ record: vi.fn().mockResolvedValue({ kind: 'quota' }) }),+ });++ runtime.start();+ await vi.waitFor(() => expect(acknowledgeEnqueue).toHaveBeenCalledOnce());+ await runtime.dispose();+ rejectAcknowledgement(new Error('offline'));+ await Promise.resolve();+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 150);+ });++ expect(acknowledgeEnqueue).toHaveBeenCalledOnce();+ });++ it('continues the backend run and reports when local recovery cannot be written', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const journal = createTestJournal({ record: vi.fn().mockResolvedValue({ kind: 'quota' }) });+ const enqueueGenerate = vi.fn().mockResolvedValue({ enqueued: 1, itemIds: [77], requested: 1 });+ const commands = createTestCommands();+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal,+ });++ runtime.start();++ await vi.waitFor(() => expect(enqueueGenerate).toHaveBeenCalledTimes(1));+ expect(commands.recordError).toHaveBeenCalledWith(+ expect.objectContaining({ area: 'queue-recovery', namespace: 'queue', projectId: project.id })+ );++ runtime.dispose();+ });++ it('records but does not enqueue an item cancelled while run ownership is being acquired', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ let finishAcquire: (result: { kind: 'acquired'; release(): Promise<void> }) => void = () => undefined;+ const release = vi.fn().mockResolvedValue(undefined);+ const locks: QueueRunLockPort = {+ acquire: vi.fn(+ () =>+ new Promise<QueueRunLock>((resolve) => {+ finishAcquire = resolve;+ })+ ),+ };+ const recordedItems: QueueItem[] = [];+ const journal = createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: queueItem, projectId: 'project-1', queueItemId: queueItem.id }],+ kind: 'available',+ }),+ record: vi.fn((_projectId, item) => {+ recordedItems.push(structuredClone(item));+ return Promise.resolve({ kind: 'stored' as const });+ }),+ });+ const backend = createTestBackend();+ const commands = createTestCommands({+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ listeners.forEach((listener) => listener());+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend,+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ locks,+ });++ runtime.start();+ await vi.waitFor(() => expect(locks.acquire).toHaveBeenCalled());+ queueItem.status = 'cancelled';+ queueItem.cancellationPending = true;+ listeners.forEach((listener) => listener());+ finishAcquire({ kind: 'acquired', release });++ await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));+ expect(recordedItems).toContainEqual(expect.objectContaining({ cancellationPending: true, status: 'cancelled' }));+ expect(journal.settle).toHaveBeenCalledWith(project.id, queueItem.id);+ expect(backend.enqueueGenerate).not.toHaveBeenCalled();++ runtime.dispose();+ });++ it('reconciles exactly once after a project closes and reopens while ownership is pending', async () => {+ const queueItem = { ...createPendingQueueItem(), backendItemIds: [88], status: 'running' as const };+ const projects: Array<{ id: string; queue: { items: QueueItem[] } }> = [+ { id: 'project-1', queue: { items: [queueItem] } },+ ];+ const listeners = new Set<() => void>();+ let finishAcquire: (result: QueueRunLock) => void = () => undefined;+ const release = vi.fn().mockResolvedValue(undefined);+ let acquisitionCount = 0;+ const locks: QueueRunLockPort = {+ acquire: vi.fn(() => {+ acquisitionCount += 1;+ if (acquisitionCount > 1) {+ return Promise.resolve<QueueRunLock>({ kind: 'acquired', release });+ }+ return new Promise<QueueRunLock>((resolve) => {+ finishAcquire = resolve;+ });+ }),+ };+ const journal = createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: queueItem, projectId: 'project-1', queueItemId: queueItem.id }],+ kind: 'available',+ }),+ });+ const getItem = vi.fn().mockResolvedValue({+ id: 88,+ origin: buildQueueItemOrigin(queueItem.id, 'project-1'),+ status: 'in_progress',+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ getItem }),+ history: {+ commands: createTestCommands({+ restoreFromJournal: ({ items, projectId }) => {+ const project = projects.find((candidate) => candidate.id === projectId);+ if (project) {+ project.queue.items = items as QueueItem[];+ }+ },+ }),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ locks,+ });++ runtime.start();+ await vi.waitFor(() => expect(locks.acquire).toHaveBeenCalledTimes(1));+ projects.splice(0, 1);+ listeners.forEach((listener) => listener());+ projects.push({ id: 'project-1', queue: { items: [] } });+ listeners.forEach((listener) => listener());+ finishAcquire({ kind: 'acquired', release });++ await vi.waitFor(() => expect(getItem).toHaveBeenCalledTimes(1));+ expect(locks.acquire).toHaveBeenCalledTimes(2);+ runtime.dispose();+ });++ it('does not let result routing from a closed lifecycle mutate a reopened project', async () => {+ const queueItem: QueueItem = { ...createPendingQueueItem(), backendItemIds: [88], status: 'running' };+ const projects: Array<{ id: string; queue: { items: QueueItem[] } }> = [+ { id: 'project-1', queue: { items: [queueItem] } },+ ];+ const listeners = new Set<() => void>();+ let finishResults: (images: QueueResultImage[]) => void = () => undefined;+ const results = new Promise<QueueResultImage[]>((resolve) => {+ finishResults = resolve;+ });+ const getResultImages = vi.fn(() => results);+ const getItem = vi.fn().mockResolvedValue({+ id: 88,+ origin: buildQueueItemOrigin(queueItem.id, 'project-1'),+ status: 'completed',+ });+ const commands = createTestCommands({+ restoreFromJournal: ({ items, projectId }) => {+ const project = projects.find((candidate) => candidate.id === projectId);+ if (project) {+ project.queue.items = items as QueueItem[];+ }+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ getItem, getResultImages }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: queueItem, projectId: 'project-1', queueItemId: queueItem.id }],+ kind: 'available',+ }),+ }),+ });++ runtime.start();+ await vi.waitFor(() => expect(getResultImages).toHaveBeenCalled());+ projects.splice(0, 1);+ listeners.forEach((listener) => listener());+ projects.push({ id: 'project-1', queue: { items: [] } });+ listeners.forEach((listener) => listener());+ await vi.waitFor(() => expect(getItem).toHaveBeenCalledTimes(2));++ finishResults([]);+ await vi.waitFor(() => expect(commands.routeResults).toHaveBeenCalledTimes(1));+ expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'cancelled' }));+ await runtime.dispose();+ });++ it('keeps ownership until an in-flight journal write drains on close', async () => {+ const queueItem: QueueItem = { ...createPendingQueueItem(), backendItemIds: [88], status: 'running' };+ const projects: Array<{ id: string; queue: { items: QueueItem[] } }> = [+ { id: 'project-1', queue: { items: [queueItem] } },+ ];+ const listeners = new Set<() => void>();+ let finishRecord: (result: { kind: 'stored' }) => void = () => undefined;+ const record = vi.fn(+ () =>+ new Promise<{ kind: 'stored' }>((resolve) => {+ finishRecord = resolve;+ })+ );+ const release = vi.fn().mockResolvedValue(undefined);+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend(),+ history: {+ commands: createTestCommands(),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({ record }),+ locks: { acquire: vi.fn().mockResolvedValue({ kind: 'acquired', release }) },+ });++ runtime.start();+ await vi.waitFor(() => expect(record).toHaveBeenCalled());+ projects.splice(0, 1);+ listeners.forEach((listener) => listener());+ await Promise.resolve();+ expect(release).not.toHaveBeenCalled();++ finishRecord({ kind: 'stored' });+ await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));+ runtime.dispose();+ });++ it('coalesces status bursts to one in-flight and one latest journal write', async () => {+ const initial: QueueItem = { ...createPendingQueueItem(), backendItemIds: [88, 89], status: 'running' };+ const project = { id: 'project-1', queue: { items: [initial] } };+ const listeners = new Set<() => void>();+ let finishFirst: (result: { kind: 'stored' }) => void = () => undefined;+ const record = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise<{ kind: 'stored' }>((resolve) => {+ finishFirst = resolve;+ })+ )+ .mockResolvedValue({ kind: 'stored' });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ getItem: vi.fn().mockResolvedValue({+ id: 88,+ origin: buildQueueItemOrigin(initial.id, project.id),+ status: 'in_progress',+ }),+ }),+ history: {+ commands: createTestCommands(),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({ record }),+ });++ runtime.start();+ await vi.waitFor(() => expect(record).toHaveBeenCalledTimes(1));+ project.queue.items = [{ ...initial, completedBackendItemIds: [88] }];+ listeners.forEach((listener) => listener());+ project.queue.items = [{ ...initial, completedBackendItemIds: [88, 89] }];+ listeners.forEach((listener) => listener());++ finishFirst({ kind: 'stored' });+ await vi.waitFor(() => expect(record).toHaveBeenCalledTimes(2));+ expect(record.mock.calls[1]?.[1]).toMatchObject({ completedBackendItemIds: [88, 89] });+ await runtime.dispose();+ });++ it('retains recovery and ownership until backend cancellation is acknowledged', async () => {+ const queueItem: QueueItem = { ...createPendingQueueItem(), backendItemIds: [88], status: 'running' };+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ let finishCancel: () => void = () => undefined;+ const cancelQueueItems = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finishCancel = resolve;+ })+ );+ const journal = createTestJournal();+ const release = vi.fn().mockResolvedValue(undefined);+ const commands = createTestCommands({+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ listeners.forEach((listener) => listener());+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ cancelQueueItems }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ locks: { acquire: vi.fn().mockResolvedValue({ kind: 'acquired', release }) },+ });++ runtime.start();+ await vi.waitFor(() => expect(journal.record).toHaveBeenCalled());+ queueItem.status = 'cancelled';+ queueItem.cancellationPending = true;+ listeners.forEach((listener) => listener());+ await vi.waitFor(() => expect(cancelQueueItems).toHaveBeenCalledWith([88]));+ expect(cancelQueueItems).toHaveBeenCalledTimes(1);+ expect(journal.record).toHaveBeenLastCalledWith(+ project.id,+ expect.objectContaining({ cancellationPending: true, status: 'cancelled' })+ );+ expect(journal.settle).not.toHaveBeenCalled();+ expect(release).not.toHaveBeenCalled();++ finishCancel();+ await vi.waitFor(() => expect(journal.settle).toHaveBeenCalledWith(project.id, queueItem.id));+ await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));+ listeners.forEach((listener) => listener());+ await Promise.resolve();+ expect(cancelQueueItems).toHaveBeenCalledTimes(1);+ expect(journal.settle).toHaveBeenCalledTimes(1);+ await runtime.dispose();+ });++ it('retains ownership and retries a failed terminal journal removal', async () => {+ vi.useFakeTimers();+ const queueItem: QueueItem = {+ ...createPendingQueueItem(),+ backendItemIds: [88],+ cancellationPending: true,+ status: 'cancelled',+ };+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ const settle = vi+ .fn<QueueRunJournalPort['settle']>()+ .mockResolvedValueOnce({ kind: 'unavailable' })+ .mockResolvedValueOnce({ kind: 'removed' });+ const release = vi.fn().mockResolvedValue(undefined);+ const commands = createTestCommands({+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ listeners.forEach((listener) => listener());+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ cancelQueueItems: vi.fn().mockResolvedValue(undefined) }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({ settle }),+ locks: { acquire: vi.fn().mockResolvedValue({ kind: 'acquired', release }) },+ });++ runtime.start();+ await vi.advanceTimersByTimeAsync(1);++ expect(settle).toHaveBeenCalledTimes(1);+ expect(release).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(100);+ expect(settle).toHaveBeenCalledTimes(2);+ await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));+ await runtime.dispose();+ vi.useRealTimers();+ });++ it('restores a durable cancellation intent and retries cancellation before settling it', async () => {+ const queueItem: QueueItem = {+ ...createPendingQueueItem(),+ backendItemIds: [88],+ cancellationPending: true,+ status: 'cancelled',+ };+ const project = { id: 'project-1', queue: { items: [] as QueueItem[] } };+ const listeners = new Set<() => void>();+ const cancelQueueItems = vi.fn().mockResolvedValue(undefined);+ const journal = createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: queueItem, projectId: project.id, queueItemId: queueItem.id }],+ kind: 'available',+ }),+ });+ const commands = createTestCommands({+ restoreFromJournal: ({ items }) => {+ project.queue.items = items as QueueItem[];+ },+ setCancellationPending: ({ pending }) => {+ const item = project.queue.items[0];+ if (item) {+ item.cancellationPending = pending || undefined;+ }+ listeners.forEach((listener) => listener());+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ cancelQueueItems,+ getItem: vi.fn().mockResolvedValue({+ id: 88,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'in_progress',+ }),+ }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ });++ runtime.start();++ await vi.waitFor(() => expect(cancelQueueItems).toHaveBeenCalledWith([88]));+ await vi.waitFor(() => expect(journal.settle).toHaveBeenCalledWith(project.id, queueItem.id));+ expect(project.queue.items[0]?.cancellationPending).toBeUndefined();+ await runtime.dispose();+ });++ it('clears a restored cancellation intent when its backend run is already gone', async () => {+ const queueItem: QueueItem = {+ ...createPendingQueueItem(),+ backendItemIds: [88],+ cancellationPending: true,+ status: 'cancelled',+ };+ const project = { id: 'project-1', queue: { items: [] as QueueItem[] } };+ const listeners = new Set<() => void>();+ const journal = createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: queueItem, projectId: project.id, queueItemId: queueItem.id }],+ kind: 'available',+ }),+ });+ const commands = createTestCommands({+ restoreFromJournal: ({ items }) => {+ project.queue.items = items as QueueItem[];+ },+ setCancellationPending: ({ pending }) => {+ const item = project.queue.items[0];+ if (item) {+ item.cancellationPending = pending || undefined;+ }+ listeners.forEach((listener) => listener());+ },+ });+ const cancelQueueItems = vi.fn().mockRejectedValue(new ApiError('not found', 404));+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ cancelQueueItems,+ getItem: vi.fn().mockRejectedValue(new ApiError('not found', 404)),+ }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ });++ runtime.start();++ await vi.waitFor(() => expect(journal.settle).toHaveBeenCalledWith(project.id, queueItem.id));+ expect(project.queue.items[0]?.cancellationPending).toBeUndefined();+ expect(cancelQueueItems).toHaveBeenCalledTimes(1);+ listeners.forEach((listener) => listener());+ await Promise.resolve();+ expect(journal.settle).toHaveBeenCalledTimes(1);+ await runtime.dispose();+ });++ it('fallback-acknowledges a proven local-only cancelled run found only by its receipt', async () => {+ const queueItem: QueueItem = {+ ...createPendingQueueItem(),+ cancellationPending: true,+ localRecoveryState: 'local-only',+ status: 'cancelled',+ };+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ const acknowledgeEnqueue = vi.fn().mockResolvedValue(undefined);+ const commands = createTestCommands({+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ listeners.forEach((listener) => listener());+ },+ setLocalRecoveryState: ({ state }) => {+ queueItem.localRecoveryState = state;+ listeners.forEach((listener) => listener());+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ acknowledgeEnqueue,+ getEnqueueReceipt: vi.fn().mockResolvedValue({+ batchId: 'batch-1',+ enqueued: 1,+ itemIds: [77],+ requested: 1,+ }),+ getItem: vi.fn().mockRejectedValue(new ApiError('not found', 404)),+ }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal: createTestJournal({ record: vi.fn().mockResolvedValue({ kind: 'quota' }) }),+ });++ runtime.start();++ await vi.waitFor(() => expect(acknowledgeEnqueue).toHaveBeenCalledWith(project.id, queueItem.id));+ expect(queueItem.cancellationPending).toBeUndefined();+ await runtime.dispose();+ });++ it('cancels an enqueue accepted after local cancellation before settling recovery', async () => {+ const queueItem: QueueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ let finishEnqueue: (result: {+ batchId: string;+ enqueued: number;+ itemIds: number[];+ requested: number;+ }) => void = () => undefined;+ const enqueueGenerate = vi.fn(+ () =>+ new Promise<{ batchId: string; enqueued: number; itemIds: number[]; requested: number }>((resolve) => {+ finishEnqueue = resolve;+ })+ );+ const cancelQueueItems = vi.fn().mockResolvedValue(undefined);+ const cancelQueueItemsByBatchIds = vi.fn().mockResolvedValue(undefined);+ const journal = createTestJournal();+ const commands = createTestCommands({+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ listeners.forEach((listener) => listener());+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ cancelQueueItems, cancelQueueItemsByBatchIds, enqueueGenerate }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ });++ runtime.start();+ await vi.waitFor(() => expect(enqueueGenerate).toHaveBeenCalledTimes(1));+ queueItem.status = 'cancelled';+ queueItem.cancellationPending = true;+ listeners.forEach((listener) => listener());+ await vi.waitFor(() =>+ expect(journal.record).toHaveBeenLastCalledWith(+ project.id,+ expect.objectContaining({ cancellationPending: true, status: 'cancelled' })+ )+ );+ expect(journal.settle).not.toHaveBeenCalled();++ finishEnqueue({ batchId: 'webv2:local-queue-item', enqueued: 1, itemIds: [88], requested: 1 });+ await vi.waitFor(() => expect(cancelQueueItemsByBatchIds).toHaveBeenCalledWith(['webv2:local-queue-item']));+ expect(cancelQueueItems).not.toHaveBeenCalled();+ await vi.waitFor(() => expect(journal.settle).toHaveBeenCalledWith(project.id, queueItem.id));+ await runtime.dispose();+ });++ it('reconciles an ambiguously accepted enqueue instead of failing or submitting twice', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const commands = createTestCommands();+ const enqueueGenerate = vi.fn().mockRejectedValueOnce(new Error('response lost'));+ const listItems = vi+ .fn()+ .mockResolvedValueOnce([])+ .mockResolvedValue([+ {+ batchId: 'webv2:local-queue-item',+ id: 88,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'in_progress',+ },+ ]);+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal(),+ });++ runtime.start();++ await vi.waitFor(() => expect(commands.markBackendSubmitted).toHaveBeenCalled(), { timeout: 2_000 });+ expect(enqueueGenerate).toHaveBeenCalledTimes(1);+ expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));+ runtime.dispose();+ });++ it('keeps reconciling after three consecutive lost enqueue responses', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const commands = createTestCommands();+ const enqueueGenerate = vi+ .fn()+ .mockRejectedValueOnce(new Error('response lost 1'))+ .mockRejectedValueOnce(new Error('response lost 2'))+ .mockRejectedValueOnce(new Error('response lost 3'))+ .mockResolvedValue({ batchId: 'backend-batch', enqueued: 1, itemIds: [88], requested: 1 });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems: vi.fn().mockResolvedValue([]) }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal(),+ });++ runtime.start();++ await vi.waitFor(() => expect(enqueueGenerate).toHaveBeenCalledTimes(4), { timeout: 4_000 });+ expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));+ await runtime.dispose();+ });++ it('owns and journals a fresh pending run while offline, then submits it after reconnect', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ let connectionStatus: BackendConnectionStatus = 'disconnected';+ let connectionListener: ((status: BackendConnectionStatus, error?: string) => void) | undefined;+ const enqueueGenerate = vi.fn().mockResolvedValue({ enqueued: 1, itemIds: [77], requested: 1 });+ const journal = createTestJournal();+ const acquire = vi.fn().mockResolvedValue({ kind: 'acquired', release: vi.fn().mockResolvedValue(undefined) });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ enqueueGenerate,+ onConnectionChange: (listener) => {+ connectionListener = listener;+ listener(connectionStatus);+ return vi.fn();+ },+ }),+ history: {+ commands: createTestCommands(),+ getSnapshot: () => ({ connectionStatus, isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ locks: { acquire },+ });- expect(createQueueItemBackendSubmission({ id: 'project-1' }, queueItem)).toEqual({- error: 'Queue item is missing a compiled backend submission.',- kind: 'invalid',+ runtime.start();++ await vi.waitFor(() => expect(acquire).toHaveBeenCalledWith(project.id, queueItem.id));+ await vi.waitFor(() => expect(journal.record).toHaveBeenCalledWith(project.id, queueItem));+ expect(enqueueGenerate).not.toHaveBeenCalled();++ connectionStatus = 'connected';+ connectionListener?.('connected');+ listeners.forEach((listener) => listener());+ await vi.waitFor(() => expect(enqueueGenerate).toHaveBeenCalledTimes(1));+ await runtime.dispose();+ });++ it('bounds ownership acquisition and journal writes while preparing many offline runs', async () => {+ const projects = Array.from({ length: 40 }, (_, index) => ({+ id: `project-${index}`,+ queue: { items: [{ ...createPendingQueueItem(), id: `queue-item-${index}` }] },+ }));+ let activeAcquisitions = 0;+ let activeRecords = 0;+ let maxAcquisitions = 0;+ let maxRecords = 0;+ const acquire = vi.fn(async (): Promise<QueueRunLock> => {+ activeAcquisitions += 1;+ maxAcquisitions = Math.max(maxAcquisitions, activeAcquisitions);+ await Promise.resolve();+ activeAcquisitions -= 1;+ return { kind: 'acquired', release: vi.fn().mockResolvedValue(undefined) };+ });+ const record = vi.fn<QueueRunJournalPort['record']>(async () => {+ activeRecords += 1;+ maxRecords = Math.max(maxRecords, activeRecords);+ await Promise.resolve();+ activeRecords -= 1;+ return { kind: 'stored' };+ });+ const backend = createTestBackend();+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend,+ history: {+ commands: createTestCommands(),+ getSnapshot: () => ({ connectionStatus: 'disconnected', isHydrated: true, projects }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal({ record }),+ locks: { acquire },});++ runtime.start();++ await vi.waitFor(() => expect(record).toHaveBeenCalledTimes(projects.length));+ expect(maxAcquisitions).toBeLessThanOrEqual(16);+ expect(maxRecords).toBeLessThanOrEqual(16);+ expect(backend.enqueueGenerate).not.toHaveBeenCalled();+ await runtime.dispose();});- it('adopts a persisted backend run before submission so reload cannot duplicate it', async () => {+ it('settles a cancellation when a pending enqueue accepts no items and never retries it', async () => {+ vi.useFakeTimers();const queueItem = createPendingQueueItem();const project = { id: 'project-1', queue: { items: [queueItem] } };- const enqueueGenerate = vi.fn();+ const listeners = new Set<() => void>();+ let finishEnqueue: (result: { enqueued: number; itemIds: number[]; requested: number }) => void = () => undefined;+ const enqueueGenerate = vi.fn(+ () =>+ new Promise<{ enqueued: number; itemIds: number[]; requested: number }>((resolve) => {+ finishEnqueue = resolve;+ })+ );+ const journal = createTestJournal();+ const commands = createTestCommands({+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ },+ setLocalRecoveryState: vi.fn(),+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ });++ runtime.start();+ await vi.waitFor(() => expect(enqueueGenerate).toHaveBeenCalledTimes(1));+ queueItem.status = 'cancelled';+ queueItem.cancellationPending = true;+ listeners.forEach((listener) => listener());+ finishEnqueue({ enqueued: 0, itemIds: [], requested: 1 });++ await vi.waitFor(() => expect(journal.settle).toHaveBeenCalledWith(project.id, queueItem.id));+ await vi.advanceTimersByTimeAsync(10_000);+ expect(enqueueGenerate).toHaveBeenCalledTimes(1);+ expect(queueItem.cancellationPending).toBeUndefined();+ await runtime.dispose();+ vi.useRealTimers();+ });++ it('adopts a partially accepted enqueue instead of abandoning its backend items', async () => {+ const queueItem = createPendingQueueItem();+ queueItem.snapshot.presentation.batchCount = 2;+ if (queueItem.snapshot.backendSubmission.kind !== 'invalid') {+ queueItem.snapshot.backendSubmission.batchCount = 2;+ }+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const commands = createTestCommands();+ const enqueueGenerate = vi+ .fn()+ .mockResolvedValueOnce({ batchId: 'webv2:local-queue-item', enqueued: 1, itemIds: [88], requested: 2 });+ const listItems = vi+ .fn()+ .mockResolvedValueOnce([])+ .mockResolvedValue([+ {+ batchId: 'webv2:local-queue-item',+ id: 88,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'in_progress',+ },+ ]);+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ enqueueGenerate, listItems }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal(),+ });++ runtime.start();++ await vi.waitFor(() => expect(commands.markBackendSubmitted).toHaveBeenCalled(), { timeout: 2_000 });+ expect(enqueueGenerate).toHaveBeenCalledTimes(1);+ expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));+ expect(commands.recordError).toHaveBeenCalledWith(+ expect.objectContaining({+ area: 'queue-submission',+ message: expect.stringContaining('accepted 1 of 2'),+ projectId: project.id,+ })+ );+ await runtime.dispose();+ });++ it('bounds per-item result and video reads for a large restored run', async () => {+ const backendItemIds = Array.from({ length: 40 }, (_, index) => index + 1);+ const queueItem: QueueItem = {+ ...createPendingQueueItem(),+ backendItemIds,+ status: 'running',+ };+ queueItem.snapshot.destination = 'gallery';+ queueItem.snapshot.galleryBoardId = 'board-1';+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ let activeImageReads = 0;+ let activeVideoReads = 0;+ let maxImageReads = 0;+ let maxVideoReads = 0;+ const getResultImages = vi.fn(async () => {+ activeImageReads += 1;+ maxImageReads = Math.max(maxImageReads, activeImageReads);+ await Promise.resolve();+ activeImageReads -= 1;+ return [];+ });+ const getResultVideoNames = vi.fn(async () => {+ activeVideoReads += 1;+ maxVideoReads = Math.max(maxVideoReads, activeVideoReads);+ await Promise.resolve();+ activeVideoReads -= 1;+ return [];+ });+ const commands = createTestCommands();+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({+ getItem: vi.fn((itemId: number) =>+ Promise.resolve({+ batchId: 'batch-1',+ id: itemId,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'completed' as const,+ })+ ),+ getResultImages,+ getResultVideoNames,+ }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal(),+ });++ runtime.start();++ await vi.waitFor(() => expect(commands.routeResults).toHaveBeenCalledTimes(1));+ expect(getResultImages.mock.calls.length).toBeGreaterThanOrEqual(backendItemIds.length);+ expect(getResultVideoNames.mock.calls.length).toBeGreaterThanOrEqual(backendItemIds.length);+ expect(maxImageReads).toBeLessThanOrEqual(16);+ expect(maxVideoReads).toBeLessThanOrEqual(16);+ await runtime.dispose();+ });++ it('retries transient reconciliation failures while the connection remains up', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listItems = vi+ .fn()+ .mockRejectedValueOnce(new Error('transient'))+ .mockResolvedValueOnce([+ {+ batchId: 'backend-batch',+ id: 88,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'in_progress',+ },+ ]);+ const commands = createTestCommands();+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ listItems }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal(),+ });++ runtime.start();++ await vi.waitFor(() => expect(listItems).toHaveBeenCalledTimes(2), { timeout: 2_000 });+ expect(commands.markBackendSubmitted).toHaveBeenCalled();+ runtime.dispose();+ });++ it('restores journal rows before reconciliation and leaves a contended run to its owning tab', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [] as QueueItem[] } };+ const listeners = new Set<() => void>();+ const restoreFromJournal = vi.fn(({ items }: { items: unknown[] }) => {+ project.queue.items = items as QueueItem[];+ });+ const journal = createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: queueItem, projectId: project.id, queueItemId: queueItem.id }],+ kind: 'available',+ }),+ });+ const acquire = vi.fn().mockResolvedValue({ kind: 'contended' });+ const locks: QueueRunLockPort = { acquire };+ const backend = createTestBackend();+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend,+ history: {+ commands: createTestCommands({ restoreFromJournal }),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ locks,+ });++ runtime.start();++ await vi.waitFor(() => expect(acquire).toHaveBeenCalledWith(project.id, queueItem.id));+ expect(restoreFromJournal).toHaveBeenCalledWith({ items: [queueItem], projectId: project.id });+ expect(backend.listItems).not.toHaveBeenCalled();+ expect(backend.enqueueGenerate).not.toHaveBeenCalled();+ expect(journal.record).not.toHaveBeenCalled();++ queueItem.status = 'cancelled';+ listeners.forEach((listener) => listener());+ await Promise.resolve();+ expect(journal.settle).not.toHaveBeenCalled();++ runtime.dispose();+ });++ it('retries reconciliation after another tab releases run ownership', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [] as QueueItem[] } };+ const release = vi.fn().mockResolvedValue(undefined);+ const acquire = vi+ .fn<QueueRunLockPort['acquire']>()+ .mockResolvedValueOnce({ kind: 'contended' })+ .mockResolvedValue({ kind: 'acquired', release });const listItems = vi.fn().mockResolvedValue([{batchId: 'backend-batch',@@ -62,84 +1654,207 @@ describe('queue runtime', () => {status: 'in_progress',},]);- const backend: QueueBackendPort = {- cancelCurrentItem: vi.fn(),- cancelItem: vi.fn(),- cancelQueueItems: vi.fn(),- cancelQueueItemsByBatchIds: vi.fn(),- cancelScopedItems: vi.fn(),- clearFailedItems: vi.fn(),- clearItems: vi.fn(),- emit: vi.fn(),- enqueueGenerate,- enqueueWorkflow: vi.fn(),- getItem: vi.fn(),- getResultImages: vi.fn(),- getResultVideoNames: vi.fn().mockResolvedValue([]),- listItems,- on: vi.fn(() => vi.fn()),- onConnectionChange: vi.fn((listener) => {- listener('connected');- return vi.fn();+ const commands = createTestCommands({+ restoreFromJournal: ({ items }) => {+ project.queue.items = items as QueueItem[];+ },+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ listItems }),+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),+ subscribe: vi.fn(() => vi.fn()),+ },+ journal: createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: queueItem, projectId: project.id, queueItemId: queueItem.id }],+ kind: 'available',+ }),}),- pauseProcessor: vi.fn(),- readCurrent: vi.fn(),- readItemIds: vi.fn(),- readItemsById: vi.fn(),- readNext: vi.fn(),- readStatus: vi.fn(),- resumeProcessor: vi.fn(),- retryItems: vi.fn(),+ locks: { acquire },+ });++ runtime.start();++ await vi.waitFor(() => expect(acquire).toHaveBeenCalledTimes(2), { timeout: 2_000 });+ await vi.waitFor(() => expect(listItems).toHaveBeenCalledOnce());+ expect(commands.markBackendSubmitted).toHaveBeenCalled();++ await runtime.dispose();+ });++ it('settles the journal and releases ownership after a restored run completes', async () => {+ const queueItem = createPendingQueueItem();+ const project = { id: 'project-1', queue: { items: [queueItem] } };+ const listeners = new Set<() => void>();+ const notify = () => listeners.forEach((listener) => listener());+ const journal = createTestJournal();+ const release = vi.fn().mockResolvedValue(undefined);+ const locks: QueueRunLockPort = {+ acquire: vi.fn().mockResolvedValue({ kind: 'acquired', release }),};- const commands: QueueHistoryCommands = {- markBackendCancelled: vi.fn(),+ const commands = createTestCommands({markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {queueItem.backendBatchId = backendBatchId;queueItem.backendItemIds = backendItemIds;queueItem.status = 'running';+ notify();},- recordError: vi.fn(),- refreshBackendData: vi.fn(),- routePartialResults: vi.fn(),- routeResults: vi.fn(),- setConnectionStatus: vi.fn(),- setStatus: vi.fn(),- };+ routeResults: () => {+ queueItem.status = 'completed';+ notify();+ },+ });+ const backend = createTestBackend({+ listItems: vi.fn().mockResolvedValue([+ {+ batchId: 'backend-batch',+ id: 77,+ origin: buildQueueItemOrigin(queueItem.id, project.id),+ status: 'completed',+ },+ ]),+ });const runtime = createQueueRuntime({+ ...runtimeServices,backend,- destinations: { addImagesToGalleryBoard: vi.fn(), addVideosToGalleryBoard: vi.fn() },- ensureTemplatesLoaded: vi.fn(),history: {commands,getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),- subscribe: vi.fn(() => vi.fn()),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },},- modelLoads: {- completed: vi.fn(),- reset: vi.fn(),- started: vi.fn(),+ journal,+ locks,+ });++ runtime.start();++ await vi.waitFor(() => {+ expect(journal.settle).toHaveBeenCalledWith(project.id, queueItem.id);+ expect(release).toHaveBeenCalledTimes(1);+ });++ runtime.dispose();+ });++ it('loads and reconciles journal rows before processing a project opened mid-session', async () => {+ const restoredItem = {+ ...createPendingQueueItem(),+ backendItemIds: [88],+ status: 'running' as const,+ };+ const projects = [{ id: 'project-1', queue: { items: [] as QueueItem[] } }];+ const listeners = new Set<() => void>();+ const journal = createTestJournal({+ listForProject: vi.fn().mockImplementation((projectId: string) =>+ Promise.resolve({+ entries: projectId === 'project-2' ? [{ item: restoredItem, projectId, queueItemId: restoredItem.id }] : [],+ kind: 'available',+ })+ ),+ });+ const commands = createTestCommands({+ restoreFromJournal: ({ items, projectId }) => {+ const project = projects.find((candidate) => candidate.id === projectId);+ if (project) {+ project.queue.items = items as QueueItem[];+ }+ listeners.forEach((listener) => listener());},- nodeExecution: {- clearAll: vi.fn(),- completed: vi.fn(),- failed: vi.fn(),- progress: vi.fn(),- settleRunning: vi.fn(),- started: vi.fn(),+ });+ const getItem = vi.fn().mockResolvedValue({+ id: 88,+ origin: buildQueueItemOrigin(restoredItem.id, 'project-2'),+ status: 'in_progress',+ });+ const backend = createTestBackend({ getItem });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend,+ history: {+ commands,+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },},+ journal,});runtime.start();+ await vi.waitFor(() => expect(journal.listForProject).toHaveBeenCalledWith('project-1'));- await vi.waitFor(() => {- expect(queueItem).toMatchObject({- backendBatchId: 'backend-batch',- backendItemIds: [77],- status: 'running',- });+ projects.push({ id: 'project-2', queue: { items: [] } });+ listeners.forEach((listener) => listener());++ await vi.waitFor(() => expect(getItem).toHaveBeenCalledWith(88));+ expect(journal.listForProject).toHaveBeenCalledWith('project-2');+ expect(backend.enqueueGenerate).not.toHaveBeenCalled();++ runtime.dispose();+ });++ it('retains a running journal row when its project tab closes', async () => {+ const queueItem = { ...createPendingQueueItem(), backendItemIds: [88], status: 'running' as const };+ const projects: Array<{ id: string; queue: { items: QueueItem[] } }> = [+ { id: 'project-1', queue: { items: [queueItem] } },+ ];+ const listeners = new Set<() => void>();+ const journal = createTestJournal({+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: queueItem, projectId: 'project-1', queueItemId: queueItem.id }],+ kind: 'available',+ }),+ });+ const release = vi.fn().mockResolvedValue(undefined);+ const getItem = vi.fn().mockResolvedValue({+ id: 88,+ origin: buildQueueItemOrigin(queueItem.id, 'project-1'),+ status: 'in_progress',+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend: createTestBackend({ getItem }),+ history: {+ commands: createTestCommands({+ restoreFromJournal: ({ items, projectId }) => {+ const project = projects.find((candidate) => candidate.id === projectId);+ if (project) {+ project.queue.items = items as QueueItem[];+ }+ listeners.forEach((listener) => listener());+ },+ }),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects }),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ journal,+ locks: { acquire: vi.fn().mockResolvedValue({ kind: 'acquired', release }) },});- expect(listItems).toHaveBeenCalledTimes(1);- expect(enqueueGenerate).not.toHaveBeenCalled();++ runtime.start();+ await vi.waitFor(() => expect(journal.record).toHaveBeenCalled());++ projects.splice(0, 1);+ listeners.forEach((listener) => listener());++ await vi.waitFor(() => expect(release).toHaveBeenCalledTimes(1));+ expect(journal.settle).not.toHaveBeenCalled();++ projects.push({ id: 'project-1', queue: { items: [] } });+ listeners.forEach((listener) => listener());++ await vi.waitFor(() => expect(getItem).toHaveBeenCalledTimes(2));+ expect(journal.listForProject).toHaveBeenCalledWith('project-1');runtime.dispose();});@@ -216,8 +1931,13 @@ describe('queue runtime video board routing', () => {queueItem.backendItemIds = backendItemIds;queueItem.status = 'running';},+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ },+ setLocalRecoveryState: vi.fn(),recordError: vi.fn(),refreshBackendData: vi.fn(),+ restoreFromJournal: vi.fn(),routePartialResults: vi.fn(),routeResults: vi.fn(),setConnectionStatus: vi.fn(),@@ -443,8 +2163,13 @@ describe('queue runtime workflow run capture', () => {queueItem.backendItemIds = backendItemIds;queueItem.status = 'running';},+ setCancellationPending: ({ pending }) => {+ queueItem.cancellationPending = pending || undefined;+ },+ setLocalRecoveryState: vi.fn(),recordError: vi.fn(),refreshBackendData: vi.fn(),+ restoreFromJournal: vi.fn(),routePartialResults: vi.fn(),routeResults: vi.fn(),setConnectionStatus: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.tsindex 3ea58ea5d8..2bf71b047a 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts@@ -10,18 +10,21 @@ import type {import type { BackendConnectionStatus } from '@platform/transport/types';import { collectGraphInputMediaNames } from '@features/queue/core/graphInputMedia';-import { isQueuePromptSeedBehaviour } from '@features/queue/core/promptBatch';+import { isQueuePromptSeedBehaviour, MAX_QUEUE_BATCH_ITEMS } from '@features/queue/core/promptBatch';import { shouldSubmitPendingQueueItem } from '@features/queue/core/submissionRules';import {createQueueCoordinator,+ QueueEnqueueNotAcceptedError,QueueItemCancelledError,type QueueCoordinator,type QueueModelLoadPort,type QueueNodeExecutionPort,type ReconcileInput,+ type ReconcileOutcome,} from '@features/queue/runtime/coordinator';+import { mapWithConcurrency } from '@platform/core/concurrency';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';-import { getApiErrorMessage } from '@platform/transport/http';+import { ApiError, getApiErrorMessage } from '@platform/transport/http';export interface QueueResultDestinationPort {addImagesToGalleryBoard(boardId: string, imageNames: string[]): Promise<void>;@@ -29,10 +32,30 @@ export interface QueueResultDestinationPort {}export interface QueueRuntime {- dispose(): void;+ dispose(): Promise<void>;start(): void;}+export interface QueueRunJournalPort {+ listForProject(+ projectId: string+ ): Promise<+ | { entries: Array<{ item: unknown; projectId: string; queueItemId: string }>; kind: 'available' }+ | { kind: 'unavailable' }+ >;+ record(+ projectId: string,+ item: QueueItem+ ): Promise<{ kind: 'invalid' | 'quota' | 'stored' | 'too-large' | 'unavailable' }>;+ settle(projectId: string, queueItemId: string): Promise<{ kind: 'removed' | 'unavailable' }>;+}++export type QueueRunLock = { kind: 'acquired'; release(): Promise<void> } | { kind: 'contended' | 'unavailable' };++export interface QueueRunLockPort {+ acquire(projectId: string, queueItemId: string): Promise<QueueRunLock>;+}+export interface QueueHistoryProject {id: string;queue: { items: QueueItem[] };@@ -46,8 +69,15 @@ export interface QueueHistoryCommands {projectId: string;queueItemId: string;}): void;+ setCancellationPending(payload: { pending: boolean; projectId: string; queueItemId: string }): void;+ setLocalRecoveryState(payload: {+ projectId: string;+ queueItemId: string;+ state: NonNullable<QueueItem['localRecoveryState']>;+ }): void;recordError(payload: { area: string; message: string; namespace: 'queue'; projectId?: string }): void;refreshBackendData(): void;+ restoreFromJournal(payload: { items: unknown[]; projectId: string }): void;routePartialResults(payload: {backendItemId: number;images: QueueResultImage[];@@ -114,7 +144,9 @@ export const createQueueItemBackendSubmission = (if (typeof submission.batchCount !== 'number' ||!Number.isFinite(submission.batchCount) ||- submission.batchCount < 1+ !Number.isSafeInteger(submission.batchCount) ||+ submission.batchCount < 1 ||+ submission.batchCount > MAX_QUEUE_BATCH_ITEMS) {return { error: 'Queue item backend submission has an invalid batch count.', kind: 'invalid' };}@@ -181,32 +213,519 @@ const getRouteTarget = (history: QueueHistoryPort, localQueueItemId: string) =>})).find((target) => target.queueItem !== undefined);+const getRunKey = (projectId: string, queueItemId: string): string => JSON.stringify([projectId, queueItemId]);++const QUEUE_RUNTIME_CONCURRENCY = 16;++interface RunAttempt {+ generation: number;+ key: string;+ projectId: string;+ queueItemId: string;+}++const getJournalSignature = (item: QueueItem): string =>+ JSON.stringify([+ item.status,+ item.cancellationPending,+ item.backendBatchId,+ item.backendItemIds,+ item.completedBackendItemIds,+ item.cancelledBackendItemIds,+ ]);+export const createQueueRuntime = ({backend,destinations,+ ensureProjectPersisted,ensureTemplatesLoaded,history,+ journal,+ locks,modelLoads,nodeExecution,workflowRuns,}: {backend: QueueBackendPort;destinations: QueueResultDestinationPort;+ ensureProjectPersisted?(projectId: string): Promise<'ready' | 'refused' | 'retry'>;ensureTemplatesLoaded: () => void;history: QueueHistoryPort;+ journal?: QueueRunJournalPort;+ locks?: QueueRunLockPort;modelLoads: QueueModelLoadPort;nodeExecution: QueueNodeExecutionPort;workflowRuns?: QueueWorkflowRunSink;}): QueueRuntime => {const owner = captureAccountScope();const commands = history.commands;- const startedQueueItemIds = new Set<string>();- const cancelledQueueItemIds = new Set<string>();+ const startedRunKeys = new Set<string>();+ const reconcileRetryRunKeys = new Set<string>();const detachers: Array<() => void> = [];- let reconcileState: 'idle' | 'running' | 'done' = 'idle';+ const loadedProjectIds = new Set<string>();+ const loadingProjectIds = new Set<string>();+ const pendingReconcileRunKeys = new Set<string>();+ const trackedRuns = new Map<string, { projectId: string; queueItemId: string; signature: string }>();+ const journalOperations = new Map<string, Promise<void>>();+ const journalRecordFlushes = new Map<string, Promise<void>>();+ const journalSettleFlushes = new Map<string, Promise<void>>();+ const pendingJournalRecords = new Map<+ string,+ { item: QueueItem; projectId: string; restoreLocalOnly: boolean; signature: string; token: number }+ >();+ const pendingJournalSettles = new Map<string, { ownershipEpoch: number; projectId: string; queueItemId: string }>();+ const durableJournalSignatures = new Map<string, string>();+ const reportedJournalFailures = new Set<string>();+ const ownedLocks = new Map<string, Extract<QueueRunLock, { kind: 'acquired' }>>();+ const lockRequests = new Map<string, Promise<boolean>>();+ const preparingRunKeys = new Set<string>();+ const activeAttempts = new Map<string, RunAttempt>();+ const ownershipEpochs = new Map<string, number>();+ const latestJournalWriteTokens = new Map<string, number>();+ const pendingFallbackAcks = new Map<string, { projectId: string; queueItemId: string }>();+ const fallbackAckOperations = new Map<string, Promise<void>>();+ let nextAttemptGeneration = 0;+ let nextJournalWriteToken = 0;+ const cancellationOperations = new Map<string, Promise<void>>();+ const submissionOperations = new Map<string, Promise<unknown>>();+ const cancelRequestedRunKeys = new Set<string>();+ let reconcileRetryDelayMs = 100;+ let retryTimer: ReturnType<typeof setTimeout> | undefined;+ let hasInitialized = false;+ let isInitializing = false;+ let isReconciling = false;let isDisposed = false;let isStarted = false;const isActive = (): boolean => !isDisposed && isAccountScopeCurrent(owner);+ const beginAttempt = (projectId: string, queueItemId: string): RunAttempt => {+ const key = getRunKey(projectId, queueItemId);+ const attempt = {+ generation: ++nextAttemptGeneration,+ key,+ projectId,+ queueItemId,+ };+ ownershipEpochs.set(key, (ownershipEpochs.get(key) ?? 0) + 1);+ activeAttempts.set(attempt.key, attempt);+ return attempt;+ };+ const isAttemptCurrent = (attempt: RunAttempt): boolean =>+ isActive() && activeAttempts.get(attempt.key)?.generation === attempt.generation;+ const invalidateAttempt = (projectId: string, queueItemId: string): void => {+ activeAttempts.delete(getRunKey(projectId, queueItemId));+ };++ const scheduleRetry = (): void => {+ if (!isActive() || retryTimer !== undefined) {+ return;+ }+ const delay = reconcileRetryDelayMs;+ reconcileRetryDelayMs = Math.min(reconcileRetryDelayMs * 2, 5_000);+ retryTimer = setTimeout(() => {+ retryTimer = undefined;+ if (!isActive()) {+ return;+ }+ for (const runKey of reconcileRetryRunKeys) {+ startedRunKeys.delete(runKey);+ pendingReconcileRunKeys.add(runKey);+ }+ reconcileRetryRunKeys.clear();+ for (const runKey of pendingJournalSettles.keys()) {+ void flushJournalSettle(runKey);+ }+ for (const runKey of pendingFallbackAcks.keys()) {+ void flushFallbackAck(runKey);+ }+ synchronize();+ }, delay);+ };++ const reportJournalFailure = (projectId: string, queueItemId: string, kind: string): void => {+ const key = `write:${kind}`;+ if (!isActive() || reportedJournalFailures.has(key)) {+ return;+ }+ reportedJournalFailures.add(key);+ commands.recordError({+ area: 'queue-recovery',+ message: `Local recovery for queue item ${queueItemId} is unavailable (${kind}). The backend run will continue.`,+ namespace: 'queue',+ projectId,+ });+ };++ const reportJournalLoadFailure = (projectId?: string): void => {+ const key = 'load';+ if (!isActive() || reportedJournalFailures.has(key)) {+ return;+ }+ reportedJournalFailures.add(key);+ commands.recordError({+ area: 'queue-recovery',+ message: 'Queue recovery storage is unavailable. Runs can continue but will not survive a reload.',+ namespace: 'queue',+ ...(projectId ? { projectId } : {}),+ });+ };++ const enqueueJournalOperation = (key: string, operation: () => Promise<void>): Promise<void> => {+ const previous = journalOperations.get(key) ?? Promise.resolve();+ const next = previous+ .catch(() => undefined)+ .then(operation)+ .catch(() => undefined)+ .finally(() => {+ if (journalOperations.get(key) === next) {+ journalOperations.delete(key);+ }+ });+ journalOperations.set(key, next);+ return next;+ };++ const flushJournalRecords = (key: string): Promise<void> => {+ if (!journal) {+ return Promise.resolve();+ }+ const activeFlush = journalRecordFlushes.get(key);+ if (activeFlush) {+ return activeFlush;+ }+ const flush = (async () => {+ while (pendingJournalRecords.has(key)) {+ const pending = pendingJournalRecords.get(key)!;+ pendingJournalRecords.delete(key);+ const result = await journal.record(pending.projectId, pending.item);+ if (result.kind === 'stored') {+ durableJournalSignatures.set(key, pending.signature);+ if (isActive()) {+ commands.setLocalRecoveryState({+ projectId: pending.projectId,+ queueItemId: pending.item.id,+ state: 'durable',+ });+ }+ } else {+ durableJournalSignatures.delete(key);+ reportJournalFailure(pending.projectId, pending.item.id, result.kind);+ const target = getRouteTarget(history, pending.item.id);+ if (+ pending.restoreLocalOnly &&+ latestJournalWriteTokens.get(key) === pending.token &&+ isActive() &&+ target?.project.id === pending.projectId &&+ target.queueItem?.localRecoveryState === 'uncertain' &&+ (!locks || ownedLocks.has(key))+ ) {+ commands.setLocalRecoveryState({+ projectId: pending.projectId,+ queueItemId: pending.item.id,+ state: 'local-only',+ });+ }+ }+ }+ })()+ .catch(() => {+ durableJournalSignatures.delete(key);+ })+ .finally(() => {+ if (journalRecordFlushes.get(key) === flush) {+ journalRecordFlushes.delete(key);+ }+ if (pendingJournalRecords.has(key)) {+ void flushJournalRecords(key);+ }+ });+ journalRecordFlushes.set(key, flush);+ return flush;+ };++ const recordActiveRun = async (projectId: string, item: QueueItem): Promise<boolean> => {+ const key = getRunKey(projectId, item.id);+ const signature = getJournalSignature(item);+ const tracked = trackedRuns.get(key);+ if (tracked?.signature === signature) {+ await journalRecordFlushes.get(key);+ return durableJournalSignatures.get(key) === signature;+ }+ trackedRuns.set(key, { projectId, queueItemId: item.id, signature });+ if (!journal) {+ return false;+ }+ const restoreLocalOnly = item.localRecoveryState === 'local-only';+ const token = ++nextJournalWriteToken;+ latestJournalWriteTokens.set(key, token);+ if (restoreLocalOnly) {+ commands.setLocalRecoveryState({ projectId, queueItemId: item.id, state: 'uncertain' });+ }+ pendingJournalRecords.set(key, { item, projectId, restoreLocalOnly, signature, token });+ await flushJournalRecords(key);+ return durableJournalSignatures.get(key) === signature;+ };++ const drainJournal = async (key: string): Promise<void> => {+ while (journalRecordFlushes.has(key) || journalOperations.has(key)) {+ await Promise.all([journalRecordFlushes.get(key), journalOperations.get(key)]);+ }+ };++ const releaseRunOwnership = (projectId: string, queueItemId: string): void => {+ const key = getRunKey(projectId, queueItemId);+ const lock = ownedLocks.get(key);+ if (!lock) {+ return;+ }+ ownedLocks.delete(key);+ void lock.release().catch(() => undefined);+ };++ const releaseRunOwnershipAfterJournal = (projectId: string, queueItemId: string): void => {+ const key = getRunKey(projectId, queueItemId);+ const epoch = ownershipEpochs.get(key) ?? 0;+ void drainJournal(key).finally(() => {+ if ((ownershipEpochs.get(key) ?? 0) === epoch && !pendingJournalSettles.has(key)) {+ releaseRunOwnership(projectId, queueItemId);+ }+ });+ };++ const flushFallbackAck = (key: string): Promise<void> => {+ const pending = pendingFallbackAcks.get(key);+ if (!pending || !backend.acknowledgeEnqueue || !isActive()) {+ return Promise.resolve();+ }+ if (history.getSnapshot().connectionStatus !== 'connected') {+ scheduleRetry();+ return Promise.resolve();+ }+ const active = fallbackAckOperations.get(key);+ if (active) {+ return active;+ }+ const operation = backend+ .acknowledgeEnqueue(pending.projectId, pending.queueItemId)+ .then(() => {+ if (pendingFallbackAcks.get(key) === pending) {+ pendingFallbackAcks.delete(key);+ }+ reconcileRetryDelayMs = 100;+ })+ .catch(() => scheduleRetry())+ .finally(() => {+ if (fallbackAckOperations.get(key) === operation) {+ fallbackAckOperations.delete(key);+ }+ });+ fallbackAckOperations.set(key, operation);+ return operation;+ };++ const scheduleFallbackAck = (projectId: string, queueItemId: string): void => {+ const key = getRunKey(projectId, queueItemId);+ if (!pendingFallbackAcks.has(key)) {+ pendingFallbackAcks.set(key, { projectId, queueItemId });+ }+ void flushFallbackAck(key);+ };++ const flushJournalSettle = (key: string): Promise<void> => {+ if (!journal) {+ return Promise.resolve();+ }+ const active = journalSettleFlushes.get(key);+ if (active) {+ return active;+ }+ const pending = pendingJournalSettles.get(key);+ if (!pending) {+ return Promise.resolve();+ }+ const recordFlush = journalRecordFlushes.get(key);+ const flush = enqueueJournalOperation(key, async () => {+ await recordFlush;+ let result: Awaited<ReturnType<QueueRunJournalPort['settle']>>;+ try {+ result = await journal.settle(pending.projectId, pending.queueItemId);+ } catch {+ result = { kind: 'unavailable' };+ }+ if (result.kind === 'removed') {+ if (pendingJournalSettles.get(key) === pending) {+ pendingJournalSettles.delete(key);+ }+ reconcileRetryDelayMs = 100;+ if ((ownershipEpochs.get(key) ?? 0) === pending.ownershipEpoch) {+ releaseRunOwnership(pending.projectId, pending.queueItemId);+ }+ } else {+ reportJournalFailure(pending.projectId, pending.queueItemId, result.kind);+ }+ }).finally(() => {+ if (journalSettleFlushes.get(key) === flush) {+ journalSettleFlushes.delete(key);+ }+ if (pendingJournalSettles.has(key)) {+ scheduleRetry();+ }+ });+ journalSettleFlushes.set(key, flush);+ return flush;+ };++ const settleRun = (projectId: string, queueItemId: string): void => {+ const key = getRunKey(projectId, queueItemId);+ const target = getRouteTarget(history, queueItemId);+ if (+ target?.project.id === projectId &&+ target.queueItem?.localRecoveryState === 'local-only' &&+ target.queueItem.backendItemIds?.length+ ) {+ scheduleFallbackAck(projectId, queueItemId);+ }+ trackedRuns.delete(key);+ durableJournalSignatures.delete(key);+ startedRunKeys.delete(key);+ pendingReconcileRunKeys.delete(key);+ reconcileRetryRunKeys.delete(key);+ cancelRequestedRunKeys.delete(key);+ invalidateAttempt(projectId, queueItemId);+ pendingJournalRecords.delete(key);+ const ownershipEpoch = ownershipEpochs.get(key) ?? 0;+ if (!journal) {+ releaseRunOwnership(projectId, queueItemId);+ return;+ }+ if (!pendingJournalSettles.has(key)) {+ pendingJournalSettles.set(key, { ownershipEpoch, projectId, queueItemId });+ }+ void flushJournalSettle(key);+ };++ const completeCancellation = (+ projectId: string,+ queueItemId: string,+ acceptedBackendItemIds?: readonly number[]+ ): void => {+ const target = getRouteTarget(history, queueItemId);+ if (+ acceptedBackendItemIds?.length &&+ target?.project.id === projectId &&+ target.queueItem?.localRecoveryState === 'local-only'+ ) {+ scheduleFallbackAck(projectId, queueItemId);+ }+ settleRun(projectId, queueItemId);+ if (isActive()) {+ commands.setCancellationPending({ pending: false, projectId, queueItemId });+ }+ };++ const cancelRun = (+ projectId: string,+ queueItem: QueueItem,+ backendItemIds = queueItem.backendItemIds,+ backendBatchId = queueItem.backendBatchId+ ): Promise<void> => {+ const key = getRunKey(projectId, queueItem.id);+ const active = cancellationOperations.get(key);+ if (active) {+ return active;+ }+ const cancellationItem: QueueItem = {+ ...queueItem,+ backendBatchId,+ backendItemIds,+ cancellationPending: true,+ status: 'cancelled',+ };+ cancelRequestedRunKeys.add(key);+ const operation = recordActiveRun(projectId, cancellationItem)+ .then(() => coordinator.cancelRun({ backendBatchId, backendItemIds }))+ .then(() => {+ completeCancellation(projectId, queueItem.id, backendItemIds);+ })+ .catch((error: unknown) => {+ if (isActive()) {+ commands.recordError({+ area: 'queue-cancel',+ message: toErrorMessage(error),+ namespace: 'queue',+ projectId,+ });+ reconcileRetryRunKeys.add(key);+ scheduleRetry();+ }+ })+ .finally(() => cancellationOperations.delete(key));+ cancellationOperations.set(key, operation);+ commands.setCancellationPending({ pending: true, projectId, queueItemId: queueItem.id });+ return operation;+ };++ const acquireRunOwnership = (projectId: string, queueItemId: string): Promise<boolean> => {+ const key = getRunKey(projectId, queueItemId);+ if (ownedLocks.has(key) || !locks) {+ return Promise.resolve(true);+ }+ const pending = lockRequests.get(key);+ if (pending) {+ return pending;+ }+ const request = locks+ .acquire(projectId, queueItemId)+ .then(async (result) => {+ if (!isActive()) {+ if (result.kind === 'acquired') {+ await result.release().catch(() => undefined);+ }+ return false;+ }+ if (result.kind === 'acquired') {+ ownedLocks.set(key, result);+ return true;+ }+ return result.kind === 'unavailable';+ })+ .catch(() => false)+ .finally(() => lockRequests.delete(key));+ lockRequests.set(key, request);+ return request;+ };++ interface ResultReadTask {+ execute(): Promise<void>;+ }+ const pendingResultReads: ResultReadTask[] = [];+ let resultReadFlush: Promise<void> | undefined;+ const scheduleResultReadFlush = (): void => {+ if (resultReadFlush) {+ return;+ }+ const flush = Promise.resolve().then(async () => {+ while (pendingResultReads.length > 0) {+ const batch = pendingResultReads.splice(0);+ await mapWithConcurrency(batch, QUEUE_RUNTIME_CONCURRENCY, (task) => task.execute());+ }+ });+ resultReadFlush = flush.finally(() => {+ resultReadFlush = undefined;+ });+ };+ const runResultRead = <T>(operation: () => Promise<T>): Promise<T> =>+ new Promise<T>((resolve, reject) => {+ pendingResultReads.push({+ execute: async () => {+ try {+ resolve(await operation());+ } catch (error) {+ reject(error);+ }+ },+ });+ scheduleResultReadFlush();+ });const addImagesToDestination = async (queueItem: QueueItem, imageNames: string[]): Promise<void> => {if (!isActive() || queueItem.snapshot.destination !== 'gallery') {@@ -262,8 +781,8 @@ export const createQueueRuntime = ({const options = queueItem.snapshot.filterIntermediateResults? { ...imageOptions, excludeIntermediate: true }: imageOptions;- const namesPerItem = await Promise.all(- deliverableItemIds.map((backendItemId) => backend.getResultVideoNames(backendItemId, options))+ const namesPerItem = await mapWithConcurrency(deliverableItemIds, QUEUE_RUNTIME_CONCURRENCY, (backendItemId) =>+ runResultRead(() => backend.getResultVideoNames(backendItemId, options)));// A video primitive echoes the run's INPUT video into session.results (e.g. the// source clip of an extend-video workflow) — exclude it like input images.@@ -354,7 +873,8 @@ export const createQueueRuntime = ({// pass the run's backend item ids explicitly (enqueue result / reconcile outcome /// persisted ids) — reading queueItem.backendItemIds here would always see undefined// on the fresh-submit and adopted paths.- backendItemIds: number[]+ backendItemIds: number[],+ attempt: RunAttempt): Promise<void> => {try {const allImages = await coordinator.waitForResults(@@ -363,7 +883,15 @@ export const createQueueRuntime = ({getQueueItemResultImageOptions(queueItem));- if (!isActive()) {+ if (!isAttemptCurrent(attempt)) {+ return;+ }+ const target = getRouteTarget(history, queueItem.id);+ if (+ target?.project.id !== projectId ||+ !target.queueItem ||+ (target.queueItem.status !== 'pending' && target.queueItem.status !== 'running')+ ) {return;}@@ -373,7 +901,7 @@ export const createQueueRuntime = ({// coverage for items completed in a previous session. Never throws.await addResultVideosToDestination(projectId, queueItem, backendItemIds);- if (!isActive()) {+ if (!isAttemptCurrent(attempt)) {return;}@@ -383,7 +911,7 @@ export const createQueueRuntime = ({commands.refreshBackendData();}} catch (error) {- if (!isActive()) {+ if (!isAttemptCurrent(attempt)) {return;}@@ -404,17 +932,28 @@ export const createQueueRuntime = ({const routeBackendItemResults = async (projectId: string,queueItem: QueueItem,- backendItemId: number+ backendItemId: number,+ attempt: RunAttempt): Promise<void> => {try {- const images = await backend.getResultImages(- backendItemId,- queueItem.id,- queueItem.snapshot.submittedAt,- getQueueItemResultImageOptions(queueItem)+ const images = await runResultRead(() =>+ backend.getResultImages(+ backendItemId,+ queueItem.id,+ queueItem.snapshot.submittedAt,+ getQueueItemResultImageOptions(queueItem)+ ));- if (!isActive()) {+ if (!isAttemptCurrent(attempt)) {+ return;+ }+ const target = getRouteTarget(history, queueItem.id);+ if (+ target?.project.id !== projectId ||+ !target.queueItem ||+ (target.queueItem.status !== 'pending' && target.queueItem.status !== 'running')+ ) {return;}@@ -422,7 +961,7 @@ export const createQueueRuntime = ({// Never throws — a board-attach hiccup must not block routePartialResults below.await addResultVideosToDestination(projectId, queueItem, [backendItemId]);- if (!isActive()) {+ if (!isAttemptCurrent(attempt)) {return;}@@ -436,7 +975,7 @@ export const createQueueRuntime = ({commands.refreshBackendData();}} catch (error) {- if (isActive()) {+ if (isAttemptCurrent(attempt)) {commands.recordError({area: 'queue-results',message: toErrorMessage(error),@@ -447,6 +986,43 @@ export const createQueueRuntime = ({}};+ const pendingResultRoutes = new Map<+ string,+ { attempt: RunAttempt; backendItemId: number; projectId: string; queueItem: QueueItem }+ >();+ let resultRoutingFlush: Promise<void> | undefined;+ const scheduleResultRoute = (+ projectId: string,+ queueItem: QueueItem,+ backendItemId: number,+ attempt: RunAttempt+ ): Promise<void> => {+ const key = JSON.stringify([attempt.generation, projectId, queueItem.id, backendItemId]);+ pendingResultRoutes.set(key, { attempt, backendItemId, projectId, queueItem });+ if (!resultRoutingFlush) {+ const flush = Promise.resolve().then(async () => {+ while (isActive() && pendingResultRoutes.size > 0) {+ const batch = [...pendingResultRoutes.values()];+ pendingResultRoutes.clear();+ await mapWithConcurrency(+ batch,+ QUEUE_RUNTIME_CONCURRENCY,+ ({ attempt, backendItemId, projectId, queueItem }) =>+ routeBackendItemResults(projectId, queueItem, backendItemId, attempt)+ );+ }+ });+ resultRoutingFlush = flush.finally(() => {+ resultRoutingFlush = undefined;+ });+ }+ return resultRoutingFlush;+ };++ const coordinatorBackend: QueueBackendPort = {+ ...backend,+ getResultImages: (...args) => runResultRead(() => backend.getResultImages(...args)),+ };const coordinator = createQueueCoordinator({onBackendItemCancelled: (localQueueItemId, backendItemId) => {@@ -473,11 +1049,20 @@ export const createQueueRuntime = ({const target = getRouteTarget(history, localQueueItemId);- if (!target?.queueItem || target.queueItem.completedBackendItemIds?.includes(backendItemId)) {+ if (+ !target?.queueItem ||+ target.queueItem.status === 'cancelled' ||+ target.queueItem.status === 'failed' ||+ target.queueItem.status === 'completed' ||+ target.queueItem.completedBackendItemIds?.includes(backendItemId)+ ) {return;}- return routeBackendItemResults(target.project.id, target.queueItem, backendItemId);+ const attempt = activeAttempts.get(getRunKey(target.project.id, target.queueItem.id));+ if (attempt) {+ return scheduleResultRoute(target.project.id, target.queueItem, backendItemId, attempt);+ }},onGalleryRefresh: () => {if (isActive()) {@@ -485,17 +1070,74 @@ export const createQueueRuntime = ({}},},- { backend, modelLoads, nodeExecution }+ { backend: coordinatorBackend, modelLoads, nodeExecution });- const submitQueueItem = (project: QueueHistoryProject, queueItem: QueueItem): void => {- const submission = createQueueItemBackendSubmission(project, queueItem);+ const submitQueueItem = async (+ project: QueueHistoryProject,+ queueItem: QueueItem,+ attempt: RunAttempt+ ): Promise<void> => {+ const runKey = getRunKey(project.id, queueItem.id);+ const canSubmit = (item: QueueItem): boolean =>+ shouldSubmitPendingQueueItem(item) || (item.status === 'cancelled' && cancelRequestedRunKeys.has(runKey));+ if (!(await acquireRunOwnership(project.id, queueItem.id))) {+ startedRunKeys.delete(runKey);+ reconcileRetryRunKeys.add(runKey);+ scheduleRetry();+ return;+ }+ if (!isAttemptCurrent(attempt)) {+ if (!activeAttempts.has(attempt.key)) {+ releaseRunOwnershipAfterJournal(project.id, queueItem.id);+ }+ return;+ }+ let target = getRouteTarget(history, queueItem.id);+ if (target?.project.id !== project.id || !target.queueItem || !canSubmit(target.queueItem)) {+ releaseRunOwnership(project.id, queueItem.id);+ return;+ }+ await recordActiveRun(project.id, target.queueItem);+ if (!isAttemptCurrent(attempt)) {+ return;+ }+ target = getRouteTarget(history, queueItem.id);+ if (target?.project.id !== project.id || !target.queueItem || !canSubmit(target.queueItem)) {+ settleRun(project.id, queueItem.id);+ return;+ }++ const currentQueueItem = target.queueItem;+ const projectPersistence = ensureProjectPersisted+ ? await ensureProjectPersisted(project.id).catch(() => 'retry' as const)+ : 'ready';+ if (!isAttemptCurrent(attempt)) {+ return;+ }+ if (projectPersistence === 'retry' || history.getSnapshot().connectionStatus !== 'connected') {+ startedRunKeys.delete(runKey);+ reconcileRetryRunKeys.add(runKey);+ scheduleRetry();+ return;+ }+ if (projectPersistence === 'refused') {+ settleRun(project.id, currentQueueItem.id);+ commands.setStatus({+ error: 'This run was not submitted because its project cannot be saved.',+ projectId: project.id,+ queueItemId: currentQueueItem.id,+ status: 'failed',+ });+ return;+ }+ const submission = createQueueItemBackendSubmission(project, currentQueueItem);if (submission.kind === 'invalid') {commands.setStatus({error: submission.error,projectId: project.id,- queueItemId: queueItem.id,+ queueItemId: currentQueueItem.id,status: 'failed',});return;@@ -503,66 +1145,234 @@ export const createQueueRuntime = ({const request =submission.kind === 'generate'- ? coordinator.submitGenerate(queueItem.id, submission.request)- : coordinator.submitWorkflow(queueItem.id, submission.request);+ ? coordinator.submitGenerate(currentQueueItem.id, submission.request)+ : coordinator.submitWorkflow(currentQueueItem.id, submission.request);+ submissionOperations.set(runKey, request);- request- .then(({ batchId, itemIds }) => {- if (!isActive()) {+ await request+ .then(async ({ batchId, enqueued, itemIds, requested }) => {+ if (!isAttemptCurrent(attempt)) {return;}+ const target = getRouteTarget(history, currentQueueItem.id);+ if (target?.project.id !== project.id || !target.queueItem) {+ return cancelRun(project.id, currentQueueItem, itemIds, batchId);+ }+ if (target.queueItem.status === 'cancelled') {+ return cancelRun(project.id, target.queueItem, itemIds, batchId);+ }++ if (enqueued < requested) {+ commands.recordError({+ area: 'queue-submission',+ message: `The backend queue accepted ${enqueued} of ${requested} requested items. The accepted items will continue.`,+ namespace: 'queue',+ projectId: project.id,+ });+ }+commands.markBackendSubmitted({backendBatchId: batchId,backendItemIds: itemIds,projectId: project.id,- queueItemId: queueItem.id,+ queueItemId: currentQueueItem.id,});+ const submittedTarget = getRouteTarget(history, currentQueueItem.id);+ if (submittedTarget?.project.id !== project.id || !submittedTarget.queueItem) {+ return cancelRun(project.id, currentQueueItem, itemIds, batchId);+ }+ await recordActiveRun(project.id, submittedTarget.queueItem);void backend.resumeProcessor().catch(() => undefined);- return routeRunResults(coordinator, project.id, queueItem, itemIds);+ return routeRunResults(coordinator, project.id, currentQueueItem, itemIds, attempt);}).catch((error: unknown) => {- if (isActive()) {+ if (!isAttemptCurrent(attempt)) {+ return;+ }+ if (error instanceof QueueEnqueueNotAcceptedError) {+ const target = getRouteTarget(history, currentQueueItem.id);+ if (target?.project.id === project.id && target.queueItem?.cancellationPending === true) {+ completeCancellation(project.id, currentQueueItem.id);+ } else {+ settleRun(project.id, currentQueueItem.id);+ commands.setStatus({+ error: error.message,+ projectId: project.id,+ queueItemId: currentQueueItem.id,+ status: 'failed',+ });+ }+ return;+ }+ if (+ error instanceof ApiError &&+ error.status >= 400 &&+ error.status < 500 &&+ ![408, 429].includes(error.status)+ ) {commands.setStatus({error: toErrorMessage(error),projectId: project.id,- queueItemId: queueItem.id,+ queueItemId: currentQueueItem.id,status: 'failed',});+ return;+ }+ startedRunKeys.delete(runKey);+ reconcileRetryRunKeys.add(runKey);+ scheduleRetry();+ })+ .finally(() => {+ if (submissionOperations.get(runKey) === request) {+ submissionOperations.delete(runKey);}});};+ const synchronizeRunPersistence = (): void => {+ if (!hasInitialized || !isActive()) {+ return;+ }+ const activeKeys = new Set<string>();+ const projects = history.getSnapshot().projects;+ const openProjectIds = new Set(projects.map((project) => project.id));+ for (const project of projects) {+ for (const item of project.queue.items) {+ const key = getRunKey(project.id, item.id);+ if (item.status === 'pending' || item.status === 'running') {+ activeKeys.add(key);+ if (!locks || ownedLocks.has(key) || trackedRuns.has(key)) {+ void recordActiveRun(project.id, item);+ }+ } else if (item.status === 'cancelled' && item.cancellationPending === true) {+ activeKeys.add(key);+ cancelRequestedRunKeys.add(key);+ if (trackedRuns.has(key)) {+ void recordActiveRun(project.id, item);+ if (+ history.getSnapshot().connectionStatus === 'connected' &&+ (item.backendBatchId || item.backendItemIds?.length)+ ) {+ void cancelRun(project.id, item);+ } else if (!submissionOperations.has(key) && !pendingReconcileRunKeys.has(key)) {+ pendingReconcileRunKeys.add(key);+ startedRunKeys.delete(key);+ }+ }+ } else if (trackedRuns.has(key)) {+ settleRun(project.id, item.id);+ }+ }+ }+ for (const [key, tracked] of trackedRuns) {+ if (!activeKeys.has(key)) {+ if (openProjectIds.has(tracked.projectId)) {+ settleRun(tracked.projectId, tracked.queueItemId);+ } else {+ coordinator.detachRun(tracked.queueItemId);+ trackedRuns.delete(key);+ startedRunKeys.delete(key);+ pendingReconcileRunKeys.delete(key);+ reconcileRetryRunKeys.delete(key);+ pendingJournalRecords.delete(key);+ releaseRunOwnershipAfterJournal(tracked.projectId, tracked.queueItemId);+ }+ }+ }+ for (const [key, attempt] of activeAttempts) {+ if (activeKeys.has(key)) {+ continue;+ }+ activeAttempts.delete(key);+ startedRunKeys.delete(key);+ pendingReconcileRunKeys.delete(key);+ reconcileRetryRunKeys.delete(key);+ coordinator.detachRun(attempt.queueItemId);+ if (!trackedRuns.has(key)) {+ releaseRunOwnershipAfterJournal(attempt.projectId, attempt.queueItemId);+ }+ }+ };++ const prepareActiveRuns = (): void => {+ if (!hasInitialized || !isActive()) {+ return;+ }+ const candidates = history.getSnapshot().projects.flatMap((project) =>+ project.queue.items+ .filter((item) => {+ const key = getRunKey(project.id, item.id);+ return (+ !trackedRuns.has(key) &&+ !preparingRunKeys.has(key) &&+ !reconcileRetryRunKeys.has(key) &&+ (item.status === 'pending' || item.status === 'running' || item.cancellationPending === true)+ );+ })+ .map((item) => ({ attempt: beginAttempt(project.id, item.id), item, project }))+ );+ if (candidates.length === 0) {+ return;+ }+ for (const { item, project } of candidates) {+ preparingRunKeys.add(getRunKey(project.id, item.id));+ }+ void mapWithConcurrency(candidates, QUEUE_RUNTIME_CONCURRENCY, async ({ attempt, item, project }) => {+ const key = getRunKey(project.id, item.id);+ try {+ if (!(await acquireRunOwnership(project.id, item.id))) {+ reconcileRetryRunKeys.add(key);+ scheduleRetry();+ return;+ }+ if (!isAttemptCurrent(attempt)) {+ releaseRunOwnershipAfterJournal(project.id, item.id);+ return;+ }+ const target = getRouteTarget(history, item.id);+ if (+ target?.project.id !== project.id ||+ !target.queueItem ||+ (target.queueItem.status !== 'pending' &&+ target.queueItem.status !== 'running' &&+ target.queueItem.cancellationPending !== true)+ ) {+ releaseRunOwnership(project.id, item.id);+ return;+ }+ await recordActiveRun(project.id, target.queueItem);+ } finally {+ preparingRunKeys.delete(key);+ }+ }).finally(() => {+ if (isActive()) {+ synchronize();+ }+ });+ };+const processQueueItems = (): void => {- if (!isActive() || reconcileState !== 'done') {+ if (!hasInitialized || !isActive() || history.getSnapshot().connectionStatus !== 'connected' || isReconciling) {return;}for (const project of history.getSnapshot().projects) {+ if (!loadedProjectIds.has(project.id)) {+ continue;+ }for (const queueItem of project.queue.items) {- if (shouldSubmitPendingQueueItem(queueItem) && !startedQueueItemIds.has(queueItem.id)) {- startedQueueItemIds.add(queueItem.id);- submitQueueItem(project, queueItem);- }-+ const runKey = getRunKey(project.id, queueItem.id);if (- queueItem.status === 'cancelled' &&- (queueItem.backendBatchId || queueItem.backendItemIds?.length) &&- !cancelledQueueItemIds.has(queueItem.id)+ shouldSubmitPendingQueueItem(queueItem) &&+ trackedRuns.has(runKey) &&+ !preparingRunKeys.has(runKey) &&+ !pendingReconcileRunKeys.has(runKey) &&+ !startedRunKeys.has(runKey)) {- cancelledQueueItemIds.add(queueItem.id);- coordinator- .cancelRun({ backendBatchId: queueItem.backendBatchId, backendItemIds: queueItem.backendItemIds })- .catch((error: unknown) => {- if (isActive()) {- commands.recordError({- area: 'queue-cancel',- message: toErrorMessage(error),- namespace: 'queue',- });- }- });+ startedRunKeys.add(runKey);+ void submitQueueItem(project, queueItem, beginAttempt(project.id, queueItem.id));}}}@@ -570,66 +1380,185 @@ export const createQueueRuntime = ({const reconcile = (): void => {if (+ !hasInitialized ||!isActive() ||- reconcileState !== 'idle' ||+ isReconciling ||!history.getSnapshot().isHydrated ||history.getSnapshot().connectionStatus !== 'connected') {return;}- reconcileState = 'running';const openItems = history.getSnapshot().projects.flatMap((project) =>project.queue.items- .filter((queueItem) => queueItem.status === 'pending' || queueItem.status === 'running')+ .filter(+ (queueItem) =>+ pendingReconcileRunKeys.has(getRunKey(project.id, queueItem.id)) &&+ !preparingRunKeys.has(getRunKey(project.id, queueItem.id)) &&+ !startedRunKeys.has(getRunKey(project.id, queueItem.id)) &&+ (queueItem.status === 'pending' ||+ queueItem.status === 'running' ||+ (queueItem.status === 'cancelled' && cancelRequestedRunKeys.has(getRunKey(project.id, queueItem.id))))+ ).map((queueItem) => ({ project, queueItem })));- for (const { queueItem } of openItems) {- startedQueueItemIds.add(queueItem.id);+ if (openItems.length === 0) {+ return;+ }+ isReconciling = true;+ const attempts = new Map<string, RunAttempt>();+ for (const { project, queueItem } of openItems) {+ const runKey = getRunKey(project.id, queueItem.id);+ startedRunKeys.add(runKey);+ pendingReconcileRunKeys.delete(runKey);+ attempts.set(runKey, beginAttempt(project.id, 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) => {+ mapWithConcurrency(openItems, QUEUE_RUNTIME_CONCURRENCY, async (item) => ({+ ...item,+ attempt: attempts.get(getRunKey(item.project.id, item.queueItem.id))!,+ owned: await acquireRunOwnership(item.project.id, item.queueItem.id),+ }))+ .then(async (ownership) => {+ const ownedItems = ownership.flatMap((item) => {+ if (!item.owned) {+ startedRunKeys.delete(item.attempt.key);+ reconcileRetryRunKeys.add(item.attempt.key);+ scheduleRetry();+ return [];+ }+ if (!isAttemptCurrent(item.attempt)) {+ if (!activeAttempts.has(item.attempt.key)) {+ releaseRunOwnershipAfterJournal(item.project.id, item.queueItem.id);+ }+ return [];+ }+ const target = getRouteTarget(history, item.queueItem.id);+ if (+ target?.project.id === item.project.id &&+ target.queueItem &&+ (target.queueItem.status === 'pending' ||+ target.queueItem.status === 'running' ||+ (target.queueItem.status === 'cancelled' &&+ cancelRequestedRunKeys.has(getRunKey(item.project.id, item.queueItem.id))))+ ) {+ return [{ ...item, project: target.project, queueItem: target.queueItem }];+ }+ releaseRunOwnership(item.project.id, item.queueItem.id);+ return [];+ });+ if (!isActive() || ownedItems.length === 0) {+ return { outcomes: new Map<string, ReconcileOutcome>(), ownedItems };+ }+ await mapWithConcurrency(ownedItems, QUEUE_RUNTIME_CONCURRENCY, ({ project, queueItem }) =>+ recordActiveRun(project.id, queueItem)+ );+ if (!isActive()) {+ return { outcomes: new Map<string, ReconcileOutcome>(), ownedItems: [] };+ }+ const inputs: ReconcileInput[] = ownedItems.map(({ project, queueItem }) => ({+ backendBatchId: queueItem.backendBatchId,+ backendItemIds: queueItem.backendItemIds,+ id: queueItem.id,+ projectId: project.id,+ status: queueItem.status === 'running' ? 'running' : 'pending',+ }));+ return { outcomes: await coordinator.reconcile(inputs), ownedItems };+ })+ .then(({ outcomes, ownedItems }) => {if (!isActive()) {return;}- for (const { project, queueItem } of openItems) {+ if (ownedItems.length > 0) {+ reconcileRetryDelayMs = 100;+ }+ for (const { project, queueItem } of ownedItems) {+ const attempt = attempts.get(getRunKey(project.id, queueItem.id));+ if (!attempt || !isAttemptCurrent(attempt)) {+ continue;+ }+ const target = getRouteTarget(history, queueItem.id);+ if (+ target?.project.id !== project.id ||+ !target.queueItem ||+ (target.queueItem.status !== 'pending' &&+ target.queueItem.status !== 'running' &&+ !(+ target.queueItem.status === 'cancelled' &&+ cancelRequestedRunKeys.has(getRunKey(project.id, queueItem.id))+ ))+ ) {+ settleRun(project.id, queueItem.id);+ continue;+ }+ const currentQueueItem = target.queueItem;+ const runKey = getRunKey(project.id, currentQueueItem.id);+ const cancelRequested = cancelRequestedRunKeys.has(runKey);+ reconcileRetryRunKeys.delete(runKey);const outcome = outcomes.get(queueItem.id);+ if ((outcome?.kind === 'adopted' || outcome?.kind === 'resumed') && outcome.missingBackendItemIds?.length) {+ commands.recordError({+ area: 'queue-reconciliation',+ message: `${outcome.missingBackendItemIds.length} accepted queue item${outcome.missingBackendItemIds.length === 1 ? ' is' : 's are'} no longer available. The surviving items will continue.`,+ namespace: 'queue',+ projectId: project.id,+ });+ }++ if (cancelRequested) {+ if (outcome?.kind === 'adopted') {+ void cancelRun(project.id, currentQueueItem, outcome.backendItemIds, outcome.backendBatchId);+ } else if (outcome?.kind === 'resumed') {+ void cancelRun(project.id, currentQueueItem, outcome.backendItemIds ?? currentQueueItem.backendItemIds);+ } else if (outcome?.kind === 'enqueue') {+ completeCancellation(project.id, currentQueueItem.id);+ } else if (outcome?.kind === 'missing') {+ completeCancellation(project.id, currentQueueItem.id, outcome.backendItemIds);+ }+ continue;+ }+switch (outcome?.kind) {case 'enqueue':- startedQueueItemIds.delete(queueItem.id);+ startedRunKeys.delete(runKey);break;case 'adopted':commands.markBackendSubmitted({backendBatchId: outcome.backendBatchId,backendItemIds: outcome.backendItemIds,projectId: project.id,- queueItemId: queueItem.id,+ queueItemId: currentQueueItem.id,});- void routeRunResults(coordinator, project.id, queueItem, outcome.backendItemIds);+ void routeRunResults(coordinator, project.id, currentQueueItem, outcome.backendItemIds, attempt);break;case 'resumed':- void routeRunResults(coordinator, project.id, queueItem, queueItem.backendItemIds ?? []);+ void routeRunResults(+ coordinator,+ project.id,+ currentQueueItem,+ outcome.backendItemIds ?? currentQueueItem.backendItemIds ?? [],+ attempt+ );break;case 'missing':+ if (outcome.backendItemIds?.length) {+ commands.markBackendSubmitted({+ backendBatchId: outcome.backendBatchId,+ backendItemIds: outcome.backendItemIds,+ projectId: project.id,+ queueItemId: currentQueueItem.id,+ });+ }commands.setStatus({error: 'This run is no longer on the backend queue (it may have been cleared).',notify: false,projectId: project.id,- queueItemId: queueItem.id,+ queueItemId: currentQueueItem.id,status: 'failed',});break;@@ -648,27 +1577,169 @@ export const createQueueRuntime = ({});for (const { project, queueItem } of openItems) {- if (queueItem.status === 'pending') {- startedQueueItemIds.delete(queueItem.id);+ const attempt = attempts.get(getRunKey(project.id, queueItem.id));+ if (!attempt || !isAttemptCurrent(attempt)) {+ continue;+ }+ reconcileRetryRunKeys.add(attempt.key);+ startedRunKeys.delete(attempt.key);+ }+ scheduleRetry();+ })+ .finally(() => {+ if (isActive()) {+ isReconciling = false;+ synchronize();+ }+ });+ };++ const loadProjectJournal = (projectId: string): void => {+ if (!journal) {+ loadedProjectIds.add(projectId);+ return;+ }+ loadingProjectIds.add(projectId);+ void journal+ .listForProject(projectId)+ .then((result) => {+ if (!isActive()) {+ return;+ }+ if (result.kind === 'available') {+ for (const entry of result.entries) {+ const key = getRunKey(projectId, entry.queueItemId);+ pendingReconcileRunKeys.add(key);+ const item = entry.item as Partial<QueueItem>;+ if (item.status === 'cancelled' && item.cancellationPending === true) {+ cancelRequestedRunKeys.add(key);+ }+ }+ commands.restoreFromJournal({ items: result.entries.map((entry) => entry.item), projectId });+ } else {+ reportJournalLoadFailure(projectId);+ }+ })+ .catch(() => reportJournalLoadFailure(projectId))+ .finally(() => {+ loadingProjectIds.delete(projectId);+ if (!isActive()) {+ return;+ }+ const project = history.getSnapshot().projects.find((candidate) => candidate.id === projectId);+ if (!project) {+ return;+ }+ loadedProjectIds.add(projectId);+ for (const item of project?.queue.items ?? []) {+ if (item.status === 'pending' || item.status === 'running') {+ pendingReconcileRunKeys.add(getRunKey(projectId, item.id));+ } else if (item.cancellationPending === true) {+ const key = getRunKey(projectId, item.id);+ pendingReconcileRunKeys.add(key);+ cancelRequestedRunKeys.add(key);+ }+ }+ synchronize();+ });+ };++ const discoverProjects = (): void => {+ if (!hasInitialized || !isActive()) {+ return;+ }+ const projects = history.getSnapshot().projects;+ const openProjectIds = new Set(projects.map((project) => project.id));+ for (const projectId of loadedProjectIds) {+ if (!openProjectIds.has(projectId)) {+ loadedProjectIds.delete(projectId);+ }+ }+ for (const project of projects) {+ if (!loadedProjectIds.has(project.id) && !loadingProjectIds.has(project.id)) {+ loadProjectJournal(project.id);+ }+ }+ };++ const initialize = (): void => {+ if (hasInitialized || isInitializing || !isActive() || !history.getSnapshot().isHydrated) {+ return;+ }+ isInitializing = true;+ const projectsAtStart = [...history.getSnapshot().projects];+ const initializeProjects = async (): Promise<void> => {+ if (journal) {+ for (const project of projectsAtStart) {+ const result = await journal.listForProject(project.id);+ if (!isActive()) {+ return;+ }+ if (result.kind === 'available') {+ for (const entry of result.entries) {+ const key = getRunKey(project.id, entry.queueItemId);+ pendingReconcileRunKeys.add(key);+ const item = entry.item as Partial<QueueItem>;+ if (item.status === 'cancelled' && item.cancellationPending === true) {+ cancelRequestedRunKeys.add(key);+ }+ }+ commands.restoreFromJournal({ items: result.entries.map((entry) => entry.item), projectId: project.id });} else {- commands.setStatus({- error: 'Could not reconcile this run with the backend queue after reload.',- projectId: project.id,- queueItemId: queueItem.id,- status: 'failed',- });+ reportJournalLoadFailure(project.id);+ }+ }+ }+ if (!isActive()) {+ return;+ }+ for (const project of projectsAtStart) {+ loadedProjectIds.add(project.id);+ for (const item of project.queue.items) {+ if (item.status === 'pending' || item.status === 'running' || item.cancellationPending === true) {+ const key = getRunKey(project.id, item.id);+ pendingReconcileRunKeys.add(key);+ if (item.cancellationPending === true) {+ cancelRequestedRunKeys.add(key);+ }+ }+ }+ }+ hasInitialized = true;+ };+ void initializeProjects()+ .catch(() => {+ if (!isActive()) {+ return;+ }+ reportJournalLoadFailure();+ for (const project of projectsAtStart) {+ loadedProjectIds.add(project.id);+ for (const item of project.queue.items) {+ if (item.status === 'pending' || item.status === 'running' || item.cancellationPending === true) {+ const key = getRunKey(project.id, item.id);+ pendingReconcileRunKeys.add(key);+ if (item.cancellationPending === true) {+ cancelRequestedRunKeys.add(key);+ }+ }}}+ hasInitialized = true;}).finally(() => {+ isInitializing = false;if (isActive()) {- reconcileState = 'done';- processQueueItems();+ synchronize();}});};const synchronize = (): void => {+ initialize();+ discoverProjects();+ prepareActiveRuns();+ synchronizeRunPersistence();reconcile();processQueueItems();};@@ -689,22 +1760,68 @@ export const createQueueRuntime = ({}commands.setConnectionStatus({ error, status });+ if (status === 'connected') {+ for (const runKey of reconcileRetryRunKeys) {+ reconcileRetryRunKeys.delete(runKey);+ startedRunKeys.delete(runKey);+ pendingReconcileRunKeys.add(runKey);+ }+ for (const runKey of pendingFallbackAcks.keys()) {+ void flushFallbackAck(runKey);+ }+ }synchronize();}));synchronize();};- const dispose = (): void => {+ const dispose = async (): Promise<void> => {isDisposed = true;+ if (retryTimer !== undefined) {+ clearTimeout(retryTimer);+ retryTimer = undefined;+ }for (const detach of detachers.splice(0)) {detach();}- startedQueueItemIds.clear();- cancelledQueueItemIds.clear();coordinator.dispose();+ pendingResultRoutes.clear();+ await resultRoutingFlush?.catch(() => undefined);+ await resultReadFlush?.catch(() => undefined);+ await Promise.all(+ [...cancellationOperations.values(), ...submissionOperations.values(), ...lockRequests.values()].map(+ (operation) => operation.catch(() => undefined)+ )+ );+ while (journalRecordFlushes.size > 0 || journalOperations.size > 0 || pendingJournalRecords.size > 0) {+ for (const key of pendingJournalRecords.keys()) {+ void flushJournalRecords(key);+ }+ await Promise.all(+ [...journalRecordFlushes.values(), ...journalOperations.values()].map((operation) =>+ operation.catch(() => undefined)+ )+ );+ }+ startedRunKeys.clear();+ preparingRunKeys.clear();+ pendingJournalSettles.clear();+ journalSettleFlushes.clear();+ pendingFallbackAcks.clear();+ fallbackAckOperations.clear();+ reconcileRetryRunKeys.clear();+ pendingReconcileRunKeys.clear();+ trackedRuns.clear();+ activeAttempts.clear();+ ownershipEpochs.clear();+ latestJournalWriteTokens.clear();+ for (const [key, lock] of ownedLocks) {+ ownedLocks.delete(key);+ await lock.release().catch(() => undefined);+ }};return { dispose, start };diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.tsindex 7be105bd1a..ec72e7a09e 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts@@ -1,5 +1,6 @@import type {QueueBackendItem,+ QueueEnqueueResult,QueueEnqueueGenerateRequest,QueueItemProgress,QueueResultImage,@@ -19,6 +20,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {createQueueCoordinator,+ QueueEnqueueNotAcceptedError,QueueItemCancelledError,type QueueCoordinator,type QueueCoordinatorBackendPort,@@ -154,8 +156,11 @@ const generateRequest: QueueEnqueueGenerateRequest = {interface Harness {activeProgressTarget: { clear: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };api: {- [Key in Exclude<keyof QueueCoordinatorBackendPort, 'emit' | 'on' | 'onConnectionChange'>]: ReturnType<typeof vi.fn>;- };+ [Key in Exclude<+ keyof QueueCoordinatorBackendPort,+ 'emit' | 'on' | 'onConnectionChange' | 'getEnqueueReceipt'+ >]: ReturnType<typeof vi.fn>;+ } & { getEnqueueReceipt?: ReturnType<typeof vi.fn> };callbacks: { [Key in keyof QueueCoordinatorCallbacks]: ReturnType<typeof vi.fn> };coordinator: QueueCoordinator;hub: ReturnType<typeof createSocketHub>;@@ -181,6 +186,9 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Har},};const api = {+ getEnqueueReceipt: undefined as+ | ReturnType<typeof vi.fn<(projectId: string, queueItemId: string) => Promise<QueueEnqueueResult | null>>>+ | undefined,cancelQueueItems: vi.fn(() => Promise.resolve()),cancelQueueItemsByBatchIds: vi.fn(() => Promise.resolve()),enqueueGenerate: vi.fn(() => Promise.resolve({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })),@@ -216,6 +224,9 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Harconst coordinator = createQueueCoordinator(callbacks, {backend: {...api,+ get getEnqueueReceipt() {+ return api.getEnqueueReceipt;+ },emit: hub.emit,on: hub.on,onConnectionChange: hub.onConnectionChange,@@ -435,17 +446,20 @@ describe('queueCoordinator', () => {it('rejects runs when the backend queue accepts no items', async () => {harness.api.enqueueGenerate.mockResolvedValue({ batchId: 'batch-1', enqueued: 0, itemIds: [], requested: 1 });- await expect(harness.coordinator.submitGenerate('local-1', generateRequest)).rejects.toThrow(- 'The backend queue did not accept this generation.'+ await expect(harness.coordinator.submitGenerate('local-1', generateRequest)).rejects.toBeInstanceOf(+ QueueEnqueueNotAcceptedError);});- it('rejects runs when the backend queue accepts only part of the batch', async () => {+ it('tracks every item when the backend queue accepts only part of the batch', async () => {harness.api.enqueueGenerate.mockResolvedValue({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 2 });- await expect(harness.coordinator.submitGenerate('local-1', generateRequest)).rejects.toThrow(- 'The backend queue accepted 1 of 2 requested items.'- );+ await expect(harness.coordinator.submitGenerate('local-1', generateRequest)).resolves.toEqual({+ batchId: 'batch-1',+ enqueued: 1,+ itemIds: [1],+ requested: 2,+ });});it('coalesces gallery refreshes across a burst of completions', async () => {@@ -523,6 +537,26 @@ describe('queueCoordinator', () => {expect(harness.progressImage.clear).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });});+ it('detaches one local run without disturbing another', async () => {+ harness.coordinator.connect();+ harness.api.enqueueGenerate+ .mockResolvedValueOnce({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })+ .mockResolvedValueOnce({ batchId: 'batch-2', enqueued: 1, itemIds: [2], requested: 1 });+ await harness.coordinator.submitGenerate('local-1', generateRequest);+ await harness.coordinator.submitGenerate('local-2', { ...generateRequest, sourceQueueItemId: 'local-2' });+ const detachedResults = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');+ const survivingResults = harness.coordinator.waitForResults('local-2', '2026-06-10T00:00:00Z');++ harness.coordinator.detachRun('local-1');++ await expect(detachedResults).rejects.toBeInstanceOf(QueueItemCancelledError);+ expect(harness.progressImage.clear).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });+ expect(harness.progressImage.clear).not.toHaveBeenCalledWith();++ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 2, status: 'completed' }));+ await expect(survivingResults).resolves.toEqual([expect.objectContaining({ imageName: 'image-2.png' })]);+ });+it('publishes the active target before a progress image is available', async () => {harness.coordinator.connect();await harness.coordinator.submitGenerate('local-1', generateRequest);@@ -802,6 +836,46 @@ describe('queueCoordinator', () => {});describe('reconcile', () => {+ it('looks up the exact receipt for pending runs without downloading queue history', async () => {+ harness.api.getEnqueueReceipt = vi.fn().mockResolvedValue({+ batchId: 'batch-9',+ enqueued: 1,+ itemIds: [7],+ requested: 1,+ });+ harness.api.getItem.mockResolvedValue(+ createQueueBackendItem({ batchId: 'batch-9', id: 7, origin: buildQueueItemOrigin('local-1', 'project-1') })+ );++ const outcomes = await harness.coordinator.reconcile([+ { id: 'local-1', projectId: 'project-1', status: 'pending' },+ ]);++ expect(harness.api.getEnqueueReceipt).toHaveBeenCalledWith('project-1', 'local-1');+ expect(harness.api.listItems).not.toHaveBeenCalled();+ expect(outcomes.get('local-1')).toEqual({ backendBatchId: 'batch-9', backendItemIds: [7], kind: 'adopted' });+ });++ it('does not resubmit an accepted run whose backend items were cleared', async () => {+ harness.api.getEnqueueReceipt = vi.fn().mockResolvedValue({+ batchId: 'batch-9',+ enqueued: 1,+ itemIds: [7],+ requested: 1,+ });+ harness.api.getItem.mockRejectedValue(new ApiError('not found', 404));++ const outcomes = await harness.coordinator.reconcile([+ { id: 'local-1', projectId: 'project-1', status: 'pending' },+ ]);++ expect(outcomes.get('local-1')).toEqual({+ backendBatchId: 'batch-9',+ backendItemIds: [7],+ kind: 'missing',+ });+ expect(harness.api.listItems).not.toHaveBeenCalled();+ });it('adopts pending items the backend already accepted, by origin', async () => {harness.api.listItems.mockResolvedValue([createQueueBackendItem({ batchId: 'batch-9', id: 7, origin: buildQueueItemOrigin('local-1') }),@@ -814,7 +888,9 @@ describe('queueCoordinator', () => {});it('resumes running items and settles them from their listed terminal status', async () => {- harness.api.getItem.mockResolvedValue(createQueueBackendItem({ id: 7, status: 'completed' }));+ harness.api.getItem.mockResolvedValue(+ createQueueBackendItem({ id: 7, origin: buildQueueItemOrigin('local-1'), status: 'completed' })+ );const outcomes = await harness.coordinator.reconcile([{ backendItemIds: [7], id: 'local-1', status: 'running' }]);@@ -826,15 +902,93 @@ describe('queueCoordinator', () => {expect(images.map((image) => image.imageName)).toEqual(['image-7.png']);});+ it('bounds backend reads while reconciling and collecting a large run', async () => {+ const backendItemIds = Array.from({ length: 64 }, (_, index) => index + 1);+ let activeItemReads = 0;+ let maxItemReads = 0;+ let activeResultReads = 0;+ let maxResultReads = 0;+ harness.api.getItem.mockImplementation(async (itemId: number) => {+ activeItemReads += 1;+ maxItemReads = Math.max(maxItemReads, activeItemReads);+ await new Promise((resolve) => {+ setTimeout(resolve, 1);+ });+ activeItemReads -= 1;+ return createQueueBackendItem({+ id: itemId,+ origin: buildQueueItemOrigin('local-1', 'project-1'),+ status: 'completed',+ });+ });+ harness.api.getResultImages.mockImplementation(async (itemId: number, sourceQueueItemId: string) => {+ activeResultReads += 1;+ maxResultReads = Math.max(maxResultReads, activeResultReads);+ await new Promise((resolve) => {+ setTimeout(resolve, 1);+ });+ activeResultReads -= 1;+ return [createImage(`image-${itemId}.png`, sourceQueueItemId)];+ });++ await harness.coordinator.reconcile([+ { backendItemIds, id: 'local-1', projectId: 'project-1', status: 'running' },+ ]);+ const images = await harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');++ expect(images).toHaveLength(64);+ expect(maxItemReads).toBeLessThanOrEqual(16);+ expect(maxResultReads).toBeLessThanOrEqual(16);+ });++ it('never adopts persisted backend ids from another project or local run', async () => {+ harness.api.getItem.mockResolvedValue(+ createQueueBackendItem({ id: 7, origin: buildQueueItemOrigin('other-local', 'other-project') })+ );++ const outcomes = await harness.coordinator.reconcile([+ { backendItemIds: [7], id: 'local-1', projectId: 'project-1', status: 'running' },+ ]);++ expect(outcomes.get('local-1')).toEqual({ backendItemIds: [7], kind: 'missing' });+ });+it('marks running items missing when their backend items vanished', async () => {harness.api.getItem.mockRejectedValue(new ApiError('not found', 404));const outcomes = await harness.coordinator.reconcile([{ backendItemIds: [7], id: 'local-1', status: 'running' }]);- expect(outcomes.get('local-1')).toEqual({ kind: 'missing' });+ expect(outcomes.get('local-1')).toEqual({ backendItemIds: [7], kind: 'missing' });expect(harness.api.listItems).not.toHaveBeenCalled();});+ it('resumes the surviving items when part of an accepted batch was pruned', async () => {+ harness.api.getItem.mockImplementation((itemId: number) =>+ itemId === 7+ ? Promise.reject(new ApiError('not found', 404))+ : Promise.resolve(+ createQueueBackendItem({+ id: itemId,+ origin: buildQueueItemOrigin('local-1', 'project-1'),+ status: 'completed',+ })+ )+ );++ const outcomes = await harness.coordinator.reconcile([+ { backendItemIds: [7, 8], id: 'local-1', projectId: 'project-1', status: 'running' },+ ]);++ expect(outcomes.get('local-1')).toEqual({+ backendItemIds: [8],+ kind: 'resumed',+ missingBackendItemIds: [7],+ });+ await expect(harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z')).resolves.toEqual([+ expect.objectContaining({ imageName: 'image-8.png' }),+ ]);+ });+it('asks for a fresh enqueue when a pending item left no backend trace', async () => {harness.api.listItems.mockResolvedValue([]);@@ -908,15 +1062,15 @@ describe('queueCoordinator', () => {await expect(resultsPromise).rejects.toThrow('no longer on the backend queue');});- it('prefers precise item ids for cancellation, falling back to batch id', async () => {+ it('prefers one batch cancellation request, falling back to item ids', async () => {await harness.coordinator.cancelRun({ backendBatchId: 'batch-1', backendItemIds: [1, 2] });- expect(harness.api.cancelQueueItems).toHaveBeenCalledWith([1, 2]);- expect(harness.api.cancelQueueItemsByBatchIds).not.toHaveBeenCalled();+ expect(harness.api.cancelQueueItemsByBatchIds).toHaveBeenCalledWith(['batch-1']);+ expect(harness.api.cancelQueueItems).not.toHaveBeenCalled();- await harness.coordinator.cancelRun({ backendBatchId: 'batch-2' });+ await harness.coordinator.cancelRun({ backendItemIds: [1, 2] });- expect(harness.api.cancelQueueItemsByBatchIds).toHaveBeenCalledWith(['batch-2']);+ expect(harness.api.cancelQueueItems).toHaveBeenCalledWith([1, 2]);});it('treats stale missing backend items as already cancelled', async () => {diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.tsindex 07182c09a3..5504f33666 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts@@ -17,6 +17,7 @@ import {import {isTerminalBackendStatus,parseQueueItemOrigin,+ parseQueueItemOriginProjectId,type InvocationCompleteEvent,type InvocationErrorEvent,type InvocationProgressEvent,@@ -30,12 +31,14 @@ import {type ProgressImageTarget,} from '@features/queue/data/progressImageStore';import { queueItemProgressStore, type QueueItemProgressSink } from '@features/queue/data/progressStore';+import { mapWithConcurrency } from '@platform/core/concurrency';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';const GALLERY_REFRESH_COALESCE_MS = 400;const SAFETY_SWEEP_INTERVAL_MS = 30_000;const TERMINAL_EVENT_BUFFER_LIMIT = 256;+const BACKEND_READ_CONCURRENCY = 16;/*** Queue's view of model-load activity derived from socket events. The@@ -65,6 +68,7 @@ export type QueueCoordinatorBackendPort = Pick<| 'enqueueGenerate'| 'enqueueWorkflow'| 'getItem'+ | 'getEnqueueReceipt'| 'getResultImages'| 'listItems'| 'on'@@ -90,8 +94,17 @@ export class QueueItemCancelledError extends Error {}}+/** Thrown when an enqueue response definitively reports zero accepted items. */+export class QueueEnqueueNotAcceptedError extends Error {+ constructor(workKind: 'generation' | 'workflow') {+ super(`The backend queue did not accept this ${workKind}. The queue may be full.`);+ this.name = 'QueueEnqueueNotAcceptedError';+ }+}+export interface ReconcileInput {id: string;+ projectId?: string;status: 'pending' | 'running';backendItemIds?: number[];backendBatchId?: string;@@ -99,11 +112,11 @@ export interface ReconcileInput {export type ReconcileOutcome =/** A pending item the backend already accepted before the reload; do not re-enqueue. */- | { kind: 'adopted'; backendItemIds: number[]; backendBatchId?: string }+ | { kind: 'adopted'; backendItemIds: number[]; backendBatchId?: string; missingBackendItemIds?: number[] }/** A running item whose backend items were found again; its results are awaitable. */- | { kind: 'resumed' }+ | { kind: 'resumed'; backendItemIds?: number[]; missingBackendItemIds?: number[] }/** A running item whose backend items no longer exist (queue cleared or pruned). */- | { kind: 'missing' }+ | { kind: 'missing'; backendItemIds?: number[]; backendBatchId?: string }/** A pending item the backend has never seen; submit it normally. */| { kind: 'enqueue' };@@ -114,6 +127,7 @@ export interface CancelRunRequest {export interface QueueCoordinator {connect(): void;+ detachRun(localQueueItemId: string): void;dispose(): void;/*** Match persisted pending/running queue items against the live backend queue@@ -622,22 +636,32 @@ export const createQueueCoordinator = (return outcomes;}- const backendItems = items.every((item) => item.backendItemIds?.length)+ const resolvedItems = await mapWithConcurrency(items, BACKEND_READ_CONCURRENCY, async (item) => {+ if (item.backendItemIds?.length || !item.projectId || !backend.getEnqueueReceipt) {+ return item;+ }+ const receipt = await backend.getEnqueueReceipt(item.projectId, item.id);+ return receipt ? { ...item, backendBatchId: receipt.batchId, backendItemIds: receipt.itemIds } : item;+ });+ const canReadExactItems = resolvedItems.every(+ (item) => item.backendItemIds?.length || (item.projectId && backend.getEnqueueReceipt)+ );+ const backendItems = canReadExactItems? (- await Promise.all(- items- .flatMap((item) => item.backendItemIds ?? [])- .map(async (itemId) => {- try {- return await backend.getItem(itemId);- } catch (error) {- if (error instanceof ApiError && error.status === 404) {- return undefined;- }-- throw error;+ await mapWithConcurrency(+ [...new Set(resolvedItems.flatMap((item) => item.backendItemIds ?? []))],+ BACKEND_READ_CONCURRENCY,+ async (itemId) => {+ try {+ return await backend.getItem(itemId);+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) {+ return undefined;}- })++ throw error;+ }+ })).filter((item) => item !== undefined): await backend.listItems();@@ -647,30 +671,34 @@ export const createQueueCoordinator = (}const backendItemsById = new Map(backendItems.map((item) => [item.id, item]));- const backendItemsByLocalId = new Map<string, QueueBackendItem[]>();- for (const backendItem of backendItems) {- const localQueueItemId = parseQueueItemOrigin(backendItem.origin);-- if (localQueueItemId) {- backendItemsByLocalId.set(localQueueItemId, [- ...(backendItemsByLocalId.get(localQueueItemId) ?? []),- backendItem,- ]);- }- }-- for (const item of items) {+ for (const item of resolvedItems) {+ const matchesIdentity = (backendItem: QueueBackendItem | undefined): backendItem is QueueBackendItem =>+ backendItem !== undefined &&+ parseQueueItemOrigin(backendItem.origin) === item.id &&+ (item.projectId === undefined || parseQueueItemOriginProjectId(backendItem.origin) === item.projectId);const knownBackendItems = item.backendItemIds?.length? item.backendItemIds.map((backendItemId) => backendItemsById.get(backendItemId))- : (backendItemsByLocalId.get(item.id) ?? []);- const foundBackendItems = knownBackendItems.filter((backendItem) => backendItem !== undefined);+ : backendItems.filter(matchesIdentity);+ const foundBackendItems = knownBackendItems.filter(matchesIdentity);+ const missingBackendItemIds = item.backendItemIds?.filter(+ (_backendItemId, index) => !matchesIdentity(knownBackendItems[index])+ );- if (foundBackendItems.length !== knownBackendItems.length || foundBackendItems.length === 0) {+ if (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' });+ outcomes.set(+ item.id,+ item.status === 'pending' && !item.backendItemIds?.length+ ? { kind: 'enqueue' }+ : {+ ...(item.backendBatchId ? { backendBatchId: item.backendBatchId } : {}),+ ...(item.backendItemIds?.length ? { backendItemIds: item.backendItemIds } : {}),+ kind: 'missing',+ }+ );continue;}@@ -685,25 +713,31 @@ export const createQueueCoordinator = (outcomes.set(item.id,- item.status === 'running' ? { kind: 'resumed' } : { backendBatchId, backendItemIds, kind: 'adopted' }+ item.status === 'running'+ ? {+ kind: 'resumed',+ ...(missingBackendItemIds?.length ? { backendItemIds, missingBackendItemIds } : {}),+ }+ : {+ backendBatchId,+ backendItemIds,+ kind: 'adopted',+ ...(missingBackendItemIds?.length ? { missingBackendItemIds } : {}),+ });}return outcomes;};- /** Reject partial acceptance and start tracking the accepted backend items. */+ /** Start tracking the accepted backend items. */const adoptEnqueueResult = (localQueueItemId: string,result: QueueEnqueueResult,workKind: 'generation' | 'workflow'): QueueEnqueueResult => {if (result.enqueued === 0) {- throw new Error(`The backend queue did not accept this ${workKind}. The queue may be full.`);- }-- if (result.requested !== result.enqueued) {- throw new Error(`The backend queue accepted ${result.enqueued} of ${result.requested} requested items.`);+ throw new QueueEnqueueNotAcceptedError(workKind);}beginRun(localQueueItemId, result.itemIds, result.batchId);@@ -764,12 +798,13 @@ export const createQueueCoordinator = (throw new QueueItemCancelledError(localQueueItemId);}- const imagesPerItem = await Promise.all(- completedBackendItemIds.map((backendItemId) =>+ const imagesPerItem = await mapWithConcurrency(+ completedBackendItemIds,+ BACKEND_READ_CONCURRENCY,+ (backendItemId) =>options? backend.getResultImages(backendItemId, localQueueItemId, queuedAt, options): backend.getResultImages(backendItemId, localQueueItemId, queuedAt)- ));return imagesPerItem.flat();@@ -784,13 +819,13 @@ export const createQueueCoordinator = (const cancelRun = async ({ backendBatchId, backendItemIds }: CancelRunRequest): Promise<void> => {try {- if (backendItemIds?.length) {- await backend.cancelQueueItems(backendItemIds);+ if (backendBatchId) {+ await backend.cancelQueueItemsByBatchIds([backendBatchId]);return;}- if (backendBatchId) {- await backend.cancelQueueItemsByBatchIds([backendBatchId]);+ if (backendItemIds?.length) {+ await backend.cancelQueueItems(backendItemIds);}} catch (error) {if (error instanceof ApiError && error.status === 404) {@@ -801,5 +836,24 @@ export const createQueueCoordinator = (}};- return { cancelRun, connect, dispose, reconcile, submitGenerate, submitWorkflow, waitForResults };+ const detachRun = (localQueueItemId: string): void => {+ const run = runs.get(localQueueItemId);+ for (const backendItemId of run?.backendItemIds ?? []) {+ const wait = waits.get(backendItemId);+ if (wait?.localQueueItemId === localQueueItemId) {+ waits.delete(backendItemId);+ wait.settle({ status: 'canceled' });+ }+ }+ runs.delete(localQueueItemId);+ runProgress.delete(localQueueItemId);+ for (let itemIndex = 1; itemIndex <= (run?.backendItemIds.length ?? 0); itemIndex += 1) {+ const target = { itemIndex, queueItemId: localQueueItemId };+ activeProgressTarget.clear(target);+ progressImage.clear(target);+ }+ progress.clear(localQueueItemId);+ };++ return { cancelRun, connect, detachRun, dispose, reconcile, submitGenerate, submitWorkflow, waitForResults };};diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/receiptAcknowledgements.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/receiptAcknowledgements.test.tsnew file mode 100644index 0000000000..5a751088e7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/runtime/receiptAcknowledgements.test.ts@@ -0,0 +1,62 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createQueueReceiptAcknowledgements } from './receiptAcknowledgements';++afterEach(() => vi.useRealTimers());++describe('queue receipt acknowledgements', () => {+ it('retains failed cleanup and retries without needing an active queue run', async () => {+ vi.useFakeTimers();+ const receipt = { projectId: 'project-1', queueItemId: 'run-1' };+ let pending = [receipt];+ const acknowledge = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(undefined);+ const remove = vi.fn(() => {+ pending = [];+ return Promise.resolve({ kind: 'removed' as const });+ });+ const worker = createQueueReceiptAcknowledgements({+ acknowledge,+ isActive: () => true,+ store: {+ acknowledgeReceipt: remove,+ listPendingReceipts: () => Promise.resolve({ kind: 'available', entries: pending }),+ },+ });++ await worker.flush();+ expect(remove).not.toHaveBeenCalled();+ await worker.flush();+ await worker.flush();+ expect(acknowledge).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(acknowledge).toHaveBeenCalledTimes(2);+ expect(remove).toHaveBeenCalledWith('project-1', 'run-1');+ worker.dispose();+ });++ it('does not mutate storage after its owner is disposed during acknowledgement', async () => {+ let finish!: () => void;+ const acknowledge = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const remove = vi.fn();+ const worker = createQueueReceiptAcknowledgements({+ acknowledge,+ isActive: () => true,+ store: {+ acknowledgeReceipt: remove,+ listPendingReceipts: () =>+ Promise.resolve({ kind: 'available', entries: [{ projectId: 'p', queueItemId: 'q' }] }),+ },+ });+ const flushing = worker.flush();+ await vi.waitFor(() => expect(acknowledge).toHaveBeenCalledOnce());+ worker.dispose();+ finish();+ await flushing;+ expect(remove).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/receiptAcknowledgements.ts b/invokeai/frontend/webv2/src/features/queue/runtime/receiptAcknowledgements.tsnew file mode 100644index 0000000000..b3c9a18bb2--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/runtime/receiptAcknowledgements.ts@@ -0,0 +1,101 @@+import { mapWithConcurrency } from '@platform/core/concurrency';++export interface QueueReceiptStorePort {+ acknowledgeReceipt(projectId: string, queueItemId: string): Promise<{ kind: 'removed' | 'unavailable' }>;+ listPendingReceipts(): Promise<+ { entries: Array<{ projectId: string; queueItemId: string }>; kind: 'available' } | { kind: 'unavailable' }+ >;+}++export const createQueueReceiptAcknowledgements = ({+ acknowledge,+ isActive,+ store,+}: {+ acknowledge(projectId: string, queueItemId: string): Promise<void>;+ isActive(): boolean;+ store: QueueReceiptStorePort;+}) => {+ let disposed = false;+ let pending: Promise<void> | undefined;+ let requested = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let delayMs = 1_000;+ const active = () => !disposed && isActive();++ const retry = (): void => {+ if (timer !== undefined || !active()) {+ return;+ }+ timer = setTimeout(() => {+ timer = undefined;+ void flush();+ }, delayMs);+ delayMs = Math.min(delayMs * 2, 30_000);+ };++ const drain = async (): Promise<void> => {+ while (active()) {+ requested = false;+ const result = await store.listPendingReceipts();+ if (!active()) {+ return;+ }+ if (result.kind !== 'available') {+ retry();+ return;+ }+ if (result.entries.length === 0) {+ delayMs = 1_000;+ return;+ }+ const results = await mapWithConcurrency(result.entries, 8, async (entry) => {+ if (!active()) {+ return false;+ }+ try {+ await acknowledge(entry.projectId, entry.queueItemId);+ return active() && (await store.acknowledgeReceipt(entry.projectId, entry.queueItemId)).kind === 'removed';+ } catch {+ return false;+ }+ });+ if (results.some((removed) => !removed)) {+ retry();+ return;+ }+ }+ };++ const flush = (): Promise<void> => {+ if (!active()) {+ return Promise.resolve();+ }+ requested = true;+ if (pending) {+ return pending;+ }+ if (timer !== undefined) {+ return Promise.resolve();+ }+ pending = drain()+ .catch(retry)+ .finally(() => {+ pending = undefined;+ if (requested && timer === undefined && active()) {+ void flush();+ }+ });+ return pending;+ };++ return {+ dispose() {+ disposed = true;+ if (timer !== undefined) {+ clearTimeout(timer);+ }+ },+ flush,+ };+};diff --git a/invokeai/frontend/webv2/src/platform/browser/webLocks.ts b/invokeai/frontend/webv2/src/platform/browser/webLocks.tsindex 75d939d210..40fcba5991 100644--- a/invokeai/frontend/webv2/src/platform/browser/webLocks.ts+++ b/invokeai/frontend/webv2/src/platform/browser/webLocks.ts@@ -1,8 +1,13 @@-export type ExclusiveLockResult =+export type BrowserLockResult =| { kind: 'acquired'; release(): Promise<void> }- | { kind: 'contended' | 'unavailable' };+ | { kind: 'contended' }+ | { kind: 'unavailable' };-export const acquireExclusiveLock = (name: string, lockManager?: LockManager): Promise<ExclusiveLockResult> => {+const acquireLock = (+ name: string,+ mode: 'exclusive' | 'shared',+ lockManager?: LockManager+): Promise<BrowserLockResult> => {let manager = lockManager;if (!manager) {try {@@ -25,7 +30,7 @@ export const acquireExclusiveLock = (name: string, lockManager?: LockManager): Ptry {let request: Promise<void>;request = manager- .request(name, { ifAvailable: true, mode: 'exclusive' }, async (lock) => {+ .request(name, { ifAvailable: true, mode }, async (lock) => {if (!lock) {didResolve = true;resolve({ kind: 'contended' });@@ -57,3 +62,11 @@ export const acquireExclusiveLock = (name: string, lockManager?: LockManager): P}});};++export type ExclusiveLockResult = BrowserLockResult;++export const acquireExclusiveLock = (name: string, lockManager?: LockManager): Promise<BrowserLockResult> =>+ acquireLock(name, 'exclusive', lockManager);++export const acquireSharedLock = (name: string, lockManager?: LockManager): Promise<BrowserLockResult> =>+ acquireLock(name, 'shared', lockManager);diff --git a/invokeai/frontend/webv2/src/workbench/components/WorkbenchUnavailableScreen.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/components/WorkbenchUnavailableScreen.browser.test.tsxindex d71355c369..00ed7efd76 100644--- a/invokeai/frontend/webv2/src/workbench/components/WorkbenchUnavailableScreen.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/WorkbenchUnavailableScreen.browser.test.tsx@@ -27,6 +27,9 @@ const harness = vi.hoisted(() => ({),}));vi.mock('@platform/browser/downloadBlob', () => ({ downloadText: harness.downloadText }));+vi.mock('@workbench/queue-integration/QueueRecoveryNotice', () => ({+ QueueRecoveryNotice: () => <div data-testid="queue-recovery-notice">queue recovery</div>,+}));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));import { WorkbenchUnavailableScreen } from './WorkbenchUnavailableScreen';@@ -91,6 +94,7 @@ describe('WorkbenchUnavailableScreen', () => {expect(onRetry).toHaveBeenCalledOnce();expect(harness.downloadText).toHaveBeenCalledWith('{"id":"project-1"}', 'project-1.json', 'application/json');+ expect(document.querySelector('[data-testid="queue-recovery-notice"]')).not.toBeNull();});it('does not misreport inaccessible recovery storage as an empty draft list', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/components/WorkbenchUnavailableScreen.tsx b/invokeai/frontend/webv2/src/workbench/components/WorkbenchUnavailableScreen.tsxindex 5635f37f54..0ae3b38812 100644--- a/invokeai/frontend/webv2/src/workbench/components/WorkbenchUnavailableScreen.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/WorkbenchUnavailableScreen.tsx@@ -3,6 +3,7 @@ import type { RecoverableProjectDraft, SyncedWorkbenchPersistence } from '@workbimport { Alert, Box, Button, Flex, Heading, HStack, Spinner, Stack, Text } from '@chakra-ui/react';import { downloadText } from '@platform/browser/downloadBlob';import { useMountEffect } from '@platform/react/useMountEffect';+import { QueueRecoveryNotice } from '@workbench/queue-integration/QueueRecoveryNotice';import { useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -149,6 +150,7 @@ export const WorkbenchUnavailableScreen = ({</Button>) : null}</Stack>+ <QueueRecoveryNotice /></Stack></Box></Flex>diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.mdnew file mode 100644index 0000000000..44dd30a151--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md@@ -0,0 +1,24 @@+# Project persistence++The backend project record is authoritative. Writes use `expected_revision`; a divergent revision or remotely deleted project requires an explicit user decision. Editing can continue while that decision is pending. Saving a copy reuses one reserved identity through `createProjectSettled`, including after a lost response.++`ProjectDocumentV2` allowlists editable document fields. Queue runs, events, graph history, and undo are not project documents. Documents are limited to 32 MiB of UTF-8 JSON on both sides of the API. The workflow library is the durable home for saved workflows; undo and capped events are session-only.++## Browser recovery++- Account-owned IndexedDB stores only unacknowledged project drafts, active queue runs, receipt acknowledgements, and bounded recall values. Clean server documents are not mirrored.+- Draft generations fence acknowledgements. Draft writer ownership and cross-tab notifications prevent one editor from overwriting another editor's unacknowledged work.+- Queue ownership uses Web Locks. Journal writes precede submission; backend receipts make retries safe after lost responses. Accepted IDs must be durable before their receipt can expire. Fresh runs that never reached browser storage use best-effort terminal acknowledgement instead.+- Completed, failed, and cancelled runs retain exact recall values in an LRU cache, capped at 500 entries / 32 MiB. Eviction removes recall convenience, not project data or active-run recovery.+- Projects with journal entries remain reachable even if another tab saved an empty session. Automatic reopening is bounded; remaining entries can be opened, exported as queue-recovery JSON, or explicitly discarded. Discarding local recovery does not cancel backend work.+- Browser-storage failures do not block backend project loads or saves. Recovery warnings distinguish degraded local durability from successful server persistence.++## Intentional cutover++The old workbench mirror, sync map, and refused-project localStorage keys are deleted on initialization. Their contents are not migrated. Export any needed browser-only work with the old build before upgrading.++Cold-start offline editing is not supported. When the backend cannot load, the unavailable screen provides retry and local draft/run exports. Conflicted or schema-refused drafts are retained until explicitly resolved or deleted; they are never silently evicted.++## Verification++Run `pnpm lint`, `pnpm test`, `pnpm test:browser`, and `pnpm run test:performance:build` from webv2. Queue receipt tests also cover backend admission, account isolation, project deletion, partial acceptance, and idempotent retries. Browser tests exercise actual IndexedDB transactions and Web Locks.diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.tsindex 9b2178366c..3d31c5eea5 100644--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts@@ -3,6 +3,7 @@ import type { Project, WorkbenchState } from '@workbench/projectContracts';import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';+import { createAccountOwnedQueueRunJournal } from '@workbench/queue-integration/queueRunJournal';import { createDraftProject, createInitialWorkbenchState } from '@workbench/workbenchState';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -20,8 +21,30 @@ import {} from './durableSyncedPersistence';import { createDeterministicProjectId } from './ids';import { serializeProjectDocumentV2 } from './projectDocument';+import { acquireProjectMutationLock } from './projectLifecycleLocks';import { getProjectSyncSnapshot, registerOpenProject, unregisterOpenProject } from './syncStore';+const listQueueRunProjectIds = vi.hoisted(() =>+ vi.fn<() => Promise<{ kind: 'available'; projectIds: string[] } | { kind: 'unavailable' }>>(() =>+ Promise.resolve({ kind: 'available', projectIds: [] })+ )+);++vi.mock('./projectLifecycleLocks', () => ({+ acquireProjectMutationLock: vi.fn(() =>+ Promise.resolve({ kind: 'acquired' as const, release: () => Promise.resolve() })+ ),+}));+vi.mock('@workbench/queue-integration/queueRunJournal', () => ({+ createAccountOwnedQueueRunJournal: vi.fn(() =>+ Promise.resolve({+ close: vi.fn(),+ listProjectIds: listQueueRunProjectIds,+ listForProject: vi.fn(() => Promise.resolve({ entries: [], kind: 'available', removedCorrupt: 0 })),+ })+ ),+}));+const now = '2026-09-03T12:00:00.000Z';const stateWith = (projects: Project[]): WorkbenchState => ({@@ -127,9 +150,81 @@ const createService = (beforeEach(() => {accountLifecycle.activate('durable-sync-test');+ vi.mocked(acquireProjectMutationLock).mockReset();+ vi.mocked(acquireProjectMutationLock).mockResolvedValue({+ kind: 'acquired',+ release: () => Promise.resolve(),+ });+ vi.mocked(createAccountOwnedQueueRunJournal).mockReset();+ vi.mocked(createAccountOwnedQueueRunJournal).mockResolvedValue({+ availability: 'available',+ acknowledgeReceipt: vi.fn(),+ listPendingReceipts: vi.fn(),+ close: vi.fn(),+ deleteForProject: vi.fn(),+ listAll: vi.fn(),+ listProjectIds: listQueueRunProjectIds,+ listForProject: vi.fn(() => Promise.resolve({ entries: [], kind: 'available' as const, removedCorrupt: 0 })),+ record: vi.fn(),+ settle: vi.fn(),+ });+ listQueueRunProjectIds.mockReset();+ listQueueRunProjectIds.mockResolvedValue({ kind: 'available', projectIds: [] });});describe('durable project persistence', () => {+ it('refuses to retarget a project while it has active queue runs', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const project = createDraftProject([]);+ project.queue.items = [{ status: 'running' } as Project['queue']['items'][number]];++ await expect(createService(owner, api).resolveConflictSaveAsNew(project)).rejects.toThrow(+ 'Wait for active queue runs'+ );+ expect(api.createProject).not.toHaveBeenCalled();+ });++ it('refuses conflict resolution while another tab owns a project run', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const project = createDraftProject([]);+ vi.mocked(acquireProjectMutationLock).mockResolvedValueOnce({ kind: 'contended' });++ await expect(createService(owner, api).resolveConflictSaveAsNew(project)).rejects.toThrow('active queue runs');++ expect(api.createProject).not.toHaveBeenCalled();+ });++ it('refuses conflict resolution when a dormant queue journal row exists', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const project = createDraftProject([]);+ const release = vi.fn().mockResolvedValue(undefined);+ vi.mocked(acquireProjectMutationLock).mockResolvedValueOnce({ kind: 'acquired', release });+ vi.mocked(createAccountOwnedQueueRunJournal).mockResolvedValueOnce({+ availability: 'available',+ acknowledgeReceipt: vi.fn(),+ listPendingReceipts: vi.fn(),+ close: vi.fn(),+ deleteForProject: vi.fn(),+ listAll: vi.fn(),+ listProjectIds: vi.fn().mockResolvedValue({ kind: 'available', projectIds: [project.id] }),+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: {}, projectId: project.id, queueItemId: 'run-1', submissionOrder: 1 }],+ kind: 'available',+ removedCorrupt: 0,+ }),+ record: vi.fn(),+ settle: vi.fn(),+ });++ await expect(createService(owner, api).resolveConflictSaveAsNew(project)).rejects.toThrow('active queue runs');++ expect(api.createProject).not.toHaveBeenCalled();+ expect(release).toHaveBeenCalledOnce();+ });+it('deletes the legacy mirror keys before loading', async () => {const owner = captureAccountScope();const clearLegacyStorage = vi.fn();@@ -213,6 +308,128 @@ describe('durable project persistence', () => {expect(listForProject).not.toHaveBeenCalled();});+ it('restores a server project with durable queue work after another tab empties the session', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const project = createDraftProject([]);+ api.records.set(project.id, toRecord(project));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: '',+ openProjectIds: [],+ });+ listQueueRunProjectIds.mockResolvedValue({ kind: 'available', projectIds: [project.id] });++ const loaded = await createService(owner, api).loadWorkbench();++ expect(loaded.state.projects.map((candidate) => candidate.id)).toEqual([project.id]);+ expect(loaded.state.activeProjectId).toBe(project.id);+ });++ it('bounds journal-driven auto-open deterministically and reports retained overflow', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const projects = ['queue-c', 'queue-a', 'queue-b'].map((id) => ({ ...createDraftProject([]), id }));+ for (const project of projects) {+ api.records.set(project.id, toRecord(project));+ }+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: '',+ openProjectIds: [],+ });+ listQueueRunProjectIds.mockResolvedValue({+ kind: 'available',+ projectIds: projects.map((project) => project.id),+ });+ const service = createDurableSyncedWorkbenchPersistence(owner, {+ api,+ autoOpenQueueRunProjectLimit: 1,+ draftStore: Promise.resolve(createMemoryProjectDraftStore()),+ editorSession: Promise.resolve({ id: 'editor-1', release: () => Promise.resolve() }),+ now: () => now,+ writerToken: 'writer-1',+ });++ const loaded = await service.loadWorkbench();++ expect(loaded.state.projects.map((project) => project.id)).toEqual(['queue-a']);+ expect(loaded.queueRecovery).toEqual({+ projects: [+ { projectId: 'queue-b', reason: 'open-limit' },+ { projectId: 'queue-c', reason: 'open-limit' },+ ],+ status: 'available',+ });+ });++ it('restores a draft-backed journal project after its server record was deleted', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const draftStore = createMemoryProjectDraftStore();+ const project = createDraftProject([]);+ await draftStore.stage({+ baseRevision: 1,+ documentJson: JSON.stringify(serializeProjectDocumentV2(project)),+ documentSchemaVersion: 2,+ editorSessionId: 'older-editor',+ generation: 1,+ projectId: project.id,+ updatedAt: 1,+ writerToken: 'older-writer',+ });+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: '',+ openProjectIds: [],+ });+ listQueueRunProjectIds.mockResolvedValue({ kind: 'available', projectIds: [project.id] });++ const loaded = await createService(owner, api, draftStore).loadWorkbench();++ expect(loaded.state.projects.map((candidate) => candidate.id)).toEqual([project.id]);+ expect(loaded.conflicts).toEqual([expect.objectContaining({ kind: 'deleted', projectId: project.id })]);+ expect(loaded.queueRecovery.projects).toEqual([]);+ });++ it('reports a journal project that has neither a server record nor a recoverable draft', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: '',+ openProjectIds: [],+ });+ listQueueRunProjectIds.mockResolvedValue({ kind: 'available', projectIds: ['orphan-project'] });++ const loaded = await createService(owner, api).loadWorkbench();++ expect(loaded.queueRecovery).toEqual({+ projects: [{ projectId: 'orphan-project', reason: 'project-unavailable' }],+ status: 'available',+ });+ expect(loaded.state.projects).toHaveLength(1);+ expect(loaded.state.projects[0]!.id).not.toBe('orphan-project');+ });++ it('loads backend projects when queue recovery storage is unavailable', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const project = createDraftProject([]);+ api.records.set(project.id, toRecord(project));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: project.id,+ openProjectIds: [project.id],+ });+ listQueueRunProjectIds.mockResolvedValue({ kind: 'unavailable' });++ const loaded = await createService(owner, api).loadWorkbench();++ expect(loaded.state.projects.map((candidate) => candidate.id)).toEqual([project.id]);+ expect(loaded.queueRecovery).toEqual({ projects: [], status: 'unavailable' });+ });+it('bounds account-wide draft auto-open while keeping overflow drafts recoverable', async () => {const owner = captureAccountScope();const api = createApi();@@ -1778,8 +1995,8 @@ describe('durable project persistence', () => {releaseCreate();const [copy] = await Promise.all([resolving, saving]);- expect(copy.project.name).toBe(backgroundEdit.name);- expect(api.records.get(copy.targetProjectId)?.name).toBe(backgroundEdit.name);+ expect(copy.project.name).toBe(`${backgroundEdit.name} (copy)`);+ expect(api.records.get(copy.targetProjectId)?.name).toBe(`${backgroundEdit.name} (copy)`);await expect(draftStore.get(copy.targetProjectId, 'editor-1')).resolves.toMatchObject({ kind: 'empty' });});diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.tsindex 5bbe6e93ec..5b31e68fae 100644--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts@@ -7,6 +7,8 @@ import {isCanvasSchemaVersionSupported,MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,} from '@workbench/canvasSchemaVersion';+import { hasActiveQueueRuns } from '@workbench/queue-integration/activeQueueRuns';+import { createAccountOwnedQueueRunJournal } from '@workbench/queue-integration/queueRunJournal';import {createDraftProject,createInitialWorkbenchState,@@ -59,10 +61,10 @@ import { selectCoverImageName } from './projectAssets';import {PROJECT_DOCUMENT_SCHEMA_VERSION,PROJECT_DOCUMENT_MAX_BYTES,- serializeProjectDocumentV2,serializeProjectDocumentV2Json,} from './projectDocument';import { deserializeProjectDocument, deserializeProjectRecord } from './projectHydration';+import { acquireProjectMutationLock } from './projectLifecycleLocks';import { fetchSessionBlobStrict, serializeSessionBlob, SESSION_STATE_KEY } from './session';import { getOpenProject, reportProjectSync, reportProjectSyncEntry, resolveProjectSyncConflict } from './syncStore';import { deleteWorkbenchDatabase } from './workbenchDatabase';@@ -187,9 +189,20 @@ export interface DurableWorkbenchSaveResult {snapshot: HydratedWorkbenchSnapshot;}+export interface QueueRecoveryProject {+ projectId: string;+ reason: 'open-limit' | 'project-unavailable';+}++export interface QueueRecoveryState {+ projects: QueueRecoveryProject[];+ status: 'available' | 'unavailable';+}+export interface DurableHydratedWorkbenchSnapshot extends HydratedWorkbenchSnapshot {conflicts: ProjectConflictInfo[];localDraftStatus: LocalDraftStatus;+ queueRecovery: QueueRecoveryState;}export interface DurableProjectPersistenceApi {@@ -224,12 +237,15 @@ interface DurableSyncedPersistenceDependencies {api?: DurableProjectPersistenceApi;autoOpenDraftByteLimit?: number;autoOpenDraftLimit?: number;+ autoOpenQueueRunProjectLimit?: number;clearLegacyStorage?: () => void;databaseDeleteTimeoutMs?: number;deleteDatabase?: typeof deleteWorkbenchDatabase;draftStore?: Promise<ProjectDraftStore>;editorSession?: Promise<EditorSession>;now?: () => string;+ projectMutationLock?: (projectId: string) => ReturnType<typeof acquireProjectMutationLock>;+ queueRunJournal?: typeof createAccountOwnedQueueRunJournal;saveDraftAsNew?: SaveDraftAsNew;writerToken?: string;}@@ -342,6 +358,7 @@ export class ProjectDraftWriteRejectedError extends Error {export interface DurableSyncedWorkbenchPersistence {acknowledgeProjectResolution(projectId: string): void;+ abortProjectResolution(projectId: string): void;adoptProjectRecord(record: ProjectRecordDTO): ProjectLoadResult;clearWorkbench(): Promise<void>;close(): void;@@ -384,6 +401,11 @@ export const createDurableSyncedWorkbenchPersistence = (const api = dependencies.api ?? productionApi;const autoOpenDraftByteLimit = dependencies.autoOpenDraftByteLimit ?? 64 * 1024 * 1024;const autoOpenDraftLimit = dependencies.autoOpenDraftLimit ?? 8;+ const requestedQueueRunProjectLimit = dependencies.autoOpenQueueRunProjectLimit ?? 8;+ const autoOpenQueueRunProjectLimit =+ Number.isSafeInteger(requestedQueueRunProjectLimit) && requestedQueueRunProjectLimit >= 0+ ? requestedQueueRunProjectLimit+ : 8;const clearLegacyStorage =dependencies.clearLegacyStorage ??(() => {@@ -402,6 +424,41 @@ export const createDurableSyncedWorkbenchPersistence = ((draftStorePromise ??= dependencies.draftStore ?? createAccountOwnedProjectDraftStore(owner));const getEditorSessionForService = () => (editorSessionPromise ??= dependencies.editorSession ?? getEditorSession());const now = dependencies.now ?? (() => new Date().toISOString());+ const getProjectMutationLock =+ dependencies.projectMutationLock ??+ ((projectId: string) => acquireProjectMutationLock(owner.storageSuffix, projectId));+ const openQueueRunJournal = dependencies.queueRunJournal ?? createAccountOwnedQueueRunJournal;+ const listQueueRunProjectIds = async (): Promise<+ { kind: 'available'; projectIds: string[] } | { kind: 'unavailable' }+ > => {+ let journal: Awaited<ReturnType<typeof openQueueRunJournal>>;+ try {+ journal = await openQueueRunJournal(owner);+ } catch {+ return { kind: 'unavailable' };+ }+ try {+ return await journal.listProjectIds();+ } catch {+ return { kind: 'unavailable' };+ } finally {+ journal.close();+ }+ };+ const assertNoDurableQueueRuns = async (projectId: string): Promise<void> => {+ const journal = await openQueueRunJournal(owner);+ try {+ const result = await journal.listForProject(projectId);+ if (result.kind === 'unavailable') {+ throw new Error('Active queue runs could not be verified.');+ }+ if (result.entries.length > 0) {+ throw new Error('Wait for active queue runs to finish before resolving this project.');+ }+ } finally {+ journal.close();+ }+ };const writerToken = dependencies.writerToken ?? crypto.randomUUID();const saveAsNew = dependencies.saveDraftAsNew ?? saveDraftAsNew;const deleteDatabase = dependencies.deleteDatabase ?? deleteWorkbenchDatabase;@@ -426,6 +483,7 @@ export const createDurableSyncedWorkbenchPersistence = (const closedRetargetTargetsAwaitingAck = new Set<string>();const draftEditorSessionIds = new Map<string, string>();const copyCaptureProjectIds = new Set<string>();+ const projectMutationLocks = new Map<string, { release(): Promise<void> }>();const reservedCopyTargetIds = new Set<string>();const projectResolutionFences = new Map<string,@@ -455,6 +513,14 @@ export const createDurableSyncedWorkbenchPersistence = (localDraftStatus = localDraftFailures.size === 0 ? 'ok' : 'unavailable';};const projectDraftFailureKey = (projectId: string): string => `project:${projectId}`;+ const releaseProjectMutation = (projectId: string): void => {+ const lock = projectMutationLocks.get(projectId);+ if (!lock) {+ return;+ }+ projectMutationLocks.delete(projectId);+ void lock.release().catch(() => undefined);+ };const assertOwner = (): void => assertAccountScopeCurrent(owner);const assertNotCleared = (): void => {@@ -498,6 +564,10 @@ export const createDurableSyncedWorkbenchPersistence = (return;}isClosed = true;+ for (const [projectId, lock] of projectMutationLocks) {+ projectMutationLocks.delete(projectId);+ void lock.release().catch(() => undefined);+ }if (draftStorePromise) {void draftStorePromise.then((store) => store.close());}@@ -1614,7 +1684,9 @@ export const createDurableSyncedWorkbenchPersistence = (return {acknowledgeProjectResolution: (projectId) => {projectResolutionFences.delete(projectId);+ releaseProjectMutation(projectId);},+ abortProjectResolution: releaseProjectMutation,adoptProjectRecord: (record) => {assertOwner();if (reservedCopyTargetIds.has(record.project_id)) {@@ -1839,8 +1911,13 @@ export const createDurableSyncedWorkbenchPersistence = (const session = await getEditorSessionForService();let summaries: ProjectSummaryDTO[];let sessionBlob: WorkbenchSessionBlob | null;+ let queueRunProjects: Awaited<ReturnType<typeof listQueueRunProjectIds>>;try {- [summaries, sessionBlob] = await Promise.all([api.listProjects(owner.signal), api.loadSession(owner.signal)]);+ [summaries, sessionBlob, queueRunProjects] = await Promise.all([+ api.listProjects(owner.signal),+ api.loadSession(owner.signal),+ listQueueRunProjectIds(),+ ]);} catch (error) {throw new WorkbenchBackendUnavailableError(error);}@@ -1919,8 +1996,24 @@ export const createDurableSyncedWorkbenchPersistence = (const sessionProjectIds = sessionBlob? (sessionBlob.openProjectIds ?? summaries.map((summary) => summary.project_id)): summaries.slice(0, 1).map((summary) => summary.project_id);+ const alreadyRequestedProjectIds = new Set([+ ...sessionProjectIds,+ ...handoffTargetIds,+ ...(options?.openProjectId ? [options.openProjectId] : []),+ ]);+ const queueRunProjectCandidates =+ queueRunProjects.kind === 'available'+ ? [...new Set(queueRunProjects.projectIds)]+ .filter((projectId) => !alreadyRequestedProjectIds.has(projectId))+ .sort((left, right) => left.localeCompare(right))+ : [];+ const queueRunProjectIds = queueRunProjectCandidates.slice(0, autoOpenQueueRunProjectLimit);+ const recoverableQueueProjects: QueueRecoveryProject[] = queueRunProjectCandidates+ .slice(autoOpenQueueRunProjectLimit)+ .map((projectId) => ({ projectId, reason: 'open-limit' }));const alwaysOpenProjectIds = new Set([...sessionProjectIds,+ ...queueRunProjectIds,...handoffTargetIds,...(options?.openProjectId ? [options.openProjectId] : []),]);@@ -1951,6 +2044,7 @@ export const createDurableSyncedWorkbenchPersistence = (}const requestedIds = new Set([...sessionProjectIds.map((projectId) => loadRetargets.get(projectId) ?? projectId),+ ...queueRunProjectIds,...draftIds,...handoffTargetIds,...(options?.openProjectId ? [options.openProjectId] : []),@@ -2158,6 +2252,12 @@ export const createDurableSyncedWorkbenchPersistence = (});assertOwner();+ for (const projectId of queueRunProjectIds) {+ if (!loadedProjects.has(projectId)) {+ recoverableQueueProjects.push({ projectId, reason: 'project-unavailable' });+ }+ }+const projects = [...requestedIds].flatMap((projectId) => {const project = loadedProjects.get(projectId);return project ? [project] : [];@@ -2192,7 +2292,15 @@ export const createDurableSyncedWorkbenchPersistence = (reportSync(projects);const snapshot = toSnapshot(state, now());snapshot.refusedProjects = refusedProjects;- return { ...snapshot, conflicts: [...conflicts.values()], localDraftStatus };+ return {+ ...snapshot,+ conflicts: [...conflicts.values()],+ localDraftStatus,+ queueRecovery: {+ projects: recoverableQueueProjects.filter(({ projectId }) => !loadedProjects.has(projectId)),+ status: queueRunProjects.kind,+ },+ };})();loadPromise = loading;void loading.catch(() => {@@ -2252,7 +2360,20 @@ export const createDurableSyncedWorkbenchPersistence = (recomputeHasPending();});},- resolveConflictDiscard: (projectId) => {+ resolveConflictDiscard: async (projectId) => {+ const mutationLock = await getProjectMutationLock(projectId);+ if (mutationLock.kind === 'contended') {+ throw new Error('Wait for active queue runs to finish before discarding this project.');+ }+ if (mutationLock.kind === 'unavailable') {+ throw new Error('Discard is unavailable because cross-tab coordination could not be established.');+ }+ try {+ await assertNoDurableQueueRuns(projectId);+ } catch (error) {+ await mutationLock.release();+ throw error;+ }projectResolutionFences.set(projectId, { kind: 'pending' });return enqueue(async () => {await deleteDraft(projectId);@@ -2266,26 +2387,50 @@ export const createDurableSyncedWorkbenchPersistence = (if (lastKnownState) {lastKnownState = applyProjectResolutionFences(lastKnownState);}+ projectMutationLocks.set(projectId, mutationLock);}).catch((error) => {projectResolutionFences.delete(projectId);+ void mutationLock.release().catch(() => undefined);throw error;});},- resolveConflictSaveAsNew: (inputProject) => {+ resolveConflictSaveAsNew: async (inputProject) => {+ if (hasActiveQueueRuns(inputProject)) {+ throw new Error('Wait for active queue runs to finish before saving this project as new.');+ }if (isTerminallyCleared) {- return Promise.reject(new Error('Workbench persistence was cleared and must be reloaded.'));+ throw new Error('Workbench persistence was cleared and must be reloaded.');}if (copyCaptureProjectIds.has(inputProject.id)) {- return Promise.reject(new Error('A project copy is already being saved.'));+ throw new Error('A project copy is already being saved.');}+ copyCaptureProjectIds.add(inputProject.id);const invocationGeneration = generations.get(inputProject.id) ?? 0;+ const mutationLock = await getProjectMutationLock(inputProject.id).catch((error) => {+ copyCaptureProjectIds.delete(inputProject.id);+ throw error;+ });+ if (mutationLock.kind === 'contended') {+ copyCaptureProjectIds.delete(inputProject.id);+ throw new Error('Wait for active queue runs to finish before saving this project as new.');+ }+ if (mutationLock.kind === 'unavailable') {+ copyCaptureProjectIds.delete(inputProject.id);+ throw new Error('Saving as new is unavailable because cross-tab coordination could not be established.');+ }+ try {+ await assertNoDurableQueueRuns(inputProject.id);+ } catch (error) {+ copyCaptureProjectIds.delete(inputProject.id);+ await mutationLock.release();+ throw error;+ }let reservedTargetId: string | null = null;- copyCaptureProjectIds.add(inputProject.id);+ let handedOffMutationLock = false;return enqueue(async () => {const projectId = inputProject.id;const currentDocument = serializeProjectDocumentV2Json(inputProject);let owned = await requireDraft(projectId);- let copyProjectGeneration = invocationGeneration;if (owned.draft.documentJson !== currentDocument.documentJson &&owned.draft.generation <= invocationGeneration@@ -2293,9 +2438,6 @@ export const createDurableSyncedWorkbenchPersistence = (await stageProject(inputProject, currentDocument);owned = await requireDraft(projectId);}- if (owned.draft.documentJson === currentDocument.documentJson) {- copyProjectGeneration = owned.draft.generation;- }const { editorSessionId, store } = owned;const durable = await store.get(projectId, editorSessionId);if (@@ -2308,7 +2450,9 @@ export const createDurableSyncedWorkbenchPersistence = (throw new Error('Save as new requires an up-to-date local recovery draft. Free browser storage and retry.');}const draft = durable.draft;- const project = inputProject;+ const copyProjectGeneration = draft.generation;+ const sourceDocument = JSON.parse(draft.documentJson) as Record<string, unknown>;+ const sourceProjectName = typeof sourceDocument.name === 'string' ? sourceDocument.name : inputProject.name;const conflict = conflicts.get(projectId);if (!conflict) {throw new Error('The project no longer has a conflict to resolve.');@@ -2350,8 +2494,8 @@ export const createDurableSyncedWorkbenchPersistence = (draft.documentJson,].join('\u0000'));- const name = `${project.name} (copy)`;- const document = { ...serializeProjectDocumentV2(project), id: copyProjectId, name };+ const name = `${sourceProjectName} (copy)`;+ const document = { ...sourceDocument, id: copyProjectId, name };const documentJson = JSON.stringify(document);const documentByteSize = getUtf8ByteSize(documentJson);if (documentByteSize > PROJECT_DOCUMENT_MAX_BYTES) {@@ -2367,7 +2511,7 @@ export const createDurableSyncedWorkbenchPersistence = (getProjectCanvasSchemaRequirement(document)),copyProjectName: name,- copySourceProjectName: project.name,+ copySourceProjectName: sourceProjectName,};})());if (isCopyTargetOpen(proposedReservation.copyProjectId)) {@@ -2527,12 +2671,21 @@ export const createDurableSyncedWorkbenchPersistence = (sourceProjectId: projectId,targetProjectId: copyProjectId,};- }).finally(() => {- copyCaptureProjectIds.delete(inputProject.id);- if (reservedTargetId) {- reservedCopyTargetIds.delete(reservedTargetId);- }- });+ })+ .then((result) => {+ projectMutationLocks.set(inputProject.id, mutationLock);+ handedOffMutationLock = true;+ return result;+ })+ .finally(async () => {+ copyCaptureProjectIds.delete(inputProject.id);+ if (reservedTargetId) {+ reservedCopyTargetIds.delete(reservedTargetId);+ }+ if (!handedOffMutationLock) {+ await mutationLock.release();+ }+ });},resolveConflictUseServer: (projectId) => {projectResolutionFences.set(projectId, { kind: 'pending' });diff --git a/invokeai/frontend/webv2/src/workbench/projects/indexedDbDraftStore.browser.test.ts b/invokeai/frontend/webv2/src/workbench/projects/indexedDbDraftStore.browser.test.tsindex 2fbc0dbb4e..34ea3331eb 100644--- a/invokeai/frontend/webv2/src/workbench/projects/indexedDbDraftStore.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/indexedDbDraftStore.browser.test.ts@@ -187,12 +187,13 @@ describe('IndexedDB project drafts', () => {stores.push(database);expect(database.name).toBe(getWorkbenchDatabaseName(suffix));- expect(database.version).toBe(3);+ expect(database.version).toBe(4);expect([...database.objectStoreNames]).toEqual(['draftBodies','draftWriters','drafts','metadata',+ 'queueReceiptAcks','queueRuns','recallBodies','recallCache',@@ -255,7 +256,7 @@ describe('IndexedDB project drafts', () => {const upgraded = await openWorkbenchDatabase(suffix);stores.push(upgraded);- expect(upgraded.version).toBe(3);+ expect(upgraded.version).toBe(4);expect(await upgraded.count('recallCache')).toBe(0);expect([...upgraded.objectStoreNames]).toContain('recallBodies');expect([...upgraded.transaction('draftWriters').store.indexNames]).toEqual(['byRetarget']);diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex 0d702fa918..d47005ad78 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -1,3 +1,4 @@+import type { BrowserLockResult } from '@platform/browser/webLocks';import type * as accountLifecycleModule from '@platform/state/accountLifecycle';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -25,9 +26,25 @@ const api = vi.hoisted(() => ({/** The copying itself is `duplicateProject`'s own test; this file owns the library's part of it. */const duplication = vi.hoisted(() => ({ duplicateProjectRecord: vi.fn() }));+const projectLocks = vi.hoisted(() => ({+ acquireProjectMutationLock: vi.fn<() => Promise<BrowserLockResult>>(() =>+ Promise.resolve({ kind: 'acquired', release: () => Promise.resolve() })+ ),+}));+const queueJournal = vi.hoisted(() => ({+ createAccountOwnedQueueRunJournal: vi.fn(() =>+ Promise.resolve({+ close: vi.fn(),+ deleteForProject: vi.fn(() => Promise.resolve({ kind: 'removed' as const })),+ listForProject: vi.fn(() => Promise.resolve({ entries: [], kind: 'available' as const, removedCorrupt: 0 })),+ })+ ),+}));vi.mock('./api', () => api);vi.mock('./invk/duplicateProject', () => duplication);+vi.mock('./projectLifecycleLocks', () => projectLocks);+vi.mock('@workbench/queue-integration/queueRunJournal', () => queueJournal);let library: typeof libraryModule;let syncStore: typeof syncStoreModule;@@ -57,6 +74,14 @@ beforeEach(async () => {api.getProjectBoardSnapshot.mockReset();api.getProjectBoardSnapshot.mockResolvedValue({ items: [] });duplication.duplicateProjectRecord.mockReset();+ projectLocks.acquireProjectMutationLock.mockReset();+ projectLocks.acquireProjectMutationLock.mockResolvedValue({ kind: 'acquired', release: () => Promise.resolve() });+ queueJournal.createAccountOwnedQueueRunJournal.mockReset();+ queueJournal.createAccountOwnedQueueRunJournal.mockResolvedValue({+ close: vi.fn(),+ deleteForProject: vi.fn(() => Promise.resolve({ kind: 'removed' })),+ listForProject: vi.fn(() => Promise.resolve({ entries: [], kind: 'available', removedCorrupt: 0 })),+ });library = await import('./library');syncStore = await import('./syncStore');@@ -259,6 +284,30 @@ describe('library mutations', () => {expect(api.deleteProject).toHaveBeenCalledWith('closed', expect.any(AbortSignal));});+ it('does not delete while another tab owns an active project run', async () => {+ projectLocks.acquireProjectMutationLock.mockResolvedValueOnce({ kind: 'contended' });++ await expect(library.deleteLibraryProject('closed')).rejects.toThrow('active queue runs');++ expect(api.deleteProject).not.toHaveBeenCalled();+ expect(queueJournal.createAccountOwnedQueueRunJournal).not.toHaveBeenCalled();+ });++ it('fails closed when durable queue runs cannot be verified', async () => {+ const release = vi.fn().mockResolvedValue(undefined);+ projectLocks.acquireProjectMutationLock.mockResolvedValueOnce({ kind: 'acquired', release });+ queueJournal.createAccountOwnedQueueRunJournal.mockResolvedValueOnce({+ close: vi.fn(),+ deleteForProject: vi.fn(),+ listForProject: vi.fn().mockResolvedValue({ kind: 'unavailable' }),+ });++ await expect(library.deleteLibraryProject('closed')).rejects.toThrow('could not be verified');++ expect(api.deleteProject).not.toHaveBeenCalled();+ expect(release).toHaveBeenCalledOnce();+ });+/*** A project left marked deleted never autosaves again for the rest of the session, and nothing* says so. Unmarking belongs with the mark, inside the handle, rather than in each caller's catch.diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex df53f125d3..ebe7c499ce 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -208,24 +208,52 @@ export const isProjectSummaryCompatible = (summary: ProjectSummary): boolean =>/** Permanently remove a project from the server, its board with it. The only deletion path. */export const deleteLibraryProject = async (projectId: string): Promise<void> => {const owner = captureAccountScope();+ const [{ acquireProjectMutationLock }, { createAccountOwnedQueueRunJournal }] = await Promise.all([+ import('./projectLifecycleLocks'),+ import('@workbench/queue-integration/queueRunJournal'),+ ]);+ assertAccountScopeCurrent(owner);const openProject = getOpenProject(projectId);-- if (openProject) {- // Queueing ensures an in-flight save finishes before DELETE is sent.- await openProject.deleteOnServer();- } else {- await apiDeleteProject(projectId, owner.signal);+ const mutationLock = await acquireProjectMutationLock(owner.storageSuffix, projectId);+ if (mutationLock.kind === 'contended') {+ throw new Error('Wait for active queue runs to finish before deleting this project.');+ }+ if (mutationLock.kind === 'unavailable') {+ throw new Error('Project deletion is unavailable because cross-tab coordination could not be established.');}+ let journal;++ try {+ journal = await createAccountOwnedQueueRunJournal(owner);+ const queueRuns = await journal.listForProject(projectId);+ if (queueRuns.kind === 'unavailable') {+ throw new Error('Project deletion is unavailable because active queue runs could not be verified.');+ }+ if (queueRuns.entries.length > 0) {+ throw new Error('Wait for active queue runs to finish before deleting this project.');+ }++ if (openProject) {+ // Queueing ensures an in-flight save finishes before DELETE is sent.+ await openProject.deleteOnServer();+ } else {+ await apiDeleteProject(projectId, owner.signal);+ }- assertAccountScopeCurrent(owner);- openProject?.close();- forgetProjectCover(projectId, owner);- store.patchSnapshot({ summaries: store.getSnapshot().summaries.filter((summary) => summary.id !== projectId) });-- // The saved session outlives the editor, so a deleted project has to leave it here or the next- // boot tries to open something the server no longer has.- await pruneSessionProject(projectId, owner.signal);- await refreshOpenProjects();+ assertAccountScopeCurrent(owner);+ await journal.deleteForProject(projectId);+ openProject?.close();+ forgetProjectCover(projectId, owner);+ store.patchSnapshot({ summaries: store.getSnapshot().summaries.filter((summary) => summary.id !== projectId) });++ // The saved session outlives the editor, so a deleted project has to leave it here or the next+ // boot tries to open something the server no longer has.+ await pruneSessionProject(projectId, owner.signal);+ await refreshOpenProjects();+ } finally {+ journal?.close();+ await mutationLock.release();+ }};/**diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectLifecycleLocks.ts b/invokeai/frontend/webv2/src/workbench/projects/projectLifecycleLocks.tsnew file mode 100644index 0000000000..0d696e74f6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/projectLifecycleLocks.ts@@ -0,0 +1,12 @@+import { acquireExclusiveLock, type BrowserLockResult } from '@platform/browser/webLocks';++const LOCK_PREFIX = 'invokeai:v7:webv2:project-lifecycle';++export const getProjectLifecycleLockName = (storageSuffix: string, projectId: string): string =>+ `${LOCK_PREFIX}${storageSuffix}:${JSON.stringify(projectId)}`;++export const acquireProjectMutationLock = (+ storageSuffix: string,+ projectId: string,+ acquire: (name: string) => Promise<BrowserLockResult> = acquireExclusiveLock+): Promise<BrowserLockResult> => acquire(getProjectLifecycleLockName(storageSuffix, projectId));diff --git a/invokeai/frontend/webv2/src/workbench/projects/session.test.ts b/invokeai/frontend/webv2/src/workbench/projects/session.test.tsindex bf70de4bcf..c23fed3673 100644--- a/invokeai/frontend/webv2/src/workbench/projects/session.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/session.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { getClientStateValue } from './api';-import { fetchSessionBlobStrict } from './session';+import { fetchSessionBlobStrict, peekOpenProjectIds } from './session';vi.mock('./api', () => ({getClientStateValue: vi.fn(),@@ -18,3 +18,41 @@ describe('fetchSessionBlobStrict', () => {await expect(fetchSessionBlobStrict()).rejects.toBe(failure);});});++describe('peekOpenProjectIds', () => {+ beforeEach(() => vi.mocked(getClientStateValue).mockReset());++ it('keeps the editor route reachable when durable queue work survives an empty session', async () => {+ vi.mocked(getClientStateValue).mockResolvedValueOnce(+ JSON.stringify({ account: {}, activeProjectId: '', openProjectIds: [] })+ );++ await expect(+ peekOpenProjectIds({+ listDurableRecoveryProjectIds: () => Promise.resolve({ kind: 'available', projectIds: ['queue-project'] }),+ })+ ).resolves.toEqual(['queue-project']);+ });++ it('keeps the editor route reachable when browser recovery storage cannot be inspected', async () => {+ vi.mocked(getClientStateValue).mockResolvedValueOnce(+ JSON.stringify({ account: {}, activeProjectId: '', openProjectIds: [] })+ );++ await expect(+ peekOpenProjectIds({+ listDurableRecoveryProjectIds: () => Promise.resolve({ kind: 'unavailable' }),+ })+ ).resolves.toBeNull();+ });++ it('does not inspect browser recovery storage for a nonempty session', async () => {+ vi.mocked(getClientStateValue).mockResolvedValueOnce(+ JSON.stringify({ account: {}, activeProjectId: 'server-project', openProjectIds: ['server-project'] })+ );+ const listDurableRecoveryProjectIds = vi.fn();++ await expect(peekOpenProjectIds({ listDurableRecoveryProjectIds })).resolves.toEqual(['server-project']);+ expect(listDurableRecoveryProjectIds).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/session.ts b/invokeai/frontend/webv2/src/workbench/projects/session.tsindex 0c8115e90f..dcdf07d483 100644--- a/invokeai/frontend/webv2/src/workbench/projects/session.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/session.ts@@ -1,8 +1,11 @@import type { LaunchpadIntentId } from '@workbench/launchpad/intents';import type { BuiltInLayoutPresetId } from '@workbench/layoutContracts';import type { AccountState, WorkbenchState } from '@workbench/projectContracts';+import type { QueueRunJournal } from '@workbench/queue-integration/queueRunJournal';import type { WorkbenchPreferences } from '@workbench/settings/contracts';+import type { ProjectDraftStore } from './draftStore';+import { getClientStateValue, setClientStateValue } from './api';/**@@ -101,6 +104,65 @@ export const fetchSessionBlob = async (signal?: AbortSignal): Promise<WorkbenchSexport const fetchSessionBlobStrict = async (signal?: AbortSignal): Promise<WorkbenchSessionBlob | null> =>parseSessionBlob(await getClientStateValue(SESSION_STATE_KEY, signal));+type DurableRecoveryProjectIdsResult = { kind: 'available'; projectIds: string[] } | { kind: 'unavailable' };++const listDurableRecoveryProjectIds = async (): Promise<DurableRecoveryProjectIdsResult> => {+ let draftStore: ProjectDraftStore;+ let queueRunJournal: QueueRunJournal;+ try {+ const [{ captureAccountScope }, { createAccountOwnedProjectDraftStore }, { createAccountOwnedQueueRunJournal }] =+ await Promise.all([+ import('@platform/state/accountLifecycle'),+ import('./indexedDbDraftStore'),+ import('@workbench/queue-integration/queueRunJournal'),+ ]);+ const owner = captureAccountScope();+ const [draftStoreResult, queueRunJournalResult] = await Promise.allSettled([+ createAccountOwnedProjectDraftStore(owner),+ createAccountOwnedQueueRunJournal(owner),+ ]);+ if (draftStoreResult.status === 'rejected' || queueRunJournalResult.status === 'rejected') {+ if (draftStoreResult.status === 'fulfilled') {+ draftStoreResult.value.close();+ }+ if (queueRunJournalResult.status === 'fulfilled') {+ queueRunJournalResult.value.close();+ }+ return { kind: 'unavailable' };+ }+ draftStore = draftStoreResult.value;+ queueRunJournal = queueRunJournalResult.value;+ } catch {+ return { kind: 'unavailable' };+ }++ try {+ const [drafts, retargets, queueRuns] = await Promise.all([+ draftStore.list({ limit: 1 }),+ draftStore.listRetargets({ limit: 1 }),+ queueRunJournal.listProjectIds(),+ ]);+ if (drafts.kind !== 'available' || retargets.kind !== 'available' || queueRuns.kind !== 'available') {+ return { kind: 'unavailable' };+ }+ return {+ kind: 'available',+ projectIds: [+ ...new Set([+ ...queueRuns.projectIds,+ ...drafts.items.map((draft) => draft.projectId),+ ...retargets.items.map((handoff) => handoff.targetProjectId),+ ]),+ ],+ };+ } catch {+ return { kind: 'unavailable' };+ } finally {+ draftStore.close();+ queueRunJournal.close();+ }+};+/*** Take a deleted project out of the saved session, which the `/app` guard and the Launchpad's* "open" grouping read. Best-effort and silent: the deletion has already happened, and failing to@@ -141,8 +203,18 @@ export const pruneSessionProject = async (projectId: string, signal?: AbortSigna* backend is unreachable) — the guard must not redirect on null, only on a* definite empty session.*/-export const peekOpenProjectIds = async (): Promise<string[] | null> => {+export const peekOpenProjectIds = async (+ dependencies: {+ listDurableRecoveryProjectIds?: () => Promise<DurableRecoveryProjectIdsResult>;+ } = {}+): Promise<string[] | null> => {const blob = await fetchSessionBlob();- return blob?.openProjectIds ?? null;+ if (!blob?.openProjectIds || blob.openProjectIds.length > 0) {+ return blob?.openProjectIds ?? null;+ }++ const recovery = await (dependencies.listDurableRecoveryProjectIds ?? listDurableRecoveryProjectIds)();++ return recovery.kind === 'available' ? recovery.projectIds : null;};diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsxindex fbfa1bdffc..208ccff51b 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx@@ -1,4 +1,5 @@import type { Project } from '@workbench/projectContracts';+import type { ProjectCommandResult } from '@workbench/workbenchStore';import { accountLifecycle } from '@platform/state/accountLifecycle';import { createDraftProject } from '@workbench/workbenchState';@@ -10,7 +11,8 @@ import { userEvent } from 'vitest/browser';import { serializeProjectDocumentV2Json } from './projectDocument';const harness = vi.hoisted(() => ({- close: vi.fn<() => { ok: true } | { ok: false; reason: 'last-project' }>(),+ close: vi.fn<() => ProjectCommandResult>(),+ deleteLibraryProject: vi.fn(),flush: vi.fn(),navigate: vi.fn(),notifyError: vi.fn(),@@ -20,6 +22,10 @@ const harness = vi.hoisted(() => ({}));vi.mock('@features/generation/react', () => ({ flushGenerateDrafts: vi.fn() }));+vi.mock('./library', () => ({+ deleteLibraryProject: harness.deleteLibraryProject,+ refreshProjectLibrary: vi.fn(),+}));vi.mock('@tanstack/react-router', () => ({ useNavigate: () => harness.navigate }));vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: harness.notifyError }) }));vi.mock('@workbench/WorkbenchContext', () => ({@@ -44,8 +50,13 @@ let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const Harness = () => {- const { closeProject } = useProjectActions();- return <button onClick={() => closeProject(harness.project)}>close</button>;+ const { closeProject, deleteProject } = useProjectActions();+ return (+ <>+ <button onClick={() => closeProject(harness.project)}>close</button>+ <button onClick={() => void deleteProject(harness.project)}>delete</button>+ </>+ );};beforeEach(() => {@@ -53,6 +64,8 @@ beforeEach(() => {harness.project = createDraftProject([]);harness.close.mockReset();harness.close.mockReturnValue({ ok: true });+ harness.deleteLibraryProject.mockReset();+ harness.deleteLibraryProject.mockResolvedValue(undefined);harness.flush.mockReset();harness.navigate.mockReset();harness.notifyError.mockReset();@@ -73,6 +86,27 @@ afterEach(async () => {});describe('useProjectActions', () => {+ it('blocks project deletion while a queue run is active', async () => {+ harness.project.queue.items = [{ status: 'running' } as Project['queue']['items'][number]];+ await act(() => root?.render(<Harness />));++ await act(() => userEvent.click(document.querySelectorAll('button')[1]!));++ expect(harness.notifyError).toHaveBeenCalledWith('projects.deleteFailed', 'projects.activeRunsMustFinish');+ expect(harness.deleteLibraryProject).not.toHaveBeenCalled();+ });++ it('blocks project close before flushing while a queue run is active', async () => {+ harness.project.queue.items = [{ status: 'pending' } as Project['queue']['items'][number]];+ await act(() => root?.render(<Harness />));++ await act(() => userEvent.click(document.querySelector('button')!));++ expect(harness.notifyError).toHaveBeenCalledWith('projects.closeBlocked', 'projects.activeRunsMustFinish');+ expect(harness.flush).not.toHaveBeenCalled();+ expect(harness.close).not.toHaveBeenCalled();+ });+it('reports a rejected close flush and keeps the tab open', async () => {harness.flush.mockRejectedValueOnce(new Error('network failed'));await act(() => root?.render(<Harness />));@@ -112,6 +146,29 @@ describe('useProjectActions', () => {expect(harness.releaseProjectSync).toHaveBeenCalledOnce();});+ it('keeps the tab open when queue work starts while the close flush is in flight', async () => {+ harness.flush.mockImplementationOnce((project: Project) => {+ harness.project = {+ ...harness.project,+ queue: { items: [{ status: 'running' } as Project['queue']['items'][number]] },+ };+ return Promise.resolve({+ documentJson: serializeProjectDocumentV2Json(project).documentJson,+ kind: 'acknowledged' as const,+ });+ });+ harness.close.mockReturnValue({ ok: false, reason: 'active-queue-runs' });+ await act(() => root?.render(<Harness />));++ await act(() => userEvent.click(document.querySelector('button')!));+ await vi.waitFor(() => expect(harness.notifyError).toHaveBeenCalledOnce());++ expect(harness.notifyError).toHaveBeenCalledWith('projects.closeBlocked', 'projects.activeRunsMustFinish');+ expect(harness.close).toHaveBeenCalledOnce();+ expect(harness.releaseProjectSync).not.toHaveBeenCalled();+ expect(harness.navigate).not.toHaveBeenCalled();+ });+it('keeps the last tab open when its empty session cannot be committed', async () => {harness.close.mockReturnValue({ ok: false, reason: 'last-project' });harness.flush.mockImplementationOnce((project: Project) =>@@ -130,4 +187,25 @@ describe('useProjectActions', () => {expect(harness.releaseProjectSync).not.toHaveBeenCalled();expect(harness.navigate).not.toHaveBeenCalled();});++ it('does not navigate home when queue work starts during last-tab close', async () => {+ harness.close+ .mockReturnValueOnce({ ok: false, reason: 'last-project' })+ .mockReturnValueOnce({ ok: false, reason: 'active-queue-runs' });+ harness.flush.mockImplementationOnce((project: Project) =>+ Promise.resolve({+ documentJson: serializeProjectDocumentV2Json(project).documentJson,+ kind: 'acknowledged' as const,+ })+ );+ await act(() => root?.render(<Harness />));++ await act(() => userEvent.click(document.querySelector('button')!));+ await vi.waitFor(() => expect(harness.notifyError).toHaveBeenCalledOnce());++ expect(harness.persistEmptySession).toHaveBeenCalledOnce();+ expect(harness.notifyError).toHaveBeenCalledWith('projects.closeBlocked', 'projects.activeRunsMustFinish');+ expect(harness.releaseProjectSync).not.toHaveBeenCalled();+ expect(harness.navigate).not.toHaveBeenCalled();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.tsindex 25d925136e..26deb66ab7 100644--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts@@ -8,6 +8,7 @@ import {} from '@platform/state/accountLifecycle';import { getApiErrorMessage } from '@platform/transport/http';import { useNavigate } from '@tanstack/react-router';+import { hasActiveQueueRuns } from '@workbench/queue-integration/activeQueueRuns';import { useNotify } from '@workbench/useNotify';import {useWorkbenchCommands,@@ -56,6 +57,9 @@ export const useProjectActions = (): {persistenceService.releaseProjectSync(projectId);return;}+ if (closeResult.reason === 'active-queue-runs') {+ throw new Error(t('projects.activeRunsMustFinish'));+ }if (closeResult.reason !== 'last-project') {throw new Error(t('projects.file.notSynced'));}@@ -66,6 +70,9 @@ export const useProjectActions = (): {persistenceService.releaseProjectSync(projectId);return;}+ if (retry.reason === 'active-queue-runs') {+ throw new Error(t('projects.activeRunsMustFinish'));+ }if (retry.reason !== 'last-project') {throw new Error(t('projects.file.notSynced'));}@@ -122,6 +129,11 @@ export const useProjectActions = (): {const owner = captureAccountScope();flushGenerateDrafts();+ if (hasActiveQueueRuns(queries.getProject(project.id) ?? project)) {+ notify.error(t('projects.closeBlocked'), t('projects.activeRunsMustFinish'));+ return;+ }+void (async () => {for (let attempt = 0; attempt < CLOSE_FLUSH_ATTEMPTS; attempt += 1) {const current = queries.getProject(project.id);@@ -161,6 +173,11 @@ export const useProjectActions = (): {const deleteProject = async (project: Project): Promise<void> => {flushGenerateDrafts();+ if (hasActiveQueueRuns(project)) {+ notify.error(t('projects.deleteFailed'), t('projects.activeRunsMustFinish'));+ return;+ }+const owner = captureAccountScope();try {// Open projects delete through the sync engine so in-flight saves finish first.diff --git a/invokeai/frontend/webv2/src/workbench/projects/workbenchDatabase.ts b/invokeai/frontend/webv2/src/workbench/projects/workbenchDatabase.tsindex e6656af206..ebd9513c05 100644--- a/invokeai/frontend/webv2/src/workbench/projects/workbenchDatabase.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/workbenchDatabase.ts@@ -2,16 +2,19 @@ import { openDB, type DBSchema, type IDBPDatabase } from 'idb';import type { ProjectDraftBody, ProjectDraftMetadata, ProjectDraftWriterClaim } from './draftStore';-export const WORKBENCH_DATABASE_VERSION = 3;+export const WORKBENCH_DATABASE_VERSION = 4;export const WORKBENCH_DRAFT_STORE = 'drafts';export const WORKBENCH_DRAFT_BODY_STORE = 'draftBodies';export const WORKBENCH_DRAFT_WRITER_STORE = 'draftWriters';export const WORKBENCH_QUEUE_RUN_STORE = 'queueRuns';+export const WORKBENCH_QUEUE_RECEIPT_STORE = 'queueReceiptAcks';export const WORKBENCH_RECALL_CACHE_STORE = 'recallCache';export const WORKBENCH_RECALL_CACHE_BODY_STORE = 'recallBodies';export const WORKBENCH_DATABASE_METADATA_STORE = 'metadata';export interface QueueRunDatabaseRecord {+ receiptAcknowledged?: boolean;+ byteSize?: number;itemJson: string;key: string;schemaVersion: 1;@@ -21,6 +24,12 @@ export interface QueueRunDatabaseRecord {updatedAt: number;}+export interface QueueReceiptAcknowledgement {+ key: string;+ projectId: string;+ queueItemId: string;+}+export interface RecallCacheDatabaseRecord {byteSize: number;lastAccessOrder: number;@@ -59,6 +68,10 @@ export interface WorkbenchDatabaseSchema extends DBSchema {key: string;value: QueueRunDatabaseRecord;};+ queueReceiptAcks: {+ key: string;+ value: QueueReceiptAcknowledgement;+ };recallCache: {indexes: { byLastAccessOrder: number };key: string;@@ -142,6 +155,9 @@ export const openWorkbenchDatabase = (.objectStore(WORKBENCH_DRAFT_WRITER_STORE).createIndex('byRetarget', ['projectId', 'editorSessionId', 'retargetedToProjectId']);}+ if (oldVersion < 4) {+ database.createObjectStore(WORKBENCH_QUEUE_RECEIPT_STORE, { keyPath: 'key' });+ }},});return new Promise((resolve, reject) => {diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsxindex 64bcc9b238..6a25c7d783 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx@@ -9,6 +9,7 @@ import { useMountEffect } from '@platform/react/useMountEffect';import { Button, CloseButton } from '@platform/ui/Button';import { JsonPreview } from '@platform/ui/JsonPreview';import {+ EMPTY_IMAGE_RECALL_CAPABILITIES,getCurrentGenerateValues,getImageRecallTitle,RecallActionButtons,@@ -21,8 +22,8 @@ import { FileTextIcon, WandSparklesIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { getQueueRecallCapabilities, planQueueRecall } from './queueRecall';-import { useLocalGenerateValues, useLocalQueueItemSource } from './useLocalGenerateValues';+import { getQueueRecallCapabilities, getVideoQueueRecallCapabilities, planQueueRecall } from './queueRecall';+import { useLocalRecallSnapshot } from './useLocalRecallSnapshot';const selectGenerateRecallValues = createGenerateFormValuesSelector();@@ -38,18 +39,24 @@ export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {const { generation, widgets } = useWorkbenchCommands();const openWidget = useOpenWorkbenchWidget();const notify = useNotify();- const localGenerateValues = useLocalGenerateValues(item.origin);- // A video item's prompt belongs to the Video panel, which owns its own prompt- // values. Only knowable for items this client submitted; see the hook's note.- const isVideoItem = useLocalQueueItemSource(item.origin) === 'video';+ const recall = useLocalRecallSnapshot(item.origin);+ const isRecallPending = recall === undefined;+ const localGenerateValues = recall?.generateValues ?? null;+ const videoSnapshot = recall?.videoValues ?? null;+ const isVideoItem = recall?.sourceId === 'video';const [jsonOpen, setJsonOpen] = useState(false);const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);const models = useModelsSelector((snapshot) => snapshot.models);const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);const meta = useMemo(() => extractGenerationMeta(item), [item]);const capabilities = useMemo(- () => getQueueRecallCapabilities(localGenerateValues, meta),- [localGenerateValues, meta]+ () =>+ isRecallPending+ ? EMPTY_IMAGE_RECALL_CAPABILITIES+ : isVideoItem+ ? getVideoQueueRecallCapabilities(videoSnapshot, meta)+ : getQueueRecallCapabilities(localGenerateValues, meta),+ [isRecallPending, isVideoItem, localGenerateValues, meta, videoSnapshot]);useMountEffect(() => {@@ -58,8 +65,11 @@ export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {const onRecall = useCallback((kind: ImageRecallKind) => {+ if (isRecallPending) {+ return;+ }const current = getCurrentGenerateValues({ generateValues, supportedModels });- const plan = planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues });+ const plan = planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues, videoSnapshot });if (!plan) {notify.info(@@ -90,6 +100,7 @@ export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {generateValues,generation,isVideoItem,+ isRecallPending,localGenerateValues,meta,notify,@@ -97,6 +108,7 @@ export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {supportedModels,t,widgets,+ videoSnapshot,]);diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsxnew file mode 100644index 0000000000..8254785466--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx@@ -0,0 +1,251 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { ChakraProvider } from '@chakra-ui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act, StrictMode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import type { QueueRunJournal } from './queueRunJournal';++const harness = vi.hoisted(() => {+ const controller = new AbortController();+ return {+ accountCurrent: true,+ deleteForProject: vi.fn(),+ downloadText: vi.fn(),+ journalClose: vi.fn(),+ listForProject: vi.fn(),+ listProjectIds: vi.fn(),+ lockResult: { kind: 'acquired', release: vi.fn(() => Promise.resolve()) } as+ | { kind: 'acquired'; release(): Promise<void> }+ | { kind: 'contended' }+ | { kind: 'unavailable' },+ onOpen: vi.fn(),+ owner: {+ accountId: 'account-1',+ epoch: 7,+ signal: controller.signal,+ storageSuffix: ':account-1',+ } as AccountScope,+ };+});++vi.mock('@platform/browser/downloadBlob', () => ({ downloadText: harness.downloadText }));+vi.mock('@platform/state/accountLifecycle', () => ({+ AccountScopeExpiredError: class AccountScopeExpiredError extends Error {},+ assertAccountScopeCurrent: () => {+ if (!harness.accountCurrent) {+ throw new Error('account expired');+ }+ },+ captureAccountScope: () => harness.owner,+ isAccountScopeCurrent: () => harness.accountCurrent,+}));+vi.mock('@platform/ui/ConfirmDialog', () => ({+ ConfirmDialog: ({ body, isOpen, onConfirm }: { body: string; isOpen: boolean; onConfirm(): Promise<void> | void }) =>+ isOpen ? (+ <div>+ <span>{body}</span>+ <button data-testid="confirm-discard" onClick={() => void onConfirm()}>+ confirm+ </button>+ </div>+ ) : null,+}));+vi.mock('@workbench/projects/projectLifecycleLocks', () => ({+ acquireProjectMutationLock: vi.fn(() => Promise.resolve(harness.lockResult)),+}));+vi.mock('./queueRunJournal', () => ({+ createAccountOwnedQueueRunJournal: vi.fn(() =>+ Promise.resolve({+ availability: 'available',+ close: harness.journalClose,+ deleteForProject: harness.deleteForProject,+ listForProject: harness.listForProject,+ listProjectIds: harness.listProjectIds,+ } as unknown as QueueRunJournal)+ ),+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: { count?: number; number?: number; projectId?: string }) =>+ values ? `${key}:${JSON.stringify(values)}` : key,+ }),+}));++import { QueueRecoveryNotice } from './QueueRecoveryNotice';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+let queryClient: QueryClient | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const EMPTY_OPEN_PROJECT_IDS: string[] = [];+const renderNotice = async ({ openProjectIds = EMPTY_OPEN_PROJECT_IDS }: { openProjectIds?: string[] } = {}) => {+ await act(() => {+ root?.render(+ <StrictMode>+ <QueryClientProvider client={queryClient!}>+ <ChakraProvider value={system}>+ <QueueRecoveryNotice openProjectIds={openProjectIds} onOpen={harness.onOpen} />+ </ChakraProvider>+ </QueryClientProvider>+ </StrictMode>+ );+ });+ await act(async () => {+ await vi.waitFor(() => expect(harness.listProjectIds).toHaveBeenCalled());+ await vi.waitFor(() => expect(document.body.textContent).not.toContain('shell.queueRecovery.loading'));+ });+};++const clickButton = async (text: string) => {+ const button = Array.from(document.querySelectorAll('button')).find((candidate) => candidate.textContent === text);+ expect(button).toBeDefined();+ await act(() => userEvent.click(button!));+};++beforeEach(() => {+ harness.accountCurrent = true;+ harness.deleteForProject.mockReset();+ harness.deleteForProject.mockResolvedValue({ kind: 'removed' });+ harness.downloadText.mockReset();+ harness.journalClose.mockReset();+ harness.listForProject.mockReset();+ harness.listForProject.mockResolvedValue({ entries: [], kind: 'available', removedCorrupt: 0 });+ harness.listProjectIds.mockReset();+ harness.listProjectIds.mockResolvedValue({+ kind: 'available',+ projectIds: ['open-project', 'closed-1', 'closed-2'],+ });+ harness.lockResult = { kind: 'acquired', release: vi.fn(() => Promise.resolve()) };+ harness.onOpen.mockReset();+ harness.onOpen.mockResolvedValue(undefined);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root?.unmount());+ queryClient?.clear();+ host?.remove();+ host = null;+ queryClient = null;+ root = null;+});++describe('QueueRecoveryNotice', () => {+ it('lists only closed journal projects and exports the selected project in the explicit recovery format', async () => {+ harness.listForProject.mockImplementation((projectId) =>+ Promise.resolve({+ entries: [+ {+ item: { id: `run-${projectId}`, status: 'running' },+ projectId,+ queueItemId: `run-${projectId}`,+ submissionOrder: 3,+ },+ ],+ kind: 'available',+ removedCorrupt: 0,+ })+ );+ await renderNotice({ openProjectIds: ['open-project'] });++ expect(document.body.textContent).toContain('closed-1');+ expect(document.body.textContent).not.toContain('open-project');+ await clickButton('shell.queueRecovery.next');+ expect(document.body.textContent).toContain('closed-2');+ await clickButton('shell.queueRecovery.export');+ await vi.waitFor(() => expect(harness.downloadText).toHaveBeenCalledOnce());++ expect(harness.listForProject).toHaveBeenCalledWith('closed-2');+ const [json, fileName, mediaType] = harness.downloadText.mock.calls[0]!;+ expect(JSON.parse(json)).toEqual({+ exportedAt: expect.any(String),+ format: 'invokeai-webv2-queue-run-recovery',+ projectId: 'closed-2',+ runs: [+ {+ item: { id: 'run-closed-2', status: 'running' },+ queueItemId: 'run-closed-2',+ submissionOrder: 3,+ },+ ],+ schemaVersion: 1,+ });+ expect(fileName).toBe('closed-2.queue-recovery.json');+ expect(mediaType).toBe('application/json');+ });++ it('discards only the selected project after confirmation and releases the lifecycle lock', async () => {+ await renderNotice({ openProjectIds: ['open-project'] });+ await clickButton('shell.queueRecovery.next');+ await clickButton('shell.queueRecovery.discard');+ expect(document.body.textContent).toContain('shell.queueRecovery.discardConfirmBody');+ await act(() => userEvent.click(document.querySelector<HTMLButtonElement>('[data-testid="confirm-discard"]')!));+ await vi.waitFor(() => expect(harness.deleteForProject).toHaveBeenCalledOnce());++ expect(harness.deleteForProject).toHaveBeenCalledWith('closed-2');+ expect(harness.lockResult.kind === 'acquired' ? harness.lockResult.release : undefined).toHaveBeenCalledOnce();+ });++ it('opens the selected existing project without reading its journal payload', async () => {+ await renderNotice({ openProjectIds: ['open-project'] });+ await clickButton('shell.queueRecovery.open');+ await vi.waitFor(() => expect(harness.onOpen).toHaveBeenCalledWith('closed-1'));++ expect(harness.listForProject).not.toHaveBeenCalled();+ });++ it('includes every journal project when no open-project filter is supplied', async () => {+ await renderNotice();+ await clickButton('shell.queueRecovery.next');+ await clickButton('shell.queueRecovery.next');++ expect(document.body.textContent).toContain('open-project');+ });++ it('fails closed when another tab holds the project lifecycle lock', async () => {+ harness.lockResult = { kind: 'contended' };+ await renderNotice({ openProjectIds: ['open-project'] });+ await clickButton('shell.queueRecovery.discard');+ await act(() => userEvent.click(document.querySelector<HTMLButtonElement>('[data-testid="confirm-discard"]')!));+ await vi.waitFor(() => expect(document.body.textContent).toContain('shell.queueRecovery.lockContended'));++ expect(harness.deleteForProject).not.toHaveBeenCalled();+ });++ it('shows unknown recovery state when IndexedDB cannot be inspected', async () => {+ harness.listProjectIds.mockResolvedValueOnce({ kind: 'unavailable' });+ await renderNotice();++ expect(document.body.textContent).toContain('shell.queueRecovery.storageUnavailable');+ expect(document.body.textContent).not.toContain('shell.queueRecovery.none');+ });++ it('suppresses downloads and state updates when the account or component expires during export', async () => {+ let resolveLoad: ((value: { entries: []; kind: 'available'; removedCorrupt: 0 }) => void) | null = null;+ harness.listForProject.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveLoad = resolve;+ })+ );+ await renderNotice({ openProjectIds: ['open-project'] });+ await clickButton('shell.queueRecovery.export');+ const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>('button'));+ expect(buttons.every((button) => button.disabled)).toBe(true);++ harness.accountCurrent = false;+ await act(() => root?.unmount());+ await act(() => resolveLoad?.({ entries: [], kind: 'available', removedCorrupt: 0 }));++ expect(harness.downloadText).not.toHaveBeenCalled();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.tsxnew file mode 100644index 0000000000..717b4a3341--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.tsx@@ -0,0 +1,250 @@+import { Alert, Button, HStack, Spinner, Stack, Text } from '@chakra-ui/react';+import { downloadText } from '@platform/browser/downloadBlob';+import { useMountEffect } from '@platform/react/useMountEffect';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';+import { useQueryClient } from '@tanstack/react-query';+import { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import {+ createQueueRecoveryExport,+ discardQueueRecoveryProject,+ getQueueRecoveryExportName,+ QueueRecoveryError,+} from './queueRecovery';+import { getQueueRecoveryProjectIdsQueryKey, useQueueRecoveryProjectIds } from './useQueueRecoveryProjectIds';++type PendingAction = 'discard' | 'export' | 'open';++const getErrorKey = (error: unknown): string => {+ if (error instanceof QueueRecoveryError) {+ if (error.code === 'lock-contended') {+ return 'shell.queueRecovery.lockContended';+ }+ if (error.code === 'lock-unavailable') {+ return 'shell.queueRecovery.lockUnavailable';+ }+ return 'shell.queueRecovery.storageUnavailable';+ }+ return 'shell.queueRecovery.actionFailed';+};++export const QueueRecoveryNotice = ({+ onOpen,+ openProjectIds,+}: {+ onOpen?: (projectId: string) => Promise<void>;+ openProjectIds?: readonly string[];+}) => {+ const { t } = useTranslation();+ const queryClient = useQueryClient();+ const [owner] = useState(captureAccountScope);+ const query = useQueueRecoveryProjectIds(owner);+ const [selectedIndex, setSelectedIndex] = useState(0);+ const [pendingAction, setPendingAction] = useState<PendingAction | null>(null);+ const [discardProjectId, setDiscardProjectId] = useState<string | null>(null);+ const [errorKey, setErrorKey] = useState<string | null>(null);+ const isMountedRef = useRef(true);+ const actionInFlightRef = useRef(false);++ useMountEffect(() => {+ isMountedRef.current = true;+ return () => {+ isMountedRef.current = false;+ };+ });++ const openIds = new Set(openProjectIds);+ const projectIds =+ query.data?.kind === 'available' ? query.data.projectIds.filter((projectId) => !openIds.has(projectId)) : [];+ const visibleIndex = Math.min(selectedIndex, Math.max(0, projectIds.length - 1));+ const projectId = projectIds[visibleIndex];+ const isBusy = pendingAction !== null || discardProjectId !== null;++ const canUpdate = useCallback(() => isMountedRef.current && isAccountScopeCurrent(owner), [owner]);+ const exportProject = useCallback(async () => {+ if (!projectId || isBusy || actionInFlightRef.current || !canUpdate()) {+ return;+ }+ const selectedProjectId = projectId;+ actionInFlightRef.current = true;+ setErrorKey(null);+ setPendingAction('export');+ try {+ const json = await createQueueRecoveryExport(owner, selectedProjectId);+ if (!canUpdate()) {+ return;+ }+ downloadText(json, getQueueRecoveryExportName(selectedProjectId), 'application/json');+ await queryClient.invalidateQueries({ queryKey: getQueueRecoveryProjectIdsQueryKey(owner) });+ } catch (error) {+ if (canUpdate()) {+ setErrorKey(getErrorKey(error));+ }+ } finally {+ actionInFlightRef.current = false;+ if (canUpdate()) {+ setPendingAction(null);+ }+ }+ }, [canUpdate, isBusy, owner, projectId, queryClient]);+ const openProject = useCallback(async () => {+ if (!onOpen || !projectId || isBusy || actionInFlightRef.current || !canUpdate()) {+ return;+ }+ const selectedProjectId = projectId;+ actionInFlightRef.current = true;+ setErrorKey(null);+ setPendingAction('open');+ try {+ await onOpen(selectedProjectId);+ } catch {+ if (canUpdate()) {+ setErrorKey('shell.queueRecovery.openFailed');+ }+ } finally {+ actionInFlightRef.current = false;+ if (canUpdate()) {+ setPendingAction(null);+ }+ }+ }, [canUpdate, isBusy, onOpen, projectId]);+ const confirmDiscard = useCallback(async () => {+ const selectedProjectId = discardProjectId;+ if (!selectedProjectId || pendingAction !== null || actionInFlightRef.current) {+ return;+ }+ actionInFlightRef.current = true;+ setErrorKey(null);+ setPendingAction('discard');+ try {+ await discardQueueRecoveryProject(owner, selectedProjectId);+ if (!canUpdate()) {+ return;+ }+ await queryClient.invalidateQueries({ queryKey: getQueueRecoveryProjectIdsQueryKey(owner) });+ } catch (error) {+ if (canUpdate()) {+ setErrorKey(getErrorKey(error));+ }+ } finally {+ actionInFlightRef.current = false;+ if (canUpdate()) {+ setPendingAction(null);+ setDiscardProjectId(null);+ }+ }+ }, [canUpdate, discardProjectId, owner, pendingAction, queryClient]);+ const selectPrevious = useCallback(() => {+ setErrorKey(null);+ setSelectedIndex((index) => Math.max(0, index - 1));+ }, []);+ const selectNext = useCallback(() => {+ setErrorKey(null);+ setSelectedIndex((index) => Math.min(projectIds.length - 1, index + 1));+ }, [projectIds.length]);+ const openDiscardConfirmation = useCallback(() => {+ if (projectId && !isBusy && canUpdate()) {+ setDiscardProjectId(projectId);+ }+ }, [canUpdate, isBusy, projectId]);+ const closeDiscardConfirmation = useCallback(() => {+ if (pendingAction === null) {+ setDiscardProjectId(null);+ }+ }, [pendingAction]);+ const handleExport = useCallback(() => void exportProject(), [exportProject]);+ const handleOpen = useCallback(() => void openProject(), [openProject]);++ if (query.isPending) {+ return (+ <HStack color="fg.muted" px="4" py="2">+ <Spinner size="xs" />+ <Text fontSize="sm">{t('shell.queueRecovery.loading')}</Text>+ </HStack>+ );+ }+ if (query.data?.kind === 'unavailable' || query.isError) {+ return (+ <Alert.Root borderRadius="none" status="warning" variant="surface">+ <Alert.Indicator />+ <Alert.Content>+ <Alert.Title>{t('shell.queueRecovery.storageUnavailableTitle')}</Alert.Title>+ <Alert.Description>{t('shell.queueRecovery.storageUnavailable')}</Alert.Description>+ </Alert.Content>+ </Alert.Root>+ );+ }+ if (!projectId) {+ return null;+ }++ return (+ <>+ <Alert.Root borderRadius="none" status="warning" variant="surface">+ <Alert.Indicator />+ <Alert.Content>+ <HStack align="center" flexWrap="wrap" gap="4" justify="space-between" w="full">+ <Stack gap="0.5" minW="0">+ <Alert.Title>{t('shell.queueRecovery.title')}</Alert.Title>+ <Alert.Description overflowWrap="anywhere">+ {t('shell.queueRecovery.description', { projectId })}+ {projectIds.length > 1+ ? ` ${t('shell.queueRecovery.position', {+ count: projectIds.length,+ number: visibleIndex + 1,+ })}`+ : null}+ </Alert.Description>+ {errorKey ? <Text color="fg.error">{t(errorKey)}</Text> : null}+ </Stack>+ <HStack flexShrink="0" flexWrap="wrap">+ {projectIds.length > 1 ? (+ <>+ <Button disabled={isBusy || visibleIndex === 0} onClick={selectPrevious} size="sm" variant="ghost">+ {t('shell.queueRecovery.previous')}+ </Button>+ <Button+ disabled={isBusy || visibleIndex === projectIds.length - 1}+ onClick={selectNext}+ size="sm"+ variant="ghost"+ >+ {t('shell.queueRecovery.next')}+ </Button>+ </>+ ) : null}+ {onOpen ? (+ <Button disabled={isBusy} loading={pendingAction === 'open'} onClick={handleOpen} size="sm">+ {t('shell.queueRecovery.open')}+ </Button>+ ) : null}+ <Button+ disabled={isBusy}+ loading={pendingAction === 'export'}+ onClick={handleExport}+ size="sm"+ variant="outline"+ >+ {t('shell.queueRecovery.export')}+ </Button>+ <Button disabled={isBusy} onClick={openDiscardConfirmation} size="sm" variant="ghost">+ {t('shell.queueRecovery.discard')}+ </Button>+ </HStack>+ </HStack>+ </Alert.Content>+ </Alert.Root>+ <ConfirmDialog+ body={t('shell.queueRecovery.discardConfirmBody')}+ confirmLabel={t('shell.queueRecovery.discard')}+ isDestructive+ isOpen={discardProjectId !== null}+ title={t('shell.queueRecovery.discardConfirmTitle')}+ onClose={closeDiscardConfirmation}+ onConfirm={confirmDiscard}+ />+ </>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/activeQueueRuns.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/activeQueueRuns.tsnew file mode 100644index 0000000000..bf2b811d08--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/activeQueueRuns.ts@@ -0,0 +1,14 @@+import type { Project } from '@workbench/projectContracts';++export const hasActiveQueueRuns = (project: Pick<Project, 'queue'>): boolean =>+ project.queue.items.some(+ (item) => item.status === 'pending' || item.status === 'running' || item.cancellationPending === true+ );++export const hasInFlightQueueRuns = (project: Pick<Project, 'queue'>): boolean =>+ project.queue.items.some(+ (item) =>+ item.status === 'running' ||+ item.cancellationPending === true ||+ (item.status === 'pending' && Boolean(item.backendBatchId || item.backendItemIds?.length))+ );diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/localQueueItemSource.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/localQueueItemSource.test.tsindex 076f3b2614..0509c057ab 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/localQueueItemSource.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/localQueueItemSource.test.ts@@ -4,7 +4,7 @@ import { buildQueueItemOrigin } from '@features/queue/contracts';import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { describe, expect, it, vi } from 'vitest';-import { getLocalQueueItemSource } from './useLocalGenerateValues';+import { getLocalQueueItemSource } from './useLocalRecallSnapshot';vi.mock('@features/queue/devices', async (importOriginal) => {const original = (await importOriginal()) as Record<string, unknown>;diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.tsindex eb9f0464c3..38d05641cc 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts@@ -1,11 +1,13 @@import type { GenerateWidgetValues } from '@features/generation/contracts';+import { createDefaultVideoWidgetValues } from '@features/video';import { describe, expect, it } from 'vitest';import {buildQueueRecallValues,buildVideoQueueRecallPatch,getQueueRecallCapabilities,+ getVideoQueueRecallCapabilities,planQueueRecall,} from './queueRecall';@@ -163,6 +165,32 @@ describe('buildQueueRecallValues', () => {});describe('buildVideoQueueRecallPatch', () => {+ it('recalls exact video settings or a randomized remix without crossing into Generate', () => {+ const snapshot = {+ ...createDefaultVideoWidgetValues(),+ positivePrompt: 'snapshot prompt',+ seed: 123,+ shouldRandomizeSeed: false,+ };+ expect(getVideoQueueRecallCapabilities(snapshot, {})).toEqual({+ all: true,+ remix: true,+ prompts: true,+ seed: true,+ dimensions: false,+ clipSkip: false,+ });+ expect(+ planQueueRecall('all', { current: null, isVideoItem: true, meta: {}, snapshot: null, videoSnapshot: snapshot })+ ).toEqual({ target: 'video', patch: snapshot });+ expect(buildVideoQueueRecallPatch('remix', {}, snapshot)).toEqual({ ...snapshot, shouldRandomizeSeed: true });+ expect(snapshot.shouldRandomizeSeed).toBe(false);+ expect(buildVideoQueueRecallPatch('seed', { seed: 456 }, snapshot)).toEqual({+ seed: 456,+ shouldRandomizeSeed: false,+ });+ });+it('patches only the prompt keys, so the rest of the Video panel is untouched', () => {expect(buildVideoQueueRecallPatch('prompts', { negativePrompt: 'blurry', positivePrompt: 'a fox running' })diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.tsindex e4b458ce96..b6e018d0bf 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts@@ -3,6 +3,8 @@ import type { QueueGenerationMeta } from '@features/queue/contracts';import type { VideoWidgetValues } from '@features/video';import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-actions';+import { cloneVideoWidgetValues } from '@features/video';+/*** Snapshot/session-based recall for queue items, mirroring the image-metadata* recall semantics: partial kinds merge the recalled fields into the CURRENT@@ -23,6 +25,18 @@ export const getQueueRecallCapabilities = (seed: meta.seed !== undefined || (snapshot !== null && !snapshot.shouldRandomizeSeed),});+export const getVideoQueueRecallCapabilities = (+ snapshot: VideoWidgetValues | null,+ meta: QueueGenerationMeta+): ImageRecallCapabilities => ({+ all: snapshot !== null,+ clipSkip: false,+ dimensions: false,+ prompts: snapshot !== null || meta.positivePrompt !== undefined,+ remix: snapshot !== null,+ seed: meta.seed !== undefined || (snapshot !== null && !snapshot.shouldRandomizeSeed),+});+export const buildQueueRecallValues = (kind: ImageRecallKind,{@@ -99,27 +113,26 @@ export const buildQueueRecallValues = (return snapshot ? { ...current, clipSkip: snapshot.clipSkip } : null;};-/**- * The Video-panel equivalent of {@link buildQueueRecallValues}, for a queue item- * this client submitted from Video. Video's prompt is its own widget value, so a- * video item's prompt must not be recalled into Generate's — the two panels hold- * independent text.- *- * Only the verbs a video item can actually offer are handled. Its `snapshot` in- * {@link getQueueRecallCapabilities} is always null (that lookup is Generate-- * shaped), so `all`/`remix`/`dimensions`/`clipSkip` are disabled for video items- * and never reach here; prompts and seed come from the session meta, which is- * recorded identically for video and image batches.- *- * Returns a PATCH, not a whole values object: the panel's other settings belong- * to whatever the user has configured now, and a wholesale write would drag a- * model-family transition along with it.- */export const buildVideoQueueRecallPatch = (kind: ImageRecallKind,- meta: QueueGenerationMeta+ meta: QueueGenerationMeta,+ snapshot: VideoWidgetValues | null = null): Partial<VideoWidgetValues> | null => {+ if (kind === 'all' || kind === 'remix') {+ if (!snapshot) {+ return null;+ }+ const values = cloneVideoWidgetValues(snapshot);+ return kind === 'remix' ? { ...values, shouldRandomizeSeed: true } : values;+ }if (kind === 'prompts') {+ if (snapshot) {+ return {+ positivePrompt: snapshot.positivePrompt,+ negativePrompt: snapshot.negativePrompt,+ negativePromptEnabled: snapshot.negativePromptEnabled,+ };+ }if (meta.positivePrompt === undefined) {return null;}@@ -141,7 +154,8 @@ export const buildVideoQueueRecallPatch = (}if (kind === 'seed') {- return meta.seed === undefined ? null : { seed: meta.seed, shouldRandomizeSeed: false };+ const seed = meta.seed ?? (snapshot && !snapshot.shouldRandomizeSeed ? snapshot.seed : undefined);+ return seed === undefined ? null : { seed, shouldRandomizeSeed: false };}return null;@@ -165,6 +179,7 @@ export const planQueueRecall = (isVideoItem,meta,snapshot,+ videoSnapshot = null,}: {current: GenerateWidgetValues | null;/**@@ -175,10 +190,11 @@ export const planQueueRecall = (isVideoItem: boolean;meta: QueueGenerationMeta;snapshot: GenerateWidgetValues | null;+ videoSnapshot?: VideoWidgetValues | null;}): QueueRecallPlan | null => {if (isVideoItem) {- const patch = buildVideoQueueRecallPatch(kind, meta);+ const patch = buildVideoQueueRecallPatch(kind, meta, videoSnapshot);return patch ? { patch, target: 'video' } : null;}diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecallCache.browser.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecallCache.browser.test.tsindex 83f8014bda..1266db78af 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecallCache.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecallCache.browser.test.ts@@ -236,9 +236,22 @@ describe('IndexedDB queue recall cache', () => {journal.record('project-1', {cancellable: true,id: 'queue-1',- snapshot: { backendSubmission: {}, sourceId: 'workflow', submittedAt: 'now' },+ snapshot: {+ backendSubmission: { batchCount: 1, graph: { edges: [], id: 'graph', nodes: {} }, kind: 'workflow' },+ canvas: {+ document: { bbox: { height: 512, width: 512, x: 0, y: 0 }, height: 512, width: 512 },+ documentRevision: 1,+ },+ destination: 'gallery',+ filterIntermediateResults: true,+ galleryBoardId: null,+ graph: { id: 'graph', label: 'Graph' },+ presentation: { batchCount: 1, height: 512, width: 512 },+ sourceId: 'workflow',+ submittedAt: '2026-09-03T00:00:00.000Z',+ },status: 'pending',- } as never)+ })).resolves.toEqual({ kind: 'unavailable' });await expect(cache.put(createSnapshot('queue-1'))).resolves.toEqual({ kind: 'stored' });diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecovery.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecovery.tsnew file mode 100644index 0000000000..a572e397be--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecovery.ts@@ -0,0 +1,116 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { acquireProjectMutationLock } from '@workbench/projects/projectLifecycleLocks';++import { createAccountOwnedQueueRunJournal, type QueueRunJournal } from './queueRunJournal';++export const QUEUE_RECOVERY_EXPORT_FORMAT = 'invokeai-webv2-queue-run-recovery';+export const QUEUE_RECOVERY_EXPORT_SCHEMA_VERSION = 1;++export type QueueRecoveryProjectIdsResult = { kind: 'available'; projectIds: string[] } | { kind: 'unavailable' };++export type QueueRecoveryErrorCode = 'lock-contended' | 'lock-unavailable' | 'storage-unavailable';++export class QueueRecoveryError extends Error {+ constructor(readonly code: QueueRecoveryErrorCode) {+ super(code);+ this.name = 'QueueRecoveryError';+ }+}++interface QueueRecoveryDependencies {+ acquireLock?: typeof acquireProjectMutationLock;+ journal?: (owner: AccountScope) => Promise<QueueRunJournal>;+ now?: () => number;+}++const openJournal = (owner: AccountScope, dependencies: QueueRecoveryDependencies): Promise<QueueRunJournal> =>+ (dependencies.journal ?? createAccountOwnedQueueRunJournal)(owner);++export const listQueueRecoveryProjectIds = async (+ owner: AccountScope,+ dependencies: QueueRecoveryDependencies = {}+): Promise<QueueRecoveryProjectIdsResult> => {+ let journal: QueueRunJournal | null = null;+ try {+ assertAccountScopeCurrent(owner);+ journal = await openJournal(owner, dependencies);+ assertAccountScopeCurrent(owner);+ const result = await journal.listProjectIds();+ assertAccountScopeCurrent(owner);+ return result.kind === 'available'+ ? { kind: 'available', projectIds: [...new Set(result.projectIds)].sort() }+ : result;+ } catch {+ return { kind: 'unavailable' };+ } finally {+ journal?.close();+ }+};++export const createQueueRecoveryExport = async (+ owner: AccountScope,+ projectId: string,+ dependencies: QueueRecoveryDependencies = {}+): Promise<string> => {+ let journal: QueueRunJournal | null = null;+ try {+ assertAccountScopeCurrent(owner);+ journal = await openJournal(owner, dependencies);+ assertAccountScopeCurrent(owner);+ const result = await journal.listForProject(projectId);+ assertAccountScopeCurrent(owner);+ if (result.kind === 'unavailable') {+ throw new QueueRecoveryError('storage-unavailable');+ }+ return JSON.stringify({+ exportedAt: new Date((dependencies.now ?? Date.now)()).toISOString(),+ format: QUEUE_RECOVERY_EXPORT_FORMAT,+ projectId,+ runs: result.entries.map(({ item, queueItemId, submissionOrder }) => ({ item, queueItemId, submissionOrder })),+ schemaVersion: QUEUE_RECOVERY_EXPORT_SCHEMA_VERSION,+ });+ } finally {+ journal?.close();+ }+};++export const discardQueueRecoveryProject = async (+ owner: AccountScope,+ projectId: string,+ dependencies: QueueRecoveryDependencies = {}+): Promise<void> => {+ assertAccountScopeCurrent(owner);+ const lock = await (dependencies.acquireLock ?? acquireProjectMutationLock)(owner.storageSuffix, projectId);+ if (lock.kind === 'contended') {+ throw new QueueRecoveryError('lock-contended');+ }+ if (lock.kind === 'unavailable') {+ throw new QueueRecoveryError('lock-unavailable');+ }++ let journal: QueueRunJournal | null = null;+ try {+ assertAccountScopeCurrent(owner);+ journal = await openJournal(owner, dependencies);+ assertAccountScopeCurrent(owner);+ const result = await journal.deleteForProject(projectId);+ assertAccountScopeCurrent(owner);+ if (result.kind === 'unavailable') {+ throw new QueueRecoveryError('storage-unavailable');+ }+ } finally {+ journal?.close();+ await lock.release();+ }+};++export const getQueueRecoveryExportName = (projectId: string): string => {+ const safeProjectId = projectId+ .trim()+ .replaceAll(/[^\w.-]+/g, '-')+ .replaceAll(/^-+|-+$/g, '')+ .slice(0, 96);+ return `${safeProjectId || 'project'}.queue-recovery.json`;+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.tsindex 074acc4740..c22f24675a 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts@@ -5,6 +5,7 @@ import {openWorkbenchDatabase,type WorkbenchDatabase,} from '@workbench/projects/workbenchDatabase';+import { createWorkbenchStore } from '@workbench/workbenchStore';import { afterEach, describe, expect, it } from 'vitest';import { createIndexedDbQueueRunJournal } from './queueRunJournal';@@ -12,7 +13,7 @@ import { createIndexedDbQueueRunJournal } from './queueRunJournal';const databases: WorkbenchDatabase[] = [];const suffixes = new Set<string>();-const createJournal = async (options?: { maxRunBytes?: number }) => {+const createJournal = async (options?: Parameters<typeof createIndexedDbQueueRunJournal>[1]) => {const suffix = `:queue-journal-test:${crypto.randomUUID()}`;suffixes.add(suffix);const database = await openWorkbenchDatabase(suffix);@@ -25,23 +26,28 @@ const createItem = (overrides: Partial<WorkbenchQueueItem> = {}): WorkbenchQueuecancellable: true,id: 'queue-item-1',snapshot: {- backendSubmission: { error: 'test fixture', kind: 'invalid' },- canvas: { marker: 'canvas' },+ backendSubmission: {+ batchCount: 1,+ graph: { edges: [], id: 'backend-graph-1', nodes: {} },+ kind: 'workflow',+ },+ canvas: {+ document: { bbox: { height: 512, width: 512, x: 0, y: 0 }, height: 512, width: 512 },+ documentRevision: 1,+ },destination: 'gallery',filterIntermediateResults: true,galleryBoardId: null,- graph: { edges: [], id: 'graph-1', label: 'Graph', nodes: [], updatedAt: 'now', version: 1 },- presentation: { batchCount: 1 },+ graph: { id: 'graph-1', label: 'Graph' },+ presentation: { batchCount: 1, height: 512, width: 512 },sourceId: 'workflow',submittedAt: '2026-09-03T00:00:00.000Z',- widgetInstances: {},- widgetStates: {},},status: 'pending',...overrides,}) as WorkbenchQueueItem;-const rejectFirstPutWithQuota = (database: WorkbenchDatabase): WorkbenchDatabase => {+const rejectFirstPutWithQuota = (database: WorkbenchDatabase, failingStore = 'queueRuns'): WorkbenchDatabase => {let isArmed = true;return new Proxy(database, {get(target, property) {@@ -53,7 +59,7 @@ const rejectFirstPutWithQuota = (database: WorkbenchDatabase): WorkbenchDatabaseif (transactionProperty === 'objectStore') {return (storeName: string) => {const store = transactionTarget.objectStore(storeName);- if (storeName !== 'queueRuns') {+ if (storeName !== failingStore) {return store;}return new Proxy(store, {@@ -94,6 +100,91 @@ afterEach(async () => {});describe('IndexedDB queue run journal', () => {+ it('queues receipt cleanup when explicitly discarding a project journal', async () => {+ const { journal } = await createJournal();+ await journal.record('project-1', createItem());+ await journal.record('project-2', createItem({ id: 'other-run' }));+ expect(await journal.deleteForProject('project-1')).toEqual({ kind: 'removed' });+ expect(await journal.listPendingReceipts()).toMatchObject({+ kind: 'available',+ entries: [{ projectId: 'project-1', queueItemId: 'queue-item-1' }],+ });+ expect(await journal.listProjectIds()).toEqual({ kind: 'available', projectIds: ['project-2'] });+ });++ it('skips malformed receipt cleanup keys without blocking later acknowledgements', async () => {+ const { database, journal } = await createJournal();+ await database.put('queueReceiptAcks', { key: '0-corrupt', projectId: '', queueItemId: 'bad' });+ await journal.record('project-1', createItem({ backendItemIds: [11], status: 'running' }));+ expect(await journal.listPendingReceipts()).toEqual({+ kind: 'available',+ entries: [+ {+ key: JSON.stringify(['project-1', 'queue-item-1']),+ projectId: 'project-1',+ queueItemId: 'queue-item-1',+ },+ ],+ });+ });++ it('lists distinct projects without decoding their run payloads', async () => {+ const { database, journal } = await createJournal();+ await journal.record('project-1', createItem());+ await journal.record('project-1', createItem({ id: 'run-2' }));+ await journal.record('project-2', createItem());+ const records = await database.getAll('queueRuns');+ for (const record of records) {+ await database.put('queueRuns', { ...record, itemJson: 'invalid-json' });+ }+ expect(await journal.listProjectIds()).toEqual({+ kind: 'available',+ projectIds: ['project-1', 'project-2'],+ });+ journal.close();+ expect(await journal.listProjectIds()).toEqual({ kind: 'unavailable' });+ });++ it('retains the run when receipt cleanup cannot be stored and permits retry after quota recovers', async () => {+ const { database, journal } = await createJournal();+ await journal.record('project-1', createItem());+ const recoveringJournal = createIndexedDbQueueRunJournal(rejectFirstPutWithQuota(database, 'queueReceiptAcks'));+ expect(await recoveringJournal.settle('project-1', 'queue-item-1')).toEqual({ kind: 'unavailable' });+ expect((await journal.listAll()).kind).toBe('available');+ expect(await journal.listAll()).toMatchObject({ entries: [{ queueItemId: 'queue-item-1' }] });+ expect(await recoveringJournal.settle('project-1', 'queue-item-1')).toEqual({ kind: 'removed' });+ expect(await journal.listAll()).toMatchObject({ entries: [] });+ expect(await journal.listPendingReceipts()).toMatchObject({ entries: [{ queueItemId: 'queue-item-1' }] });+ });++ it('retains receipt cleanup after settlement and retries it across adapter reloads', async () => {+ const { database, journal } = await createJournal();+ await journal.record('project-1', createItem({ backendItemIds: [11], status: 'running' }));++ await expect(journal.listPendingReceipts()).resolves.toMatchObject({+ kind: 'available',+ entries: [{ projectId: 'project-1', queueItemId: 'queue-item-1' }],+ });+ await journal.settle('project-1', 'queue-item-1');+ const reloaded = createIndexedDbQueueRunJournal(database);+ await expect(reloaded.listPendingReceipts()).resolves.toMatchObject({+ kind: 'available',+ entries: [{ projectId: 'project-1', queueItemId: 'queue-item-1' }],+ });+ await reloaded.acknowledgeReceipt('project-1', 'queue-item-1');+ await expect(reloaded.listPendingReceipts()).resolves.toEqual({ kind: 'available', entries: [] });+ });++ it('does not repeatedly enqueue receipt cleanup for already acknowledged active runs', async () => {+ const { journal } = await createJournal();+ const item = createItem({ backendItemIds: [11, 12], status: 'running' });+ await journal.record('project-1', item);+ await journal.acknowledgeReceipt('project-1', item.id);+ await journal.record('project-1', { ...item, completedBackendItemIds: [11] });+ await journal.settle('project-1', item.id);++ await expect(journal.listPendingReceipts()).resolves.toEqual({ kind: 'available', entries: [] });+ });it('round-trips active runs and coalesces status updates', async () => {const { journal } = await createJournal();await expect(journal.record('project-1', createItem())).resolves.toEqual({ kind: 'stored' });@@ -117,6 +208,49 @@ describe('IndexedDB queue run journal', () => {});});+ it('round-trips a durable cancellation intent but rejects settled cancellation history', async () => {+ const { journal } = await createJournal();++ await expect(+ journal.record('project-1', createItem({ backendItemIds: [11], cancellationPending: true, status: 'cancelled' }))+ ).resolves.toEqual({ kind: 'stored' });+ await expect(journal.listForProject('project-1')).resolves.toMatchObject({+ entries: [{ item: { backendItemIds: [11], cancellationPending: true, status: 'cancelled' } }],+ kind: 'available',+ });+ await expect(+ journal.record('project-1', createItem({ backendItemIds: [11], status: 'cancelled' }))+ ).resolves.toEqual({ kind: 'invalid' });+ });++ it('restores a round-tripped run through the workbench trust boundary', async () => {+ const { journal } = await createJournal();+ const store = createWorkbenchStore();+ const projectId = store.getState().activeProjectId;+ const item = createItem({ backendBatchId: 'batch-1', backendItemIds: [11], status: 'running' });+ await journal.record(projectId, item);++ const loaded = await journal.listForProject(projectId);+ expect(loaded.kind).toBe('available');+ store.commands.queue.restoreFromJournal({+ items: loaded.kind === 'available' ? loaded.entries.map((entry) => entry.item) : [],+ projectId,+ });++ expect(store.getState().projects[0]?.queue.items).toEqual([+ expect.objectContaining({+ backendBatchId: 'batch-1',+ backendItemIds: [11],+ id: item.id,+ snapshot: expect.objectContaining({+ canvas: item.snapshot.canvas,+ graph: { id: 'graph-1', label: 'Graph' },+ }),+ status: 'running',+ }),+ ]);+ });+it('restores newest-first submission order without moving a run when its status changes', async () => {const { journal } = await createJournal();await journal.record('project-1', createItem({ id: 'queue-item-1' }));@@ -156,6 +290,19 @@ describe('IndexedDB queue run journal', () => {await expect(journal.listAll()).resolves.toMatchObject({ entries: [], kind: 'available' });});+ it('deletes all runs for one project without touching another', async () => {+ const { journal } = await createJournal();+ await journal.record('project-1', createItem({ id: 'one' }));+ await journal.record('project-1', createItem({ id: 'two' }));+ await journal.record('project-2', createItem({ id: 'three' }));++ await expect(journal.deleteForProject('project-1')).resolves.toEqual({ kind: 'removed' });+ await expect(journal.listAll()).resolves.toMatchObject({+ entries: [{ item: { id: 'three' }, projectId: 'project-2' }],+ kind: 'available',+ });+ });+it('skips corrupt rows without hiding valid runs', async () => {const { database, journal } = await createJournal();await journal.record('project-1', createItem());@@ -177,7 +324,7 @@ describe('IndexedDB queue run journal', () => {expect(await database.get('queueRuns', '["project-2","queue-item-2"]')).toBeUndefined();});- it('keeps restored payloads untrusted until the project-aware normalizer accepts them', async () => {+ it('removes deeply invalid payloads at the storage boundary', async () => {const { database, journal } = await createJournal();const item = createItem();await database.put('queueRuns', {@@ -196,11 +343,31 @@ describe('IndexedDB queue run journal', () => {});const loaded = await journal.listAll();- expect(loaded).toMatchObject({ kind: 'available', removedCorrupt: 0 });- if (loaded.kind === 'available') {- const candidate: unknown = loaded.entries[0]?.item;- expect(candidate).toMatchObject({ id: 'queue-item-1' });- }+ expect(loaded).toEqual({ entries: [], kind: 'available', removedCorrupt: 1 });+ expect(await database.count('queueRuns')).toBe(0);+ });++ it('removes malformed rows without hiding valid runs', async () => {+ const { database, journal } = await createJournal();+ await journal.record('project-1', createItem({ id: 'valid' }));+ const malformed = createItem({ id: 'malformed' }) as unknown as Record<string, unknown>;+ malformed.backendItemIds = 7;+ await database.put('queueRuns', {+ itemJson: JSON.stringify(malformed),+ key: '["project-1","malformed"]',+ projectId: 'project-1',+ queueItemId: 'malformed',+ schemaVersion: 1,+ submissionOrder: 2,+ updatedAt: 2,+ });++ await expect(journal.listForProject('project-1')).resolves.toMatchObject({+ entries: [{ item: { id: 'valid' } }],+ kind: 'available',+ removedCorrupt: 1,+ });+ expect(await database.get('queueRuns', '["project-1","malformed"]')).toBeUndefined();});it('rejects malformed and oversized records without poisoning the journal', async () => {@@ -208,10 +375,19 @@ describe('IndexedDB queue run journal', () => {const { journal } = await createJournal({ maxRunBytes: baselineBytes + 8 });await expect(journal.record('', createItem())).resolves.toEqual({ kind: 'invalid' });await expect(journal.record('project-1', createItem({ id: '' }))).resolves.toEqual({ kind: 'invalid' });- const cyclic = createItem() as WorkbenchQueueItem & { cycle?: unknown };- cyclic.cycle = cyclic;+ const cyclic = createItem();+ if (cyclic.snapshot.backendSubmission.kind === 'invalid') {+ throw new Error('Expected a compiled submission');+ }+ (cyclic.snapshot.backendSubmission.graph as unknown as Record<string, unknown>).cycle =+ cyclic.snapshot.backendSubmission;await expect(journal.record('project-1', cyclic)).resolves.toEqual({ kind: 'invalid' });- await expect(journal.record('project-1', createItem({ error: 'x'.repeat(256) }))).resolves.toEqual({+ const oversized = createItem();+ if (oversized.snapshot.backendSubmission.kind === 'invalid') {+ throw new Error('Expected a compiled submission');+ }+ (oversized.snapshot.backendSubmission.graph as unknown as Record<string, unknown>).padding = 'x'.repeat(256);+ await expect(journal.record('project-1', oversized)).resolves.toEqual({kind: 'too-large',});await expect(journal.record('project-1', createItem())).resolves.toEqual({ kind: 'stored' });@@ -243,4 +419,54 @@ describe('IndexedDB queue run journal', () => {expect(journal.availability).toBe('available');await expect(journal.record('project-1', createItem())).resolves.toEqual({ kind: 'stored' });});++ it('bounds aggregate entry count without evicting active runs', async () => {+ const { journal } = await createJournal({ maxEntries: 1 });++ await expect(journal.record('project-1', createItem({ id: 'first' }))).resolves.toEqual({ kind: 'stored' });+ await expect(journal.record('project-1', createItem({ id: 'second' }))).resolves.toEqual({ kind: 'quota' });+ await expect(journal.record('project-1', createItem({ id: 'first', status: 'running' }))).resolves.toEqual({+ kind: 'stored',+ });+ await expect(journal.listAll()).resolves.toMatchObject({+ entries: [{ item: { id: 'first', status: 'running' } }],+ kind: 'available',+ });+ });++ it('bounds aggregate bytes without evicting active runs', async () => {+ const itemBytes = new TextEncoder().encode(JSON.stringify(createItem())).byteLength;+ const { journal } = await createJournal({ totalMaxBytes: itemBytes + 32 });++ await expect(journal.record('project-1', createItem({ id: 'first' }))).resolves.toEqual({ kind: 'stored' });+ await expect(journal.record('project-1', createItem({ id: 'second' }))).resolves.toEqual({ kind: 'quota' });+ await expect(journal.listAll()).resolves.toMatchObject({+ entries: [{ item: { id: 'first' } }],+ kind: 'available',+ });+ });++ it('never expires active rows to admit newer work', async () => {+ let currentTime = 100;+ const { journal } = await createJournal({ maxEntries: 1, now: () => currentTime });+ await journal.record('closed-project', createItem({ id: 'old-active-run' }));++ currentTime = 30 * 24 * 60 * 60 * 1_000;+ await expect(journal.record('open-project', createItem({ id: 'new-run' }))).resolves.toEqual({ kind: 'quota' });+ await expect(journal.listAll()).resolves.toMatchObject({+ entries: [{ item: { id: 'old-active-run' }, projectId: 'closed-project' }],+ kind: 'available',+ removedCorrupt: 0,+ });+ });++ it('repairs negative aggregate metadata before enforcing budgets', async () => {+ const { database, journal } = await createJournal({ maxEntries: 1 });+ await database.put('metadata', { key: 'queueRunCount', value: -100 });+ await database.put('metadata', { key: 'queueRunTotalBytes', value: -100 });++ await expect(journal.record('project-1', createItem({ id: 'first' }))).resolves.toEqual({ kind: 'stored' });+ await expect(journal.record('project-1', createItem({ id: 'second' }))).resolves.toEqual({ kind: 'quota' });+ await expect(database.get('metadata', 'queueRunCount')).resolves.toEqual({ key: 'queueRunCount', value: 1 });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.tsindex 696350683b..e95e7f594d 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.ts@@ -1,16 +1,22 @@import type { AccountScope } from '@platform/state/accountLifecycle';-import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';+import type { IDBPObjectStore } from 'idb';import { acquireAccountOwnedWorkbenchDatabase } from '@workbench/projects/accountOwnedWorkbenchDatabase';import {isWorkbenchDatabaseAvailable,WORKBENCH_DATABASE_METADATA_STORE,WORKBENCH_QUEUE_RUN_STORE,+ WORKBENCH_QUEUE_RECEIPT_STORE,+ type QueueReceiptAcknowledgement,type QueueRunDatabaseRecord,type WorkbenchDatabase,+ type WorkbenchDatabaseSchema,} from '@workbench/projects/workbenchDatabase';+import { normalizeRestoredQueueItem } from '@workbench/queue-integration/queueRunRestoration';export const QUEUE_RUN_MAX_BYTES = 32 * 1024 * 1024;+export const QUEUE_RUN_TOTAL_MAX_BYTES = 128 * 1024 * 1024;+export const QUEUE_RUN_MAX_ENTRIES = 10_000;export interface QueueRunJournalEntry {/** Untrusted serialized candidate. Normalize it against the current project before restoration. */@@ -29,21 +35,58 @@ export type QueueRunJournalSettleResult = { kind: 'removed' | 'unavailable' };export interface QueueRunJournal {readonly availability: 'available' | 'unavailable';close(): void;+ acknowledgeReceipt(projectId: string, queueItemId: string): Promise<QueueRunJournalSettleResult>;+ listPendingReceipts(): Promise<+ { entries: QueueReceiptAcknowledgement[]; kind: 'available' } | { kind: 'unavailable' }+ >;+ deleteForProject(projectId: string): Promise<QueueRunJournalSettleResult>;listAll(): Promise<QueueRunJournalLoadResult>;+ listProjectIds(): Promise<{ kind: 'available'; projectIds: string[] } | { kind: 'unavailable' }>;listForProject(projectId: string): Promise<QueueRunJournalLoadResult>;- record(projectId: string, item: WorkbenchQueueItem): Promise<QueueRunJournalWriteResult>;+ record(projectId: string, item: unknown): Promise<QueueRunJournalWriteResult>;settle(projectId: string, queueItemId: string): Promise<QueueRunJournalSettleResult>;}const getByteSize = (value: string): number => new TextEncoder().encode(value).byteLength;const QUEUE_RUN_SUBMISSION_SEQUENCE_KEY = 'queueRunSubmissionSequence';-const QUEUE_RUN_STORES = [WORKBENCH_DATABASE_METADATA_STORE, WORKBENCH_QUEUE_RUN_STORE] as const;+const QUEUE_RUN_TOTAL_BYTES_KEY = 'queueRunTotalBytes';+const QUEUE_RUN_COUNT_KEY = 'queueRunCount';+const QUEUE_RUN_STORES = [+ WORKBENCH_DATABASE_METADATA_STORE,+ WORKBENCH_QUEUE_RUN_STORE,+ WORKBENCH_QUEUE_RECEIPT_STORE,+] as const;+type ReceiptStore = IDBPObjectStore<+ WorkbenchDatabaseSchema,+ typeof QUEUE_RUN_STORES,+ typeof WORKBENCH_QUEUE_RECEIPT_STORE,+ 'readwrite'+>;+const queueReceiptAcknowledgement = async (store: ReceiptStore, record: QueueReceiptAcknowledgement): Promise<void> => {+ if (!(await store.getKey(record.key)) && (await store.count()) >= QUEUE_RUN_MAX_ENTRIES) {+ throw new DOMException('Queue receipt cleanup capacity exceeded.', 'QuotaExceededError');+ }+ await store.put(record);+};+type QueueRunStore = IDBPObjectStore<+ WorkbenchDatabaseSchema,+ typeof QUEUE_RUN_STORES,+ typeof WORKBENCH_QUEUE_RUN_STORE,+ 'readwrite'+>;+type MetadataStore = IDBPObjectStore<+ WorkbenchDatabaseSchema,+ typeof QUEUE_RUN_STORES,+ typeof WORKBENCH_DATABASE_METADATA_STORE,+ 'readwrite'+>;const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.length > 0;interface ActiveQueueItemEnvelope {+ cancellationPending?: boolean;cancellable: boolean;id: string;snapshot: { backendSubmission: object; sourceId: string; submittedAt: string };- status: 'pending' | 'running';+ status: 'cancelled' | 'pending' | 'running';}const isActiveQueueItemEnvelope = (value: unknown): value is ActiveQueueItemEnvelope => {if (!value || typeof value !== 'object') {@@ -53,7 +96,9 @@ const isActiveQueueItemEnvelope = (value: unknown): value is ActiveQueueItemEnveconst snapshot = item.snapshot as Partial<ActiveQueueItemEnvelope['snapshot']> | undefined;return (isNonEmptyString(item.id) &&- (item.status === 'pending' || item.status === 'running') &&+ (item.status === 'pending' ||+ item.status === 'running' ||+ (item.status === 'cancelled' && item.cancellationPending === true)) &&typeof item.cancellable === 'boolean' &&Boolean(snapshot && typeof snapshot === 'object') &&isNonEmptyString(snapshot?.sourceId) &&@@ -68,6 +113,13 @@ const observeTransaction = <T extends { done: Promise<unknown> }>(transaction: Tvoid transaction.done.catch(() => undefined);return transaction;};+const abortTransaction = (transaction: { abort(): void }): void => {+ try {+ transaction.abort();+ } catch {+ // A failed write may already have aborted the transaction.+ }+};const decodeRecord = (record: QueueRunDatabaseRecord, maxRunBytes: number): QueueRunJournalEntry | null => {if (@@ -86,8 +138,8 @@ const decodeRecord = (record: QueueRunDatabaseRecord, maxRunBytes: number): Queureturn null;}try {- const item: unknown = JSON.parse(record.itemJson);- return isActiveQueueItemEnvelope(item) && item.id === record.queueItemId+ const item = normalizeRestoredQueueItem(JSON.parse(record.itemJson));+ return item?.id === record.queueItemId? {item,projectId: record.projectId,@@ -102,35 +154,89 @@ const decodeRecord = (record: QueueRunDatabaseRecord, maxRunBytes: number): Queuexport const createIndexedDbQueueRunJournal = (database: WorkbenchDatabase,- { maxRunBytes = QUEUE_RUN_MAX_BYTES }: { maxRunBytes?: number } = {}+ {+ maxEntries = QUEUE_RUN_MAX_ENTRIES,+ maxRunBytes = QUEUE_RUN_MAX_BYTES,+ now = Date.now,+ totalMaxBytes = QUEUE_RUN_TOTAL_MAX_BYTES,+ }: {+ maxEntries?: number;+ maxRunBytes?: number;+ now?: () => number;+ totalMaxBytes?: number;+ } = {}): QueueRunJournal => {const runByteBudget =Number.isFinite(maxRunBytes) && maxRunBytes >= 0 ? Math.floor(maxRunBytes) : QUEUE_RUN_MAX_BYTES;+ const totalByteBudget =+ Number.isFinite(totalMaxBytes) && totalMaxBytes >= 0 ? Math.floor(totalMaxBytes) : QUEUE_RUN_TOTAL_MAX_BYTES;+ const entryBudget = Number.isSafeInteger(maxEntries) && maxEntries >= 0 ? maxEntries : QUEUE_RUN_MAX_ENTRIES;let isClosed = false;let isUnavailable = false;const isAvailable = (): boolean => !isClosed && !isUnavailable && isWorkbenchDatabaseAvailable(database);const markUnavailable = (): void => {isUnavailable = true;};+ const readCounters = async (+ runStore: QueueRunStore,+ metadataStore: MetadataStore+ ): Promise<{ count: number; totalBytes: number }> => {+ const storedTotal = await metadataStore.get(QUEUE_RUN_TOTAL_BYTES_KEY);+ const storedCount = await metadataStore.get(QUEUE_RUN_COUNT_KEY);+ if (+ Number.isSafeInteger(storedTotal?.value) &&+ storedTotal!.value >= 0 &&+ Number.isSafeInteger(storedCount?.value) &&+ storedCount!.value >= 0+ ) {+ return { count: storedCount!.value, totalBytes: storedTotal!.value };+ }+ let count = 0;+ let totalBytes = 0;+ let cursor = await runStore.openCursor();+ while (cursor) {+ count += 1;+ totalBytes += getByteSize(cursor.value.itemJson);+ cursor = await cursor.continue();+ }+ return { count, totalBytes };+ };+ const writeCounters = async (metadataStore: MetadataStore, count: number, totalBytes: number): Promise<void> => {+ await metadataStore.put({ key: QUEUE_RUN_TOTAL_BYTES_KEY, value: totalBytes });+ await metadataStore.put({ key: QUEUE_RUN_COUNT_KEY, value: count });+ };const load = async (projectId?: string): Promise<QueueRunJournalLoadResult> => {if (!isAvailable()) {return { kind: 'unavailable' };}try {- const transaction = database.transaction(WORKBENCH_QUEUE_RUN_STORE, 'readwrite');- const records = projectId- ? await transaction.store.index('byProject').getAll(projectId)- : await transaction.store.getAll();+ const transaction = observeTransaction(database.transaction(QUEUE_RUN_STORES, 'readwrite'));+ const runStore = transaction.objectStore(WORKBENCH_QUEUE_RUN_STORE);+ const metadataStore = transaction.objectStore(WORKBENCH_DATABASE_METADATA_STORE);+ const countersBefore = await readCounters(runStore, metadataStore);const entries: QueueRunJournalEntry[] = [];let removedCorrupt = 0;- for (const record of records) {+ let removedBytes = 0;+ const source = projectId ? runStore.index('byProject') : runStore;+ let cursor = await source.openCursor(projectId);+ while (cursor) {+ const record = cursor.value;const entry = decodeRecord(record, runByteBudget);if (entry) {entries.push(entry);} else {removedCorrupt += 1;- await transaction.store.delete(record.key);+ removedBytes += getByteSize(record.itemJson);+ await cursor.delete();}+ cursor = await cursor.continue();+ }+ if (removedCorrupt > 0) {+ await writeCounters(+ metadataStore,+ Math.max(0, countersBefore.count - removedCorrupt),+ Math.max(0, countersBefore.totalBytes - removedBytes)+ );}await transaction.done;entries.sort((left, right) => {@@ -151,6 +257,121 @@ export const createIndexedDbQueueRunJournal = (close() {isClosed = true;},+ async listProjectIds() {+ if (!isAvailable()) {+ return { kind: 'unavailable' };+ }+ try {+ const transaction = observeTransaction(database.transaction(WORKBENCH_QUEUE_RUN_STORE));+ const projectIds: string[] = [];+ let cursor = await transaction.store.index('byProject').openKeyCursor(undefined, 'nextunique');+ while (cursor) {+ if (isNonEmptyString(cursor.key)) {+ projectIds.push(cursor.key);+ }+ cursor = await cursor.continue();+ }+ await transaction.done;+ return { kind: 'available', projectIds };+ } catch {+ return { kind: 'unavailable' };+ }+ },+ async listPendingReceipts() {+ if (!isAvailable()) {+ return { kind: 'unavailable' };+ }+ try {+ const transaction = observeTransaction(database.transaction(WORKBENCH_QUEUE_RECEIPT_STORE, 'readwrite'));+ const entries: QueueReceiptAcknowledgement[] = [];+ let cursor = await transaction.store.openCursor();+ while (cursor && entries.length < 100) {+ const entry = cursor.value;+ if (+ entry &&+ isNonEmptyString(entry.projectId) &&+ isNonEmptyString(entry.queueItemId) &&+ entry.key === getKey(entry.projectId, entry.queueItemId)+ ) {+ entries.push(entry);+ } else {+ await cursor.delete();+ }+ cursor = await cursor.continue();+ }+ await transaction.done;+ return { entries, kind: 'available' };+ } catch {+ return { kind: 'unavailable' };+ }+ },+ async acknowledgeReceipt(projectId, queueItemId) {+ if (!isAvailable()) {+ return { kind: 'unavailable' };+ }+ try {+ const transaction = observeTransaction(database.transaction(QUEUE_RUN_STORES, 'readwrite'));+ const key = getKey(projectId, queueItemId);+ const runStore = transaction.objectStore(WORKBENCH_QUEUE_RUN_STORE);+ const existing = await runStore.get(key);+ if (existing) {+ await runStore.put({ ...existing, receiptAcknowledged: true });+ }+ await transaction.objectStore(WORKBENCH_QUEUE_RECEIPT_STORE).delete(key);+ await transaction.done;+ return { kind: 'removed' };+ } catch {+ return { kind: 'unavailable' };+ }+ },+ async deleteForProject(projectId) {+ if (!isAvailable()) {+ return { kind: 'unavailable' };+ }+ if (!isNonEmptyString(projectId)) {+ return { kind: 'removed' };+ }+ try {+ const transaction = observeTransaction(database.transaction(QUEUE_RUN_STORES, 'readwrite'));+ const runStore = transaction.objectStore(WORKBENCH_QUEUE_RUN_STORE);+ const metadataStore = transaction.objectStore(WORKBENCH_DATABASE_METADATA_STORE);+ const countersBefore = await readCounters(runStore, metadataStore);+ let removedCount = 0;+ let removedBytes = 0;+ let cursor = await runStore.index('byProject').openCursor(projectId);+ while (cursor) {+ const record = cursor.value;+ if (!record.receiptAcknowledged && isNonEmptyString(record.queueItemId)) {+ try {+ await queueReceiptAcknowledgement(transaction.objectStore(WORKBENCH_QUEUE_RECEIPT_STORE), {+ key: getKey(projectId, record.queueItemId),+ projectId,+ queueItemId: record.queueItemId,+ });+ } catch (error) {+ abortTransaction(transaction);+ throw error;+ }+ }+ removedCount += 1;+ removedBytes += getByteSize(cursor.value.itemJson);+ await cursor.delete();+ cursor = await cursor.continue();+ }+ await writeCounters(+ metadataStore,+ Math.max(0, countersBefore.count - removedCount),+ Math.max(0, countersBefore.totalBytes - removedBytes)+ );+ await transaction.done;+ return { kind: 'removed' };+ } catch (error) {+ if (!isQuotaError(error)) {+ markUnavailable();+ }+ return { kind: 'unavailable' };+ }+ },listAll: () => load(),listForProject(projectId) {return isNonEmptyString(projectId)@@ -161,12 +382,16 @@ export const createIndexedDbQueueRunJournal = (if (!isAvailable()) {return { kind: 'unavailable' };}- if (!isNonEmptyString(projectId) || !isActiveQueueItemEnvelope(item)) {+ if (!isNonEmptyString(projectId)) {+ return { kind: 'invalid' };+ }+ const normalized = normalizeRestoredQueueItem(item);+ if (!normalized) {return { kind: 'invalid' };}let itemJson: string;try {- itemJson = JSON.stringify(item);+ itemJson = JSON.stringify(normalized);} catch {return { kind: 'invalid' };}@@ -184,8 +409,17 @@ export const createIndexedDbQueueRunJournal = (const transaction = observeTransaction(database.transaction(QUEUE_RUN_STORES, 'readwrite'));const runStore = transaction.objectStore(WORKBENCH_QUEUE_RUN_STORE);const metadataStore = transaction.objectStore(WORKBENCH_DATABASE_METADATA_STORE);- const key = getKey(projectId, item.id);+ const key = getKey(projectId, normalized.id);const existing = await runStore.get(key);+ const { count, totalBytes } = await readCounters(runStore, metadataStore);+ const existingBytes = existing ? getByteSize(existing.itemJson) : 0;+ const nextTotalBytes = totalBytes - existingBytes + getByteSize(itemJson);+ const nextCount = count + (existing ? 0 : 1);+ if (nextTotalBytes > totalByteBudget || nextCount > entryBudget) {+ await writeCounters(metadataStore, count, totalBytes);+ await transaction.done;+ return { kind: 'quota' };+ }let submissionOrder = existing?.submissionOrder;if (!Number.isSafeInteger(submissionOrder) || (submissionOrder as number) <= 0) {const sequence = await metadataStore.get(QUEUE_RUN_SUBMISSION_SEQUENCE_KEY);@@ -195,15 +429,30 @@ export const createIndexedDbQueueRunJournal = (}const stableSubmissionOrder = submissionOrder as number;const record: QueueRunDatabaseRecord = {+ receiptAcknowledged: existing?.receiptAcknowledged,+ byteSize: getByteSize(itemJson),itemJson,key,projectId,- queueItemId: item.id,+ queueItemId: normalized.id,schemaVersion: 1,submissionOrder: stableSubmissionOrder,- updatedAt: Date.now(),+ updatedAt: now(),};await runStore.put(record);+ if (!existing?.receiptAcknowledged && normalized.backendItemIds?.length) {+ try {+ await queueReceiptAcknowledgement(transaction.objectStore(WORKBENCH_QUEUE_RECEIPT_STORE), {+ key,+ projectId,+ queueItemId: normalized.id,+ });+ } catch (error) {+ abortTransaction(transaction);+ throw error;+ }+ }+ await writeCounters(metadataStore, nextCount, nextTotalBytes);await transaction.done;return { kind: 'stored' };} catch (error) {@@ -222,10 +471,43 @@ export const createIndexedDbQueueRunJournal = (return { kind: 'removed' };}try {- await database.delete(WORKBENCH_QUEUE_RUN_STORE, getKey(projectId, queueItemId));+ const transaction = observeTransaction(database.transaction(QUEUE_RUN_STORES, 'readwrite'));+ const runStore = transaction.objectStore(WORKBENCH_QUEUE_RUN_STORE);+ const metadataStore = transaction.objectStore(WORKBENCH_DATABASE_METADATA_STORE);+ const key = getKey(projectId, queueItemId);+ const existing = await runStore.get(key);+ if (existing && !existing.receiptAcknowledged) {+ try {+ await queueReceiptAcknowledgement(transaction.objectStore(WORKBENCH_QUEUE_RECEIPT_STORE), {+ key,+ projectId,+ queueItemId,+ });+ } catch (error) {+ abortTransaction(transaction);+ throw error;+ }+ }+ await runStore.delete(key);+ if (existing) {+ const storedTotal = await metadataStore.get(QUEUE_RUN_TOTAL_BYTES_KEY);+ const storedCount = await metadataStore.get(QUEUE_RUN_COUNT_KEY);+ if (Number.isSafeInteger(storedTotal?.value)) {+ await metadataStore.put({+ key: QUEUE_RUN_TOTAL_BYTES_KEY,+ value: Math.max(0, storedTotal!.value - getByteSize(existing.itemJson)),+ });+ }+ if (Number.isSafeInteger(storedCount?.value)) {+ await metadataStore.put({ key: QUEUE_RUN_COUNT_KEY, value: Math.max(0, storedCount!.value - 1) });+ }+ }+ await transaction.done;return { kind: 'removed' };- } catch {- markUnavailable();+ } catch (error) {+ if (!isQuotaError(error)) {+ markUnavailable();+ }return { kind: 'unavailable' };}},@@ -240,8 +522,12 @@ export const createAccountOwnedQueueRunJournal = async (if (!lease) {return {availability: 'unavailable',+ acknowledgeReceipt: () => Promise.resolve({ kind: 'unavailable' }),+ listPendingReceipts: () => Promise.resolve({ kind: 'unavailable' }),close: () => undefined,+ deleteForProject: () => Promise.resolve({ kind: 'unavailable' }),listAll: () => Promise.resolve({ kind: 'unavailable' }),+ listProjectIds: () => Promise.resolve({ kind: 'unavailable' }),listForProject: () => Promise.resolve({ kind: 'unavailable' }),record: () => Promise.resolve({ kind: 'unavailable' }),settle: () => Promise.resolve({ kind: 'unavailable' }),diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunLocks.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunLocks.test.tsnew file mode 100644index 0000000000..bb7c755957--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunLocks.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it, vi } from 'vitest';++import { createQueueRunLockPort, getQueueRunLockName } from './queueRunLocks';++describe('queue run locks', () => {+ it('isolates ownership by account, project, and queue item without delimiter collisions', async () => {+ const acquire = vi.fn().mockResolvedValue({ kind: 'contended' });+ const acquireProject = vi.fn().mockResolvedValue({ kind: 'acquired', release: vi.fn() });+ const locks = createQueueRunLockPort(':account-1', acquire, acquireProject);++ await expect(locks.acquire('a:b', 'c')).resolves.toEqual({ kind: 'contended' });+ await locks.acquire('a', 'b:c');++ expect(acquire.mock.calls.map(([name]) => name)).toEqual([+ getQueueRunLockName(':account-1', 'a:b', 'c'),+ getQueueRunLockName(':account-1', 'a', 'b:c'),+ ]);+ expect(acquire.mock.calls[0]?.[0]).not.toBe(acquire.mock.calls[1]?.[0]);+ });++ it('holds a shared project lease for the lifetime of an acquired run', async () => {+ const calls: string[] = [];+ const locks = createQueueRunLockPort(+ ':account-1',+ vi.fn().mockResolvedValue({ kind: 'acquired', release: () => void calls.push('run') }),+ vi.fn().mockResolvedValue({ kind: 'acquired', release: () => void calls.push('project') })+ );++ const lock = await locks.acquire('project-1', 'item-1');+ expect(lock.kind).toBe('acquired');+ if (lock.kind === 'acquired') {+ await lock.release();+ }+ expect(calls).toEqual(['run', 'project']);+ });++ it('releases the project lease when run acquisition rejects', async () => {+ const releaseProject = vi.fn().mockResolvedValue(undefined);+ const locks = createQueueRunLockPort(+ ':account-1',+ vi.fn().mockRejectedValue(new Error('lock failure')),+ vi.fn().mockResolvedValue({ kind: 'acquired', release: releaseProject })+ );++ await expect(locks.acquire('project-1', 'item-1')).rejects.toThrow('lock failure');+ expect(releaseProject).toHaveBeenCalledOnce();+ });++ it('releases the project lease when run release rejects', async () => {+ const releaseProject = vi.fn().mockResolvedValue(undefined);+ const locks = createQueueRunLockPort(+ ':account-1',+ vi.fn().mockResolvedValue({ kind: 'acquired', release: () => Promise.reject(new Error('release failure')) }),+ vi.fn().mockResolvedValue({ kind: 'acquired', release: releaseProject })+ );++ const lock = await locks.acquire('project-1', 'item-1');+ if (lock.kind !== 'acquired') {+ throw new Error('Expected lock acquisition');+ }+ await expect(lock.release()).rejects.toThrow('release failure');+ expect(releaseProject).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunLocks.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunLocks.tsnew file mode 100644index 0000000000..2e339fd52e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunLocks.ts@@ -0,0 +1,48 @@+import type { QueueRunLockPort } from '@features/queue';++import {+ acquireExclusiveLock,+ acquireSharedLock,+ type BrowserLockResult,+ type ExclusiveLockResult,+} from '@platform/browser/webLocks';+import { getProjectLifecycleLockName } from '@workbench/projects/projectLifecycleLocks';++const LOCK_PREFIX = 'invokeai:v7:webv2:queue-run';++export const getQueueRunLockName = (storageSuffix: string, projectId: string, queueItemId: string): string =>+ `${LOCK_PREFIX}${storageSuffix}:${JSON.stringify([projectId, queueItemId])}`;++export const createQueueRunLockPort = (+ storageSuffix: string,+ acquireRun: (name: string) => Promise<ExclusiveLockResult> = acquireExclusiveLock,+ acquireProject: (name: string) => Promise<BrowserLockResult> = acquireSharedLock+): QueueRunLockPort => ({+ async acquire(projectId, queueItemId) {+ const projectLock = await acquireProject(getProjectLifecycleLockName(storageSuffix, projectId));+ if (projectLock.kind !== 'acquired') {+ return projectLock;+ }+ let runLock: ExclusiveLockResult;+ try {+ runLock = await acquireRun(getQueueRunLockName(storageSuffix, projectId, queueItemId));+ } catch (error) {+ await projectLock.release();+ throw error;+ }+ if (runLock.kind !== 'acquired') {+ await projectLock.release();+ return runLock;+ }+ return {+ kind: 'acquired',+ async release() {+ try {+ await runLock.release();+ } finally {+ await projectLock.release();+ }+ },+ };+ },+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.test.tsnew file mode 100644index 0000000000..6b0c48a6d3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.test.ts@@ -0,0 +1,52 @@+import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';++import { createDefaultVideoWidgetValues } from '@features/video';+import { expect, it, vi } from 'vitest';++import { withQueueRecallCache } from './queueRunPersistence';++it('retains exact recall when a terminal item disappears before journal settlement', async () => {+ const put = vi.fn().mockResolvedValue({ kind: 'stored' });+ const settle = vi.fn().mockResolvedValue({ kind: 'removed' });+ const journal = { record: vi.fn().mockResolvedValue({ kind: 'stored' }), settle };+ const videoValues = createDefaultVideoWidgetValues();+ const item = {+ id: 'q',+ status: 'pending',+ snapshot: {+ sourceId: 'video',+ submittedAt: '2026-09-04T00:00:00Z',+ recall: { videoValues },+ },+ } as WorkbenchQueueItem;+ const persistence = withQueueRecallCache(journal, { put }, () => undefined);+ await persistence.record('p', item);+ await persistence.settle('p', 'q');+ expect(put).toHaveBeenCalledWith({+ projectId: 'p',+ queueItemId: 'q',+ sourceId: 'video',+ submittedAt: '2026-09-04T00:00:00Z',+ videoValues,+ });+ expect(settle).toHaveBeenCalledWith('p', 'q');+});++it('does not prevent run cleanup when the optional recall cache fails', async () => {+ const settle = vi.fn().mockResolvedValue({ kind: 'removed' });+ const item = {+ id: 'q',+ status: 'failed',+ snapshot: {+ sourceId: 'video',+ submittedAt: '2026-09-04T00:00:00Z',+ recall: { videoValues: createDefaultVideoWidgetValues() },+ },+ } as WorkbenchQueueItem;+ const persistence = withQueueRecallCache(+ { record: vi.fn(), settle },+ { put: vi.fn().mockRejectedValue(new Error('quota')) },+ () => item+ );+ await expect(persistence.settle('p', 'q')).resolves.toEqual({ kind: 'removed' });+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.tsnew file mode 100644index 0000000000..75aae385c7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.ts@@ -0,0 +1,46 @@+import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';++import type { QueueRecallCache, QueueRecallSnapshotInput } from './queueRecallCache';+import type { QueueRunJournal } from './queueRunJournal';++export const withQueueRecallCache = <T extends Pick<QueueRunJournal, 'record' | 'settle'>>(+ journal: T,+ cache: Pick<QueueRecallCache, 'put'>,+ getItem: (projectId: string, queueItemId: string) => WorkbenchQueueItem | undefined+): T => {+ const pendingRecall = new Map<string, QueueRecallSnapshotInput>();+ const keyOf = (projectId: string, queueItemId: string) => JSON.stringify([projectId, queueItemId]);+ const remember = (projectId: string, item: WorkbenchQueueItem): void => {+ const { recall, sourceId, submittedAt } = item.snapshot;+ if (recall?.generateValues || recall?.videoValues) {+ pendingRecall.set(keyOf(projectId, item.id), {+ ...recall,+ projectId,+ queueItemId: item.id,+ sourceId,+ submittedAt,+ });+ }+ };+ return {+ ...journal,+ record(projectId, item) {+ const liveItem = item as WorkbenchQueueItem;+ remember(projectId, liveItem);+ return journal.record(projectId, item);+ },+ async settle(projectId, queueItemId) {+ const key = keyOf(projectId, queueItemId);+ const item = getItem(projectId, queueItemId);+ if (item) {+ remember(projectId, item);+ }+ const snapshot = pendingRecall.get(key);+ if (snapshot) {+ await cache.put(snapshot).catch(() => undefined);+ pendingRecall.delete(key);+ }+ return journal.settle(projectId, queueItemId);+ },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.tsnew file mode 100644index 0000000000..5a051ed315--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts@@ -0,0 +1,160 @@+import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';++import { cloneGenerateWidgetValues, normalizeGenerateWidgetValues } from '@features/generation/settings';+import { MAX_QUEUE_BATCH_ITEMS } from '@features/queue';+import { cloneVideoWidgetValues, normalizeVideoWidgetValues } from '@features/video';++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);+const isBackendItemIdList = (value: unknown): value is number[] =>+ Array.isArray(value) &&+ value.length <= MAX_QUEUE_BATCH_ITEMS &&+ new Set(value).size === value.length &&+ value.every((item) => Number.isSafeInteger(item) && item > 0);++export const normalizeRestoredQueueItem = (value: unknown): WorkbenchQueueItem | null => {+ if (+ !isRecord(value) ||+ (value.status !== 'pending' &&+ value.status !== 'running' &&+ !(value.status === 'cancelled' && value.cancellationPending === true))+ ) {+ return null;+ }+ const snapshot = value.snapshot;+ if (+ typeof value.id !== 'string' ||+ value.id.length === 0 ||+ typeof value.cancellable !== 'boolean' ||+ !isRecord(snapshot) ||+ !isRecord(snapshot.backendSubmission) ||+ (snapshot.backendSubmission.kind !== 'generate' &&+ snapshot.backendSubmission.kind !== 'workflow' &&+ snapshot.backendSubmission.kind !== 'invalid') ||+ (snapshot.sourceId !== 'canvas' &&+ snapshot.sourceId !== 'generate' &&+ snapshot.sourceId !== 'upscale' &&+ snapshot.sourceId !== 'video' &&+ snapshot.sourceId !== 'workflow') ||+ (snapshot.destination !== 'canvas' && snapshot.destination !== 'gallery') ||+ !isRecord(snapshot.graph) ||+ typeof snapshot.graph.id !== 'string' ||+ typeof snapshot.graph.label !== 'string' ||+ (snapshot.galleryBoardId !== null && typeof snapshot.galleryBoardId !== 'string') ||+ typeof snapshot.filterIntermediateResults !== 'boolean' ||+ (snapshot.resultNodeIds !== undefined &&+ (!Array.isArray(snapshot.resultNodeIds) || snapshot.resultNodeIds.some((id) => typeof id !== 'string'))) ||+ !isRecord(snapshot.presentation) ||+ !isFiniteNumber(snapshot.presentation.batchCount) ||+ !Number.isSafeInteger(snapshot.presentation.batchCount) ||+ snapshot.presentation.batchCount < 1 ||+ snapshot.presentation.batchCount > MAX_QUEUE_BATCH_ITEMS ||+ !isFiniteNumber(snapshot.presentation.height) ||+ snapshot.presentation.height <= 0 ||+ !isFiniteNumber(snapshot.presentation.width) ||+ snapshot.presentation.width <= 0 ||+ (snapshot.presentation.positivePrompt !== undefined && typeof snapshot.presentation.positivePrompt !== 'string') ||+ typeof snapshot.submittedAt !== 'string' ||+ !isRecord(snapshot.canvas) ||+ !isFiniteNumber(snapshot.canvas.documentRevision) ||+ !Number.isSafeInteger(snapshot.canvas.documentRevision) ||+ snapshot.canvas.documentRevision < 0 ||+ !isRecord(snapshot.canvas.document) ||+ !isRecord(snapshot.canvas.document.bbox)+ ) {+ return null;+ }+ if (+ (value.backendItemIds !== undefined && !isBackendItemIdList(value.backendItemIds)) ||+ (value.completedBackendItemIds !== undefined && !isBackendItemIdList(value.completedBackendItemIds)) ||+ (value.cancelledBackendItemIds !== undefined && !isBackendItemIdList(value.cancelledBackendItemIds))+ ) {+ return null;+ }+ const backendItemIds = value.backendItemIds;+ const completedBackendItemIds = value.completedBackendItemIds;+ const cancelledBackendItemIds = value.cancelledBackendItemIds;+ const backendIds = new Set(backendItemIds ?? []);+ const cancelledIds = new Set(cancelledBackendItemIds ?? []);+ if (+ [...(completedBackendItemIds ?? []), ...(cancelledBackendItemIds ?? [])].some((id) => !backendIds.has(id)) ||+ completedBackendItemIds?.some((id) => cancelledIds.has(id))+ ) {+ return null;+ }+ const { bbox } = snapshot.canvas.document;+ if (+ !isFiniteNumber(bbox.x) ||+ !isFiniteNumber(bbox.y) ||+ !isFiniteNumber(bbox.width) ||+ bbox.width <= 0 ||+ !isFiniteNumber(bbox.height) ||+ bbox.height <= 0 ||+ !isFiniteNumber(snapshot.canvas.document.width) ||+ snapshot.canvas.document.width <= 0 ||+ !isFiniteNumber(snapshot.canvas.document.height) ||+ snapshot.canvas.document.height <= 0 ||+ (value.backendBatchId !== undefined &&+ (typeof value.backendBatchId !== 'string' || value.backendBatchId.length === 0))+ ) {+ return null;+ }++ let recall: WorkbenchQueueItem['snapshot']['recall'];+ try {+ const rawRecall = isRecord(snapshot.recall) ? snapshot.recall : null;+ if ((snapshot.sourceId === 'canvas' || snapshot.sourceId === 'generate') && isRecord(rawRecall?.generateValues)) {+ const values = normalizeGenerateWidgetValues(rawRecall.generateValues);+ if (values) {+ recall = { generateValues: cloneGenerateWidgetValues(values) };+ }+ } else if (snapshot.sourceId === 'video' && isRecord(rawRecall?.videoValues)) {+ const values = normalizeVideoWidgetValues(rawRecall.videoValues);+ if (values) {+ recall = { videoValues: cloneVideoWidgetValues(values) };+ }+ }+ } catch {+ recall = undefined;+ }++ return {+ ...(value.backendBatchId === undefined ? {} : { backendBatchId: value.backendBatchId }),+ ...(backendItemIds === undefined ? {} : { backendItemIds: [...backendItemIds] }),+ ...(cancelledBackendItemIds === undefined ? {} : { cancelledBackendItemIds: [...cancelledBackendItemIds] }),+ ...(value.cancellationPending === true ? { cancellationPending: true } : {}),+ cancellable: value.cancellable,+ ...(completedBackendItemIds === undefined ? {} : { completedBackendItemIds: [...completedBackendItemIds] }),+ id: value.id,+ snapshot: {+ backendSubmission: snapshot.backendSubmission as WorkbenchQueueItem['snapshot']['backendSubmission'],+ canvas: {+ document: {+ bbox: { height: bbox.height, width: bbox.width, x: bbox.x, y: bbox.y },+ height: snapshot.canvas.document.height,+ width: snapshot.canvas.document.width,+ },+ documentRevision: snapshot.canvas.documentRevision,+ },+ destination: snapshot.destination,+ filterIntermediateResults: snapshot.filterIntermediateResults,+ galleryBoardId: snapshot.galleryBoardId,+ graph: { id: snapshot.graph.id, label: snapshot.graph.label },+ presentation: {+ batchCount: snapshot.presentation.batchCount,+ height: snapshot.presentation.height,+ ...(snapshot.presentation.positivePrompt === undefined+ ? {}+ : { positivePrompt: snapshot.presentation.positivePrompt }),+ width: snapshot.presentation.width,+ },+ ...(recall ? { recall } : {}),+ ...(snapshot.resultNodeIds === undefined ? {} : { resultNodeIds: [...snapshot.resultNodeIds] }),+ sourceId: snapshot.sourceId,+ submittedAt: snapshot.submittedAt,+ },+ status: value.status,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.tsdeleted file mode 100644index 1f34782499..0000000000--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.ts+++ /dev/null@@ -1,72 +0,0 @@-import type { GenerateWidgetValues } from '@features/generation/contracts';-import type { InvocationSourceId } from '@workbench/invocationContracts';-import type { Project } from '@workbench/projectContracts';--import { parseQueueItemOrigin } from '@features/queue/contracts';-import { useWorkbenchSelector } from '@workbench/WorkbenchContext';--/**- * The full Generate settings snapshot for a server queue item, if this client- * submitted it. webv2 stamps the local submission id into each item's `origin`,- * so we decode it and look the snapshot up in local state. Present → "Use again"- * can recall the exact settings (model, steps, LoRAs, …); absent (item from- * another client, or a cleared snapshot) → only field_values are recoverable.- */-/**- * The local queue item a server item's origin points at, or null. The single- * resolution both lookups below build on: deriving the item's source and its- * Generate snapshot from two independent scans would let them disagree about- * WHICH item they matched, and a capability matrix computed from one item while- * the recall routes by another is how a verb ends up enabled but unserviceable.- */-const findLocalQueueItem = (- projects: readonly Pick<Project, 'queue'>[],- origin?: string | null-): Project['queue']['items'][number] | null => {- const localId = parseQueueItemOrigin(origin);-- if (!localId) {- return null;- }-- for (const project of projects) {- const localItem = project.queue.items.find((queueItem) => queueItem.id === localId);-- if (localItem) {- return localItem;- }- }-- return null;-};--export const useLocalGenerateValues = (origin?: string | null): GenerateWidgetValues | null =>- useWorkbenchSelector((snapshot) => {- const localItem = findLocalQueueItem(snapshot.projects, origin);-- if (!localItem || (localItem.snapshot.sourceId !== 'generate' && localItem.snapshot.sourceId !== 'canvas')) {- return null;- }-- return localItem.snapshot.recall?.generateValues ?? null;- });--/**- * The invocation source a server queue item was submitted from, if this client- * submitted it. Decoded the same way as {@link useLocalGenerateValues}, but kept- * separate because it answers a different question and returns a primitive, so- * it re-renders its host only when the source actually changes.- *- * `null` means "unknown", not "not video": a foreign item — or one whose local- * snapshot has been cleared — carries no source, and its `field_values` cannot- * distinguish a video batch from an image one (both record a seed and prompts- * through the same batch plan). Callers must treat null as the Generate-shaped- * default rather than assuming a source.- */-export const getLocalQueueItemSource = (- projects: readonly Pick<Project, 'queue'>[],- origin?: string | null-): InvocationSourceId | null => findLocalQueueItem(projects, origin)?.snapshot.sourceId ?? null;--export const useLocalQueueItemSource = (origin?: string | null): InvocationSourceId | null =>- useWorkbenchSelector((snapshot) => getLocalQueueItemSource(snapshot.projects, origin));diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.browser.test.tsxnew file mode 100644index 0000000000..38988e3729--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.browser.test.tsx@@ -0,0 +1,56 @@+import { buildQueueItemOrigin } from '@features/queue/contracts';+import { createDefaultVideoWidgetValues } from '@features/video';+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';++import { createAccountOwnedQueueRecallCache } from './queueRecallCache';+import { useLocalRecallSnapshot } from './useLocalRecallSnapshot';++vi.mock('@workbench/WorkbenchContext', () => ({+ useWorkbenchSelector: (selector: (state: { projects: [] }) => unknown) => selector({ projects: [] }),+}));++let root: Root | undefined;+let host: HTMLDivElement | undefined;+let client: QueryClient | undefined;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ client?.clear();+ accountLifecycle.invalidate();+});++it('restores exact video recall after reload without loading an open project', async () => {+ accountLifecycle.activate(`recall-hook-${crypto.randomUUID()}`);+ const cache = await createAccountOwnedQueueRecallCache(captureAccountScope());+ expect(+ await cache.put({+ projectId: 'p',+ queueItemId: 'q',+ sourceId: 'video',+ submittedAt: '2026-09-04T00:00:00Z',+ videoValues: { ...createDefaultVideoWidgetValues(), positivePrompt: 'durable video prompt' },+ })+ ).toEqual({ kind: 'stored' });+ cache.close();+ const Probe = () => {+ const recall = useLocalRecallSnapshot(buildQueueItemOrigin('q', 'p'));+ return <span>{recall?.videoValues?.positivePrompt ?? 'missing'}</span>;+ };+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(() =>+ root!.render(+ <QueryClientProvider client={client!}>+ <Probe />+ </QueryClientProvider>+ )+ );+ await vi.waitFor(() => expect(host?.textContent).toBe('durable video prompt'));+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.pending.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.pending.browser.test.tsxnew file mode 100644index 0000000000..47a7a51662--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.pending.browser.test.tsx@@ -0,0 +1,79 @@+import { buildQueueItemOrigin } from '@features/queue/contracts';+import { createDefaultVideoWidgetValues } from '@features/video';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';++const harness = vi.hoisted(() => ({+ close: vi.fn(),+ get: vi.fn(),+}));++vi.mock('./queueRecallCache', () => ({+ createAccountOwnedQueueRecallCache: vi.fn(() =>+ Promise.resolve({+ close: harness.close,+ get: harness.get,+ })+ ),+}));+vi.mock('@workbench/WorkbenchContext', () => ({+ useWorkbenchSelector: (selector: (state: { projects: [] }) => unknown) => selector({ projects: [] }),+}));++import { useLocalRecallSnapshot } from './useLocalRecallSnapshot';++let root: Root | undefined;+let host: HTMLDivElement | undefined;+let client: QueryClient | undefined;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ client?.clear();+ accountLifecycle.invalidate();+});++it('keeps recall pending until the durable source resolves, then identifies video', async () => {+ accountLifecycle.activate(`recall-pending-${crypto.randomUUID()}`);+ let resolveGet: ((value: unknown) => void) | undefined;+ harness.get.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveGet = resolve;+ })+ );+ const Probe = () => {+ const recall = useLocalRecallSnapshot(buildQueueItemOrigin('q', 'p'));+ return <span>{recall === undefined ? 'pending' : (recall?.sourceId ?? 'missing')}</span>;+ };+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ client = new QueryClient({ defaultOptions: { queries: { gcTime: 0, retry: false } } });+ await act(() =>+ root!.render(+ <QueryClientProvider client={client!}>+ <Probe />+ </QueryClientProvider>+ )+ );++ expect(host.textContent).toBe('pending');+ await act(async () => {+ resolveGet?.({+ kind: 'found',+ snapshot: {+ projectId: 'p',+ queueItemId: 'q',+ sourceId: 'video',+ submittedAt: '2026-09-04T00:00:00Z',+ videoValues: createDefaultVideoWidgetValues(),+ },+ });+ await vi.waitFor(() => expect(host?.textContent).toBe('video'));+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.tsnew file mode 100644index 0000000000..07f5c0fe02--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts@@ -0,0 +1,87 @@+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { InvocationSourceId } from '@workbench/invocationContracts';+import type { Project } from '@workbench/projectContracts';++import { normalizeGenerateWidgetValues } from '@features/generation/settings';+import { parseQueueItemOrigin, parseQueueItemOriginProjectId } from '@features/queue/contracts';+import { normalizeVideoWidgetValues, type VideoWidgetValues } from '@features/video';+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';+import { useQuery } from '@tanstack/react-query';+import { useWorkbenchSelector } from '@workbench/WorkbenchContext';++import { createAccountOwnedQueueRecallCache } from './queueRecallCache';++export interface LocalRecallSnapshot {+ generateValues?: GenerateWidgetValues;+ sourceId: InvocationSourceId;+ videoValues?: VideoWidgetValues;+}++const findLocalQueueItem = (projects: readonly Pick<Project, 'id' | 'queue'>[], origin?: string | null) => {+ const localId = parseQueueItemOrigin(origin);+ const projectId = parseQueueItemOriginProjectId(origin);+ if (!localId) {+ return null;+ }+ for (const project of projects) {+ if (projectId && project.id !== projectId) {+ continue;+ }+ const item = project.queue.items.find((candidate) => candidate.id === localId);+ if (item) {+ return item;+ }+ }+ return null;+};++export const getLocalQueueItemSource = (+ projects: readonly Pick<Project, 'id' | 'queue'>[],+ origin?: string | null+): InvocationSourceId | null => findLocalQueueItem(projects, origin)?.snapshot.sourceId ?? null;++/** `undefined` means the durable lookup is pending; `null` means it completed without a usable snapshot. */+export const useLocalRecallSnapshot = (origin?: string | null): LocalRecallSnapshot | null | undefined => {+ const owner = captureAccountScope();+ const localItem = useWorkbenchSelector((state) => findLocalQueueItem(state.projects, origin));+ const queueItemId = parseQueueItemOrigin(origin);+ const projectId = parseQueueItemOriginProjectId(origin);+ const { data, isPending } = useQuery({+ enabled: !localItem && queueItemId !== null,+ queryKey: ['queue-recall', owner.epoch, projectId, queueItemId],+ retry: false,+ staleTime: 30_000,+ async queryFn(): Promise<LocalRecallSnapshot | null> {+ if (!queueItemId) {+ return null;+ }+ const cache = await createAccountOwnedQueueRecallCache(owner);+ try {+ const result = await cache.get(queueItemId);+ assertAccountScopeCurrent(owner);+ if (result.kind !== 'found' || (projectId && result.snapshot.projectId !== projectId)) {+ return null;+ }+ const snapshot = result.snapshot;+ return {+ sourceId: snapshot.sourceId,+ generateValues: snapshot.generateValues+ ? (normalizeGenerateWidgetValues(snapshot.generateValues) ?? undefined)+ : undefined,+ videoValues: snapshot.videoValues+ ? (normalizeVideoWidgetValues(snapshot.videoValues) ?? undefined)+ : undefined,+ };+ } finally {+ cache.close();+ }+ },+ });+ if (localItem) {+ return { ...localItem.snapshot.recall, sourceId: localItem.snapshot.sourceId };+ }+ if (queueItemId !== null && isPending) {+ return undefined;+ }+ return data ?? null;+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueRecoveryProjectIds.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueRecoveryProjectIds.tsnew file mode 100644index 0000000000..a4c37ecb6f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueRecoveryProjectIds.ts@@ -0,0 +1,20 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { queryOptions, useQuery } from '@tanstack/react-query';++import { listQueueRecoveryProjectIds } from './queueRecovery';++export const getQueueRecoveryProjectIdsQueryKey = (owner: AccountScope) =>+ ['workbench', 'queue-recovery-project-ids', owner.accountId, owner.epoch] as const;++export const queueRecoveryProjectIdsQueryOptions = (owner: AccountScope) =>+ queryOptions({+ gcTime: 0,+ queryFn: () => listQueueRecoveryProjectIds(owner),+ queryKey: getQueueRecoveryProjectIdsQueryKey(owner),+ refetchInterval: 10_000,+ retry: false,+ staleTime: 2_000,+ });++export const useQueueRecoveryProjectIds = (owner: AccountScope) => useQuery(queueRecoveryProjectIdsQueryOptions(owner));diff --git a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.browser.test.tsxindex f1fd3c2f97..7735a1f6e1 100644--- a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.browser.test.tsx@@ -1,4 +1,5 @@import type { Project } from '@workbench/projectContracts';+import type { ProjectCommandResult } from '@workbench/workbenchStore';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';@@ -9,8 +10,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';const harness = vi.hoisted(() => ({+ abortProjectResolution: vi.fn(),acknowledgeProjectResolution: vi.fn(),- closeProject: vi.fn<() => { ok: true } | { ok: false; reason: 'last-project' }>(() => ({ ok: true })),+ closeProject: vi.fn<() => ProjectCommandResult>(() => ({ ok: true })),conflict: undefined as| { detectedAt: string; kind: 'deleted' }| { detectedAt: string; kind: 'revision'; serverRevision: number }@@ -39,7 +41,7 @@ const harness = vi.hoisted(() => ({),resolveConflictDiscard: vi.fn(() => Promise.resolve()),resolveConflictUseServer: vi.fn(),- retargetProject: vi.fn(() => ({ ok: true })),+ retargetProject: vi.fn<() => ProjectCommandResult>(() => ({ ok: true })),reportError: vi.fn(),}));@@ -74,6 +76,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({}),useWorkbenchPersistenceService: () => ({acknowledgeProjectResolution: harness.acknowledgeProjectResolution,+ abortProjectResolution: harness.abortProjectResolution,deleteRecoverableDraft: harness.deleteRecoverableDraft,getRecoverableDraftDocument: harness.getRecoverableDraftDocument,getProjectDraftDocument: vi.fn(),@@ -101,6 +104,7 @@ beforeEach(() => {harness.retargetProject.mockClear();harness.retargetProject.mockReturnValue({ ok: true });harness.acknowledgeProjectResolution.mockClear();+ harness.abortProjectResolution.mockClear();harness.closeProject.mockClear();harness.closeProject.mockReturnValue({ ok: true });harness.createProject.mockClear();@@ -143,6 +147,22 @@ describe('ProjectConflictBanner', () => {);});+ it('releases the save-as-new fence when the reducer cannot retarget', async () => {+ harness.conflict = { detectedAt: '2026-09-03T12:00:00.000Z', kind: 'revision', serverRevision: 2 };+ harness.retargetProject.mockReturnValueOnce({ ok: false, reason: 'target-already-open' });+ await renderBanner();+ const button = Array.from(document.querySelectorAll('button')).find(+ (candidate) => candidate.textContent === 'shell.projectConflict.saveAsNew'+ );++ await act(() => userEvent.click(button!));+ await act(() => userEvent.click(document.querySelector<HTMLButtonElement>('[data-testid="confirm-resolution"]')!));+ await vi.waitFor(() => expect(harness.abortProjectResolution).toHaveBeenCalledWith('project-1'));++ expect(harness.acknowledgeProjectResolution).not.toHaveBeenCalled();+ expect(harness.reportError).toHaveBeenCalledOnce();+ });+it('exports the live project including edits newer than the autosave draft', async () => {harness.conflict = { detectedAt: '2026-09-03T12:00:00.000Z', kind: 'revision', serverRevision: 2 };harness.project = { ...harness.project, name: 'unsaved click-time edit' };@@ -217,6 +237,21 @@ describe('ProjectConflictBanner', () => {);});+ it('releases the discard fence when the project cannot close', async () => {+ harness.conflict = { detectedAt: '2026-09-03T12:00:00.000Z', kind: 'deleted' };+ harness.closeProject.mockReturnValueOnce({ ok: false, reason: 'active-queue-runs' });+ await renderBanner();+ const discard = Array.from(document.querySelectorAll('button')).find(+ (button) => button.textContent === 'shell.projectConflict.discard'+ );++ await act(() => userEvent.click(discard!));+ await act(() => userEvent.click(document.querySelector<HTMLButtonElement>('[data-testid="confirm-resolution"]')!));+ await vi.waitFor(() => expect(harness.abortProjectResolution).toHaveBeenCalledWith('project-1'));++ expect(harness.acknowledgeProjectResolution).not.toHaveBeenCalled();+ });+it('exports a newer-format draft without opening it in the editor', async () => {harness.recoverableDrafts = [{ editorSessionId: 'newer-editor', generation: 1, projectId: 'future-project', updatedAt: 1 },diff --git a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsxindex fed7513a7b..4604f82def 100644--- a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx@@ -82,8 +82,10 @@ export const ProjectConflictBanner = () => {targetProjectId: result.targetProjectId,});if (!retargeted.ok) {+ persistence.abortProjectResolution(project.id);throw new Error(t('shell.projectConflict.copyOpenedDuringResolution'));}+ persistence.acknowledgeProjectResolution(project.id);}),[persistence, persistenceAdapter, project, run, t]);@@ -154,15 +156,20 @@ export const ProjectConflictBanner = () => {if (action === 'discard') {await run(action, async () => {await persistence.resolveConflictDiscard(projectId);- let closeResult = projects.close(projectId);- if (!closeResult.ok && closeResult.reason === 'last-project') {- projects.create();- closeResult = projects.close(projectId);+ try {+ let closeResult = projects.close(projectId);+ if (!closeResult.ok && closeResult.reason === 'last-project') {+ projects.create();+ closeResult = projects.close(projectId);+ }+ if (!closeResult.ok) {+ throw new Error(t('shell.projectConflict.actionFailed'));+ }+ persistence.acknowledgeProjectResolution(projectId);+ } catch (error) {+ persistence.abortProjectResolution(projectId);+ throw error;}- if (!closeResult.ok) {- throw new Error(t('shell.projectConflict.actionFailed'));- }- persistence.acknowledgeProjectResolution(projectId);});}}, [persistence, persistenceAdapter, projectId, projects, recoverableDraft, resolutionAction, run, saveAsNew, t]);diff --git a/invokeai/frontend/webv2/src/workbench/shell/QueueRecoveryBanner.tsx b/invokeai/frontend/webv2/src/workbench/shell/QueueRecoveryBanner.tsxnew file mode 100644index 0000000000..c8483216b4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/QueueRecoveryBanner.tsx@@ -0,0 +1,15 @@+import { useProjectActions } from '@workbench/projects/useProjectActions';+import { QueueRecoveryNotice } from '@workbench/queue-integration/QueueRecoveryNotice';+import { shallowEqual, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';++export const QueueRecoveryBanner = () => {+ const openProjectIds = useWorkbenchSelector(+ (snapshot) => snapshot.projects.map((project) => project.id),+ shallowEqual+ );+ const { openProject } = useProjectActions();+ const handleOpen = useCallback((projectId: string) => openProject(projectId, projectId), [openProject]);++ return <QueueRecoveryNotice openProjectIds={openProjectIds} onOpen={handleOpen} />;+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsxindex b7be687697..e053e74cd0 100644--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx@@ -51,6 +51,7 @@ import {import { WorkbenchNotificationToaster } from './notifications';import { LeftPanel, RightPanel } from './Panels';import { ProjectConflictBanner } from './ProjectConflictBanner';+import { QueueRecoveryBanner } from './QueueRecoveryBanner';import { StatusBar } from './StatusBar';import { TopBar } from './topbar';@@ -271,6 +272,7 @@ export const WorkbenchShell = () => {<DocumentTitleProgress /><TopBar /><ProjectConflictBanner />+ <QueueRecoveryBanner /><Flex aria-labelledby="workbench-project-heading" as="main" flex="1" minH="0" overflow="hidden"><VisuallyHidden as="h1" id="workbench-project-heading">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsxindex 0f3c9a3688..6f445f82d5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx@@ -90,6 +90,15 @@ const DetailsSection = ({ project }: { project: ProjectPanelViewModel }) => {const lastSavedAt = useWorkbenchSelector((snapshot) => snapshot.autosave.lastSavedAt);const projectSync = useProjectSyncSelector((snapshot) => snapshot.projects[project.id]);const notify = useNotify();+ let running = 0;+ let queued = 0;+ for (const item of project.queue.items) {+ if (item.status === 'running' || item.cancellationPending) {+ running += 1;+ } else if (item.status === 'pending') {+ queued += 1;+ }+ }const syncLabel =backendConnectionStatus !== 'connected'@@ -135,7 +144,9 @@ const DetailsSection = ({ project }: { project: ProjectPanelViewModel }) => {{lastSavedAt ? formatTimestamp(lastSavedAt, t('common.unknownTime')) : t('common.notYet')}</DetailRow><DetailRow label={t('widgets.project.graphNodes')}>{project.projectGraph.nodes.length}</DetailRow>- <DetailRow label={t('widgets.project.queueItems')}>{project.queue.items.length}</DetailRow>+ <DetailRow label={t('widgets.project.activeRuns')}>+ {t('widgets.project.activeRunCounts', { running, queued })}+ </DetailRow><DetailRow label={t('widgets.project.events')}>{project.events.length}</DetailRow></Panel></Stack>diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 7086387c08..97c62025a4 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1825,6 +1825,112 @@ describe('workbench layout presets', () => {});describe('workbenchReducer Phase 5 generation flow', () => {+ it('restores valid active journal items while live items win duplicate ids', () => {+ const submittedState = submitGenerate(primeGenerate());+ const liveItem = getActiveProject(submittedState).queue.items[0]!;+ const restoredItem = {+ ...liveItem,+ id: 'restored-item',+ snapshot: { ...liveItem.snapshot, submittedAt: '2026-09-04T00:00:00.000Z' },+ };+ const duplicate = { ...liveItem, status: 'running' as const };++ const state = workbenchReducer(submittedState, {+ items: [duplicate, restoredItem],+ projectId: getActiveProject(submittedState).id,+ type: 'restoreQueueItemsFromJournal',+ });++ expect(getActiveProject(state).queue.items.map((item) => item.id)).toEqual([liveItem.id, restoredItem.id]);+ expect(getActiveProject(state).queue.items[0]).toEqual({ ...liveItem, localRecoveryState: 'durable' });+ expect(getActiveProject(state).queue.items[0]).not.toBe(liveItem);+ expect(getActiveProject(state).queue.items[1]).toEqual({ ...restoredItem, localRecoveryState: 'durable' });+ expect(getActiveProject(state).queue.items[1]).not.toBe(restoredItem);+ });++ it('marks a newly submitted queue item as proven local-only', () => {+ const state = submitGenerate(primeGenerate());++ expect(getActiveProject(state).queue.items[0]?.localRecoveryState).toBe('local-only');+ });++ it('never downgrades durable local recovery provenance', () => {+ let state = submitGenerate(primeGenerate());+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0]!;+ state = workbenchReducer(state, {+ projectId: project.id,+ queueItemId: queueItem.id,+ state: 'durable',+ type: 'setQueueItemLocalRecoveryState',+ });+ state = workbenchReducer(state, {+ projectId: project.id,+ queueItemId: queueItem.id,+ state: 'local-only',+ type: 'setQueueItemLocalRecoveryState',+ });++ expect(getActiveProject(state).queue.items[0]?.localRecoveryState).toBe('durable');+ });++ it('rejects malformed and terminal journal items at restoration', () => {+ const submittedState = submitGenerate(primeGenerate());+ const project = getActiveProject(submittedState);+ const queueItem = project.queue.items[0]!;+ const emptyState = {+ ...submittedState,+ projects: submittedState.projects.map((candidate) =>+ candidate.id === project.id ? { ...candidate, queue: { items: [] } } : candidate+ ),+ };++ const state = workbenchReducer(emptyState, {+ items: [+ { ...queueItem, status: 'completed' },+ { ...queueItem, id: 'bad-canvas', snapshot: { ...queueItem.snapshot, canvas: { document: {} } } },+ { ...queueItem, id: 'bad-backend-ids', backendItemIds: [1, Number.NaN] },+ { ...queueItem, id: 'non-array-backend-ids', backendItemIds: 7 },+ { ...queueItem, id: 'non-array-completed-ids', completedBackendItemIds: {} },+ { ...queueItem, id: 'duplicate-backend-ids', backendItemIds: [1, 1] },+ ],+ projectId: project.id,+ type: 'restoreQueueItemsFromJournal',+ });++ expect(getActiveProject(state).queue.items).toEqual([]);+ });++ it('restores an active run when optional recall data is malformed', () => {+ const submittedState = submitGenerate(primeGenerate());+ const project = getActiveProject(submittedState);+ const queueItem = project.queue.items[0]!;+ const emptyState = {+ ...submittedState,+ projects: submittedState.projects.map((candidate) =>+ candidate.id === project.id ? { ...candidate, queue: { items: [] } } : candidate+ ),+ };++ const state = workbenchReducer(emptyState, {+ items: [+ {+ ...queueItem,+ snapshot: { ...queueItem.snapshot, recall: { generateValues: { model: 'not-a-model-config' } } },+ },+ ],+ projectId: project.id,+ type: 'restoreQueueItemsFromJournal',+ });++ expect(getActiveProject(state).queue.items).toEqual([+ expect.objectContaining({+ id: queueItem.id,+ snapshot: expect.not.objectContaining({ recall: expect.anything() }),+ }),+ ]);+ });+it('does not notify gallery total subscribers for unchanged or non-finite totals', () => {let state = createInitialWorkbenchState();@@ -2421,7 +2527,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {});state = workbenchReducer(state, { queueItemId: queueItem.id, type: 'cancelQueueItem' });- expect(getActiveProject(state).queue.items[0]?.status).toBe('cancelled');+ expect(getActiveProject(state).queue.items[0]).toMatchObject({ cancellationPending: true, status: 'cancelled' });});it('cancels queue items from inactive projects when a project id is provided', () => {@@ -2448,9 +2554,13 @@ describe('workbenchReducer Phase 5 generation flow', () => {state = submitGenerate(primeGenerate(state));state = workbenchReducer(state, { type: 'cancelAllQueueItems' });- expect(state.projects.flatMap((project) => project.queue.items.map((item) => item.status))).toEqual([- 'cancelled',- 'cancelled',+ expect(+ state.projects.flatMap((project) =>+ project.queue.items.map((item) => ({ cancellationPending: item.cancellationPending, status: item.status }))+ )+ ).toEqual([+ { cancellationPending: true, status: 'cancelled' },+ { cancellationPending: true, status: 'cancelled' },]);});@@ -2464,9 +2574,15 @@ describe('workbenchReducer Phase 5 generation flow', () => {type: 'cancelAllQueueItemsExceptCurrent',});- expect(getActiveProject(state).queue.items.map((item) => ({ id: item.id, status: item.status }))).toEqual([- { id: getActiveProject(state).queue.items[0].id, status: 'cancelled' },- { id: firstQueueItemId, status: 'pending' },+ expect(+ getActiveProject(state).queue.items.map((item) => ({+ cancellationPending: item.cancellationPending,+ id: item.id,+ status: item.status,+ }))+ ).toEqual([+ { cancellationPending: true, id: getActiveProject(state).queue.items[0].id, status: 'cancelled' },+ { cancellationPending: undefined, id: firstQueueItemId, status: 'pending' },]);});diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 6f1bdc0129..c0e6d887e1 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -89,6 +89,7 @@ import {import { createNewCanvasState, loadCanvasState } from './canvasMigration';import { applyCanvasProjectMutation, type CanvasProjectMutation } from './canvasProjectMutations';import { gateProjectCanvases } from './projectCanvasGate';+import { normalizeRestoredQueueItem } from './queue-integration/queueRunRestoration';import { getProjectWidgetValues } from './widgetState';export { nextLayerName } from './canvasProjectMutations';import { compileGenerateGraph, resolveGenerateSeed } from '@features/generation/graph';@@ -324,7 +325,15 @@ type WorkbenchReducerAction =images: GeneratedImageContract[];}| { type: 'markQueueItemBackendCancelled'; projectId: string; queueItemId: string; backendItemId: number }+ | { type: 'setQueueItemCancellationPending'; projectId: string; queueItemId: string; pending: boolean }+ | {+ type: 'setQueueItemLocalRecoveryState';+ projectId: string;+ queueItemId: string;+ state: NonNullable<QueueItem['localRecoveryState']>;+ }| { type: 'routeQueueItemResults'; projectId: string; queueItemId: string; images: GeneratedImageContract[] }+ | { type: 'restoreQueueItemsFromJournal'; projectId: string; items: unknown[] }| { type: 'appendCanvasStagingCandidate'; projectId: string; candidate: CanvasStagingCandidateContract }| {type: 'selectGalleryItem';@@ -3146,6 +3155,7 @@ const enqueueCompiledSnapshot = (const queueItem: QueueItem = {cancellable: backendSupportsCancellation,id: queueItemId,+ localRecoveryState: 'local-only',snapshot: {backendSubmission,canvas: {@@ -4237,6 +4247,24 @@ export const __workbenchReducerInternal = (return clampCanvasStagingSelection(nextProject, previousSelectedSlot);});}+ case 'setQueueItemCancellationPending': {+ return updateProjectById(state, action.projectId, (project) =>+ updateQueueItem(project, action.queueItemId, (item) =>+ item.cancellationPending === action.pending+ ? item+ : { ...item, cancellationPending: action.pending || undefined }+ )+ );+ }+ case 'setQueueItemLocalRecoveryState': {+ return updateProjectById(state, action.projectId, (project) =>+ updateQueueItem(project, action.queueItemId, (item) =>+ item.localRecoveryState === action.state || item.localRecoveryState === 'durable'+ ? item+ : { ...item, localRecoveryState: action.state }+ )+ );+ }case 'routeQueueItemResults': {const project = state.projects.find((project) => project.id === action.projectId);const queueItem = project?.queue.items.find((item) => item.id === action.queueItemId);@@ -4263,6 +4291,33 @@ export const __workbenchReducerInternal = (}));}+ case 'restoreQueueItemsFromJournal': {+ return updateProjectById(state, action.projectId, (project) => {+ const restoredById = new Map<string, QueueItem>();++ for (const candidate of action.items) {+ const item = normalizeRestoredQueueItem(candidate);+ if (item && !restoredById.has(item.id)) {+ restoredById.set(item.id, { ...item, localRecoveryState: 'durable' });+ }+ }++ const liveItems = project.queue.items.map((item) =>+ restoredById.delete(item.id) && item.localRecoveryState !== 'durable'+ ? { ...item, localRecoveryState: 'durable' as const }+ : item+ );+ const restoredItems: QueueItem[] = [];++ for (const item of restoredById.values()) {+ restoredItems.push(item);+ }++ return restoredItems.length === 0 && liveItems.every((item, index) => item === project.queue.items[index])+ ? project+ : { ...project, queue: { items: [...liveItems, ...restoredItems] } };+ });+ }case 'appendCanvasStagingCandidate': {return updateProjectById(state, action.projectId, (project) =>appendCanvasStagingCandidate(project, action.candidate)@@ -4579,7 +4634,7 @@ export const __workbenchReducerInternal = (return item;}- return { ...item, status: 'cancelled' };+ return { ...item, cancellationPending: true, status: 'cancelled' };}),},};@@ -4623,7 +4678,7 @@ export const __workbenchReducerInternal = (queue: {items: shouldApplyQueueBulkActionToProject(project, action.projectId)? project.queue.items.map((item) =>- isCancellableQueueItem(item) ? { ...item, status: 'cancelled' } : item+ isCancellableQueueItem(item) ? { ...item, cancellationPending: true, status: 'cancelled' } : item): project.queue.items,},@@ -4668,7 +4723,7 @@ export const __workbenchReducerInternal = (items: shouldApplyQueueBulkActionToProject(project, action.projectId)? project.queue.items.map((item) =>isCancellableQueueItem(item) && item.id !== action.currentQueueItemId- ? { ...item, status: 'cancelled' }+ ? { ...item, cancellationPending: true, status: 'cancelled' }: item): project.queue.items,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.tsindex 34128182f7..5d53fa930b 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts@@ -72,6 +72,98 @@ describe('createWorkbenchStore', () => {expect(snapshot.projects).toHaveLength(1);});+ it('blocks persistence retargets only for queue work that has reached the backend', () => {+ const runningState = createInitialWorkbenchState();+ const source = runningState.projects[0]!;+ runningState.projects[0] = {+ ...source,+ queue: {+ items: [{ backendItemIds: [11], id: 'run-1', status: 'running' } as (typeof source.queue.items)[number]],+ },+ };+ const runningStore = createWorkbenchStore(runningState);+ const payload = {+ boardId: 'copy-board',+ name: `${source.name} (copy)`,+ project: { ...source, id: 'copy-id' },+ projectId: source.id,+ sourceName: source.name,+ targetProjectId: 'copy-id',+ };++ expect(runningStore.internal.persistence.retargetProject(payload)).toEqual({+ ok: false,+ reason: 'active-queue-runs',+ });++ for (const status of ['completed', 'failed', 'cancelled'] as const) {+ const terminalStore = createWorkbenchStore({+ ...runningState,+ projects: [+ {+ ...runningState.projects[0]!,+ queue: {+ items: [+ {+ backendItemIds: [11],+ id: 'run-1',+ status,+ } as (typeof source.queue.items)[number],+ ],+ },+ },+ ],+ });+ expect(terminalStore.internal.persistence.retargetProject(payload)).toEqual({ ok: true });+ }++ const pendingState = createInitialWorkbenchState();+ pendingState.projects[0] = {+ ...pendingState.projects[0]!,+ queue: { items: [{ id: 'pending-1', status: 'pending' } as (typeof source.queue.items)[number]] },+ };+ const pendingStore = createWorkbenchStore(pendingState);+ const pendingSource = pendingState.projects[0]!;+ expect(+ pendingStore.internal.persistence.retargetProject({+ ...payload,+ project: { ...pendingSource, id: 'copy-id' },+ projectId: pendingSource.id,+ sourceName: pendingSource.name,+ })+ ).toEqual({ ok: true });+ });++ it('blocks persistence retargets while durable cancellation is pending', () => {+ const state = createInitialWorkbenchState();+ const source = state.projects[0]!;+ state.projects[0] = {+ ...source,+ queue: {+ items: [+ {+ backendItemIds: [11],+ cancellationPending: true,+ id: 'run-1',+ status: 'cancelled',+ } as (typeof source.queue.items)[number],+ ],+ },+ };+ const store = createWorkbenchStore(state);++ expect(+ store.internal.persistence.retargetProject({+ boardId: 'copy-board',+ name: `${source.name} (copy)`,+ project: { ...source, id: 'copy-id' },+ projectId: source.id,+ sourceName: source.name,+ targetProjectId: 'copy-id',+ })+ ).toEqual({ ok: false, reason: 'active-queue-runs' });+ });+it("keeps each project's transient layer multi-selection across project switches", () => {const store = createWorkbenchStore();const firstProjectId = store.getSnapshot().activeProject.id;@@ -580,6 +672,36 @@ describe('createWorkbenchStore', () => {expect(store.getSnapshot().notifications).toEqual([]);});+ it.each([+ { cancellationPending: undefined, status: 'pending' as const },+ { cancellationPending: undefined, status: 'running' as const },+ { cancellationPending: true, status: 'cancelled' as const },+ ])('keeps a project open while queue work is active ($status)', ({ cancellationPending, status }) => {+ const state = createInitialWorkbenchState();+ const project = state.projects[0]!;+ state.projects[0] = {+ ...project,+ queue: {+ items: [+ {+ cancellable: true,+ ...(cancellationPending === undefined ? {} : { cancellationPending }),+ id: 'active-run',+ snapshot: {} as (typeof project.queue.items)[number]['snapshot'],+ status,+ },+ ],+ },+ };+ const store = createWorkbenchStore(state);++ expect(store.commands.projects.close(project.id)).toEqual({ ok: false, reason: 'active-queue-runs' });+ store.commands.projects.create();++ expect(store.commands.projects.close(project.id)).toEqual({ ok: false, reason: 'active-queue-runs' });+ expect(store.getSnapshot().projects.some((candidate) => candidate.id === project.id)).toBe(true);+ });+it('applies Canvas and Workflow edits without exposing aggregate reducer actions', () => {const store = createWorkbenchStore();const project = store.getSnapshot().activeProject;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 617881f676..2ba331f994 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -8,6 +8,7 @@ import {type GeneratedImageContract,} from '@features/gallery/contracts';import { createExternalStore } from '@platform/state/externalStore';+import { hasActiveQueueRuns, hasInFlightQueueRuns } from '@workbench/queue-integration/activeQueueRuns';import type { CanvasEditIntent } from './autoRoutePolicy';import type { CanvasProjectMutation } from './canvasProjectMutations';@@ -59,7 +60,10 @@ const createCommandFactory = (dispatch: WorkbenchDispatch) => {export type ProjectCommandResult =| { ok: true }- | { ok: false; reason: 'invalid-name' | 'last-project' | 'project-not-found' | 'target-already-open' };+ | {+ ok: false;+ reason: 'active-queue-runs' | 'invalid-name' | 'last-project' | 'project-not-found' | 'target-already-open';+ };const createCommands = (dispatch: WorkbenchDispatch,@@ -332,11 +336,17 @@ const createCommands = (},projects: {close: (projectId: string): ProjectCommandResult => {- if (!getState().projects.some((project) => project.id === projectId)) {+ const state = getState();+ const project = state.projects.find((project) => project.id === projectId);+ if (!project) {return { ok: false, reason: 'project-not-found' };}- if (getState().projects.length === 1) {+ if (hasActiveQueueRuns(project)) {+ return { ok: false, reason: 'active-queue-runs' };+ }++ if (state.projects.length === 1) {return { ok: false, reason: 'last-project' };}@@ -381,8 +391,11 @@ const createCommands = (clearCompleted: command('clearCompletedQueueItems'),markBackendCancelled: command('markQueueItemBackendCancelled'),markBackendSubmitted: command('markQueueItemBackendSubmitted'),+ setCancellationPending: command('setQueueItemCancellationPending'),+ setLocalRecoveryState: command('setQueueItemLocalRecoveryState'),routePartialResults: command('routeQueueItemPartialResults'),routeResults: command('routeQueueItemResults'),+ restoreFromJournal: command('restoreQueueItemsFromJournal'),setConnectionStatus: command('setBackendConnectionStatus'),setStatus: command('setQueueItemStatus'),},@@ -478,6 +491,10 @@ const createPersistenceAdapter = (dispatch: WorkbenchDispatch, getState: () => Wif (!state.projects.some((project) => project.id === payload.projectId)) {return { ok: false, reason: 'project-not-found' };}+ const source = state.projects.find((project) => project.id === payload.projectId);+ if (source && hasInFlightQueueRuns(source)) {+ return { ok: false, reason: 'active-queue-runs' };+ }if (state.projects.some((project) => project.id === payload.targetProjectId)) {return { ok: false, reason: 'target-already-open' };}