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): adversarial-review findings for video board routing
Lincoln Stein0694f70f1481
diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsxindex 135d84f637..02d3d729b9 100644--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx@@ -32,12 +32,20 @@ export const QueueRuntimeAdapter = () => {const { galleryItemOrganization } = await import('@features/gallery');assertAccountScopeCurrent(owner);- await galleryItemOrganization.moveToBoard(+ 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,diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.tsindex 4ffeb86f9a..df693acde3 100644--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts@@ -221,6 +221,11 @@ export interface QueueResultImageOptions {resultNodeIds?: readonly string[];}+export interface QueueResultVideoOptions extends QueueResultImageOptions {+ /** Drop videos whose DTO reports is_intermediate — the video analogue of filterIntermediateResults. */+ excludeIntermediate?: boolean;+}+/** User-facing Queue commands; transport and adapter details stay private. */export interface QueueFeatureCommands {cancelCurrentItem(): Promise<void>;@@ -249,7 +254,7 @@ export interface QueueBackendPort extends QueueFeatureCommands {options?: QueueResultImageOptions): Promise<QueueResultImage[]>;/** Names of the videos a completed backend item produced (no DTO hydration needed). */- getResultVideoNames(itemId: number, options?: QueueResultImageOptions): Promise<string[]>;+ getResultVideoNames(itemId: number, options?: QueueResultVideoOptions): Promise<string[]>;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/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.tsindex 06a8a91ae2..f985b34e71 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,+ QueueResultVideoOptions,} from '@features/queue/core/types';import { buildGeneratePromptBatchPlan, sanitizeBatchCount } from '@features/queue/core/promptBatch';@@ -203,13 +204,46 @@ const collectResultVideoNames = (queueItem: QueueServerItemDTO, options?: QueueR};/**- * The names of the videos a completed backend item produced. Videos need no DTO- * hydration here — the queue runtime only routes them onto the destination board.+ * True when the video's DTO reports it as an intermediate. Fail-open on transport+ * errors: the caller's board attach is best-effort, and a wrongly-attached+ * intermediate is invisible in gallery listings (which filter intermediates).*/-export const getResultVideoNames = async (itemId: number, options?: QueueResultImageOptions): Promise<string[]> => {+const isIntermediateVideo = async (videoName: string, signal: AbortSignal): Promise<boolean> => {+ try {+ const video = await apiFetchJson<{ is_intermediate?: unknown }>(+ `/api/v1/videos/i/${encodeURIComponent(videoName)}`,+ { signal }+ );++ return video.is_intermediate === true;+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) {+ // The video is already gone; report it intermediate so the caller drops it.+ return true;+ }+ return false;+ }+};++/**+ * The names of the videos a completed backend item produced. The queue runtime only+ * routes them onto the destination board, so DTOs are hydrated solely when+ * `excludeIntermediate` needs the `is_intermediate` flag (the video analogue of the+ * image path's filterIntermediateResults).+ */+export const getResultVideoNames = async (itemId: number, options?: QueueResultVideoOptions): Promise<string[]> => {const owner = captureAccountScope();const item = await getQueueItem(itemId, owner.signal);assertAccountScopeCurrent(owner);- return collectResultVideoNames(item, options);+ const videoNames = collectResultVideoNames(item, options);++ if (!options?.excludeIntermediate || videoNames.length === 0) {+ return videoNames;+ }++ const intermediateFlags = await Promise.all(videoNames.map((name) => isIntermediateVideo(name, owner.signal)));++ assertAccountScopeCurrent(owner);+ return videoNames.filter((_, index) => !intermediateFlags[index]);};diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.tsindex 4459a3c586..d53ad60c84 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts@@ -139,3 +139,150 @@ describe('queue runtime', () => {runtime.dispose();});});++describe('queue runtime video board routing', () => {+ const createHarness = (options: {+ getResultVideoNames: QueueBackendPort['getResultVideoNames'];+ galleryBoardId?: string | null;+ }) => {+ const queueItem = createPendingQueueItem();+ queueItem.snapshot.destination = 'gallery';+ queueItem.snapshot.galleryBoardId = options.galleryBoardId === undefined ? 'board-1' : options.galleryBoardId;+ queueItem.snapshot.filterIntermediateResults = true;+ delete (queueItem.snapshot as { resultNodeIds?: unknown }).resultNodeIds;+ 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([]),+ getResultVideoNames: options.getResultVideoNames,+ // The backend already accepted and completed this run before "reload": reconcile+ // adopts it and settles immediately, driving both settlement paths without sockets.+ 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 destinations = { addImagesToGalleryBoard: vi.fn(), addVideosToGalleryBoard: vi.fn() };+ const runtime = createQueueRuntime({+ backend,+ destinations,+ 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(),+ },+ });++ return { commands, destinations, runtime };+ };++ 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 });++ runtime.start();++ await vi.waitFor(() => {+ expect(destinations.addVideosToGalleryBoard).toHaveBeenCalledWith('board-1', ['clip-1.mp4']);+ });+ // filterIntermediateResults on the snapshot maps to the video-side intermediate filter.+ expect(getResultVideoNames).toHaveBeenCalledWith(77, expect.objectContaining({ excludeIntermediate: true }));++ runtime.dispose();+ });++ it('records a video-routing failure without failing the completed run', async () => {+ const getResultVideoNames = vi.fn().mockRejectedValue(new Error('transient 502'));+ const { commands, destinations, runtime } = createHarness({ getResultVideoNames });++ runtime.start();++ await vi.waitFor(() => {+ // The run still settles and records its results...+ expect(commands.routeResults).toHaveBeenCalled();+ // ...with the board-attach hiccup recorded, not fatal.+ expect(commands.recordError).toHaveBeenCalledWith(expect.objectContaining({ area: 'queue-results' }));+ });+ expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));+ expect(destinations.addVideosToGalleryBoard).not.toHaveBeenCalled();++ runtime.dispose();+ });++ it('skips the board attach entirely when no board was active at enqueue', async () => {+ const getResultVideoNames = vi.fn().mockResolvedValue(['clip-1.mp4']);+ const { commands, destinations, runtime } = createHarness({ galleryBoardId: null, getResultVideoNames });++ runtime.start();++ // Wait for full settlement first so the negative assertions below are meaningful.+ await vi.waitFor(() => {+ expect(commands.routeResults).toHaveBeenCalled();+ });+ expect(destinations.addImagesToGalleryBoard).not.toHaveBeenCalled();+ expect(destinations.addVideosToGalleryBoard).not.toHaveBeenCalled();+ expect(getResultVideoNames).not.toHaveBeenCalled();++ runtime.dispose();+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.tsindex 037e02d9fb..99c3f3baef 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts@@ -211,9 +211,27 @@ export const createQueueRuntime = ({* Uncategorized regardless of the active board. Only names are fetched — the* gallery hydrates the video itself on its own refresh. Re-attaching a video* that another settlement path already routed is a no-op server-side.+ *+ * Board attachment is cosmetic categorization: the run itself succeeded, so a+ * failure here (transient fetch error, board deleted mid-run) is recorded as a+ * queue-results error and NEVER thrown — throwing from the run-settlement path+ * would mark a completed generation "failed" and skip recording its images.*/- const addResultVideosToDestination = async (queueItem: QueueItem, backendItemIds: number[]): Promise<void> => {- if (!isActive() || queueItem.snapshot.destination !== 'gallery' || backendItemIds.length === 0) {+ const addResultVideosToDestination = async (+ projectId: string,+ queueItem: QueueItem,+ backendItemIds: number[]+ ): Promise<void> => {+ // Skip ids whose backend items were cancelled — their partial videos are not+ // deliverable results (mirrors waitForResults filtering images to completed+ // outcomes). The persisted set can miss a cancellation from the current+ // session on the resumed path; the residual is a best-effort attach of an+ // already-rendered video, not a correctness problem.+ const deliverableItemIds = backendItemIds.filter(+ (backendItemId) => !queueItem.cancelledBackendItemIds?.includes(backendItemId)+ );++ if (!isActive() || queueItem.snapshot.destination !== 'gallery' || deliverableItemIds.length === 0) {return;}@@ -223,17 +241,31 @@ export const createQueueRuntime = ({return;}- const options = getQueueItemResultImageOptions(queueItem);- const namesPerItem = await Promise.all(- backendItemIds.map((backendItemId) => backend.getResultVideoNames(backendItemId, options))- );- const videoNames = [...new Set(namesPerItem.flat())];+ try {+ const imageOptions = getQueueItemResultImageOptions(queueItem);+ const options = queueItem.snapshot.filterIntermediateResults+ ? { ...imageOptions, excludeIntermediate: true }+ : imageOptions;+ const namesPerItem = await Promise.all(+ deliverableItemIds.map((backendItemId) => backend.getResultVideoNames(backendItemId, options))+ );+ const videoNames = [...new Set(namesPerItem.flat())];- if (videoNames.length === 0 || !isActive()) {- return;- }+ if (videoNames.length === 0 || !isActive()) {+ return;+ }- await destinations.addVideosToGalleryBoard(boardId, videoNames);+ await destinations.addVideosToGalleryBoard(boardId, videoNames);+ } catch (error) {+ if (isActive()) {+ commands.recordError({+ area: 'queue-results',+ message: toErrorMessage(error),+ namespace: 'queue',+ projectId,+ });+ }+ }};/** Drop intermediates when the item asks for it, then land what remains on its destination. */@@ -256,7 +288,12 @@ export const createQueueRuntime = ({const routeRunResults = async (coordinator: QueueCoordinator,projectId: string,- queueItem: QueueItem+ queueItem: QueueItem,+ // The store is immutable and `queueItem` is a pre-submission closure, so callers must+ // 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[]): Promise<void> => {try {const allImages = await coordinator.waitForResults(@@ -270,9 +307,10 @@ export const createQueueRuntime = ({}const images = await deliverVisibleImages(queueItem, allImages);- // The live path routes videos per backend item (routeBackendItemResults); this covers- // resumed/adopted runs, where only the persisted ids are available.- await addResultVideosToDestination(queueItem, queueItem.backendItemIds ?? []);+ // The live path also routes videos per backend item as each completes+ // (routeBackendItemResults); this run-end pass is the retry/backstop and the only+ // coverage for items completed in a previous session. Never throws.+ await addResultVideosToDestination(projectId, queueItem, backendItemIds);if (!isActive()) {return;@@ -319,7 +357,8 @@ export const createQueueRuntime = ({}const visibleImages = await deliverVisibleImages(queueItem, images);- await addResultVideosToDestination(queueItem, [backendItemId]);+ // Never throws — a board-attach hiccup must not block routePartialResults below.+ await addResultVideosToDestination(projectId, queueItem, [backendItemId]);if (!isActive()) {return;@@ -419,7 +458,7 @@ export const createQueueRuntime = ({});void backend.resumeProcessor().catch(() => undefined);- return routeRunResults(coordinator, project.id, queueItem);+ return routeRunResults(coordinator, project.id, queueItem, itemIds);}).catch((error: unknown) => {if (isActive()) {@@ -518,10 +557,10 @@ export const createQueueRuntime = ({projectId: project.id,queueItemId: queueItem.id,});- void routeRunResults(coordinator, project.id, queueItem);+ void routeRunResults(coordinator, project.id, queueItem, outcome.backendItemIds);break;case 'resumed':- void routeRunResults(coordinator, project.id, queueItem);+ void routeRunResults(coordinator, project.id, queueItem, queueItem.backendItemIds ?? []);break;case 'missing':commands.setStatus({