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
fix(webv2): show a finished video in the preview when its run completes
Lincoln Steinacedb1ec46c9
diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex a875e9d21d..038b4407c1 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -9,6 +9,7 @@ export type {GalleryOrderDir,GalleryView,GeneratedImageContract,+ GeneratedVideoContract,} from './core/types';export { getGalleryBoardLabel, type GalleryBoardTranslate } from './core/boardLabels';export { normalizeGalleryImage } from './core/image';@@ -18,6 +19,7 @@ export {compareGalleryItems,formatGalleryVideoDuration,galleryImageItemToGalleryImage,+ generatedVideoToGalleryItem,isGalleryImageItem,legacyGeneratedImageToGalleryItem,parseGalleryItemKey,diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.tsindex 07d66c6538..6f827becce 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/items.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.ts@@ -1,6 +1,6 @@import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';-import type { GalleryImage, GalleryOrderDir, GeneratedImageContract } from './types';+import type { GalleryImage, GalleryOrderDir, GeneratedImageContract, GeneratedVideoContract } from './types';export type GalleryItemKind = 'image' | 'video';@@ -132,6 +132,23 @@ export const legacyGeneratedImageToGalleryItem = (image: LegacyGalleryImage): Gawidth: image.width,});+export const generatedVideoToGalleryItem = (video: GeneratedVideoContract): GalleryVideoItem => ({+ boardId: video.boardId ?? 'none',+ category: video.category,+ createdAt: video.createdAt ?? video.queuedAt,+ durationSeconds: video.durationSeconds,+ ...(video.fps === undefined ? {} : { fps: video.fps }),+ fullUrl: video.videoUrl,+ height: video.height,+ isIntermediate: video.isIntermediate,+ kind: 'video',+ ...(video.mediaOrigin === undefined ? {} : { mediaOrigin: video.mediaOrigin }),+ name: video.videoName,+ starred: false,+ thumbnailUrl: video.thumbnailUrl,+ width: video.width,+});+export const galleryImageItemToGalleryImage = (item: GalleryImageItem): GalleryImage => ({boardId: item.boardId,createdAt: item.createdAt,diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.tsindex 2614f5aea1..94732a0916 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/types.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts@@ -13,6 +13,26 @@ export interface GeneratedImageContract {width: number;}+/** A video a local run produced, as routed back from the queue. */+export interface GeneratedVideoContract {+ /** Board the backend holds the video on; unset when uncategorized. */+ boardId?: string;+ category: GalleryImage['imageCategory'];+ /** Backend creation timestamp, when known. */+ createdAt?: string;+ durationSeconds: number;+ fps?: number;+ height: number;+ isIntermediate: boolean;+ mediaOrigin?: string;+ queuedAt: string;+ sourceQueueItemId: string;+ thumbnailUrl: string;+ videoName: string;+ videoUrl: string;+ width: number;+}+export type GalleryView = 'images' | 'assets';export type GalleryOrderDir = 'ASC' | 'DESC';diff --git a/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts b/invokeai/frontend/webv2/src/features/queue/core/historyTypes.tsindex a3157c14e2..27c801a045 100644--- a/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/historyTypes.ts@@ -37,6 +37,8 @@ export interface QueueItem {backendBatchId?: string;error?: string;resultImages?: QueueResultImage[];+ /** Videos already routed to the Gallery; a repeat routing pass must not reselect them. */+ resultVideoNames?: string[];}export interface QueueState {diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.tsindex d45c7517e0..8e9d9eb105 100644--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts@@ -142,6 +142,25 @@ export interface QueueResultImage {width: number;}+export interface QueueResultVideo {+ /** Board the video is on when read (after any destination attach); unset when uncategorized. */+ boardId?: string;+ category: 'general' | 'control' | 'mask' | 'user' | 'other';+ /** Backend creation timestamp; `queuedAt` is the submission instant. */+ createdAt?: string;+ durationSeconds: number;+ fps?: number;+ height: number;+ isIntermediate: boolean;+ mediaOrigin?: string;+ queuedAt: string;+ sourceQueueItemId: string;+ thumbnailUrl: string;+ videoName: string;+ videoUrl: string;+ width: number;+}+export type QueueItemStatus = 'pending' | 'in_progress' | 'waiting' | 'completed' | 'failed' | 'canceled';export type TerminalQueueItemStatus = Extract<QueueItemStatus, 'completed' | 'failed' | 'canceled'>;export type QueueConnectionStatus = 'connecting' | 'connected' | 'disconnected';@@ -306,6 +325,8 @@ export interface QueueBackendPort extends QueueFeatureCommands {): Promise<QueueResultImage[]>;/** Names of the videos a completed backend item produced (no DTO hydration needed). */getResultVideoNames(itemId: number, options?: QueueResultVideoOptions): Promise<string[]>;+ /** Hydrate result videos for display; videos that are gone or unreadable are omitted. */+ getResultVideos(videoNames: string[], sourceQueueItemId: string, queuedAt: string): Promise<QueueResultVideo[]>;listItems(): Promise<QueueBackendItem[]>;readCurrent(scope?: QueueQueryScope, signal?: AbortSignal): Promise<QueueItemReadModel | null>;readItemIds(order: 'asc' | 'desc', scope?: QueueQueryScope, signal?: AbortSignal): Promise<QueueItemIdsReadModel>;diff --git a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.tsindex 88fd9645fc..6e15650079 100644--- a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts@@ -30,6 +30,7 @@ import {getQueueEnqueueReceipt,getResultImages,getResultVideoNames,+ getResultVideos,} from './submissionApi';/** Production adapter for the queue backend port. */@@ -53,6 +54,7 @@ export const queueBackend: QueueBackendPort = {getItem: async (itemId) => mapQueueBackendItemDTO(await getQueueItem(itemId)),getResultImages,getResultVideoNames,+ getResultVideos,listItems: async () => (await listAllQueueItems()).map(mapQueueBackendItemDTO),on: socketHub.on,onConnectionChange: socketHub.onConnectionChange,diff --git a/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts b/invokeai/frontend/webv2/src/features/queue/data/queries.test.tsindex 0ea4822466..c969b617cf 100644--- a/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts@@ -20,6 +20,7 @@ const createBackend = (): QueueBackendPort => ({getItem: vi.fn(),getResultImages: vi.fn(),getResultVideoNames: vi.fn().mockResolvedValue([]),+ getResultVideos: vi.fn().mockResolvedValue([]),listItems: vi.fn(),on: vi.fn(),onConnectionChange: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverTypes.ts b/invokeai/frontend/webv2/src/features/queue/data/serverTypes.tsindex 4b2230a476..c41d6e614b 100644--- a/invokeai/frontend/webv2/src/features/queue/data/serverTypes.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/serverTypes.ts@@ -1,4 +1,4 @@-import type { QueueItemStatus } from '@features/queue/core/types';+import type { QueueItemStatus, QueueResultVideo } from '@features/queue/core/types';/** Private HTTP wire contracts. These names and fields mirror backend JSON. */export interface QueueNodeFieldValueDTO {@@ -45,6 +45,21 @@ export interface QueueImageDTO {width: number;}+export interface QueueVideoDTO {+ board_id?: string | null;+ created_at: string;+ duration: number;+ fps?: number | null;+ height: number;+ is_intermediate: boolean;+ media_origin?: string | null;+ video_category: QueueResultVideo['category'];+ thumbnail_url: string;+ video_name: string;+ video_url: string;+ width: number;+}+export interface QueueStatusCountsDTO {batch_id?: string | null;canceled: number;diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.tsindex 095b8408f0..22a081e8a4 100644--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts@@ -4,6 +4,7 @@ import type {QueueEnqueueWorkflowRequest,QueueResultImage,QueueResultImageOptions,+ QueueResultVideo,QueueResultVideoOptions,} from '@features/queue/core/types';@@ -19,7 +20,7 @@ import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';import { absolutizeApiUrl, ApiError, apiFetch, apiFetchJson } from '@platform/transport/http';-import type { QueueImageDTO, QueueServerItemDTO } from './serverTypes';+import type { QueueImageDTO, QueueServerItemDTO, QueueVideoDTO } from './serverTypes';import { buildQueueItemOrigin } from './events';import { getQueueItem } from './serverApi';@@ -279,3 +280,58 @@ export const getResultVideoNames = async (itemId: number, options?: QueueResultVassertAccountScopeCurrent(owner);return videoNames.filter((_, index) => !intermediateFlags[index]);};++const getResultVideo = async (+ videoName: string,+ queuedAt: string,+ sourceQueueItemId: string,+ signal: AbortSignal+): Promise<QueueResultVideo | null> => {+ try {+ const video = await apiFetchJson<QueueVideoDTO>(`/api/v1/videos/i/${encodeURIComponent(videoName)}`, { signal });++ if (!Number.isFinite(video.duration)) {+ return null;+ }++ return {+ ...(video.board_id ? { boardId: video.board_id } : {}),+ category: video.video_category,+ createdAt: normalizeServerTimestamp(video.created_at),+ durationSeconds: video.duration,+ ...(typeof video.fps === 'number' ? { fps: video.fps } : {}),+ height: video.height,+ isIntermediate: video.is_intermediate,+ ...(video.media_origin ? { mediaOrigin: video.media_origin } : {}),+ queuedAt,+ sourceQueueItemId,+ thumbnailUrl: absolutizeApiUrl(video.thumbnail_url),+ videoName: video.video_name,+ videoUrl: absolutizeApiUrl(video.video_url),+ width: video.width,+ };+ } catch (error) {+ if (signal.aborted) {+ throw error;+ }+ // Display hydration is best-effort: a video that is gone or unreadable is simply not selected.+ return null;+ }+};++export const getResultVideos = async (+ videoNames: string[],+ sourceQueueItemId: string,+ queuedAt: string+): Promise<QueueResultVideo[]> => {+ const owner = captureAccountScope();+ const videos = await mapWithConcurrency(+ videoNames,+ 8,+ (videoName) => getResultVideo(videoName, queuedAt, sourceQueueItemId, owner.signal),+ { signal: owner.signal }+ );++ assertAccountScopeCurrent(owner);+ return videos.filter((video): video is QueueResultVideo => video !== null);+};diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.tsindex 7b0bfe3b85..feb794bc29 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,+ QueueResultVideo,+} from '@features/queue/core/types';import type { BackendConnectionStatus } from '@platform/transport/types';import { buildQueueItemOrigin } from '@features/queue/data/events';@@ -57,6 +62,7 @@ const createTestBackend = (overrides: Partial<QueueBackendPort> = {}): QueueBackgetItem: vi.fn(),getResultImages: vi.fn().mockResolvedValue([]),getResultVideoNames: vi.fn().mockResolvedValue([]),+ getResultVideos: vi.fn().mockResolvedValue([]),listItems: vi.fn().mockResolvedValue([]),on: vi.fn(() => vi.fn()),onConnectionChange: vi.fn((listener) => {@@ -303,6 +309,7 @@ describe('queue runtime', () => {getItem: vi.fn(),getResultImages: vi.fn(),getResultVideoNames: vi.fn().mockResolvedValue([]),+ getResultVideos: vi.fn().mockResolvedValue([]),listItems,on: vi.fn(() => vi.fn()),onConnectionChange: vi.fn((listener) => {@@ -2015,6 +2022,7 @@ describe('queue runtime', () => {describe('queue runtime video board routing', () => {const createHarness = (options: {getResultVideoNames: QueueBackendPort['getResultVideoNames'];+ getResultVideos?: QueueBackendPort['getResultVideos'];galleryBoardId?: string | null;getResultImages?: QueueBackendPort['getResultImages'];/** Nodes of the compiled submission graph — media values here mark run INPUTS. */@@ -2043,6 +2051,11 @@ describe('queue runtime video board routing', () => {getItem: vi.fn(),getResultImages: options.getResultImages ?? vi.fn().mockResolvedValue([]),getResultVideoNames: options.getResultVideoNames,+ getResultVideos:+ options.getResultVideos ??+ vi.fn((videoNames: string[], sourceQueueItemId: string, queuedAt: string) =>+ Promise.resolve(videoNames.map((videoName) => resultVideo(videoName, sourceQueueItemId, queuedAt)))+ ),// Reconcile an already-completed backend run to exercise both settlement paths without sockets.listItems: vi.fn().mockResolvedValue([{@@ -2116,17 +2129,37 @@ describe('queue runtime video board routing', () => {},});- return { commands, destinations, runtime };+ return { backend, commands, destinations, runtime };};+ const resultVideo = (videoName: string, sourceQueueItemId: string, queuedAt: string): QueueResultVideo => ({+ category: 'general',+ durationSeconds: 5,+ height: 512,+ isIntermediate: false,+ queuedAt,+ sourceQueueItemId,+ thumbnailUrl: `http://test/v/${videoName}/thumbnail`,+ videoName,+ videoUrl: `http://test/v/${videoName}`,+ width: 512,+ });+it('lands result videos on the enqueue-time board, excluding intermediates', async () => {const getResultVideoNames = vi.fn().mockResolvedValue(['clip-1.mp4']);- const { destinations, runtime } = createHarness({ getResultVideoNames });+ const { commands, destinations, runtime } = createHarness({ getResultVideoNames });runtime.start();await vi.waitFor(() => {expect(destinations.addVideosToGalleryBoard).toHaveBeenCalledWith('board-1', ['clip-1.mp4']);+ // Both passes queue follow-up reads while earlier ones drain; none may be stranded.+ expect(commands.routePartialResults).toHaveBeenCalledWith(+ expect.objectContaining({ videos: [expect.objectContaining({ videoName: 'clip-1.mp4' })] })+ );+ expect(commands.routeResults).toHaveBeenCalledWith(+ expect.objectContaining({ videos: [expect.objectContaining({ videoName: 'clip-1.mp4' })] })+ );});// filterIntermediateResults on the snapshot maps to the video-side intermediate filter.expect(getResultVideoNames).toHaveBeenCalledWith(77, expect.objectContaining({ excludeIntermediate: true }));@@ -2152,19 +2185,37 @@ describe('queue runtime video board routing', () => {runtime.dispose();});- it('skips the board attach entirely when no board was active at enqueue', async () => {+ it("routes an uncategorized run's videos for display without a board attach", async () => {const getResultVideoNames = vi.fn().mockResolvedValue(['clip-1.mp4']);const { commands, destinations, runtime } = createHarness({ galleryBoardId: null, getResultVideoNames });+ const routedClip = expect.objectContaining({ videos: [expect.objectContaining({ videoName: 'clip-1.mp4' })] });runtime.start();- // Wait for full settlement first so the negative assertions below are meaningful.await vi.waitFor(() => {- expect(commands.routeResults).toHaveBeenCalled();+ expect(commands.routePartialResults).toHaveBeenCalledWith(routedClip);+ expect(commands.routeResults).toHaveBeenCalledWith(routedClip);});expect(destinations.addImagesToGalleryBoard).not.toHaveBeenCalled();expect(destinations.addVideosToGalleryBoard).not.toHaveBeenCalled();- expect(getResultVideoNames).not.toHaveBeenCalled();++ runtime.dispose();+ });++ it('still shows a finished video when its board attach fails', async () => {+ const { commands, destinations, runtime } = createHarness({+ getResultVideoNames: vi.fn().mockResolvedValue(['clip-1.mp4']),+ });+ destinations.addVideosToGalleryBoard.mockRejectedValue(new Error('attach failed'));++ runtime.start();++ await vi.waitFor(() => {+ expect(commands.routePartialResults).toHaveBeenCalledWith(+ expect.objectContaining({ videos: [expect.objectContaining({ videoName: 'clip-1.mp4' })] })+ );+ });+ expect(commands.recordError).toHaveBeenCalledWith(expect.objectContaining({ message: 'attach failed' }));runtime.dispose();});diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.tsindex d0c7229e45..4e5af420a6 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,+ QueueResultVideo,QueueRunOrigin,} from '@features/queue/core/types';import type { BackendConnectionStatus } from '@platform/transport/types';@@ -91,8 +92,14 @@ export interface QueueHistoryCommands {images: QueueResultImage[];projectId: string;queueItemId: string;+ videos: QueueResultVideo[];+ }): void;+ routeResults(payload: {+ images: QueueResultImage[];+ projectId: string;+ queueItemId: string;+ videos: QueueResultVideo[];}): void;- routeResults(payload: { images: QueueResultImage[]; projectId: string; queueItemId: string }): void;setConnectionStatus(payload: { error?: string; status: BackendConnectionStatus }): void;setStatus(payload: {error?: string;@@ -817,6 +824,10 @@ export const createQueueRuntime = ({});resultReadFlush = flush.finally(() => {resultReadFlush = undefined;+ // A read queued after the loop drained but before this settled found the flush still set and did not start one.+ if (pendingResultReads.length > 0) {+ scheduleResultReadFlush();+ }});};const runResultRead = <T>(operation: () => Promise<T>): Promise<T> =>@@ -848,14 +859,14 @@ export const createQueueRuntime = ({};/**- * Attach generated videos to the destination board; repeat attachment is idempotent. Categorization failures are- * recorded but never turn successful generation into failure.+ * Attach generated videos to the destination board (repeat attachment is idempotent) and hydrate them for display.+ * Failures are recorded but never turn successful generation into failure.*/- const addResultVideosToDestination = async (+ const deliverResultVideos = async (projectId: string,queueItem: QueueItem,backendItemIds: number[]- ): Promise<void> => {+ ): Promise<QueueResultVideo[]> => {// Skip known cancelled backend items. Resumed cancellation records can be incomplete, so remaining attachments// are best-effort.const deliverableItemIds = backendItemIds.filter(@@ -863,41 +874,63 @@ export const createQueueRuntime = ({);if (!isActive() || queueItem.snapshot.destination !== 'gallery' || deliverableItemIds.length === 0) {- return;+ return [];}const boardId = queueItem.snapshot.galleryBoardId;-- if (!boardId || boardId === 'none') {- return;- }+ const recordError = (error: unknown): void => {+ if (isActive()) {+ commands.recordError({+ area: 'queue-results',+ message: toErrorMessage(error),+ namespace: 'queue',+ projectId,+ });+ }+ };+ let namesPerItem: string[][];try {const imageOptions = getQueueItemResultImageOptions(queueItem);const options = queueItem.snapshot.filterIntermediateResults? { ...imageOptions, excludeIntermediate: true }: imageOptions;- const namesPerItem = await mapWithConcurrency(deliverableItemIds, QUEUE_RUNTIME_CONCURRENCY, (backendItemId) =>+ namesPerItem = await mapWithConcurrency(deliverableItemIds, QUEUE_RUNTIME_CONCURRENCY, (backendItemId) =>runResultRead(() => backend.getResultVideoNames(backendItemId, options)));- // Exclude video primitives' echoed input clips from generated results.- const inputMedia = collectGraphInputMediaNames(getQueueItemCompiledGraph(queueItem));- const videoNames = [...new Set(namesPerItem.flat())].filter((name) => !inputMedia.videoNames.has(name));+ } catch (error) {+ recordError(error);+ return [];+ }- if (videoNames.length === 0 || !isActive()) {- return;+ // Exclude video primitives' echoed input clips from generated results.+ const inputMedia = collectGraphInputMediaNames(getQueueItemCompiledGraph(queueItem));+ const videoNames = [...new Set(namesPerItem.flat())].filter((name) => !inputMedia.videoNames.has(name));++ if (videoNames.length === 0 || !isActive()) {+ return [];+ }++ if (boardId && boardId !== 'none') {+ try {+ await destinations.addVideosToGalleryBoard(boardId, videoNames);+ } catch (error) {+ // A board-attach failure must not keep a finished video out of view.+ recordError(error);}+ }- await destinations.addVideosToGalleryBoard(boardId, videoNames);+ if (!isActive()) {+ return [];+ }++ try {+ return await runResultRead(() =>+ backend.getResultVideos(videoNames, queueItem.id, queueItem.snapshot.submittedAt)+ );} catch (error) {- if (isActive()) {- commands.recordError({- area: 'queue-results',- message: toErrorMessage(error),- namespace: 'queue',- projectId,- });- }+ recordError(error);+ return [];}};@@ -950,13 +983,13 @@ export const createQueueRuntime = ({const images = await deliverVisibleImages(queueItem, allImages);// The run-end video pass retries live routing and covers earlier-session completions; it must never throw.- await addResultVideosToDestination(projectId, queueItem, backendItemIds);+ const videos = await deliverResultVideos(projectId, queueItem, backendItemIds);if (!isAttemptCurrent(attempt)) {return;}- commands.routeResults({ images, projectId, queueItemId: queueItem.id });+ commands.routeResults({ images, projectId, queueItemId: queueItem.id, videos });if (queueItem.snapshot.destination === 'gallery') {commands.refreshBackendData();}@@ -1009,7 +1042,7 @@ export const createQueueRuntime = ({const visibleImages = await deliverVisibleImages(queueItem, images);// Never throws — a board-attach hiccup must not block routePartialResults below.- await addResultVideosToDestination(projectId, queueItem, [backendItemId]);+ const videos = await deliverResultVideos(projectId, queueItem, [backendItemId]);if (!isAttemptCurrent(attempt)) {return;@@ -1026,6 +1059,7 @@ export const createQueueRuntime = ({images: visibleImages,projectId,queueItemId: queueItem.id,+ videos,});if (queueItem.snapshot.destination === 'gallery') {commands.refreshBackendData();@@ -1876,7 +1910,10 @@ export const createQueueRuntime = ({coordinator.dispose();pendingResultRoutes.clear();await resultRoutingFlush?.catch(() => undefined);- await resultReadFlush?.catch(() => undefined);+ // A settling flush may start another for reads queued while it drained.+ for (let flush = resultReadFlush; flush; flush = resultReadFlush) {+ await flush.catch(() => undefined);+ }await Promise.all([...cancellationOperations.values(), ...submissionOperations.values(), ...lockRequests.values()].map((operation) => operation.catch(() => undefined)diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.tsindex 5a051ed315..515e1c3e59 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts@@ -128,6 +128,10 @@ export const normalizeRestoredQueueItem = (value: unknown): WorkbenchQueueItem |cancellable: value.cancellable,...(completedBackendItemIds === undefined ? {} : { completedBackendItemIds: [...completedBackendItemIds] }),id: value.id,+ // Keeps a restored run from reselecting videos it already showed before the reload.+ ...(Array.isArray(value.resultVideoNames) && value.resultVideoNames.every((name) => typeof name === 'string')+ ? { resultVideoNames: [...value.resultVideoNames] }+ : {}),snapshot: {backendSubmission: snapshot.backendSubmission as WorkbenchQueueItem['snapshot']['backendSubmission'],canvas: {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 520b4a6756..7f262b3efd 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1,4 +1,5 @@import type { GalleryImageItem, GalleryVideoItem, GeneratedImageContract } from '@features/gallery';+import type { GeneratedVideoContract } from '@features/gallery/contracts';import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/api';@@ -273,6 +274,20 @@ const createImage = (imageName: string, sourceQueueItemId: string): GeneratedImawidth: 512,});+const createVideo = (videoName: string, sourceQueueItemId: string, boardId?: string): GeneratedVideoContract => ({+ ...(boardId === undefined ? {} : { boardId }),+ category: 'general',+ durationSeconds: 5,+ height: 768,+ isIntermediate: false,+ queuedAt: '2026-06-09T00:00:00.000Z',+ sourceQueueItemId,+ thumbnailUrl: `/api/v1/videos/i/${videoName}/thumbnail`,+ videoName,+ videoUrl: `/api/v1/videos/i/${videoName}/full`,+ width: 512,+});+const createGalleryImageItem = (name: string, boardId = 'none'): GalleryImageItem => ({boardId,category: 'general',@@ -4794,6 +4809,136 @@ describe('workbenchReducer Phase 5 generation flow', () => {}});+ it('selects a finished Gallery video once, so a later result keeps the preview', () => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);+ const videoItem = getActiveProject(state).queue.items[0];+ const projectId = getActiveProject(state).id;++ state = workbenchReducer(state, {+ backendItemId: 1,+ images: [],+ projectId,+ queueItemId: videoItem.id,+ type: 'routeQueueItemPartialResults',+ videos: [createVideo('clip.mp4', videoItem.id, 'board-1')],+ });+ const selected = getProjectWidgetValues(getActiveProject(state), 'gallery');+ expect(selected.selectedImageName).toBe('video:clip.mp4');+ expect(selected.selectedImage).toMatchObject({+ boardId: 'board-1',+ durationSeconds: 5,+ fullUrl: '/api/v1/videos/i/clip.mp4/full',+ kind: 'video',+ });++ state = submitGenerate(state);+ const imageItem = getActiveProject(state).queue.items[0];+ state = workbenchReducer(state, {+ images: [createImage('later.png', imageItem.id)],+ projectId,+ queueItemId: imageItem.id,+ type: 'routeQueueItemResults',+ });+ // The video run's run-end pass re-reports the clip; it must not take the preview back.+ state = workbenchReducer(state, {+ images: [],+ projectId,+ queueItemId: videoItem.id,+ type: 'routeQueueItemResults',+ videos: [createVideo('clip.mp4', videoItem.id)],+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:later.png');+ });++ it('selects only videos from runs submitted after a manual selection', () => {+ vi.useFakeTimers({ now: new Date('2026-06-10T00:00:00.000Z') });++ try {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);+ const earlierItem = getActiveProject(state).queue.items[0];++ vi.setSystemTime(new Date('2026-06-10T00:00:01.000Z'));+ state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });+ vi.setSystemTime(new Date('2026-06-10T00:00:02.000Z'));+ state = submitGenerate(state);+ const laterItem = getActiveProject(state).queue.items[0];+ const projectId = getActiveProject(state).id;++ state = workbenchReducer(state, {+ images: [],+ projectId,+ queueItemId: earlierItem.id,+ type: 'routeQueueItemResults',+ videos: [createVideo('earlier.mp4', earlierItem.id)],+ });+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');++ state = workbenchReducer(state, {+ images: [],+ projectId,+ queueItemId: laterItem.id,+ type: 'routeQueueItemResults',+ videos: [createVideo('later.mp4', laterItem.id)],+ });+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('video:later.mp4');+ } finally {+ vi.useRealTimers();+ }+ });++ it("selects a run's video over images routed with it", () => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = workbenchReducer(state, {+ settings: { showProgressImagesInViewer: false },+ type: 'setActiveProjectSettings',+ });+ state = submitGenerate(state);+ const queueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('first-frame.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ videos: [createVideo('clip.mp4', queueItem.id)],+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('video:clip.mp4');+ });++ it('does not reselect a video a restored run showed before the reload', () => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ const liveItem = getActiveProject(submitGenerate(state)).queue.items[0]!;+ const projectId = getActiveProject(state).id;+ state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });+ state = workbenchReducer(state, {+ settings: { showProgressImagesInViewer: true },+ type: 'setActiveProjectSettings',+ });+ state = workbenchReducer(state, {+ items: [{ ...liveItem, id: 'restored-item', resultVideoNames: ['clip.mp4'], status: 'running' }],+ projectId,+ type: 'restoreQueueItemsFromJournal',+ });++ state = workbenchReducer(state, {+ images: [],+ projectId,+ queueItemId: 'restored-item',+ type: 'routeQueueItemResults',+ videos: [createVideo('clip.mp4', 'restored-item')],+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');+ });+it('leaves an explicit live-follow opt-out alone when submitting', () => {let state = primeGenerate();state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex e1f09b6b73..9e21393332 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -72,6 +72,8 @@ import {type GalleryBoardDeletionResult,type GallerySettings,type GeneratedImageContract,+ type GeneratedVideoContract,+ generatedVideoToGalleryItem,} from '@features/gallery/contracts';import { planSeedSubmission } from '@platform/core/seed';import { describeError } from '@platform/logging/normalize';@@ -376,6 +378,7 @@ type WorkbenchReducerAction =queueItemId: string;backendItemId: number;images: GeneratedImageContract[];+ videos?: GeneratedVideoContract[];}| { type: 'markQueueItemBackendCancelled'; projectId: string; queueItemId: string; backendItemId: number }| { type: 'setQueueItemCancellationPending'; projectId: string; queueItemId: string; pending: boolean }@@ -385,7 +388,13 @@ type WorkbenchReducerAction =queueItemId: string;state: NonNullable<QueueItem['localRecoveryState']>;}- | { type: 'routeQueueItemResults'; projectId: string; queueItemId: string; images: GeneratedImageContract[] }+ | {+ type: 'routeQueueItemResults';+ projectId: string;+ queueItemId: string;+ images: GeneratedImageContract[];+ videos?: GeneratedVideoContract[];+ }| { type: 'restoreQueueItemsFromJournal'; projectId: string; items: unknown[] }| { type: 'appendCanvasStagingCandidate'; projectId: string; candidate: CanvasStagingCandidateContract }| {@@ -2871,14 +2880,14 @@ const shouldResumeLiveFollowOnSubmit = (project: Project): boolean =>!project.settings.showProgressImagesInViewer && getLiveFollowPausedAt(project) !== null;/** Only generations submitted after the deliberate selection may replace it. */-const isSubmittedAfterLiveFollowPause = (project: Project, image: GalleryImage | undefined): boolean => {+const isSubmittedAfterLiveFollowPause = (project: Project, sourceQueueItemId: string): boolean => {const pausedAt = getLiveFollowPausedAt(project);- if (pausedAt === null || !image) {+ if (pausedAt === null) {return true;}- const submittedAt = project.queue.items.find((item) => item.id === image.sourceQueueItemId)?.snapshot.submittedAt;+ const submittedAt = project.queue.items.find((item) => item.id === sourceQueueItemId)?.snapshot.submittedAt;return submittedAt !== undefined && submittedAt > pausedAt;};@@ -2944,6 +2953,40 @@ const getQueueItemStatusAfterBackendCancellation = (return completedBackendItemIds.size > 0 || (item.resultImages?.length ?? 0) > 0 ? 'completed' : 'cancelled';};+/** Whether a newly routed result may take the Gallery selection (and so the settled Preview). */+const shouldSelectGalleryResult = (+ project: Project,+ galleryValues: Record<string, unknown>,+ sourceQueueItemId: string+): boolean =>+ typeof galleryValues.selectedImageName !== 'string' ||+ (project.settings.showProgressImagesInViewer && isSubmittedAfterLiveFollowPause(project, sourceQueueItemId));++const getGalleryResultSelectionValues = (+ galleryValues: Record<string, unknown>,+ item: GalleryItem+): Record<string, unknown> => {+ const itemKey = toGalleryItemKey(item);+ const gallerySettings = getGallerySettings(galleryValues);++ return {+ ...(item.kind === 'video' ? { compareImage: null } : {}),+ selectedImage: item,+ selectedImageName: itemKey,+ selectedImageNames: [itemKey],+ selectedImagePage: 0,+ selectedImageQuery: {+ boardId: item.boardId,+ galleryView: item.category === 'general' ? 'images' : 'assets',+ imageOrderDir: gallerySettings.imageOrderDir,+ page: 0,+ paginationMode: gallerySettings.paginationMode,+ searchTerm: '',+ starredOnly: false,+ },+ };+};+const updateGalleryWithResultImages = (project: Project, images: GeneratedImageContract[]): Project => {if (images.length === 0) {return project;@@ -2959,35 +3002,51 @@ const updateGalleryWithResultImages = (project: Project, images: GeneratedImageCconst newImages: GalleryImage[] = incomingImages.filter((image) => !previousImageNames.has(image.imageName)).map((image) => normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId)));- const shouldSelectIncomingImage =- typeof galleryValues.selectedImageName !== 'string' ||- (project.settings.showProgressImagesInViewer && isSubmittedAfterLiveFollowPause(project, newImages[0]));- const nextSelectedImage = shouldSelectIncomingImage ? newImages[0] : undefined;- const nextSelectedItem = nextSelectedImage ? legacyGeneratedImageToGalleryItem(nextSelectedImage) : undefined;- const nextSelectedItemKey = nextSelectedItem ? toGalleryItemKey(nextSelectedItem) : undefined;- const gallerySettings = getGallerySettings(galleryValues);+ const nextSelectedImage =+ newImages[0] && shouldSelectGalleryResult(project, galleryValues, newImages[0].sourceQueueItemId)+ ? newImages[0]+ : undefined;return updateProjectWidgetValues(project, 'gallery', () => ({...galleryValues,recentImages: getBoundedRecentImages([...newImages, ...previousImages]),- selectedImage: nextSelectedItem ?? galleryValues.selectedImage,- selectedImageName: nextSelectedItemKey ?? galleryValues.selectedImageName,- selectedImageNames: nextSelectedItemKey- ? [nextSelectedItemKey]- : getPersistedSelectedGalleryItemKeys(galleryValues),...(nextSelectedImage- ? {- selectedImagePage: 0,- selectedImageQuery: {- boardId: nextSelectedImage.boardId,- galleryView: nextSelectedImage.imageCategory === 'general' ? 'images' : 'assets',- imageOrderDir: gallerySettings.imageOrderDir,- page: 0,- paginationMode: gallerySettings.paginationMode,- searchTerm: '',- starredOnly: false,- },- }- : {}),+ ? getGalleryResultSelectionValues(galleryValues, legacyGeneratedImageToGalleryItem(nextSelectedImage))+ : { selectedImageNames: getPersistedSelectedGalleryItemKeys(galleryValues) }),+ }));+};++/**+ * Videos are not kept in recent images, so the queue item records which ones were routed: only the newest video not+ * routed before may take the selection, or a repeat pass would take it back from a later run.+ */+const routeGalleryResultVideos = (+ project: Project,+ queueItemId: string,+ videos: readonly GeneratedVideoContract[],+ /** The project before this routing pass selected any image, so a run's video outranks its own images. */+ policyProject: Project = project+): Project => {+ const routedNames = new Set(project.queue.items.find((item) => item.id === queueItemId)?.resultVideoNames);+ const newVideos = videos.filter((video) => !routedNames.has(video.videoName));+ const video = newVideos.at(-1);++ if (!video) {+ return project;+ }++ const nextProject = updateQueueItem(project, queueItemId, (item) => ({+ ...item,+ resultVideoNames: [...(item.resultVideoNames ?? []), ...newVideos.map((newVideo) => newVideo.videoName)],+ }));+ if (!shouldSelectGalleryResult(policyProject, getWidgetValues(policyProject, 'gallery'), video.sourceQueueItemId)) {+ return nextProject;+ }++ const galleryValues = getWidgetValues(nextProject, 'gallery');++ return updateProjectWidgetValues(nextProject, 'gallery', () => ({+ ...galleryValues,+ ...getGalleryResultSelectionValues(galleryValues, generatedVideoToGalleryItem(video)),}));};@@ -2995,7 +3054,8 @@ const routeQueueItemPartialResults = (project: Project,queueItemId: string,backendItemId: number,- images: GeneratedImageContract[]+ images: GeneratedImageContract[],+ videos: readonly GeneratedVideoContract[] = []): Project => {const queueItem = project.queue.items.find((item) => item.id === queueItemId);const destination = queueItem?.snapshot.destination ?? project.invocation.destination;@@ -3009,7 +3069,13 @@ const routeQueueItemPartialResults = (}));if (destination === 'gallery') {- return updateGalleryWithResultImages(nextProject, images);+ // A run's video is its primary output; it takes the selection over any images routed alongside it.+ return routeGalleryResultVideos(+ updateGalleryWithResultImages(nextProject, images),+ queueItemId,+ videos,+ nextProject+ );}if (images.length === 0) {@@ -3067,7 +3133,8 @@ const recordWorkflowRunPreview = (const routeQueueItemResults = (sourceProject: Project,queueItemId: string,- images: GeneratedImageContract[]+ images: GeneratedImageContract[],+ videos: readonly GeneratedVideoContract[] = []): Project => {const queueItem = sourceProject.queue.items.find((item) => item.id === queueItemId);const project = recordWorkflowRunPreview(sourceProject, queueItem, images);@@ -3083,7 +3150,13 @@ const routeQueueItemResults = (}));if (destination === 'gallery') {- return updateGalleryWithResultImages(nextProject, images);+ // A run's video is its primary output; it takes the selection over any images routed alongside it.+ return routeGalleryResultVideos(+ updateGalleryWithResultImages(nextProject, images),+ queueItemId,+ videos,+ nextProject+ );}// Stage results only into the submitted documentRevision; wholesale canvas swaps invalidate staging while@@ -4381,7 +4454,7 @@ export const __workbenchReducerInternal = (}return updateProjectById(state, action.projectId, (project) =>- routeQueueItemPartialResults(project, action.queueItemId, action.backendItemId, action.images)+ routeQueueItemPartialResults(project, action.queueItemId, action.backendItemId, action.images, action.videos));}case 'markQueueItemBackendCancelled': {@@ -4434,7 +4507,7 @@ export const __workbenchReducerInternal = (}const nextState = updateProjectById(state, action.projectId, (project) =>- routeQueueItemResults(project, action.queueItemId, action.images)+ routeQueueItemResults(project, action.queueItemId, action.images, action.videos));if (action.images.length === 0) {