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(gallery): unify live progress selection
joshistoastc24b138f183d
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex f91b669492..b8e97967b7 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -32,11 +32,12 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })const generateValues = useWidgetValuesSelector('generate', selectWidgetValues);const queueItems = useActiveProjectSelector((project) => project.queue.items);const antialiasProgressImages = useActiveProjectSelector((project) => project.settings.antialiasProgressImages);+ const liveFollowEnabled = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);const { account, gallery, notifications, widgets } = useWorkbenchCommands();const adapter = useMemo<GalleryUiAdapter>(() => ({account: {- showProgressImages: () => account.updateProjectPreferences({ showProgressImagesInViewer: true }),+ enableLiveFollow: () => account.updateProjectPreferences({ showProgressImagesInViewer: true }),},antialiasProgressImages,gallery,@@ -44,6 +45,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })generateValues,ImageActionsProvider: GalleryImageActionsAdapter,ImageContextMenu: GalleryImageContextMenu,+ liveFollowEnabled,notifications,projectId,projectName,@@ -56,6 +58,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })gallery,galleryValues,generateValues,+ liveFollowEnabled,notifications,projectId,projectName,diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex fd386989a3..41bfa52cae 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -17,9 +17,13 @@ export {type GalleryThumbnailFit,} from './core/settings';export {+ getActiveGalleryQueuePlaceholder,getGalleryCompareImage,+ getGalleryCurrentItem,getGalleryImagesRefreshToken,getGalleryRecentImagesKey,getGalleryRefreshToken,+ type GalleryCurrentItem,+ type GalleryQueuePlaceholder,} from './ui/galleryStateView';export { getSelectedGalleryImageFromValues } from './core/selection';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex ae8432e724..42f044bc02 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -77,6 +77,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>gallery.settings;const columnCount = getGalleryColumnCount(imageDensityPercent, layout);const selectedNames = useMemo(() => new Set(gallery.selectedImageNames), [gallery.selectedImageNames]);+ const isFollowingLive = gallery.currentItem?.kind === 'placeholder';const isComparisonActive =gallery.compareImageName !== null &&gallery.selectedImageName !== null &&@@ -302,7 +303,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>);const handleShowProgressImages = useCallback(() => {- account.showProgressImages();+ account.enableLiveFollow();}, [account]);const handleToggleStarred = useCallback(@@ -461,6 +462,10 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>key={cell.placeholder.id}antialiasProgressImages={antialiasProgressImages}fit={thumbnailFit}+ isSelected={+ gallery.currentItem?.kind === 'placeholder' &&+ gallery.currentItem.placeholder.id === cell.placeholder.id+ }placeholder={cell.placeholder}onClick={handleShowProgressImages}/>@@ -478,8 +483,8 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>fit={thumbnailFit}getDragImages={getDragImages}image={cell.image}- isPrimary={cell.image.imageName === gallery.selectedImageName}- isSelected={selectedNames.has(cell.image.imageName)}+ isPrimary={!isFollowingLive && cell.image.imageName === gallery.selectedImageName}+ isSelected={!isFollowingLive && selectedNames.has(cell.image.imageName)}onClick={handleThumbnailClick}onContextMenu={handleThumbnailContextMenu}onToggleStarred={handleToggleStarred}@@ -536,11 +541,13 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>const GalleryQueuePlaceholderCell = ({antialiasProgressImages,fit,+ isSelected,onClick,placeholder,}: {antialiasProgressImages: boolean;fit: GalleryThumbnailFit;+ isSelected: boolean;onClick: () => void;placeholder: GalleryQueuePlaceholder;}) => {@@ -554,15 +561,17 @@ const GalleryQueuePlaceholderCell = ({<Boxas="button"aria-label={t('widgets.preview.showInProgressDiffusion')}+ aria-selected={isSelected}aspectRatio={1}bg="bg"- borderColor={isActive ? 'accent.solid' : 'border.subtle'}- borderWidth="1px"+ borderColor={isSelected ? 'accent.solid' : 'border.subtle'}+ borderWidth={isSelected ? '2px' : '1px'}cursor="pointer"minW="0"rounded="md"overflow="hidden"position="relative"+ role="option"w="full"onClick={onClick}>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex 8f6fac412f..ea9dec2bdf 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -73,7 +73,7 @@ export interface GalleryWidgetProps {export interface GalleryUiAdapter {ImageActionsProvider: ComponentType<GalleryImageActionsOptions & { children: ReactNode }>;ImageContextMenu: ComponentType<GalleryImageContextMenuProps>;- account: { showProgressImages(): void };+ account: { enableLiveFollow(): void };antialiasProgressImages: boolean;gallery: GalleryCommandsPort;galleryValues: Record<string, unknown>;@@ -82,6 +82,7 @@ export interface GalleryUiAdapter {projectId: string;projectName: string;queueItems: QueueItem[];+ liveFollowEnabled: boolean;widgets: { patchGalleryValues(values: Record<string, unknown>): void };}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex 78247d97f8..fd973dda8b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -44,6 +44,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidggallery: galleryCommands,galleryValues,generateValues,+ liveFollowEnabled,projectId,projectName,queueItems,@@ -70,7 +71,14 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgconst { loadMore, patchImages, total } = data;const selectedBoardId = getGallerySelectedBoardId(galleryValues, data.boards);- const gallery = getGalleryStateView(galleryValues, data.boards, data.images, data.isLoadingImages, queueItems);+ const gallery = getGalleryStateView(+ galleryValues,+ data.boards,+ data.images,+ data.isLoadingImages,+ queueItems,+ liveFollowEnabled+ );const onStarredChange = useCallback((imageNames: string[], starred: boolean) => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex 1f28d0c7bc..30356f6a0a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -4,7 +4,9 @@ import type { QueueHistoryItemStatus, QueueItem } from '@features/queue/contractimport { describe, expect, it } from 'vitest';import {+ getActiveGalleryQueuePlaceholder,getBoardCounts,+ getGalleryCurrentItem,getGalleryImagesRefreshToken,getGalleryQueuePlaceholders,getGallerySelectedBoardId,@@ -178,6 +180,50 @@ describe('gallery state view', () => {expect(placeholders.map((placeholder) => placeholder.itemIndex)).toEqual([2, 3]);});+ it('derives the active gallery placeholder from the running queue item before a progress image arrives', () => {+ const pending = createQueueItem({ backendItemIds: [1], boardId: 'none', status: 'pending' });+ const running = createQueueItem({+ backendItemIds: [11, 12, 13],+ boardId: 'board-1',+ completedBackendItemIds: [11],+ status: 'running',+ });++ expect(getActiveGalleryQueuePlaceholder([pending, running])).toMatchObject({+ boardId: 'board-1',+ itemIndex: 2,+ queueItemId: running.id,+ });+ });++ it('uses one derived current item while live-follow is active', () => {+ const placeholder = {+ boardId: 'board-1',+ height: 768,+ id: 'queue-item:0',+ itemIndex: 1,+ queueItemId: 'queue-item',+ width: 512,+ };++ expect(+ getGalleryCurrentItem({+ activePlaceholder: placeholder,+ isComparisonActive: false,+ liveFollowEnabled: true,+ selectedImageName: 'saved.png',+ })+ ).toEqual({ kind: 'placeholder', placeholder });+ expect(+ getGalleryCurrentItem({+ activePlaceholder: placeholder,+ isComparisonActive: false,+ liveFollowEnabled: false,+ selectedImageName: 'saved.png',+ })+ ).toEqual({ imageName: 'saved.png', kind: 'image' });+ });+it('skips cancelled backend item slots when creating placeholders', () => {const queueItems = [createQueueItem({diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex 8a343d93d1..bf498e018d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -18,6 +18,7 @@ const UNCATEGORIZED_BOARD: GalleryBoard = {* deliver to the currently viewed board once generation completes.*/export interface GalleryQueuePlaceholder {+ boardId: string;id: string;queueItemId: string;itemIndex: number;@@ -25,9 +26,15 @@ export interface GalleryQueuePlaceholder {height: number;}+export type GalleryCurrentItem =+ | { kind: 'image'; imageName: string }+ | { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder }+ | null;+export interface GalleryStateView {boards: GalleryBoard[];compareImageName: string | null;+ currentItem: GalleryCurrentItem;galleryView: GalleryView;images: GalleryImage[];isLoading: boolean;@@ -40,6 +47,57 @@ export interface GalleryStateView {settings: GallerySettings;}+export const getActiveGalleryQueuePlaceholder = (queueItems: QueueItem[]): GalleryQueuePlaceholder | null => {+ for (const item of queueItems) {+ if (item.status !== 'running' || item.snapshot.destination !== 'gallery') {+ continue;+ }++ const boardId = item.snapshot.galleryBoardId ?? 'none';+ const { width, height } = getQueueItemSnapshotDimensions(item, { height: 1024, width: 1024 });+ const completedBackendItemIds = new Set(item.completedBackendItemIds ?? []);+ const cancelledBackendItemIds = new Set(item.cancelledBackendItemIds ?? []);++ if (item.backendItemIds?.length) {+ const index = item.backendItemIds.findIndex(+ (backendItemId) => !completedBackendItemIds.has(backendItemId) && !cancelledBackendItemIds.has(backendItemId)+ );++ if (index !== -1) {+ return { boardId, height, id: `${item.id}:${index}`, itemIndex: index + 1, queueItemId: item.id, width };+ }++ continue;+ }++ const expectedImageCount = getQueueItemSnapshotBatchCount(item);++ if (expectedImageCount > 0) {+ return { boardId, height, id: `${item.id}:0`, itemIndex: 1, queueItemId: item.id, width };+ }+ }++ return null;+};++export const getGalleryCurrentItem = ({+ activePlaceholder,+ isComparisonActive,+ liveFollowEnabled,+ selectedImageName,+}: {+ activePlaceholder: GalleryQueuePlaceholder | null;+ isComparisonActive: boolean;+ liveFollowEnabled: boolean;+ selectedImageName: string | null;+}): GalleryCurrentItem => {+ if (liveFollowEnabled && !isComparisonActive && activePlaceholder) {+ return { kind: 'placeholder', placeholder: activePlaceholder };+ }++ return selectedImageName ? { imageName: selectedImageName, kind: 'image' } : null;+};+export const getGalleryView = (values: Record<string, unknown>): GalleryView =>values.galleryView === 'assets' ? 'assets' : 'images';@@ -155,14 +213,28 @@ export const getGalleryQueuePlaceholders = (continue;}- placeholders.push({ height, id: `${item.id}:${index}`, itemIndex: index + 1, queueItemId: item.id, width });+ placeholders.push({+ boardId: targetBoardId,+ height,+ id: `${item.id}:${index}`,+ itemIndex: index + 1,+ queueItemId: item.id,+ width,+ });}continue;}for (let index = 0; index < expectedImageCount; index++) {- placeholders.push({ height, id: `${item.id}:${index}`, itemIndex: index + 1, queueItemId: item.id, width });+ placeholders.push({+ boardId: targetBoardId,+ height,+ id: `${item.id}:${index}`,+ itemIndex: index + 1,+ queueItemId: item.id,+ width,+ });}}@@ -174,7 +246,8 @@ export const getGalleryStateView = (backendBoards: GalleryBoard[],backendImages: GalleryImage[] | null,isLoading: boolean,- queueItems: QueueItem[] = []+ queueItems: QueueItem[] = [],+ liveFollowEnabled = false): GalleryStateView => {const localImages = Array.isArray(values.recentImages)? (values.recentImages as GeneratedImageContract[]).map((image) => ({@@ -196,10 +269,20 @@ export const getGalleryStateView = (const boards = backendBoards.length ? backendBoards : [{ ...UNCATEGORIZED_BOARD, imageCount: images.length }];const selectedBoardId = getGallerySelectedBoardId(values, backendBoards);const compareImage = getGalleryCompareImage(values);+ const compareImageName = compareImage?.imageName ?? null;+ const isComparisonActive =+ visibleSelectedImageName !== null && compareImageName !== null && compareImageName !== visibleSelectedImageName;+ const currentItem = getGalleryCurrentItem({+ activePlaceholder: getActiveGalleryQueuePlaceholder(queueItems),+ isComparisonActive,+ liveFollowEnabled,+ selectedImageName: visibleSelectedImageName,+ });return {boards,- compareImageName: compareImage?.imageName ?? null,+ compareImageName,+ currentItem,galleryView,images,isLoading,diff --git a/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.test.ts b/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.test.tsdeleted file mode 100644index 3848007bd2..0000000000--- a/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.test.ts+++ /dev/null@@ -1,43 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { isRevealHolding, revealHoldStore, REVEAL_HOLD_DURATION_MS } from './revealHoldStore';--describe('revealHoldStore', () => {- beforeEach(() => {- vi.useFakeTimers();- });-- afterEach(() => {- revealHoldStore.clear();- vi.useRealTimers();- });-- it('holds for the default duration and expires on its own', () => {- expect(isRevealHolding()).toBe(false);-- revealHoldStore.arm();- expect(isRevealHolding()).toBe(true);-- vi.advanceTimersByTime(REVEAL_HOLD_DURATION_MS - 1);- expect(isRevealHolding()).toBe(true);-- vi.advanceTimersByTime(1);- expect(isRevealHolding()).toBe(false);- });-- it('re-arming extends the hold instead of expiring early', () => {- revealHoldStore.arm();- vi.advanceTimersByTime(REVEAL_HOLD_DURATION_MS - 500);- revealHoldStore.arm();- vi.advanceTimersByTime(REVEAL_HOLD_DURATION_MS - 1);- expect(isRevealHolding()).toBe(true);- vi.advanceTimersByTime(1);- expect(isRevealHolding()).toBe(false);- });-- it('clear releases the hold immediately', () => {- revealHoldStore.arm();- revealHoldStore.clear();- expect(isRevealHolding()).toBe(false);- });-});diff --git a/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.ts b/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.tsdeleted file mode 100644index 127426f687..0000000000--- a/invokeai/frontend/webv2/src/features/queue/data/revealHoldStore.ts+++ /dev/null@@ -1,46 +0,0 @@-import { createExternalStore } from '@platform/state/externalStore';--/**- * A short "reveal window" after a generation completes: consumers that show- * live denoise frames suppress them while the hold is armed, so the finished- * result is actually seen before the next queue item's noise takes over. Armed- * by the queue coordinator when a backend item completes while more items are- * still running; expires on its own timer (the timer lives here, not in a- * component effect).- */--export const REVEAL_HOLD_DURATION_MS = 2000;--const store = createExternalStore<{ holdUntil: number }>({ holdUntil: 0 });--let timer: ReturnType<typeof setTimeout> | null = null;--export const revealHoldStore = {- arm(durationMs: number = REVEAL_HOLD_DURATION_MS): void {- store.patchSnapshot({ holdUntil: Date.now() + durationMs });-- if (timer) {- clearTimeout(timer);- }-- timer = setTimeout(() => {- timer = null;- store.patchSnapshot({ holdUntil: 0 });- }, durationMs);- },- clear(): void {- if (timer) {- clearTimeout(timer);- timer = null;- }-- store.patchSnapshot({ holdUntil: 0 });- },-};--export type RevealHoldSink = Pick<typeof revealHoldStore, 'arm' | 'clear'>;--export const isRevealHolding = (): boolean => store.getSnapshot().holdUntil > Date.now();--/** Whether a reveal hold is currently active. Re-evaluates when the hold arms or expires. */-export const useRevealHold = (): boolean => store.useSelector((snapshot) => snapshot.holdUntil > Date.now());diff --git a/invokeai/frontend/webv2/src/features/queue/react.ts b/invokeai/frontend/webv2/src/features/queue/react.tsindex 81f12e1ae9..74d593fc6a 100644--- a/invokeai/frontend/webv2/src/features/queue/react.ts+++ b/invokeai/frontend/webv2/src/features/queue/react.ts@@ -7,6 +7,5 @@ export {useQueueItemProgressImage,} from './data/progressImageStore';export { type QueueItemProgressSink, useQueueItemProgress } from './data/progressStore';-export { useRevealHold } from './data/revealHoldStore';export { QueueUiProvider, type QueueUiAdapter } from './ui/QueueUiContext';export { getQueueItemAccess } from './ui/queueOwnership';diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.tsindex 918e0254f0..bea91bc15a 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts@@ -26,7 +26,6 @@ import {type ProgressImageTarget,} from '@features/queue/data/progressImageStore';import { queueItemProgressStore, type QueueItemProgressSink } from '@features/queue/data/progressStore';-import { revealHoldStore, type RevealHoldSink } from '@features/queue/data/revealHoldStore';import { ApiError } from '@platform/transport/http';const GALLERY_REFRESH_COALESCE_MS = 400;@@ -181,7 +180,6 @@ export const createQueueCoordinator = (nodeExecution: QueueNodeExecutionPort;progress?: QueueItemProgressSink;progressImage?: ProgressImageSink;- revealHold?: RevealHoldSink;sweepIntervalMs?: number;}): QueueCoordinator => {@@ -190,7 +188,6 @@ export const createQueueCoordinator = (const modelLoads = options.modelLoads;const nodeExecution = options.nodeExecution;const progressImage = options.progressImage ?? progressImageStore;- const revealHold = options.revealHold ?? revealHoldStore;const galleryRefreshCoalesceMs = options.galleryRefreshCoalesceMs ?? GALLERY_REFRESH_COALESCE_MS;const sweepIntervalMs = options.sweepIntervalMs ?? SAFETY_SWEEP_INTERVAL_MS;@@ -298,22 +295,13 @@ export const createQueueCoordinator = (if (outcome.status === 'completed') {const routingPromise = callbacks.onBackendItemComplete?.(wait.localQueueItemId, backendItemId);- // Reveal window: while sibling items keep generating, hold off the next- // live frames briefly so the just-finished result is actually seen.- const settleCompleted = (): void => {- clearProgressImage();-- if (waits.size > 0) {- revealHold.arm();- }- };if (routingPromise) {void Promise.resolve(routingPromise)- .finally(settleCompleted)+ .finally(clearProgressImage).catch(() => undefined);} else {- settleCompleted();+ clearProgressImage();}}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.tsindex 456a9b3ad9..3b7fc953c1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { getPreviewBoardsRequestKey } from './PreviewWidgetView';+import { getMatchingProgressImage, getPreviewBoardsRequestKey } from './PreviewWidgetView';describe('getPreviewBoardsRequestKey', () => {it('requests boards for local generated images, not only backend gallery images', () => {@@ -15,3 +15,30 @@ describe('getPreviewBoardsRequestKey', () => {).toBeNull();});});++describe('getMatchingProgressImage', () => {+ const placeholder = {+ boardId: 'none',+ height: 768,+ id: 'queue-1:1',+ itemIndex: 2,+ queueItemId: 'queue-1',+ width: 512,+ };+ const progressImage = {+ dataUrl: 'data:image/png;base64,abc',+ height: 768,+ target: { itemIndex: 2, queueItemId: 'queue-1' },+ width: 512,+ };++ it('returns progress only when it belongs to the current placeholder', () => {+ expect(getMatchingProgressImage(progressImage, placeholder)).toBe(progressImage);+ expect(+ getMatchingProgressImage({ ...progressImage, target: { itemIndex: 1, queueItemId: 'queue-1' } }, placeholder)+ ).toBeNull();+ expect(+ getMatchingProgressImage({ ...progressImage, target: { itemIndex: 2, queueItemId: 'queue-2' } }, placeholder)+ ).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex db946d00a7..84a00c6d25 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -10,15 +10,17 @@ import {type GeneratedImageContract,} from '@features/gallery';import {+ getActiveGalleryQueuePlaceholder,getGalleryCompareImage,getGalleryImagesRefreshToken,getGalleryRecentImagesKey,getGalleryRefreshToken,getGallerySettings,+ type GalleryQueuePlaceholder,} from '@features/gallery/contracts';import { galleryBoardsOptions, galleryImagesOptions } from '@features/gallery/queries';import { createGenerateFormValuesSelector } from '@features/generation/react';-import { useProgressImage, useRevealHold, type LatestProgressImageSnapshot } from '@features/queue/react';+import { useProgressImage, type LatestProgressImageSnapshot } from '@features/queue/react';import {imageUrlToStreamingSource,progressImageToStreamingSource,@@ -50,6 +52,7 @@ import { PreviewFilmstrip } from './PreviewFilmstrip';import { PreviewFooter } from './PreviewFooter';import { PreviewFrame } from './PreviewFrame';import { previewHeaderStore } from './previewHeaderStore';+import { PreviewLiveStatusLine } from './PreviewLiveReadout';import {getPreviewComparisonMode,getPreviewFilmstripVisible,@@ -137,10 +140,27 @@ export const getPreviewBoardsRequestKey = ({refreshToken: string;}): string | null => (hasSelectedImage ? refreshToken : null);+export const getMatchingProgressImage = (+ progressImage: LatestProgressImageSnapshot | null,+ placeholder: GalleryQueuePlaceholder | null+): LatestProgressImageSnapshot | null => {+ if (+ !progressImage?.target ||+ !placeholder ||+ progressImage.target.queueItemId !== placeholder.queueItemId ||+ progressImage.target.itemIndex !== placeholder.itemIndex+ ) {+ return null;+ }++ return progressImage;+};+const selectGenerateRecallValues = createGenerateFormValuesSelector();export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));+ const queueItems = useActiveProjectSelector((project) => project.queue.items);const previewValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'preview'));const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);const { antialiasProgressImages, showProgressImagesInViewer } = useActiveProjectSelector(@@ -271,11 +291,9 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {}, [boardImages, displayBoardId, selectedImage]);const isComparing =selectedImage !== null && compareImage !== null && compareImage.imageName !== selectedImage.imageName;- // The reveal window suppresses live frames briefly after a completion so the- // finished result is seen before the next item's noise takes over.- const isRevealHolding = useRevealHold();- const shouldShowProgressImage =- showProgressImagesInViewer && progressImage !== null && !isComparing && !isRevealHolding;+ const activeGalleryPlaceholder = useMemo(() => getActiveGalleryQueuePlaceholder(queueItems), [queueItems]);+ const shouldFollowLive = showProgressImagesInViewer && activeGalleryPlaceholder !== null && !isComparing;+ const matchingProgressImage = getMatchingProgressImage(progressImage, activeGalleryPlaceholder);const exitCompare = useCallback(() => gallery.setCompareImage(null), [gallery]);const swapCompareImages = useCallback(() => {if (selectedImage && compareImage) {@@ -343,6 +361,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const selectPreviousImage = useCallback(() => selectByOffset(-1), [selectByOffset]);const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);const selectedImageName = selectedImage?.imageName ?? null;+ const headerImageName = shouldFollowLive ? null : selectedImageName;// Publish the header chrome context (the "[board] / [image]" label and the// action strip's image + actions) for the widget frame; the chrome renders@@ -350,13 +369,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {// unmount so stale chrome never outlives us.useEffect(() => {previewHeaderStore.set({- actionImage: contextMenuImage,- actions: imageActions,- boardName: selectedImageName === null ? null : boardName,- imageName: selectedImageName,- openImageMenu: openImageContextMenu,+ actionImage: shouldFollowLive ? null : contextMenuImage,+ actions: shouldFollowLive ? null : imageActions,+ boardName: headerImageName === null ? null : boardName,+ imageName: headerImageName,+ openImageMenu: shouldFollowLive ? null : openImageContextMenu,});- }, [boardName, contextMenuImage, imageActions, openImageContextMenu, selectedImageName]);+ }, [boardName, contextMenuImage, headerImageName, imageActions, openImageContextMenu, shouldFollowLive]);useEffect(() => () => previewHeaderStore.clear(), []);@@ -384,7 +403,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {return;}- if (commandId === 'viewer.deleteImage' && selectedImage) {+ if (commandId === 'viewer.deleteImage' && selectedImage && !shouldFollowLive) {void imageActions.deleteImages([selectedImage.imageName]);return;}@@ -425,7 +444,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {return (<Box ref={rootRef} p="2" h="full">- {selectedImage ? (+ {shouldFollowLive && activeGalleryPlaceholder ? (+ <LivePreview+ placeholder={activeGalleryPlaceholder}+ progressImage={matchingProgressImage}+ shouldAntialiasProgressImage={antialiasProgressImages}+ />+ ) : selectedImage ? (<>{isComparing && compareImage ? (<PreviewCompare@@ -448,9 +473,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {image={selectedImage}isLoadingBoard={isLoadingBoard}isMetadataOpen={isMetadataOpen}- progressImage={shouldShowProgressImage ? progressImage : null}selectedIndex={selectedIndex}- shouldAntialiasProgressImage={antialiasProgressImages}onContextMenu={openImageContextMenu}onNext={selectNextImage}onPrevious={selectPreviousImage}@@ -466,10 +489,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {/></>) : (- <EmptyPreview- progressImage={shouldShowProgressImage ? progressImage : null}- shouldAntialiasProgressImage={antialiasProgressImages}- />+ <EmptyPreview />)}</Box>);@@ -485,9 +505,7 @@ const SelectedImagePreview = ({isLoadingBoard,isMetadataOpen,loupeControlsRef,- progressImage,selectedIndex,- shouldAntialiasProgressImage,onContextMenu,onNext,onPrevious,@@ -504,9 +522,7 @@ const SelectedImagePreview = ({isLoadingBoard: boolean;isMetadataOpen: boolean;loupeControlsRef?: Ref<PreviewLoupeControls>;- progressImage: LatestProgressImageSnapshot | null;selectedIndex: number;- shouldAntialiasProgressImage: boolean;onContextMenu: (x: number, y: number) => void;onNext: () => void;onPrevious: () => void;@@ -522,12 +538,9 @@ const SelectedImagePreview = ({src: image.imageUrl,width: image.width,}),- liveImage: progressImageToStreamingSource(progressImage),});- const isProgressImage = previewImage?.kind === 'live';const previewWidth = previewImage?.width ?? image.width;const previewHeight = previewImage?.height ?? image.height;- const liveQueueItemId = progressImage?.target?.queueItemId ?? null;const dragImage = useMemo(() => ({ boardId: actionImage?.boardId ?? 'none', imageName: image.imageName }),[actionImage?.boardId, image.imageName]@@ -553,12 +566,11 @@ const SelectedImagePreview = ({dragImage={dragImage}frameHeight={previewHeight}frameWidth={previewWidth}- isLive={isProgressImage}+ isLive={false}liveBadgeLabel={t('common.generating')}- liveQueueItemId={liveQueueItemId}loupeControlsRef={loupeControlsRef}padding={density === 'full' ? '6' : '3'}- shouldAntialiasLiveImage={shouldAntialiasProgressImage}+ shouldAntialiasLiveImagesource={previewImage}variant="framed"onContextMenu={onContextMenu}@@ -576,10 +588,9 @@ const SelectedImagePreview = ({actions={actions}boardImageCount={boardImageCount}image={image}- isLive={isProgressImage}+ isLive={false}isLoadingBoard={isLoadingBoard}isMetadataOpen={isMetadataOpen}- liveQueueItemId={liveQueueItemId}selectedIndex={selectedIndex}onNext={onNext}onPrevious={onPrevious}@@ -589,10 +600,12 @@ const SelectedImagePreview = ({);};-const EmptyPreview = ({+const LivePreview = ({+ placeholder,progressImage,shouldAntialiasProgressImage,}: {+ placeholder: GalleryQueuePlaceholder;progressImage: LatestProgressImageSnapshot | null;shouldAntialiasProgressImage: boolean;}) => {@@ -603,14 +616,37 @@ const EmptyPreview = ({return (<PreviewFrame- frameHeight={previewImage?.height ?? 1}- frameWidth={previewImage?.width ?? 1}+ frameHeight={previewImage?.height ?? placeholder.height}+ frameWidth={previewImage?.width ?? placeholder.width}isLiveliveBadgeLabel={t('common.generating')}- liveQueueItemId={progressImage?.target?.queueItemId ?? null}+ liveQueueItemId={placeholder.queueItemId}shouldAntialiasLiveImage={shouldAntialiasProgressImage}source={previewImage}variant="inset"+ >+ <Stack align="center" color="fg" gap="2" maxW="18rem" textAlign="center">+ <Text fontSize="sm" fontWeight="800">+ {t('common.generating')}+ </Text>+ <PreviewLiveStatusLine queueItemId={placeholder.queueItemId} />+ </Stack>+ </PreviewFrame>+ );+};++const EmptyPreview = () => {+ const { t } = useTranslation();++ return (+ <PreviewFrame+ frameHeight={1}+ frameWidth={1}+ isLive={false}+ liveBadgeLabel={t('common.generating')}+ shouldAntialiasLiveImage+ source={null}+ variant="inset"><Stack align="center" color="fg" gap="2" maxW="18rem" textAlign="center"><Text fontSize="sm" fontWeight="800">diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex b6f727f4ee..0ef533a551 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1836,6 +1836,101 @@ describe('workbenchReducer Phase 5 generation flow', () => {]);});+ it('preserves the last partial Gallery result when the final aggregate repeats the batch', () => {+ let state = primeGenerate(undefined, { batchCount: 3 });++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];+ const images = ['gallery-image-1.png', 'gallery-image-2.png', 'gallery-image-3.png'].map((name) =>+ createImage(name, queueItem.id)+ );++ state = workbenchReducer(state, {+ backendItemIds: [11, 12, 13],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });++ for (const [index, image] of images.entries()) {+ state = workbenchReducer(state, {+ backendItemId: 11 + index,+ images: [image],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });+ }++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('gallery-image-3.png');++ state = workbenchReducer(state, {+ images,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('gallery-image-3.png');+ });++ it('selects the last image from a final-only Gallery batch', () => {+ let state = primeGenerate(undefined, { batchCount: 3 });++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ images: ['gallery-image-1.png', 'gallery-image-2.png', 'gallery-image-3.png'].map((name) =>+ createImage(name, queueItem.id)+ ),+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('gallery-image-3.png');+ });++ it('pauses live-follow when the user selects a saved Gallery image', () => {+ let state = createInitialWorkbenchState();++ expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(true);++ state = workbenchReducer(state, { image: createImage('selected.png', 'gallery'), type: 'selectGalleryImage' });++ expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('selected.png');+ });++ it('pauses live-follow for saved Gallery multi-selection and comparison intents', () => {+ const primaryImage = createImage('primary.png', 'gallery');+ const compareImage = createImage('compare.png', 'gallery');+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ imageNames: [primaryImage.imageName, compareImage.imageName],+ primaryImage,+ type: 'setGalleryMultiSelection',+ });++ expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);++ state = workbenchReducer(state, {+ settings: { showProgressImagesInViewer: true },+ type: 'setActiveProjectSettings',+ });+ state = workbenchReducer(state, { image: compareImage, type: 'setGalleryCompareImage' });++ expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);+ });+it('stores selected backend board id for gallery submissions', () => {let state = createInitialWorkbenchState();diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex e0ac5798b6..81954377ef 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -1618,6 +1618,22 @@ const updateGalleryValues = ();};+const updateGalleryValuesAndPauseLiveFollow = (+ state: WorkbenchState,+ getValues: (values: Record<string, unknown>) => Record<string, unknown>,+ projectId = state.activeProjectId+): WorkbenchState =>+ updateProjectById(state, projectId, (project) =>+ updateProjectWidgetValues(+ {+ ...project,+ settings: { ...project.settings, showProgressImagesInViewer: false },+ },+ 'gallery',+ getValues+ )+ );+const refreshProjectBackendData = (project: Project): Project => ({...updateProjectWidgetValues(project, 'gallery', (values) => ({...values,@@ -1693,16 +1709,20 @@ const updateGalleryWithResultImages = (project: Project, images: GeneratedImageC}const galleryValues = getWidgetValues(project, 'gallery');- const existingImages = getGalleryImages(galleryValues).filter(+ const previousImages = getGalleryImages(galleryValues);+ const previousImageNames = new Set(previousImages.map((image) => image.imageName));+ const newImages = images.filter((image) => !previousImageNames.has(image.imageName));+ const existingImages = previousImages.filter((image) => !images.some((incomingImage) => incomingImage.imageName === image.imageName));+ const nextSelectedImage = newImages.at(-1);return updateProjectWidgetValues(project, 'gallery', () => ({...galleryValues,recentImages: [...images, ...existingImages],- selectedImage: images[0] ?? galleryValues.selectedImage,- selectedImageName: images[0]?.imageName ?? galleryValues.selectedImageName,- selectedImageNames: images[0] ? [images[0].imageName] : getGallerySelectedImageNames(galleryValues),+ selectedImage: nextSelectedImage ?? galleryValues.selectedImage,+ selectedImageName: nextSelectedImage?.imageName ?? galleryValues.selectedImageName,+ selectedImageNames: nextSelectedImage ? [nextSelectedImage.imageName] : getGallerySelectedImageNames(galleryValues),}));};@@ -2557,7 +2577,7 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe);}case 'selectGalleryImage': {- return updateGalleryValues(+ return updateGalleryValuesAndPauseLiveFollow(state,(values) => ({...values,@@ -2569,7 +2589,7 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe);}case 'toggleGalleryImageInSelection': {- return updateGalleryValues(+ return updateGalleryValuesAndPauseLiveFollow(state,(values) => {const imageName = action.image.imageName;@@ -2600,7 +2620,7 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe);}case 'setGalleryMultiSelection': {- return updateGalleryValues(+ return updateGalleryValuesAndPauseLiveFollow(state,(values) => ({...values,@@ -2612,7 +2632,11 @@ export const __workbenchReducerInternal = (state: WorkbenchState, action: Workbe);}case 'setGalleryCompareImage': {- return updateGalleryValues(state, (values) => ({ ...values, compareImage: action.image }), action.projectId);+ const updateValues = (values: Record<string, unknown>) => ({ ...values, compareImage: action.image });++ return action.image+ ? updateGalleryValuesAndPauseLiveFollow(state, updateValues, action.projectId)+ : updateGalleryValues(state, updateValues, action.projectId);}case 'selectGalleryBoard': {return updateGalleryValues(