Skip to content

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.

feat(webv2): capture workflow last-run thumbnail via queue runtime sink

joshistoasta04dc866fe5a
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 29a19e9959..f33e3aa11e 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": 834029,
+ "brotliBytes": 834004,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 833782,
+ "gzipBytes": 833838,
"imageRawBytes": 156376,
- "initialRawBytes": 1938019,
+ "initialRawBytes": 1938174,
"largestAssetRawBytes": 746569,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 67403,
+ "ownedRawBytes": 67459,
"requestCount": 41,
"scriptRequestCount": 25,
"sourceOwners": [
@@ -284,15 +284,15 @@
]
},
"limits": {
- "brotliBytes": 842370,
+ "brotliBytes": 842345,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 842120,
+ "gzipBytes": 842177,
"imageRawBytes": 157940,
- "initialRawBytes": 1957400,
+ "initialRawBytes": 1957556,
"largestAssetRawBytes": 754035,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 67403,
+ "ownedRawBytes": 67459,
"requestCount": 41,
"scriptRequestCount": 25
},
@@ -302,17 +302,17 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1032617,
+ "brotliBytes": 1034640,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1029870,
+ "gzipBytes": 1031951,
"imageRawBytes": 156376,
- "initialRawBytes": 2532203,
+ "initialRawBytes": 2536883,
"largestAssetRawBytes": 746569,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 111518,
- "requestCount": 90,
- "scriptRequestCount": 74,
+ "ownedRawBytes": 111579,
+ "requestCount": 92,
+ "scriptRequestCount": 76,
"sourceOwners": [
"package:@ark-ui/react",
"package:@chakra-ui/react",
@@ -594,7 +594,11 @@
"source:src/features/workflow/core/types.ts",
"source:src/features/workflow/core/validation.ts",
"source:src/features/workflow/core/workflowJson.ts",
+ "source:src/features/workflow/data/api.ts",
+ "source:src/features/workflow/data/libraryCache.ts",
+ "source:src/features/workflow/data/runCapture.ts",
"source:src/features/workflow/data/templates.ts",
+ "source:src/features/workflow/queries.ts",
"source:src/features/workflow/react.ts",
"source:src/features/workflow/ui/WorkflowUiContext.tsx",
"source:src/features/workflow/ui/workflowUiStore.ts",
@@ -844,17 +848,17 @@
]
},
"limits": {
- "brotliBytes": 1042944,
+ "brotliBytes": 1044987,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1040169,
+ "gzipBytes": 1042271,
"imageRawBytes": 157940,
- "initialRawBytes": 2557526,
+ "initialRawBytes": 2562252,
"largestAssetRawBytes": 754035,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 111518,
- "requestCount": 90,
- "scriptRequestCount": 74
+ "ownedRawBytes": 111579,
+ "requestCount": 92,
+ "scriptRequestCount": 76
},
"owner": "workbench",
"remediationTicket": "deepen-widget-registry-loading",
diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
index 8e5221dce0..6e6a105603 100644
--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
@@ -2,6 +2,7 @@ import { invalidateGallery } from '@features/gallery/queries';
import { modelLoadActivitySink } from '@features/models';
import { nodeExecutionStore } from '@features/nodes';
import { createProductionQueueRuntime } 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';
@@ -75,6 +76,9 @@ export const QueueRuntimeAdapter = () => {
},
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();
diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.ts
index 7f1b9623cf..5710cddf25 100644
--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts
@@ -25,6 +25,8 @@ export type {
QueueSourceId,
QueueStatusReadModel,
QueueSubmissionPresentation,
+ QueueWorkflowRunCompletedEvent,
+ QueueWorkflowRunSink,
TerminalQueueItemStatus,
} from './core/types';
export {
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index b0d761742f..687b1d6ced 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -74,6 +74,12 @@ export type QueueCompiledSubmission =
batchCount: number;
graph: QueueBackendGraph;
kind: 'workflow';
+ /**
+ * The library record this run's workflow was loaded from, when the project
+ * graph is bound to one. Stamped at compile time so a completed run can be
+ * attributed back to the library record even after the editor moved on.
+ */
+ libraryWorkflowId?: string;
}
| {
batchCount: number;
@@ -113,6 +119,24 @@ export interface QueueResultImage {
width: number;
}
+/** A settled run of a library-bound workflow, reported once its results are routed. */
+export interface QueueWorkflowRunCompletedEvent {
+ /** Result images in run order; the last one is the run's final output. */
+ imageNames: readonly string[];
+ libraryWorkflowId: string;
+ projectId: string;
+ queueItemId: string;
+}
+
+/**
+ * Optional observer for completed library-bound workflow runs. The Queue owns
+ * neither the workflow library nor the gallery, so the App composition root
+ * supplies the implementation; a missing sink simply disables the notification.
+ */
+export interface QueueWorkflowRunSink {
+ onWorkflowRunCompleted(event: QueueWorkflowRunCompletedEvent): void;
+}
+
export type QueueItemStatus = 'pending' | 'in_progress' | 'waiting' | 'completed' | 'failed' | 'canceled';
export type TerminalQueueItemStatus = Extract<QueueItemStatus, 'completed' | 'failed' | 'canceled'>;
export type QueueConnectionStatus = 'connecting' | 'connected' | 'disconnected';
diff --git a/invokeai/frontend/webv2/src/features/queue/publicApi.ts b/invokeai/frontend/webv2/src/features/queue/publicApi.ts
index 220b775cbc..b3faac5a5a 100644
--- a/invokeai/frontend/webv2/src/features/queue/publicApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/publicApi.ts
@@ -1,4 +1,4 @@
-import type { QueueFeatureCommands, QueueQueryScope, QueueReadModel } from './core/types';
+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 { QueueModelLoadPort, QueueNodeExecutionPort } from './runtime/coordinator';
@@ -46,12 +46,14 @@ export const createProductionQueueRuntime = ({
history,
modelLoads,
nodeExecution,
+ workflowRuns,
}: {
destinations: QueueResultDestinationPort;
ensureTemplatesLoaded: () => void;
history: QueueHistoryPort;
modelLoads: QueueModelLoadPort;
nodeExecution: QueueNodeExecutionPort;
+ workflowRuns?: QueueWorkflowRunSink;
}): QueueRuntime =>
createQueueRuntime({
backend: queueBackend,
@@ -60,4 +62,5 @@ export const createProductionQueueRuntime = ({
history,
modelLoads,
nodeExecution,
+ workflowRuns,
});
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index 658b5a338b..473151909b 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -1,5 +1,10 @@
import type { QueueItem } from '@features/queue/core/historyTypes';
-import type { QueueBackendInvocation, QueueBackendPort, QueueResultImage } from '@features/queue/core/types';
+import type {
+ QueueBackendInvocation,
+ QueueBackendPort,
+ QueueResultImage,
+ QueueWorkflowRunSink,
+} from '@features/queue/core/types';
import { buildQueueItemOrigin } from '@features/queue/data/events';
import { describe, expect, it, vi } from 'vitest';
@@ -352,3 +357,204 @@ describe('queue runtime video board routing', () => {
runtime.dispose();
});
});
+
+describe('queue runtime workflow run capture', () => {
+ const resultImage = (imageName: string): QueueResultImage => ({
+ height: 512,
+ imageName,
+ imageUrl: `http://test/i/${imageName}`,
+ isIntermediate: false,
+ queuedAt: '2026-07-17T00:00:00.000Z',
+ sourceQueueItemId: 'local-queue-item',
+ thumbnailUrl: `http://test/t/${imageName}`,
+ width: 512,
+ });
+
+ const createHarness = (options: {
+ images?: QueueResultImage[];
+ /** Replaces the item's generate submission with a workflow one. */
+ libraryWorkflowId?: string | null;
+ onWorkflowRunCompleted?: QueueWorkflowRunSink['onWorkflowRunCompleted'];
+ }) => {
+ const queueItem = createPendingQueueItem();
+
+ queueItem.snapshot.destination = 'gallery';
+ queueItem.snapshot.galleryBoardId = null;
+ if (options.libraryWorkflowId !== undefined) {
+ queueItem.snapshot.backendSubmission = {
+ batchCount: 1,
+ graph: { edges: [], id: 'backend-graph', nodes: {} },
+ kind: 'workflow',
+ ...(options.libraryWorkflowId ? { libraryWorkflowId: options.libraryWorkflowId } : {}),
+ };
+ queueItem.snapshot.sourceId = 'workflow';
+ }
+
+ const project = { id: 'project-1', queue: { items: [queueItem] } };
+ 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: vi.fn(),
+ enqueueWorkflow: vi.fn(),
+ getItem: vi.fn(),
+ getResultImages: vi.fn().mockResolvedValue(options.images ?? [resultImage('generated.png')]),
+ getResultVideoNames: vi.fn().mockResolvedValue([]),
+ listItems: vi.fn().mockResolvedValue([
+ {
+ batchId: 'backend-batch',
+ id: 77,
+ origin: buildQueueItemOrigin(queueItem.id, project.id),
+ status: 'completed',
+ },
+ ]),
+ on: vi.fn(() => vi.fn()),
+ onConnectionChange: vi.fn(() => vi.fn()),
+ pauseProcessor: vi.fn(),
+ readCurrent: vi.fn().mockResolvedValue(null),
+ readItemIds: vi.fn().mockResolvedValue({ itemIds: [], totalCount: 0 }),
+ readItemsById: vi.fn().mockResolvedValue([]),
+ readNext: vi.fn().mockResolvedValue(null),
+ readStatus: vi.fn().mockResolvedValue({
+ processor: { isProcessing: false, isStarted: true },
+ queue: {
+ canceled: 0,
+ completed: 0,
+ failed: 0,
+ inProgress: 0,
+ pending: 0,
+ queueId: 'default',
+ total: 0,
+ waiting: 0,
+ },
+ }),
+ resumeProcessor: vi.fn(),
+ retryItems: vi.fn(),
+ };
+ const commands: QueueHistoryCommands = {
+ markBackendCancelled: vi.fn(),
+ markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {
+ queueItem.backendBatchId = backendBatchId;
+ queueItem.backendItemIds = backendItemIds;
+ queueItem.status = 'running';
+ },
+ recordError: vi.fn(),
+ refreshBackendData: vi.fn(),
+ routePartialResults: vi.fn(),
+ routeResults: vi.fn(),
+ setConnectionStatus: vi.fn(),
+ setStatus: vi.fn(),
+ };
+ const onWorkflowRunCompleted = vi.fn(options.onWorkflowRunCompleted);
+ 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(),
+ },
+ workflowRuns: { onWorkflowRunCompleted },
+ });
+
+ return { commands, onWorkflowRunCompleted, queueItem, runtime };
+ };
+
+ it('notifies the capture sink once with the completed run and its result image names', async () => {
+ const { commands, onWorkflowRunCompleted, runtime } = createHarness({
+ images: [resultImage('early.png'), resultImage('final.png')],
+ libraryWorkflowId: 'library-workflow-1',
+ });
+
+ runtime.start();
+
+ await vi.waitFor(() => {
+ expect(commands.routeResults).toHaveBeenCalled();
+ });
+ expect(onWorkflowRunCompleted).toHaveBeenCalledTimes(1);
+ expect(onWorkflowRunCompleted).toHaveBeenCalledWith({
+ imageNames: ['early.png', 'final.png'],
+ libraryWorkflowId: 'library-workflow-1',
+ projectId: 'project-1',
+ queueItemId: 'local-queue-item',
+ });
+
+ runtime.dispose();
+ });
+
+ it('never notifies for a workflow run that is not bound to a library record', async () => {
+ const { commands, onWorkflowRunCompleted, runtime } = createHarness({ libraryWorkflowId: null });
+
+ runtime.start();
+
+ await vi.waitFor(() => {
+ expect(commands.routeResults).toHaveBeenCalled();
+ });
+ expect(onWorkflowRunCompleted).not.toHaveBeenCalled();
+
+ runtime.dispose();
+ });
+
+ it('never notifies for a generate run', async () => {
+ const { commands, onWorkflowRunCompleted, runtime } = createHarness({});
+
+ runtime.start();
+
+ await vi.waitFor(() => {
+ expect(commands.routeResults).toHaveBeenCalled();
+ });
+ expect(onWorkflowRunCompleted).not.toHaveBeenCalled();
+
+ runtime.dispose();
+ });
+
+ it('never notifies for a bound workflow run that produced no images', async () => {
+ const { commands, onWorkflowRunCompleted, runtime } = createHarness({
+ images: [],
+ libraryWorkflowId: 'library-workflow-1',
+ });
+
+ runtime.start();
+
+ await vi.waitFor(() => {
+ expect(commands.routeResults).toHaveBeenCalled();
+ });
+ expect(onWorkflowRunCompleted).not.toHaveBeenCalled();
+
+ runtime.dispose();
+ });
+
+ it('settles the run normally when the capture sink throws', async () => {
+ const { commands, onWorkflowRunCompleted, runtime } = createHarness({
+ libraryWorkflowId: 'library-workflow-1',
+ onWorkflowRunCompleted: () => {
+ throw new Error('capture exploded');
+ },
+ });
+
+ runtime.start();
+
+ await vi.waitFor(() => {
+ expect(onWorkflowRunCompleted).toHaveBeenCalled();
+ });
+ expect(commands.routeResults).toHaveBeenCalled();
+ expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));
+
+ runtime.dispose();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index 09c728fbbb..3ea58ea5d8 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -5,6 +5,7 @@ import type {
QueueEnqueueWorkflowRequest,
QueueResultImage,
QueueResultImageOptions,
+ QueueWorkflowRunSink,
} from '@features/queue/core/types';
import type { BackendConnectionStatus } from '@platform/transport/types';
@@ -147,7 +148,9 @@ export const createQueueItemBackendSubmission = (
};
}
- const { kind: _, ...compiled } = submission;
+ // `libraryWorkflowId` is provenance for the completed-run sink, not something
+ // the backend enqueue accepts; it stays on the snapshot and off the request.
+ const { kind: _, libraryWorkflowId: _libraryWorkflowId, ...compiled } = submission;
return {
kind: 'workflow',
request: {
@@ -185,6 +188,7 @@ export const createQueueRuntime = ({
history,
modelLoads,
nodeExecution,
+ workflowRuns,
}: {
backend: QueueBackendPort;
destinations: QueueResultDestinationPort;
@@ -192,6 +196,7 @@ export const createQueueRuntime = ({
history: QueueHistoryPort;
modelLoads: QueueModelLoadPort;
nodeExecution: QueueNodeExecutionPort;
+ workflowRuns?: QueueWorkflowRunSink;
}): QueueRuntime => {
const owner = captureAccountScope();
const commands = history.commands;
@@ -307,6 +312,40 @@ export const createQueueRuntime = ({
return images;
};
+ /**
+ * Reports a settled run back to whoever owns the workflow library, so it can
+ * capture the output as the record's thumbnail and stamp its last-run time.
+ * Only runs compiled from a library-BOUND workflow carry an id, so an ad-hoc
+ * workflow (or any generate run) is never reported.
+ *
+ * Deliberately synchronous, unawaited, and swallowing: last-run capture is
+ * decoration hung off a completed run, and a sink that throws must not turn
+ * that run into a failure or skip its gallery refresh.
+ */
+ const notifyWorkflowRunCompleted = (projectId: string, queueItem: QueueItem, images: QueueResultImage[]): void => {
+ const submission = (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;
+
+ if (
+ !workflowRuns ||
+ submission?.kind !== 'workflow' ||
+ typeof submission.libraryWorkflowId !== 'string' ||
+ images.length === 0
+ ) {
+ return;
+ }
+
+ try {
+ workflowRuns.onWorkflowRunCompleted({
+ imageNames: images.map((image) => image.imageName),
+ libraryWorkflowId: submission.libraryWorkflowId,
+ projectId,
+ queueItemId: queueItem.id,
+ });
+ } catch {
+ // The sink owns its own error reporting; the run is already complete.
+ }
+ };
+
const routeRunResults = async (
coordinator: QueueCoordinator,
projectId: string,
@@ -339,6 +378,7 @@ export const createQueueRuntime = ({
}
commands.routeResults({ images, projectId, queueItemId: queueItem.id });
+ notifyWorkflowRunCompleted(projectId, queueItem, images);
if (queueItem.snapshot.destination === 'gallery') {
commands.refreshBackendData();
}
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/runCapture.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/runCapture.test.ts
new file mode 100644
index 0000000000..968527092b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/runCapture.test.ts
@@ -0,0 +1,220 @@
+import type { QueueWorkflowRunCompletedEvent } from '@features/queue/contracts';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { RunCaptureDeps } from './runCapture';
+
+import { createWorkflowRunCaptureSink } from './runCapture';
+
+const createDeferred = <T>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+
+ return { promise, resolve };
+};
+
+const createEvent = (overrides?: Partial<QueueWorkflowRunCompletedEvent>): QueueWorkflowRunCompletedEvent => ({
+ imageNames: ['first.png', 'last.png'],
+ libraryWorkflowId: 'workflow-1',
+ projectId: 'project-1',
+ queueItemId: 'queue-item-1',
+ ...overrides,
+});
+
+const userWorkflow = (workflowId: string) => ({ id: workflowId, meta: { category: 'user', version: '3.0.0' } });
+
+/** The sink is fire-and-forget, so tests wait for its detached chain to settle. */
+const settle = async (): Promise<void> => {
+ for (let tick = 0; tick < 5; tick += 1) {
+ await new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ }
+};
+
+/** `calls` is a parameter so a test can seed it into its own dep overrides. */
+const createHarness = (overrides?: Partial<RunCaptureDeps>, calls: string[] = []) => {
+ const blob = new Blob(['thumbnail'], { type: 'image/png' });
+ const deps: RunCaptureDeps = {
+ fetchThumbnailBlob: vi.fn((imageName: string) => {
+ calls.push(`fetch:${imageName}`);
+ return Promise.resolve(blob);
+ }),
+ getWorkflow: vi.fn((workflowId: string) => {
+ calls.push(`getWorkflow:${workflowId}`);
+ return Promise.resolve(userWorkflow(workflowId));
+ }),
+ invalidateCache: vi.fn(() => {
+ calls.push('invalidate');
+ }),
+ setThumbnail: vi.fn((workflowId: string) => {
+ calls.push(`setThumbnail:${workflowId}`);
+ return Promise.resolve();
+ }),
+ touchLastRunAt: vi.fn((workflowId: string) => {
+ calls.push(`touchLastRunAt:${workflowId}`);
+ return Promise.resolve();
+ }),
+ ...overrides,
+ };
+
+ return { blob, calls, deps, sink: createWorkflowRunCaptureSink(deps) };
+};
+
+describe('workflow run capture sink', () => {
+ it('uploads the last result thumbnail, stamps last_run_at, then invalidates the library', async () => {
+ const { blob, calls, deps, sink } = createHarness();
+
+ sink.onWorkflowRunCompleted(createEvent());
+ await settle();
+
+ expect(calls).toEqual([
+ 'getWorkflow:workflow-1',
+ // The run's LAST image is the workflow's cover, not an early intermediate.
+ 'fetch:last.png',
+ 'setThumbnail:workflow-1',
+ 'touchLastRunAt:workflow-1',
+ 'invalidate',
+ ]);
+ expect(deps.setThumbnail).toHaveBeenCalledWith('workflow-1', blob, expect.any(AbortSignal));
+ });
+
+ it('never touches a default-category workflow, which the account does not own', async () => {
+ const { calls, deps, sink } = createHarness({
+ getWorkflow: vi.fn().mockResolvedValue({ id: 'workflow-1', meta: { category: 'default', version: '3.0.0' } }),
+ });
+
+ sink.onWorkflowRunCompleted(createEvent());
+ await settle();
+
+ expect(deps.getWorkflow).toHaveBeenCalledWith('workflow-1', expect.any(AbortSignal));
+ // Nothing after the category check ran: no download, no upload, no stamp.
+ expect(calls).toEqual([]);
+ });
+
+ it('serializes captures per workflow and keeps only the latest queued run', async () => {
+ const gate = createDeferred<Blob>();
+ const blob = new Blob(['thumbnail'], { type: 'image/png' });
+ const calls: string[] = [];
+ let fetchCount = 0;
+ const { sink } = createHarness(
+ {
+ fetchThumbnailBlob: vi.fn((imageName: string) => {
+ calls.push(`fetch:${imageName}`);
+ fetchCount += 1;
+ // Hold the first capture open so the next two events queue behind it.
+ return fetchCount === 1 ? gate.promise : Promise.resolve(blob);
+ }),
+ },
+ calls
+ );
+
+ sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-1.png'] }));
+ await settle();
+ sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-2.png'] }));
+ sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-3.png'] }));
+ await settle();
+
+ // Nothing from the queued runs ran while the first capture was in flight.
+ expect(calls).toEqual(['getWorkflow:workflow-1', 'fetch:run-1.png']);
+
+ gate.resolve(blob);
+ await settle();
+
+ // run-2 was superseded by run-3 before it ever started.
+ expect(calls).toEqual([
+ 'getWorkflow:workflow-1',
+ 'fetch:run-1.png',
+ 'setThumbnail:workflow-1',
+ 'touchLastRunAt:workflow-1',
+ 'invalidate',
+ 'getWorkflow:workflow-1',
+ 'fetch:run-3.png',
+ 'setThumbnail:workflow-1',
+ 'touchLastRunAt:workflow-1',
+ 'invalidate',
+ ]);
+ });
+
+ it('stops silently when the thumbnail fetch fails, leaving last_run_at untouched', async () => {
+ const { calls, deps, sink } = createHarness({
+ fetchThumbnailBlob: vi.fn().mockRejectedValue(new Error('404 thumbnail')),
+ });
+
+ sink.onWorkflowRunCompleted(createEvent());
+ await settle();
+
+ expect(calls).toEqual(['getWorkflow:workflow-1']);
+ expect(deps.setThumbnail).not.toHaveBeenCalled();
+ expect(deps.touchLastRunAt).not.toHaveBeenCalled();
+ expect(deps.invalidateCache).not.toHaveBeenCalled();
+ });
+
+ it('stops silently when the thumbnail upload fails, leaving last_run_at untouched', async () => {
+ const { deps, sink } = createHarness({
+ setThumbnail: vi.fn().mockRejectedValue(new Error('413 payload too large')),
+ });
+
+ sink.onWorkflowRunCompleted(createEvent());
+ await settle();
+
+ expect(deps.touchLastRunAt).not.toHaveBeenCalled();
+ expect(deps.invalidateCache).not.toHaveBeenCalled();
+ });
+
+ it('keeps draining queued runs after one of them fails', async () => {
+ const { deps, sink } = createHarness({
+ getWorkflow: vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(userWorkflow('workflow-1')),
+ });
+
+ sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-1.png'] }));
+ sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-2.png'] }));
+ await settle();
+
+ expect(deps.setThumbnail).toHaveBeenCalledTimes(1);
+ expect(deps.fetchThumbnailBlob).toHaveBeenCalledWith('run-2.png', expect.any(AbortSignal));
+ });
+
+ it('ignores an event that carries no result images', async () => {
+ const { calls, sink } = createHarness();
+
+ sink.onWorkflowRunCompleted(createEvent({ imageNames: [] }));
+ await settle();
+
+ expect(calls).toEqual([]);
+ });
+
+ it('captures concurrently when the runs belong to different library records', async () => {
+ const gate = createDeferred<Blob>();
+ const blob = new Blob(['thumbnail'], { type: 'image/png' });
+ const { deps, sink } = createHarness({
+ fetchThumbnailBlob: vi.fn((imageName: string) => (imageName === 'a.png' ? gate.promise : Promise.resolve(blob))),
+ });
+
+ sink.onWorkflowRunCompleted(createEvent({ imageNames: ['a.png'], libraryWorkflowId: 'workflow-a' }));
+ sink.onWorkflowRunCompleted(createEvent({ imageNames: ['b.png'], libraryWorkflowId: 'workflow-b' }));
+ await settle();
+
+ // workflow-b never waits behind workflow-a's stalled fetch.
+ expect(deps.setThumbnail).toHaveBeenCalledWith('workflow-b', blob, expect.any(AbortSignal));
+ gate.resolve(blob);
+ await settle();
+ });
+
+ it('drops a capture whose account scope expired mid-flight', async () => {
+ const gate = createDeferred<Record<string, unknown>>();
+ const { deps, sink } = createHarness({ getWorkflow: vi.fn(() => gate.promise) });
+
+ sink.onWorkflowRunCompleted(createEvent());
+ await settle();
+ accountLifecycle.invalidate();
+ gate.resolve(userWorkflow('workflow-1'));
+ await settle();
+
+ expect(deps.setThumbnail).not.toHaveBeenCalled();
+ expect(deps.touchLastRunAt).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/runCapture.ts b/invokeai/frontend/webv2/src/features/workflow/data/runCapture.ts
new file mode 100644
index 0000000000..50fa1c2abf
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/runCapture.ts
@@ -0,0 +1,145 @@
+import type { QueueWorkflowRunCompletedEvent, QueueWorkflowRunSink } from '@features/queue/contracts';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+
+import { setLibraryWorkflowThumbnail, touchLibraryWorkflowLastRunAt } from './api';
+import { getLibraryWorkflowCached, invalidateWorkflowLibraryCache } from './libraryCache';
+
+/**
+ * Turns a completed workflow run into the library record's cover image and
+ * last-run stamp. The Queue reports the run; this module owns everything about
+ * the library, and every step is best-effort — a capture that fails leaves the
+ * record exactly as it was and never surfaces to the user, because the run it
+ * decorates already succeeded.
+ */
+
+export interface RunCaptureDeps {
+ /** Downloads the gallery thumbnail bytes for one result image. */
+ fetchThumbnailBlob(imageName: string, signal: AbortSignal): Promise<Blob>;
+ getWorkflow(workflowId: string, signal?: AbortSignal): Promise<Record<string, unknown>>;
+ invalidateCache(): void;
+ setThumbnail(workflowId: string, image: Blob, signal?: AbortSignal): Promise<void>;
+ touchLastRunAt(workflowId: string, signal?: AbortSignal): Promise<void>;
+}
+
+/**
+ * Gallery owns image URLs, but importing its public surface statically would
+ * drag the gallery UI (drag-and-drop included) into every bundle that composes
+ * the queue runtime. The URL is needed once per completed run, so it is loaded
+ * on demand instead.
+ *
+ * Plain `fetch` rather than the authenticated API helper: image media routes are
+ * served against the path-scoped session cookie — the same credentials the
+ * gallery's own `<img>` tags use to render this exact URL.
+ */
+const fetchThumbnailBlob = async (imageName: string, signal: AbortSignal): Promise<Blob> => {
+ const { galleryImageUrls } = await import('@features/gallery/utility');
+ const response = await fetch(galleryImageUrls.thumbnail(imageName), { credentials: 'same-origin', signal });
+
+ if (!response.ok) {
+ throw new Error(`Thumbnail request for ${imageName} failed with status ${response.status}.`);
+ }
+
+ return response.blob();
+};
+
+const PRODUCTION_DEPS: RunCaptureDeps = {
+ fetchThumbnailBlob,
+ getWorkflow: getLibraryWorkflowCached,
+ invalidateCache: invalidateWorkflowLibraryCache,
+ setThumbnail: setLibraryWorkflowThumbnail,
+ touchLastRunAt: touchLibraryWorkflowLastRunAt,
+};
+
+/**
+ * Bundled defaults ship in `meta.category: 'default'` and are read-only for the
+ * account, so a run of one must not write a thumbnail or a last-run stamp.
+ */
+const isUserWorkflow = (workflow: Record<string, unknown>): boolean => {
+ const meta = workflow.meta;
+
+ return typeof meta === 'object' && meta !== null && (meta as { category?: unknown }).category === 'user';
+};
+
+interface PendingCapture {
+ event: QueueWorkflowRunCompletedEvent;
+ /** The scope the run settled under; a later account owns none of its writes. */
+ owner: AccountScope;
+}
+
+export const createWorkflowRunCaptureSink = (overrides?: Partial<RunCaptureDeps>): QueueWorkflowRunSink => {
+ const deps: RunCaptureDeps = { ...PRODUCTION_DEPS, ...overrides };
+ // One drain chain per library record. Two runs of the SAME workflow must not
+ // race their thumbnail uploads (the loser would win the record), while runs of
+ // different workflows are independent and proceed in parallel.
+ const draining = new Map<string, Promise<void>>();
+ // At most one queued capture per record: while one is uploading, a newer run
+ // supersedes any other run still waiting, because only the newest output
+ // should end up as the cover.
+ const pending = new Map<string, PendingCapture>();
+
+ const capture = async ({ event, owner }: PendingCapture): Promise<void> => {
+ const { imageNames, libraryWorkflowId } = event;
+ const imageName = imageNames[imageNames.length - 1];
+
+ if (!imageName || !isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ const workflow = await deps.getWorkflow(libraryWorkflowId, owner.signal);
+
+ if (!isAccountScopeCurrent(owner) || !isUserWorkflow(workflow)) {
+ return;
+ }
+
+ const blob = await deps.fetchThumbnailBlob(imageName, owner.signal);
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ await deps.setThumbnail(libraryWorkflowId, blob, owner.signal);
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ // Ordered after the upload so a library row never advertises a fresh run
+ // against a stale cover.
+ await deps.touchLastRunAt(libraryWorkflowId, owner.signal);
+
+ if (isAccountScopeCurrent(owner)) {
+ deps.invalidateCache();
+ }
+ };
+
+ const drain = async (libraryWorkflowId: string): Promise<void> => {
+ for (let next = pending.get(libraryWorkflowId); next !== undefined; next = pending.get(libraryWorkflowId)) {
+ pending.delete(libraryWorkflowId);
+
+ try {
+ await capture(next);
+ } catch {
+ // Capture is decoration around an already-successful run: one failed
+ // record must not stop the next run from trying again.
+ }
+ }
+
+ draining.delete(libraryWorkflowId);
+ };
+
+ return {
+ onWorkflowRunCompleted: (event) => {
+ if (event.imageNames.length === 0) {
+ return;
+ }
+
+ pending.set(event.libraryWorkflowId, { event, owner: captureAccountScope() });
+
+ if (!draining.has(event.libraryWorkflowId)) {
+ draining.set(event.libraryWorkflowId, drain(event.libraryWorkflowId));
+ }
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/queries.ts b/invokeai/frontend/webv2/src/features/workflow/queries.ts
index 00d3a58d77..81fbe96aac 100644
--- a/invokeai/frontend/webv2/src/features/workflow/queries.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/queries.ts
@@ -1,2 +1,3 @@
export * from './data/api';
export * from './data/libraryCache';
+export { createWorkflowRunCaptureSink, type RunCaptureDeps } from './data/runCapture';
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 24396c24f8..14bd461114 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -2847,6 +2847,13 @@ const enqueueCompiledSnapshot = (
batchCount: sanitizeBatchCount(widgetStates.generate?.values.batchCount),
graph: backendGraph,
kind: 'workflow',
+ // Provenance for the completed-run capture: a run submitted from a
+ // library-bound graph knows which record to stamp, even after the
+ // editor has moved on to another workflow. An unbound graph stamps
+ // nothing, so an ad-hoc workflow never writes to the library.
+ ...(project.projectGraph.libraryWorkflowId
+ ? { libraryWorkflowId: project.projectGraph.libraryWorkflowId }
+ : {}),
}
: sourceGenerateSettings && effectivePrompts
? {
diff --git a/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts b/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts
new file mode 100644
index 0000000000..d7877cab72
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts
@@ -0,0 +1,118 @@
+import type * as workflowReactModule from '@features/workflow/react';
+import type { WorkbenchState } from '@workbench/projectContracts';
+
+// Feature-private document builders: the dependency policy exempts test files,
+// and hand-rolling a compilable graph literal here would only duplicate them.
+import { buildInvocationNode, createProjectGraph, projectGraphReducer } from '@features/workflow/core/document';
+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The workflow compile site stamps the project graph's library binding onto the
+ * compiled submission, which is the only place a completed run can learn which
+ * library record produced it. Templates are read imperatively by both the route
+ * resolver and the compiler, so they are stubbed as loaded here.
+ */
+
+const stringField = { batch: false, cardinality: 'SINGLE' as const, name: 'StringField' };
+
+const template = {
+ category: 'test',
+ classification: 'stable' as const,
+ description: '',
+ inputs: {
+ value: {
+ default: 'hello',
+ description: '',
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ input: 'any' as const,
+ maximum: null,
+ minimum: null,
+ multipleOf: null,
+ name: 'value',
+ options: null,
+ required: true,
+ title: 'value',
+ type: stringField,
+ uiChoiceLabels: null,
+ uiComponent: null,
+ uiHidden: false,
+ uiModelBase: null,
+ uiModelFormat: null,
+ uiModelType: null,
+ uiOrder: null,
+ },
+ },
+ nodePack: 'invokeai',
+ outputs: { out: { description: '', name: 'out', title: 'Out', type: stringField } },
+ outputType: 'source_output',
+ tags: [],
+ title: 'source',
+ type: 'source',
+ useCache: true,
+ version: '1.0.0',
+};
+
+vi.mock('@features/workflow/react', async (importOriginal) => ({
+ ...(await importOriginal<typeof workflowReactModule>()),
+ getInvocationTemplatesSnapshot: () => ({ error: null, status: 'loaded', templates: { source: template } }),
+}));
+
+const buildReadyGraph = (libraryWorkflowId?: string) => {
+ let document = createProjectGraph('run-binding');
+
+ document = projectGraphReducer(document, { node: buildInvocationNode(template, { x: 0, y: 0 }), type: 'addNode' });
+
+ return { ...document, ...(libraryWorkflowId ? { libraryWorkflowId } : {}) };
+};
+
+/** Mounts the workflow widget so the workflow source resolves as available. */
+const withWorkflowWidgetMounted = (state: WorkbenchState): WorkbenchState => ({
+ ...state,
+ projects: state.projects.map((project) => ({
+ ...project,
+ widgetRegions: {
+ ...project.widgetRegions,
+ center: { ...project.widgetRegions.center, activeInstanceId: 'workflow', instanceIds: ['workflow'] },
+ },
+ })),
+});
+
+const submitWorkflow = (libraryWorkflowId?: string) => {
+ let state = withWorkflowWidgetMounted(createInitialWorkbenchState());
+
+ state = workbenchReducer(state, {
+ document: buildReadyGraph(libraryWorkflowId),
+ label: 'Load workflow',
+ type: 'replaceProjectGraph',
+ });
+ state = workbenchReducer(state, {
+ backendSupportsCancellation: true,
+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: true },
+ type: 'submitResolvedInvocationSnapshot',
+ });
+
+ const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);
+
+ return project?.queue.items[0];
+};
+
+describe('library binding on the compiled workflow submission', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('stamps the bound library record onto the run it submits', () => {
+ expect(submitWorkflow('library-workflow-1')?.snapshot.backendSubmission).toMatchObject({
+ kind: 'workflow',
+ libraryWorkflowId: 'library-workflow-1',
+ });
+ });
+
+ // An ad-hoc workflow belongs to no library record, so a completed run of it
+ // must have nothing to write back to.
+ it('leaves an unbound workflow run unstamped', () => {
+ expect(submitWorkflow()?.snapshot.backendSubmission).not.toHaveProperty('libraryWorkflowId');
+ });
+});