Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(gallery): make preview navigation deterministic

joshistoast45f8f507649a
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
index f4c56ee721..39d4b723b9 100644
--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx
@@ -2,7 +2,7 @@ import type { GalleryUiAdapter } from '@features/gallery/react';
import type { ReactNode } from 'react';
import { GalleryUiProvider } from '@features/gallery/react';
-import { useProgressImage } from '@features/queue/react';
+import { useActiveProgressTarget } from '@features/queue/react';
import { getProjectWidgetValues } from '@workbench/widgetState';
import {
useActiveProjectId,
@@ -34,7 +34,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })
const queueItems = useActiveProjectSelector((project) => project.queue.items);
const antialiasProgressImages = useActiveProjectSelector((project) => project.settings.antialiasProgressImages);
const liveFollowEnabled = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);
- const liveProgressTarget = useProgressImage()?.target ?? null;
+ const liveProgressTarget = useActiveProgressTarget();
const { account, gallery, notifications, widgets } = useWorkbenchCommands();
const adapter = useMemo<GalleryUiAdapter>(
() => ({
diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.ts
index 5dc6ea4eba..9636e209f5 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 {
GalleryView,
GeneratedImageContract,
} from './core/types';
+export { normalizeGalleryImage } from './core/image';
export {
DEFAULT_GALLERY_SETTINGS,
getGallerySettings,
@@ -20,6 +21,7 @@ export {
getGalleryCompareImage,
getGalleryCurrentItem,
getGalleryGenerationSequence,
+ getGalleryPlaceholderInsertionIndex,
getGalleryImagesRefreshToken,
getGalleryRecentImagesKey,
getGalleryRefreshToken,
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/image.ts b/invokeai/frontend/webv2/src/features/gallery/core/image.ts
new file mode 100644
index 0000000000..10e4b4eff6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/gallery/core/image.ts
@@ -0,0 +1,10 @@
+import type { GalleryImage, GeneratedImageContract } from './types';
+
+type LocalGalleryImage = GeneratedImageContract & Partial<Pick<GalleryImage, 'boardId' | 'imageCategory' | 'starred'>>;
+
+export const normalizeGalleryImage = (image: LocalGalleryImage, fallbackBoardId = 'none'): GalleryImage => ({
+ ...image,
+ boardId: image.boardId ?? fallbackBoardId,
+ imageCategory: image.imageCategory ?? 'general',
+ starred: image.starred ?? false,
+});
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
index 42f044bc02..354d32a48e 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx
@@ -28,6 +28,7 @@ import type { GalleryQueuePlaceholder } from './galleryStateView';
import type { GalleryImageContextMenuTarget } from './GalleryUiContext';
import { getGalleryImageDragData, getGalleryImageDragId } from './galleryDnd';
+import { getGalleryPlaceholderInsertionIndex } from './galleryStateView';
import { useGalleryUi } from './GalleryUiContext';
import { useGalleryWidget } from './GalleryWidgetContext';
@@ -43,6 +44,7 @@ const THUMBNAIL_BUTTON_STYLE = {
height: '100%',
inset: 0,
minWidth: 0,
+ outline: 'none',
padding: 0,
position: 'absolute',
width: '100%',
@@ -87,21 +89,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
t('widgets.gallery.selectedBoardFallback');
const isEmpty = gallery.images.length === 0 && gallery.pendingPlaceholders.length === 0;
- // Fresh generations are unstarred, so with newest-first ordering they land
- // right after the starred block — pending placeholders go there too.
- const leadingStarredCount = useMemo(() => {
- if (imageOrderDir !== 'DESC' || !starredFirst) {
- return 0;
- }
-
- let count = 0;
-
- while (count < gallery.images.length && gallery.images[count].starred) {
- count += 1;
- }
-
- return count;
- }, [gallery.images, imageOrderDir, starredFirst]);
+ const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(gallery.images, imageOrderDir, starredFirst);
const cells = useMemo<GridCell[]>(() => {
const imageCells: GridCell[] = gallery.images.map((image, imageIndex) => ({
@@ -114,17 +102,15 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>
placeholder,
}));
- if (imageOrderDir !== 'DESC') {
- return [...imageCells, ...placeholderCells];
- }
-
- return [...imageCells.slice(0, leadingStarredCount), ...placeholderCells, ...imageCells.slice(leadingStarredCount)];
- }, [gallery.images, gallery.pendingPlaceholders, imageOrderDir, leadingStarredCount]);
+ return [
+ ...imageCells.slice(0, placeholderInsertionIndex),
+ ...placeholderCells,
+ ...imageCells.slice(placeholderInsertionIndex),
+ ];
+ }, [gallery.images, gallery.pendingPlaceholders, placeholderInsertionIndex]);
const getCellIndexForImage = (imageIndex: number): number =>
- imageOrderDir === 'DESC' && imageIndex >= leadingStarredCount
- ? imageIndex + gallery.pendingPlaceholders.length
- : imageIndex;
+ imageIndex >= placeholderInsertionIndex ? imageIndex + gallery.pendingPlaceholders.length : imageIndex;
const rowCount = Math.ceil(cells.length / columnCount);
diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
index c04aef81d6..a99512ba7c 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts
@@ -158,7 +158,7 @@ describe('gallery state view', () => {
expect(placeholders[0]).toMatchObject({
height: 768,
itemIndex: 1,
- queueItemId: 'queue-item-pending-board-1',
+ queueItemId: 'queue-item-running-board-1',
width: 512,
});
});
@@ -234,6 +234,23 @@ describe('gallery state view', () => {
expect(sequence.liveSlot).toBeNull();
});
+ it('keeps unsubmitted batches grouped after backend-ranked slots', () => {
+ const submittedBatch = createQueueItem({
+ backendItemIds: [11],
+ boardId: 'board-1',
+ localId: 'submitted-batch',
+ status: 'running',
+ });
+ const pendingBatchB = createQueueItem({ batchCount: 2, boardId: 'board-1', localId: 'batch-b' });
+ const pendingBatchA = createQueueItem({ batchCount: 2, boardId: 'board-1', localId: 'batch-a' });
+
+ expect(
+ getGalleryGenerationSequence([pendingBatchB, submittedBatch, pendingBatchA], null).chronologicalSlots.map(
+ (slot) => slot.id
+ )
+ ).toEqual(['submitted-batch:0', 'batch-a:0', 'batch-a:1', 'batch-b:0', 'batch-b:1']);
+ });
+
it('reverses the complete flattened sequence for newest-first galleries', () => {
const newerBatch = createQueueItem({
backendItemIds: [21, 22],
@@ -291,6 +308,27 @@ describe('gallery state view', () => {
).toEqual({ imageName: 'saved.png', kind: 'image' });
});
+ it('keeps the visible image selected when the active placeholder belongs to another board', () => {
+ const image = {
+ ...createImage('selected.png'),
+ boardId: 'board-1',
+ imageCategory: 'general',
+ starred: false,
+ } as const;
+ const activeItem = createQueueItem({ boardId: 'board-2', localId: 'active-other-board', status: 'running' });
+ const gallery = getGalleryStateView(
+ { selectedBoardId: 'board-1', selectedImageName: image.imageName },
+ boards,
+ [image],
+ false,
+ [activeItem],
+ true,
+ { itemIndex: 1, queueItemId: activeItem.id }
+ );
+
+ expect(gallery.currentItem).toEqual({ imageName: image.imageName, 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.ts
index 5767624293..45854ee24f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts
@@ -7,6 +7,7 @@ import type {
} from '@features/gallery/core/types';
import type { QueueItem } from '@features/queue/contracts';
+import { normalizeGalleryImage } from '@features/gallery/core/image';
import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';
import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';
@@ -69,6 +70,28 @@ interface SortableGalleryQueueSlot {
submittedAt: string;
}
+interface GalleryOrderImage {
+ starred?: boolean;
+}
+
+export const getGalleryPlaceholderInsertionIndex = (
+ images: GalleryOrderImage[],
+ imageOrderDir: GalleryOrderDir,
+ starredFirst: boolean
+): number => {
+ if (imageOrderDir !== 'DESC') {
+ return images.length;
+ }
+
+ if (!starredFirst) {
+ return 0;
+ }
+
+ const firstUnstarredIndex = images.findIndex((image) => !image.starred);
+
+ return firstUnstarredIndex === -1 ? images.length : firstUnstarredIndex;
+};
+
export const getGalleryGenerationSequence = (
queueItems: QueueItem[],
liveTarget: GalleryLiveTarget | null
@@ -116,10 +139,18 @@ export const getGalleryGenerationSequence = (
return a.backendItemId - b.backendItemId;
}
+ if (a.backendItemId !== null) {
+ return -1;
+ }
+
+ if (b.backendItemId !== null) {
+ return 1;
+ }
+
return (
a.submittedAt.localeCompare(b.submittedAt) ||
- a.placeholder.itemIndex - b.placeholder.itemIndex ||
- a.placeholder.queueItemId.localeCompare(b.placeholder.queueItemId)
+ a.placeholder.queueItemId.localeCompare(b.placeholder.queueItemId) ||
+ a.placeholder.itemIndex - b.placeholder.itemIndex
);
});
@@ -226,14 +257,29 @@ export const getGalleryQueuePlaceholders = (
searchTerm,
selectedBoardId,
}: { galleryView: GalleryView; imageOrderDir?: GalleryOrderDir; searchTerm: string; selectedBoardId: string }
+): GalleryQueuePlaceholder[] => {
+ return getVisibleGalleryQueuePlaceholders(getGalleryGenerationSequence(queueItems, null).chronologicalSlots, {
+ galleryView,
+ imageOrderDir,
+ searchTerm,
+ selectedBoardId,
+ });
+};
+
+const getVisibleGalleryQueuePlaceholders = (
+ chronologicalSlots: GalleryQueuePlaceholder[],
+ {
+ galleryView,
+ imageOrderDir,
+ searchTerm,
+ selectedBoardId,
+ }: { galleryView: GalleryView; imageOrderDir: GalleryOrderDir; searchTerm: string; selectedBoardId: string }
): GalleryQueuePlaceholder[] => {
if (galleryView !== 'images' || searchTerm.trim() !== '') {
return [];
}
- const placeholders = getGalleryGenerationSequence(queueItems, null).chronologicalSlots.filter(
- (placeholder) => placeholder.boardId === selectedBoardId
- );
+ const placeholders = chronologicalSlots.filter((placeholder) => placeholder.boardId === selectedBoardId);
return imageOrderDir === 'DESC' ? [...placeholders].reverse() : placeholders;
};
@@ -248,12 +294,9 @@ export const getGalleryStateView = (
liveTarget: GalleryLiveTarget | null = null
): GalleryStateView => {
const localImages = Array.isArray(values.recentImages)
- ? (values.recentImages as GeneratedImageContract[]).map((image) => ({
- ...image,
- boardId: 'none',
- imageCategory: 'general' as const,
- starred: false,
- }))
+ ? (values.recentImages as Array<GeneratedImageContract & Partial<GalleryImage>>).map((image) =>
+ normalizeGalleryImage(image)
+ )
: [];
const images = backendImages ?? (isLoading ? [] : localImages);
const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;
@@ -270,8 +313,15 @@ export const getGalleryStateView = (
const compareImageName = compareImage?.imageName ?? null;
const isComparisonActive =
visibleSelectedImageName !== null && compareImageName !== null && compareImageName !== visibleSelectedImageName;
+ const generationSequence = getGalleryGenerationSequence(queueItems, liveTarget);
+ const visibleActivePlaceholder =
+ settings.showPendingItems && galleryView === 'images' && searchTerm.trim() === ''
+ ? generationSequence.liveSlot?.boardId === selectedBoardId
+ ? generationSequence.liveSlot
+ : null
+ : null;
const currentItem = getGalleryCurrentItem({
- activePlaceholder: getGalleryGenerationSequence(queueItems, liveTarget).liveSlot,
+ activePlaceholder: visibleActivePlaceholder,
isComparisonActive,
liveFollowEnabled,
selectedImageName: visibleSelectedImageName,
@@ -285,7 +335,7 @@ export const getGalleryStateView = (
images,
isLoading,
pendingPlaceholders: settings.showPendingItems
- ? getGalleryQueuePlaceholders(queueItems, {
+ ? getVisibleGalleryQueuePlaceholders(generationSequence.chronologicalSlots, {
galleryView,
imageOrderDir: settings.imageOrderDir,
searchTerm,
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index 760a7623e8..91f74bc658 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -191,6 +191,11 @@ export interface QueueItemProgress {
totalItemCount?: number;
}
+export interface QueueItemProgressTarget {
+ queueItemId: string;
+ itemIndex: number;
+}
+
export interface QueueReadModel {
current: QueueItemReadModel | null;
items: QueueItemReadModel[];
diff --git a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts
new file mode 100644
index 0000000000..2bdc201d7d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts
@@ -0,0 +1,31 @@
+import type { QueueItemProgressTarget } from '@features/queue/core/types';
+
+import { createExternalStore } from '@platform/state/externalStore';
+
+export interface ActiveProgressTargetSink {
+ clear(target?: QueueItemProgressTarget): void;
+ set(target: QueueItemProgressTarget): void;
+}
+
+const store = createExternalStore<{ target: QueueItemProgressTarget | null }>({ target: null });
+
+const isSameTarget = (left: QueueItemProgressTarget | null, right: QueueItemProgressTarget): boolean =>
+ left?.queueItemId === right.queueItemId && left.itemIndex === right.itemIndex;
+
+export const activeProgressTargetStore: ActiveProgressTargetSink = {
+ clear(target) {
+ const current = store.getSnapshot().target;
+
+ if (current && (!target || isSameTarget(current, target))) {
+ store.patchSnapshot({ target: null });
+ }
+ },
+ set(target) {
+ if (!isSameTarget(store.getSnapshot().target, target)) {
+ store.patchSnapshot({ target });
+ }
+ },
+};
+
+export const useActiveProgressTarget = (): QueueItemProgressTarget | null =>
+ store.useSelector((snapshot) => snapshot.target);
diff --git a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts
index 505352f227..c4d2d2a4f6 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts
@@ -1,4 +1,5 @@
import type { QueueProgressImage } from '@features/queue/core/progressImage';
+import type { QueueItemProgressTarget } from '@features/queue/core/types';
import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';
@@ -10,10 +11,7 @@ import { createExternalStore, createKeyedTransientStore } from '@platform/state/
export type ProgressImageSnapshot = QueueProgressImage;
-export interface ProgressImageTarget {
- queueItemId: string;
- itemIndex: number;
-}
+export type ProgressImageTarget = QueueItemProgressTarget;
export type LatestProgressImageSnapshot = ProgressImageSnapshot & { target?: ProgressImageTarget };
diff --git a/invokeai/frontend/webv2/src/features/queue/react.ts b/invokeai/frontend/webv2/src/features/queue/react.ts
index 74d593fc6a..87b38fa0aa 100644
--- a/invokeai/frontend/webv2/src/features/queue/react.ts
+++ b/invokeai/frontend/webv2/src/features/queue/react.ts
@@ -1,5 +1,6 @@
/** React-facing Queue read models, kept separate from widget registration. */
export type { QueueItemProgress } from './core/types';
+export { useActiveProgressTarget } from './data/activeProgressTargetStore';
export { type ItemProgress, useItemProgress } from './data/itemProgressStore';
export {
type LatestProgressImageSnapshot,
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
index 09dca51f81..abed97a06f 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
@@ -4,6 +4,7 @@ import type {
QueueItemProgress,
QueueResultImage,
} from '@features/queue/core/types';
+import type { ActiveProgressTargetSink } from '@features/queue/data/activeProgressTargetStore';
import type { QueueItemProgressSink } from '@features/queue/data/progressStore';
import {
@@ -141,6 +142,7 @@ const generateRequest: QueueEnqueueGenerateRequest = {
};
interface Harness {
+ activeProgressTarget: { clear: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };
api: {
[Key in Exclude<keyof QueueCoordinatorBackendPort, 'emit' | 'on' | 'onConnectionChange'>]: ReturnType<typeof vi.fn>;
};
@@ -193,6 +195,7 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Har
started: vi.fn(),
};
const progressImage = { clear: vi.fn(), set: vi.fn() };
+ const activeProgressTarget = { clear: vi.fn(), set: vi.fn() } satisfies ActiveProgressTargetSink;
const hub = createSocketHub({ createSocket: () => socket });
hub.connect();
@@ -204,6 +207,7 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Har
on: hub.on,
onConnectionChange: hub.onConnectionChange,
},
+ activeProgressTarget,
galleryRefreshCoalesceMs: options.galleryRefreshCoalesceMs ?? 1,
modelLoads,
nodeExecution,
@@ -211,7 +215,18 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Har
progressImage,
});
- return { api, callbacks, coordinator, hub, modelLoads, nodeExecution, progressImage, progressEntries, socket };
+ return {
+ activeProgressTarget,
+ api,
+ callbacks,
+ coordinator,
+ hub,
+ modelLoads,
+ nodeExecution,
+ progressImage,
+ progressEntries,
+ socket,
+ };
};
describe('queueCoordinator', () => {
@@ -483,6 +498,7 @@ describe('queueCoordinator', () => {
percentage: 0.5,
totalItemCount: 1,
});
+ expect(harness.activeProgressTarget.set).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });
const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');
@@ -490,9 +506,34 @@ describe('queueCoordinator', () => {
await resultsPromise;
expect(harness.progressEntries.has('local-1')).toBe(false);
+ expect(harness.activeProgressTarget.clear).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });
expect(harness.progressImage.clear).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });
});
+ it('publishes the active target before a progress image is available', async () => {
+ harness.coordinator.connect();
+ await harness.coordinator.submitGenerate('local-1', generateRequest);
+
+ harness.socket.fire('invocation_progress', {
+ ...createStatusEvent({ item_id: 1 }),
+ message: 'Starting denoise',
+ percentage: 0.01,
+ });
+
+ expect(harness.activeProgressTarget.set).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });
+ expect(harness.progressImage.set).not.toHaveBeenCalled();
+ });
+
+ it('clears active target and image state when the connection drops', async () => {
+ harness.coordinator.connect();
+ await harness.coordinator.submitGenerate('local-1', generateRequest);
+
+ harness.hub.disconnect();
+
+ expect(harness.activeProgressTarget.clear).toHaveBeenCalledWith();
+ expect(harness.progressImage.clear).toHaveBeenCalledWith();
+ });
+
it('keeps the completed progress image until backend item result routing finishes', async () => {
let finishRouting: () => void = () => undefined;
const routingPromise = new Promise<void>((resolve) => {
@@ -637,8 +678,10 @@ describe('queueCoordinator', () => {
await harness.coordinator.submitGenerate('local-1', generateRequest);
+ // No slot is executing yet, so no active index is published — queued
+ // items must never present as live.
expect(harness.progressEntries.get('local-1')).toEqual({
- activeItemIndex: 1,
+ activeItemIndex: undefined,
completedItemCount: 0,
message: '',
percentage: null,
@@ -647,21 +690,82 @@ describe('queueCoordinator', () => {
const resultsPromise = harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z');
+ harness.socket.fire('invocation_progress', {
+ ...createStatusEvent({ item_id: 1 }),
+ message: 'Denoising',
+ percentage: 0.5,
+ });
+
+ expect(harness.progressEntries.get('local-1')).toEqual({
+ activeItemIndex: 1,
+ completedItemCount: 0,
+ message: 'Denoising',
+ percentage: 0.5,
+ totalItemCount: 2,
+ });
+
harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1 }));
+ // Between slots the item is idle again: completion is tracked, but no
+ // active index until the next progress event arrives.
expect(harness.progressEntries.get('local-1')).toEqual({
- activeItemIndex: 2,
+ activeItemIndex: undefined,
completedItemCount: 1,
message: '',
percentage: null,
totalItemCount: 2,
});
+ harness.socket.fire('invocation_progress', {
+ ...createStatusEvent({ item_id: 2 }),
+ message: 'Denoising',
+ percentage: 0.25,
+ });
+
+ expect(harness.progressEntries.get('local-1')).toEqual({
+ activeItemIndex: 2,
+ completedItemCount: 1,
+ message: 'Denoising',
+ percentage: 0.25,
+ totalItemCount: 2,
+ });
+
harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 2 }));
await resultsPromise;
});
+ it('does not clear a newer active slot when an older terminal event arrives late', async () => {
+ harness.api.enqueueGenerate.mockResolvedValue({
+ batchId: 'batch-1',
+ enqueued: 2,
+ itemIds: [1, 2],
+ requested: 2,
+ });
+ harness.coordinator.connect();
+ await harness.coordinator.submitGenerate('local-1', generateRequest);
+
+ harness.socket.fire('invocation_progress', {
+ ...createStatusEvent({ item_id: 1 }),
+ message: 'First slot',
+ percentage: 0.9,
+ });
+ harness.socket.fire('invocation_progress', {
+ ...createStatusEvent({ item_id: 2 }),
+ message: 'Second slot',
+ percentage: 0.2,
+ });
+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1 }));
+
+ expect(harness.progressEntries.get('local-1')).toEqual({
+ activeItemIndex: 2,
+ completedItemCount: 1,
+ message: 'Second slot',
+ percentage: 0.2,
+ totalItemCount: 2,
+ });
+ });
+
describe('reconcile', () => {
it('adopts pending items the backend already accepted, by origin', async () => {
harness.api.listItems.mockResolvedValue([
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
index bea91bc15a..1b8a51b3bc 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
@@ -10,6 +10,10 @@ import type {
} from '@features/queue/core/types';
import type { BackendConnectionStatus } from '@platform/transport/types';
+import {
+ activeProgressTargetStore,
+ type ActiveProgressTargetSink,
+} from '@features/queue/data/activeProgressTargetStore';
import {
isTerminalBackendStatus,
parseQueueItemOrigin,
@@ -175,6 +179,7 @@ export const createQueueCoordinator = (
options: {
/** One adapter owns Queue HTTP commands and realtime events. */
backend: QueueCoordinatorBackendPort;
+ activeProgressTarget?: ActiveProgressTargetSink;
galleryRefreshCoalesceMs?: number;
modelLoads: QueueModelLoadPort;
nodeExecution: QueueNodeExecutionPort;
@@ -184,6 +189,7 @@ export const createQueueCoordinator = (
}
): QueueCoordinator => {
const backend = options.backend;
+ const activeProgressTarget = options.activeProgressTarget ?? activeProgressTargetStore;
const progress = options.progress ?? queueItemProgressStore;
const modelLoads = options.modelLoads;
const nodeExecution = options.nodeExecution;
@@ -247,12 +253,15 @@ export const createQueueCoordinator = (
state.activeBackendItemId !== undefined && !terminalBackendItemIds.has(state.activeBackendItemId)
? state.activeBackendItemId
: undefined;
- const activeItemIndex = activeBackendItemId
- ? state.backendItemIds.indexOf(activeBackendItemId) + 1
- : Math.min(terminalBackendItemIds.size + 1, state.backendItemIds.length);
+ // activeItemIndex means "slot currently executing" — omitted while the
+ // item merely waits in the queue, so idle slots never present as live.
+ const activeItemIndex =
+ activeBackendItemId !== undefined
+ ? Math.max(1, state.backendItemIds.indexOf(activeBackendItemId) + 1)
+ : undefined;
progress.set(localQueueItemId, {
- activeItemIndex: Math.max(1, activeItemIndex),
+ activeItemIndex,
completedItemCount: terminalBackendItemIds.size,
message: state.message,
percentage: state.percentage,
@@ -278,18 +287,21 @@ export const createQueueCoordinator = (
waits.delete(backendItemId);
const progressTarget = getProgressImageTarget(wait.localQueueItemId, backendItemId);
const clearProgressImage = (): void => progressImage.clear(progressTarget);
+ activeProgressTarget.clear(progressTarget);
const state = runProgress.get(wait.localQueueItemId);
if (state) {
- state.activeBackendItemId = undefined;
+ if (state.activeBackendItemId === backendItemId) {
+ state.activeBackendItemId = undefined;
+ state.message = '';
+ state.percentage = null;
+ }
if (outcome.status === 'completed') {
state.completedBackendItemIds.add(backendItemId);
}
if (outcome.status === 'canceled') {
state.cancelledBackendItemIds.add(backendItemId);
}
- state.message = '';
- state.percentage = null;
publishRunProgress(wait.localQueueItemId);
}
@@ -428,11 +440,11 @@ export const createQueueCoordinator = (
nodeExecution.progress(event.invocation_source_id, event.percentage, event.message);
+ const target = getProgressImageTarget(wait.localQueueItemId, event.item_id);
+ activeProgressTarget.set(target);
+
if (event.image?.dataURL) {
- progressImage.set(
- { dataUrl: event.image.dataURL, height: event.image.height, width: event.image.width },
- getProgressImageTarget(wait.localQueueItemId, event.item_id)
- );
+ progressImage.set({ dataUrl: event.image.dataURL, height: event.image.height, width: event.image.width }, target);
}
const state = runProgress.get(wait.localQueueItemId);
@@ -453,6 +465,10 @@ export const createQueueCoordinator = (
* and, on (re)connect, schedules a gallery refresh and missed-event sweep.
*/
const handleConnectionChange = (status: BackendConnectionStatus): void => {
+ if (status !== 'connected') {
+ activeProgressTarget.clear();
+ progressImage.clear();
+ }
progress.clearAll?.();
nodeExecution.clearAll();
modelLoads.reset();
@@ -516,6 +532,8 @@ export const createQueueCoordinator = (
/** Detach generation listeners; the hub keeps the socket alive. */
const dispose = (): void => {
isDisposed = true;
+ activeProgressTarget.clear();
+ progressImage.clear();
for (const detach of detachers) {
detach();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
new file mode 100644
index 0000000000..d5a3fadcc6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx
@@ -0,0 +1,331 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { QueueItem } from '@features/queue/contracts';
+import type { WidgetViewProps } from '@workbench/widgetContracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const queueItem: QueueItem = {
+ cancellable: true,
+ id: 'queue-item-live',
+ snapshot: {
+ backendSubmission: { batchCount: 1, graph: { edges: [], id: 'graph-1', nodes: {} }, kind: 'workflow' },
+ destination: 'gallery',
+ filterIntermediateResults: false,
+ galleryBoardId: null,
+ graph: { id: 'graph-1', label: 'Live generation' },
+ presentation: { batchCount: 1, height: 64, width: 64 },
+ sourceId: 'workflow',
+ submittedAt: '2026-07-21T00:00:00.000Z',
+ },
+ status: 'running',
+};
+
+const mocks = vi.hoisted(() => {
+ const recentImages = [
+ {
+ height: 64,
+ imageName: 'newest',
+ imageUrl: '/images/newest/full',
+ queuedAt: '2026-07-21T00:00:00.000Z',
+ sourceQueueItemId: 'queue-item-done',
+ thumbnailUrl: '/images/newest/thumbnail',
+ width: 64,
+ },
+ {
+ height: 64,
+ imageName: 'oldest',
+ imageUrl: '/images/oldest/full',
+ queuedAt: '2026-07-21T00:00:00.000Z',
+ sourceQueueItemId: 'queue-item-done',
+ thumbnailUrl: '/images/oldest/thumbnail',
+ width: 64,
+ },
+ ];
+
+ return {
+ commands: {
+ account: { updateProjectPreferences: vi.fn() },
+ gallery: { selectImage: vi.fn(), setCompareImage: vi.fn() },
+ notifications: { reportError: vi.fn() },
+ widgets: { patchValues: vi.fn() },
+ },
+ project: {
+ queue: { items: [] as unknown[] },
+ settings: { antialiasProgressImages: false, showProgressImagesInViewer: false },
+ widgetInstances: {
+ gallery: {
+ state: {
+ values: {
+ recentImages,
+ selectedImage: { ...recentImages[0], boardId: 'none' },
+ selectedImageName: 'newest',
+ },
+ },
+ typeId: 'gallery',
+ },
+ preview: { state: { values: {} }, typeId: 'preview' },
+ },
+ },
+ recentImages,
+ useActiveProgressTarget: vi.fn(() => null as unknown),
+ useProgressImage: vi.fn(() => null as unknown),
+ };
+});
+
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectId: () => 'project-1',
+ useActiveProjectSelector: (selector: (project: typeof mocks.project) => unknown) => selector(mocks.project),
+ useWidgetValuesSelector: () => ({}),
+ useWorkbenchCommands: () => mocks.commands,
+}));
+
+vi.mock('@features/queue/react', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ useActiveProgressTarget: () => mocks.useActiveProgressTarget(),
+ useProgressImage: () => mocks.useProgressImage(),
+}));
+
+vi.mock('@features/gallery/queries', () => ({
+ galleryBoardsOptions: () => ({ enabled: false, queryFn: () => [], queryKey: ['test-boards'] }),
+ galleryImagesOptions: (query: { boardId: string }) => ({
+ queryFn: () => new Promise<never>(() => {}),
+ queryKey: ['test-images', query.boardId],
+ }),
+}));
+
+vi.mock('@workbench/image-actions', () => ({
+ EMPTY_IMAGE_RECALL_CAPABILITIES: {},
+ ImageContextMenu: () => null,
+ RecallActionButtons: () => null,
+ buildImageRecallSettings: () => ({}),
+ executeImageRecall: () => {},
+ getCurrentGenerateValues: () => ({}),
+ getGalleryCanvasImportMenuItems: () => [],
+ getImageContextMenuImages: () => [],
+ getImageContextMenuRecallRequestKey: () => null,
+ getImageRecallCapabilities: () => ({}),
+ getImageRecallMessage: () => '',
+ getImageRecallTitle: () => '',
+ getSelectedGalleryImage: () => null,
+ getSelectedGalleryImageFromValues: () => null,
+ saveBlobToDisk: () => {},
+ useImageActions: () => ({}),
+}));
+
+vi.mock('@features/generation/react', () => ({
+ GenerationUiProvider: ({ children }: { children?: unknown }) => children,
+ adjustFocusedPromptAttention: () => {},
+ createGenerateFormValuesSelector: () => () => ({}),
+ flushGenerateDrafts: () => {},
+ focusPositivePrompt: () => {},
+ promptHistoryNavigation: {},
+ useDebouncedDraftValue: () => ({}),
+ useRegisterGenerateDraftFlusher: () => {},
+}));
+
+import { PreviewWidgetView } from './PreviewWidgetView';
+
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en', resources: { en: { translation: {} } } });
+
+const disposer = () => {};
+const runtime = {
+ commands: { register: () => disposer },
+ hotkeys: { register: () => disposer },
+ instanceId: 'preview-instance',
+ workbench: { closeWidgetInstance: () => {} },
+} as unknown as WidgetViewProps['runtime'];
+const manifest = { id: 'preview', label: 'Preview' } as unknown as WidgetViewProps['manifest'];
+const instance = { id: 'preview-instance', typeId: 'preview' } as unknown as WidgetViewProps['instance'];
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const render = async () => {
+ host = document.createElement('div');
+ host.style.cssText = 'height:320px;width:480px;';
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(async () => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={new QueryClient()}>
+ <DndContext>
+ <PreviewWidgetView instance={instance} manifest={manifest} region="center" runtime={runtime} />
+ </DndContext>
+ </QueryClientProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ await Promise.resolve();
+ });
+};
+
+const getBoundary = (): HTMLElement => {
+ const boundary = host?.querySelector<HTMLElement>('[tabindex="0"]');
+
+ if (!boundary) {
+ throw new Error('Expected the preview keyboard boundary to be rendered.');
+ }
+
+ return boundary;
+};
+
+const pressArrow = async (key: 'ArrowLeft' | 'ArrowRight') => {
+ await act(async () => {
+ getBoundary().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key }));
+ await Promise.resolve();
+ });
+};
+
+beforeEach(() => {
+ mocks.commands.account.updateProjectPreferences.mockClear();
+ mocks.commands.gallery.selectImage.mockClear();
+ mocks.project.queue.items = [];
+ mocks.project.settings.showProgressImagesInViewer = false;
+ delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).compareImage;
+ delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).imageOrderDir;
+ mocks.project.widgetInstances.gallery.state.values.recentImages = mocks.recentImages;
+ mocks.project.widgetInstances.gallery.state.values.selectedImage = {
+ ...mocks.recentImages[0],
+ boardId: 'none',
+ };
+ mocks.project.widgetInstances.gallery.state.values.selectedImageName = 'newest';
+ mocks.useActiveProgressTarget.mockReturnValue(null);
+ mocks.useProgressImage.mockReturnValue(null);
+});
+
+afterEach(async () => {
+ await act(async () => {
+ root?.unmount();
+ await Promise.resolve();
+ });
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('preview keyboard navigation boundary', () => {
+ it('handles one arrow press as exactly one selection and stops propagation', async () => {
+ const documentKeydown = vi.fn();
+ document.addEventListener('keydown', documentKeydown);
+
+ try {
+ await render();
+ await pressArrow('ArrowRight');
+
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(expect.objectContaining({ imageName: 'oldest' }));
+ expect(documentKeydown).not.toHaveBeenCalled();
+ } finally {
+ document.removeEventListener('keydown', documentKeydown);
+ }
+ });
+
+ it('enables live-follow when stepping onto the active placeholder', async () => {
+ mocks.project.queue.items = [queueItem];
+ mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });
+ mocks.useProgressImage.mockReturnValue({
+ dataUrl: 'data:image/png;base64,',
+ height: 64,
+ target: { itemIndex: 1, queueItemId: 'queue-item-live' },
+ width: 64,
+ });
+
+ await render();
+ // Descending order: the live placeholder occupies the newest position, so
+ // ArrowLeft from the newest image steps onto it.
+ await pressArrow('ArrowLeft');
+
+ expect(mocks.commands.account.updateProjectPreferences).toHaveBeenCalledTimes(1);
+ expect(mocks.commands.account.updateProjectPreferences).toHaveBeenCalledWith({
+ showProgressImagesInViewer: true,
+ });
+ expect(mocks.commands.gallery.selectImage).not.toHaveBeenCalled();
+ });
+
+ it('keeps arrow navigation working while following live', async () => {
+ mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2, 3], completedBackendItemIds: [1, 2] }];
+ mocks.project.settings.showProgressImagesInViewer = true;
+ mocks.project.widgetInstances.gallery.state.values.recentImages = mocks.recentImages.map((image) => ({
+ ...image,
+ sourceQueueItemId: 'queue-item-live',
+ }));
+ mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 3, queueItemId: 'queue-item-live' });
+ mocks.useProgressImage.mockReturnValue({
+ dataUrl: 'data:image/png;base64,',
+ height: 64,
+ target: { itemIndex: 3, queueItemId: 'queue-item-live' },
+ width: 64,
+ });
+
+ await render();
+ // While following live the cursor sits on the placeholder; ArrowRight
+ // steps back onto the newest completed image.
+ await pressArrow('ArrowRight');
+
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledTimes(1);
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(expect.objectContaining({ imageName: 'newest' }));
+ });
+
+ it('uses the active placeholder board while following live, even before an image frame arrives', async () => {
+ const liveBoardImage = {
+ ...mocks.project.widgetInstances.gallery.state.values.recentImages[0],
+ boardId: 'board-live',
+ imageName: 'live-board-image',
+ imageUrl: '/images/live-board-image/full',
+ sourceQueueItemId: 'queue-item-live',
+ starred: false,
+ thumbnailUrl: '/images/live-board-image/thumbnail',
+ };
+ mocks.project.widgetInstances.gallery.state.values.recentImages = [...mocks.recentImages, liveBoardImage];
+ mocks.project.queue.items = [{ ...queueItem, snapshot: { ...queueItem.snapshot, galleryBoardId: 'board-live' } }];
+ mocks.project.settings.showProgressImagesInViewer = true;
+ mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });
+
+ await render();
+ await pressArrow('ArrowRight');
+
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(
+ expect.objectContaining({ boardId: 'board-live', imageName: 'live-board-image' })
+ );
+ });
+
+ it('orders local images oldest-first when the gallery is ascending', async () => {
+ (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).imageOrderDir = 'ASC';
+
+ await render();
+ await pressArrow('ArrowLeft');
+
+ expect(mocks.commands.gallery.selectImage).toHaveBeenCalledWith(expect.objectContaining({ imageName: 'oldest' }));
+ });
+
+ it('does not consume arrow keys in comparison mode', async () => {
+ (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).compareImage = {
+ ...mocks.project.widgetInstances.gallery.state.values.recentImages[1],
+ };
+ const documentKeydown = vi.fn();
+ document.addEventListener('keydown', documentKeydown);
+
+ try {
+ await render();
+ await pressArrow('ArrowRight');
+
+ expect(mocks.commands.gallery.selectImage).not.toHaveBeenCalled();
+ expect(documentKeydown).toHaveBeenCalledTimes(1);
+ } finally {
+ document.removeEventListener('keydown', documentKeydown);
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
index 3b7fc953c1..a690b34009 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts
@@ -1,18 +1,14 @@
import { describe, expect, it } from 'vitest';
-import { getMatchingProgressImage, getPreviewBoardsRequestKey } from './PreviewWidgetView';
+import { getMatchingProgressImage, getPreviewBoardsRequestKey, mergePreviewBoardImages } from './PreviewWidgetView';
describe('getPreviewBoardsRequestKey', () => {
it('requests boards for local generated images, not only backend gallery images', () => {
- expect(
- getPreviewBoardsRequestKey({ hasSelectedImage: true, isBackendImage: false, refreshToken: 'refresh-1' })
- ).toBe('refresh-1');
+ expect(getPreviewBoardsRequestKey({ hasSelectedImage: true, refreshToken: 'refresh-1' })).toBe('refresh-1');
});
it('does not request boards without a selected image', () => {
- expect(
- getPreviewBoardsRequestKey({ hasSelectedImage: false, isBackendImage: false, refreshToken: 'refresh-1' })
- ).toBeNull();
+ expect(getPreviewBoardsRequestKey({ hasSelectedImage: false, refreshToken: 'refresh-1' })).toBeNull();
});
});
@@ -42,3 +38,41 @@ describe('getMatchingProgressImage', () => {
).toBeNull();
});
});
+
+describe('mergePreviewBoardImages', () => {
+ const image = (imageName: string, queuedAt: string, starred = false) => ({
+ height: 64,
+ imageName,
+ imageUrl: `/images/${imageName}`,
+ queuedAt,
+ sourceQueueItemId: 'queue-1',
+ starred,
+ thumbnailUrl: `/images/${imageName}/thumbnail`,
+ width: 64,
+ });
+
+ it('deduplicates and chronologically merges optimistic images in either direction', () => {
+ const oldest = image('oldest', '2026-07-21T00:00:01.000Z');
+ const middle = image('middle', '2026-07-21T00:00:02.000Z');
+ const newest = image('newest', '2026-07-21T00:00:03.000Z');
+
+ expect(mergePreviewBoardImages([newest, oldest], [middle, newest], 'DESC', false)).toEqual([
+ newest,
+ middle,
+ oldest,
+ ]);
+ expect(mergePreviewBoardImages([oldest, newest], [middle, oldest], 'ASC', false)).toEqual([oldest, middle, newest]);
+ });
+
+ it('keeps starred backend images ahead of optimistic unstarred images', () => {
+ const starred = image('starred', '2026-07-21T00:00:01.000Z', true);
+ const optimistic = image('optimistic', '2026-07-21T00:00:03.000Z');
+ const existing = image('existing', '2026-07-21T00:00:02.000Z');
+
+ expect(mergePreviewBoardImages([starred, existing], [optimistic], 'DESC', true)).toEqual([
+ starred,
+ optimistic,
+ existing,
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
index 2864d211d3..74f624236d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx
@@ -1,3 +1,4 @@
+import type { QueueItem } from '@features/queue/contracts';
import type { WidgetViewProps } from '@workbench/widgetContracts';
import { Box, Stack, Text } from '@chakra-ui/react';
@@ -16,11 +17,12 @@ import {
getGalleryRecentImagesKey,
getGalleryRefreshToken,
getGallerySettings,
+ normalizeGalleryImage,
type GalleryQueuePlaceholder,
} from '@features/gallery/contracts';
import { galleryBoardsOptions, galleryImagesOptions } from '@features/gallery/queries';
import { createGenerateFormValuesSelector } from '@features/generation/react';
-import { useProgressImage, type LatestProgressImageSnapshot } from '@features/queue/react';
+import { useActiveProgressTarget, useProgressImage, type LatestProgressImageSnapshot } from '@features/queue/react';
import {
imageUrlToStreamingSource,
progressImageToStreamingSource,
@@ -52,6 +54,11 @@ import { PreviewFilmstrip } from './PreviewFilmstrip';
import { PreviewFooter } from './PreviewFooter';
import { PreviewFrame } from './PreviewFrame';
import { previewHeaderStore } from './previewHeaderStore';
+import {
+ getPreviewNavigationCursor,
+ getPreviewNavigationSequence,
+ getPreviewNavigationTarget,
+} from './previewNavigation';
import {
getPreviewComparisonMode,
getPreviewFilmstripVisible,
@@ -66,17 +73,20 @@ const fallbackBoards: GalleryBoard[] = [
{ archived: false, assetCount: 0, id: 'none', imageCount: 0, kind: 'uncategorized', name: 'Uncategorized' },
];
-const getGalleryImages = (values: Record<string, unknown>): PreviewImage[] =>
+const getGalleryImages = (values: Record<string, unknown>, queueItems: QueueItem[]): PreviewImage[] =>
Array.isArray(values.recentImages)
- ? (values.recentImages as GeneratedImageContract[]).map((image) => ({
- ...image,
- boardId: 'none',
- imageCategory: 'general' as const,
- }))
+ ? (() => {
+ const queueBoardIds = new Map(
+ queueItems.map((item) => [item.id, item.snapshot.galleryBoardId ?? 'none'] as const)
+ );
+
+ return (values.recentImages as Array<GeneratedImageContract & Partial<GalleryImage>>).map((image) =>
+ normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId))
+ );
+ })()
: [];
-const getSelectedImage = (values: Record<string, unknown>): PreviewImage | null => {
- const images = getGalleryImages(values);
+const getSelectedImage = (values: Record<string, unknown>, localImages: PreviewImage[]): PreviewImage | null => {
const selectedImage = values.selectedImage;
const selectedImageName = typeof values.selectedImageName === 'string' ? values.selectedImageName : null;
@@ -85,10 +95,73 @@ const getSelectedImage = (values: Record<string, unknown>): PreviewImage | null
typeof selectedImage === 'object' &&
typeof (selectedImage as GeneratedImageContract).imageName === 'string'
) {
- return selectedImage as PreviewImage;
+ const image = selectedImage as PreviewImage;
+
+ return typeof image.boardId === 'string'
+ ? image
+ : (localImages.find((candidate) => candidate.imageName === image.imageName) ?? image);
+ }
+
+ return localImages.find((image) => image.imageName === selectedImageName) ?? localImages[0] ?? null;
+};
+
+const getOrderedPreviewImages = (
+ images: PreviewImage[],
+ imageOrderDir: 'ASC' | 'DESC',
+ starredFirst: boolean,
+ inputOrder: 'display' | 'newest-first'
+): PreviewImage[] =>
+ images
+ .map((image, index) => ({ image, index }))
+ .sort((a, b) => {
+ if (starredFirst && Boolean(a.image.starred) !== Boolean(b.image.starred)) {
+ return a.image.starred ? -1 : 1;
+ }
+
+ const chronological = a.image.queuedAt.localeCompare(b.image.queuedAt);
+
+ if (chronological !== 0) {
+ return imageOrderDir === 'DESC' ? -chronological : chronological;
+ }
+
+ return inputOrder === 'newest-first' && imageOrderDir === 'ASC' ? b.index - a.index : a.index - b.index;
+ })
+ .map(({ image }) => image);
+
+const getOrderedLocalImages = ({
+ boardId,
+ galleryView,
+ images,
+ imageOrderDir,
+ starredFirst,
+}: {
+ boardId: string;
+ galleryView: GalleryView;
+ images: PreviewImage[];
+ imageOrderDir: 'ASC' | 'DESC';
+ starredFirst: boolean;
+}): PreviewImage[] =>
+ getOrderedPreviewImages(
+ images.filter((image) => getImageBoardId(image) === boardId && getImageGalleryView(image) === galleryView),
+ imageOrderDir,
+ starredFirst,
+ 'newest-first'
+ );
+
+export const mergePreviewBoardImages = (
+ backendImages: PreviewImage[],
+ localImages: PreviewImage[],
+ imageOrderDir: 'ASC' | 'DESC',
+ starredFirst: boolean
+): PreviewImage[] => {
+ const backendNames = new Set(backendImages.map((image) => image.imageName));
+ const missingLocalImages = localImages.filter((image) => !backendNames.has(image.imageName));
+
+ if (missingLocalImages.length === 0) {
+ return backendImages;
}
- return images.find((image) => image.imageName === selectedImageName) ?? images[0] ?? null;
+ return getOrderedPreviewImages([...backendImages, ...missingLocalImages], imageOrderDir, starredFirst, 'display');
};
/**
@@ -128,14 +201,11 @@ const getBoardName = (
): string =>
boardId === 'none' ? uncategorizedLabel : (boards.find((board) => board.id === boardId)?.name ?? unknownBoardLabel);
-const shouldLoadBackendBoard = (image: PreviewImage): boolean => image.sourceQueueItemId === 'backend-gallery';
-
export const getPreviewBoardsRequestKey = ({
hasSelectedImage,
refreshToken,
}: {
hasSelectedImage: boolean;
- isBackendImage: boolean;
refreshToken: string;
}): string | null => (hasSelectedImage ? refreshToken : null);
@@ -166,19 +236,31 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
(project) => project.settings
);
const progressImage = useProgressImage();
- const { gallery, notifications, widgets } = useWorkbenchCommands();
+ const activeProgressTarget = useActiveProgressTarget();
+ const { account, gallery, notifications, widgets } = useWorkbenchCommands();
const { density, rootRef } = usePreviewDensity(region);
- const selectedImage = useMemo(() => getSelectedImage(galleryValues), [galleryValues]);
+ const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : null;
+ const localImages = useMemo(() => getGalleryImages({ recentImages }, queueItems), [queueItems, recentImages]);
+ const selectedImage = useMemo(() => getSelectedImage(galleryValues, localImages), [galleryValues, localImages]);
const compareImage = getGalleryCompareImage(galleryValues);
const comparisonMode = getPreviewComparisonMode(previewValues);
- const recentImages = Array.isArray(galleryValues.recentImages) ? galleryValues.recentImages : null;
- const localImages = useMemo(() => getGalleryImages({ recentImages }), [recentImages]);
const imageBoardId = selectedImage ? getImageBoardId(selectedImage) : 'none';
const displayBoardId = selectedImage ? getDisplayBoardId(selectedImage, galleryValues) : 'none';
const selectedGalleryView = selectedImage ? getImageGalleryView(selectedImage) : 'images';
const hasSelectedImage = selectedImage !== null;
- const isBackendImage = selectedImage ? shouldLoadBackendBoard(selectedImage) : false;
const { imageOrderDir, starredFirst } = getGallerySettings(galleryValues);
+ const selectedImageName = selectedImage?.imageName ?? null;
+ const isComparing =
+ selectedImage !== null && compareImage !== null && compareImage.imageName !== selectedImage.imageName;
+ const activeGalleryPlaceholder = useMemo(
+ () => getGalleryGenerationSequence(queueItems, activeProgressTarget).liveSlot,
+ [activeProgressTarget, queueItems]
+ );
+ const matchingProgressImage = getMatchingProgressImage(progressImage, activeGalleryPlaceholder);
+ const shouldFollowLive = showProgressImagesInViewer && activeGalleryPlaceholder !== null && !isComparing;
+ const navigationBoardId = shouldFollowLive ? activeGalleryPlaceholder.boardId : imageBoardId;
+ const navigationGalleryView = shouldFollowLive ? 'images' : selectedGalleryView;
+ const hasNavigationContext = shouldFollowLive || hasSelectedImage;
const boardRefreshToken = getGalleryRefreshToken(galleryValues);
const imageRefreshToken = getGalleryImagesRefreshToken(galleryValues);
const recentImagesKey = getGalleryRecentImagesKey(galleryValues);
@@ -187,55 +269,130 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
const boardsRequestKey = getPreviewBoardsRequestKey({
hasSelectedImage,
- isBackendImage,
refreshToken: boardRefreshToken,
});
- const boardImagesRequestKey = `${imageBoardId}:${selectedGalleryView}:${imageOrderDir}:${starredFirst}:${imageRefreshToken}:${recentImagesKey}`;
+ const boardImagesRequestKey = `${navigationBoardId}:${navigationGalleryView}:${imageOrderDir}:${starredFirst}:${imageRefreshToken}:${recentImagesKey}`;
const boardsQuery = useQuery({
...galleryBoardsOptions({ revision: boardsRequestKey ?? undefined }),
enabled: boardsRequestKey !== null,
});
const boardImagesQuery = useQuery({
...galleryImagesOptions({
- boardId: imageBoardId,
- galleryView: selectedGalleryView,
+ boardId: navigationBoardId,
+ galleryView: navigationGalleryView,
orderDir: imageOrderDir,
revision: boardImagesRequestKey,
searchTerm: '',
starredFirst,
}),
- enabled: hasSelectedImage && isBackendImage,
+ enabled: hasNavigationContext,
});
const boards = boardsQuery.data ?? fallbackBoards;
- const boardImages = !hasSelectedImage
- ? EMPTY_PREVIEW_IMAGES
- : !isBackendImage
- ? localImages
- : (boardImagesQuery.data?.images ?? EMPTY_PREVIEW_IMAGES);
- const isLoadingBoard = isBackendImage && boardImagesQuery.isFetching;
- const selectedIndex = selectedImage
- ? boardImages.findIndex((image) => image.imageName === selectedImage.imageName)
- : -1;
+ const optimisticQueueItemIds = useMemo(
+ () =>
+ new Set(
+ queueItems.filter((item) => item.status === 'pending' || item.status === 'running').map((item) => item.id)
+ ),
+ [queueItems]
+ );
+ const navigationLocalImages = useMemo(() => {
+ const refreshingSelectedSourceId =
+ !shouldFollowLive && boardImagesQuery.isFetching ? selectedImage?.sourceQueueItemId : null;
+
+ return localImages.filter(
+ (image) =>
+ optimisticQueueItemIds.has(image.sourceQueueItemId) || image.sourceQueueItemId === refreshingSelectedSourceId
+ );
+ }, [
+ boardImagesQuery.isFetching,
+ localImages,
+ optimisticQueueItemIds,
+ selectedImage?.sourceQueueItemId,
+ shouldFollowLive,
+ ]);
+ const localBoardImages = useMemo(
+ () =>
+ getOrderedLocalImages({
+ boardId: navigationBoardId,
+ galleryView: navigationGalleryView,
+ images: navigationLocalImages,
+ imageOrderDir,
+ starredFirst,
+ }),
+ [imageOrderDir, navigationBoardId, navigationGalleryView, navigationLocalImages, starredFirst]
+ );
+ const backendBoardImages = boardImagesQuery.data?.images ?? EMPTY_PREVIEW_IMAGES;
+ const boardImages = useMemo(
+ () =>
+ !hasNavigationContext
+ ? EMPTY_PREVIEW_IMAGES
+ : mergePreviewBoardImages(backendBoardImages, localBoardImages, imageOrderDir, starredFirst),
+ [backendBoardImages, hasNavigationContext, imageOrderDir, localBoardImages, starredFirst]
+ );
+ const isLoadingBoard = hasNavigationContext && boardImagesQuery.isFetching;
const boardName = getBoardName(
boards,
displayBoardId,
t('widgets.gallery.uncategorized'),
t('widgets.gallery.unknownBoard')
);
+ const navigationSequence = useMemo(
+ () =>
+ getPreviewNavigationSequence({
+ activePlaceholder: activeGalleryPlaceholder,
+ boardId: navigationBoardId,
+ boardImages,
+ galleryView: navigationGalleryView,
+ imageOrderDir,
+ starredFirst,
+ }),
+ [activeGalleryPlaceholder, boardImages, imageOrderDir, navigationBoardId, navigationGalleryView, starredFirst]
+ );
+ const navigationCursor = getPreviewNavigationCursor(navigationSequence, {
+ isFollowingLive: shouldFollowLive,
+ selectedImageName,
+ });
- const selectByOffset = useCallback(
+ // One navigation action shared by the arrow keys and the footer buttons.
+ // Compare mode stays inert and never exposes the placeholder.
+ const navigate = useCallback(
(offset: -1 | 1) => {
- if (selectedIndex === -1) {
+ if (isComparing) {
return;
}
- const nextImage = boardImages[selectedIndex + offset];
+ const target = getPreviewNavigationTarget(navigationSequence, navigationCursor, offset);
- if (nextImage) {
- gallery.selectImage(nextImage);
+ if (!target) {
+ return;
+ }
+
+ if (target.kind === 'image') {
+ gallery.selectImage(target.image);
+ } else {
+ account.updateProjectPreferences({ showProgressImagesInViewer: true });
+ }
+ },
+ [account, gallery, isComparing, navigationCursor, navigationSequence]
+ );
+
+ const handleNavigationKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') {
+ return;
+ }
+
+ if (isComparing) {
+ return;
}
+
+ // stopPropagation keeps the widget hotkey runtime from handling the same
+ // arrow press a second time.
+ event.preventDefault();
+ event.stopPropagation();
+ navigate(event.key === 'ArrowLeft' ? -1 : 1);
},
- [boardImages, gallery, selectedIndex]
+ [isComparing, navigate]
);
const [contextMenuTarget, setContextMenuTarget] = useState<ImageContextMenuTarget | null>(null);
@@ -288,14 +445,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
starred: boardImage?.starred ?? selectedImage.starred ?? false,
};
}, [boardImages, displayBoardId, selectedImage]);
- const isComparing =
- selectedImage !== null && compareImage !== null && compareImage.imageName !== selectedImage.imageName;
- const activeGalleryPlaceholder = useMemo(
- () => getGalleryGenerationSequence(queueItems, progressImage?.target ?? null).liveSlot,
- [progressImage?.target, queueItems]
- );
- const matchingProgressImage = getMatchingProgressImage(progressImage, activeGalleryPlaceholder);
- const shouldFollowLive = showProgressImagesInViewer && matchingProgressImage !== null && !isComparing;
const exitCompare = useCallback(() => gallery.setCompareImage(null), [gallery]);
const swapCompareImages = useCallback(() => {
if (selectedImage && compareImage) {
@@ -359,10 +508,9 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
},
[contextMenuImage]
);
- const selectNextImage = useCallback(() => selectByOffset(1), [selectByOffset]);
- const selectPreviousImage = useCallback(() => selectByOffset(-1), [selectByOffset]);
+ const selectNextImage = useCallback(() => navigate(1), [navigate]);
+ const selectPreviousImage = useCallback(() => navigate(-1), [navigate]);
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
@@ -381,10 +529,12 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
useEffect(() => () => previewHeaderStore.clear(), []);
- // Warm the browser cache for the board neighbors so arrow-key navigation
+ // Warm the browser cache for the sequence neighbors so arrow-key navigation
// swaps without a decode flash.
- const previousNeighborUrl = boardImages[selectedIndex - 1]?.imageUrl ?? null;
- const nextNeighborUrl = boardImages[selectedIndex + 1]?.imageUrl ?? null;
+ const previousNeighbor = navigationSequence[navigationCursor - 1];
+ const nextNeighbor = navigationSequence[navigationCursor + 1];
+ const previousNeighborUrl = previousNeighbor?.kind === 'image' ? previousNeighbor.image.imageUrl : null;
+ const nextNeighborUrl = nextNeighbor?.kind === 'image' ? nextNeighbor.image.imageUrl : null;
useEffect(() => {
[previousNeighborUrl, nextNeighborUrl].forEach((url) => {
@@ -446,53 +596,67 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {
return (
<Box ref={rootRef} p="2" h="full">
- {shouldFollowLive && activeGalleryPlaceholder && matchingProgressImage ? (
- <LivePreview
- placeholder={activeGalleryPlaceholder}
- progressImage={matchingProgressImage}
- shouldAntialiasProgressImage={antialiasProgressImages}
- />
- ) : selectedImage ? (
- <>
- {isComparing && compareImage ? (
- <PreviewCompare
- baseImage={selectedImage}
- compareImage={compareImage}
- mode={comparisonMode}
- runtime={runtime}
- onExit={exitCompare}
- onModeChange={setComparisonMode}
- onSwap={swapCompareImages}
- />
- ) : (
- <SelectedImagePreview
- actionImage={contextMenuImage}
+ {/* Single always-mounted keyboard boundary: DOM focus survives swaps
+ between the live, selected, and compare branches, so arrow
+ navigation keeps working across them. */}
+ <Stack
+ aria-label={t('widgets.labels.preview')}
+ gap="3"
+ h="full"
+ minH="0"
+ outline="none"
+ tabIndex={0}
+ w="full"
+ onKeyDown={handleNavigationKeyDown}
+ >
+ {shouldFollowLive && activeGalleryPlaceholder ? (
+ <LivePreview
+ placeholder={activeGalleryPlaceholder}
+ progressImage={matchingProgressImage}
+ shouldAntialiasProgressImage={antialiasProgressImages}
+ />
+ ) : selectedImage ? (
+ <>
+ {isComparing && compareImage ? (
+ <PreviewCompare
+ baseImage={selectedImage}
+ compareImage={compareImage}
+ mode={comparisonMode}
+ runtime={runtime}
+ onExit={exitCompare}
+ onModeChange={setComparisonMode}
+ onSwap={swapCompareImages}
+ />
+ ) : (
+ <SelectedImagePreview
+ actionImage={contextMenuImage}
+ actions={imageActions}
+ filmstripImages={isFilmstripVisible && density !== 'minimal' ? boardImages : null}
+ loupeControlsRef={loupeControlsRef}
+ boardImageCount={navigationSequence.length}
+ density={density}
+ image={selectedImage}
+ isLoadingBoard={isLoadingBoard}
+ isMetadataOpen={isMetadataOpen}
+ selectedIndex={navigationCursor}
+ onContextMenu={openImageContextMenu}
+ onNext={selectNextImage}
+ onPrevious={selectPreviousImage}
+ onSelectImage={selectImage}
+ onToggleMetadata={toggleMetadata}
+ />
+ )}
+ <ImageContextMenu
actions={imageActions}
- filmstripImages={isFilmstripVisible && density !== 'minimal' ? boardImages : null}
- loupeControlsRef={loupeControlsRef}
- boardImageCount={boardImages.length}
- density={density}
- image={selectedImage}
- isLoadingBoard={isLoadingBoard}
- isMetadataOpen={isMetadataOpen}
- selectedIndex={selectedIndex}
- onContextMenu={openImageContextMenu}
- onNext={selectNextImage}
- onPrevious={selectPreviousImage}
- onSelectImage={selectImage}
- onToggleMetadata={toggleMetadata}
+ boards={boards}
+ target={contextMenuTarget}
+ onClose={closeContextMenu}
/>
- )}
- <ImageContextMenu
- actions={imageActions}
- boards={boards}
- target={contextMenuTarget}
- onClose={closeContextMenu}
- />
- </>
- ) : (
- <EmptyPreview />
- )}
+ </>
+ ) : (
+ <EmptyPreview />
+ )}
+ </Stack>
</Box>
);
};
@@ -547,23 +711,8 @@ const SelectedImagePreview = ({
() => ({ boardId: actionImage?.boardId ?? 'none', imageName: image.imageName }),
[actionImage?.boardId, image.imageName]
);
- const handleKeyDown = useCallback(
- (event: KeyboardEvent<HTMLDivElement>) => {
- if (event.key === 'ArrowLeft') {
- event.preventDefault();
- onPrevious();
- }
-
- if (event.key === 'ArrowRight') {
- event.preventDefault();
- onNext();
- }
- },
- [onNext, onPrevious]
- );
-
return (
- <Stack gap="3" h="full" minH="0" outline="none" tabIndex={0} w="full" onKeyDown={handleKeyDown}>
+ <Stack gap="3" h="full" minH="0" w="full">
<PreviewFrame
dragImage={dragImage}
frameHeight={previewHeight}
@@ -608,7 +757,7 @@ const LivePreview = ({
shouldAntialiasProgressImage,
}: {
placeholder: GalleryQueuePlaceholder;
- progressImage: LatestProgressImageSnapshot;
+ progressImage: LatestProgressImageSnapshot | null;
shouldAntialiasProgressImage: boolean;
}) => {
const { t } = useTranslation();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts
new file mode 100644
index 0000000000..ebb81260e1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts
@@ -0,0 +1,136 @@
+import type { GalleryQueuePlaceholder } from '@features/gallery/contracts';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ getPreviewNavigationCursor,
+ getPreviewNavigationSequence,
+ getPreviewNavigationTarget,
+ type PreviewNavigationItem,
+} from './previewNavigation';
+
+interface TestImage {
+ imageName: string;
+ starred?: boolean;
+}
+
+const placeholder: GalleryQueuePlaceholder = {
+ boardId: 'none',
+ height: 1024,
+ id: 'queue-1:1',
+ itemIndex: 1,
+ queueItemId: 'queue-1',
+ width: 1024,
+};
+
+const image = (imageName: string, starred = false): TestImage => ({ imageName, starred });
+
+const names = (sequence: PreviewNavigationItem<TestImage>[]): string[] =>
+ sequence.map((item) => (item.kind === 'image' ? item.image.imageName : 'placeholder'));
+
+const buildSequence = (overrides: Partial<Parameters<typeof getPreviewNavigationSequence<TestImage>>[0]> = {}) =>
+ getPreviewNavigationSequence<TestImage>({
+ activePlaceholder: placeholder,
+ boardId: 'none',
+ boardImages: [image('newest'), image('middle'), image('oldest')],
+ galleryView: 'images',
+ imageOrderDir: 'DESC',
+ starredFirst: false,
+ ...overrides,
+ });
+
+describe('getPreviewNavigationSequence', () => {
+ it('places the placeholder at the newest position in descending order', () => {
+ expect(names(buildSequence())).toEqual(['placeholder', 'newest', 'middle', 'oldest']);
+ });
+
+ it('places the placeholder at the latest chronological position in ascending order', () => {
+ expect(names(buildSequence({ imageOrderDir: 'ASC' }))).toEqual(['newest', 'middle', 'oldest', 'placeholder']);
+ });
+
+ it('places the placeholder after the leading starred block when starred-first sorts descending', () => {
+ expect(
+ names(
+ buildSequence({
+ boardImages: [image('starred-a', true), image('starred-b', true), image('newest'), image('oldest')],
+ starredFirst: true,
+ })
+ )
+ ).toEqual(['starred-a', 'starred-b', 'placeholder', 'newest', 'oldest']);
+ });
+
+ it('places the placeholder last when every image is starred', () => {
+ expect(
+ names(buildSequence({ boardImages: [image('starred-a', true), image('starred-b', true)], starredFirst: true }))
+ ).toEqual(['starred-a', 'starred-b', 'placeholder']);
+ });
+
+ it('keeps the placeholder last in ascending order even with starred-first', () => {
+ expect(
+ names(
+ buildSequence({
+ boardImages: [image('starred-a', true), image('newest')],
+ imageOrderDir: 'ASC',
+ starredFirst: true,
+ })
+ )
+ ).toEqual(['starred-a', 'newest', 'placeholder']);
+ });
+
+ it('excludes the placeholder when it belongs to another board or the assets view', () => {
+ expect(names(buildSequence({ boardId: 'board-2' }))).toEqual(['newest', 'middle', 'oldest']);
+ expect(names(buildSequence({ galleryView: 'assets' }))).toEqual(['newest', 'middle', 'oldest']);
+ });
+
+ it('returns only images when there is no active placeholder', () => {
+ expect(names(buildSequence({ activePlaceholder: null }))).toEqual(['newest', 'middle', 'oldest']);
+ });
+});
+
+describe('getPreviewNavigationCursor', () => {
+ const sequence = buildSequence();
+
+ it('resolves to the placeholder while following live', () => {
+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: true, selectedImageName: 'middle' })).toBe(0);
+ });
+
+ it('resolves to the selected image otherwise', () => {
+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedImageName: 'middle' })).toBe(2);
+ });
+
+ it('is unresolved when the selected image is absent from the sequence', () => {
+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedImageName: 'missing' })).toBe(-1);
+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedImageName: null })).toBe(-1);
+ });
+});
+
+describe('getPreviewNavigationTarget', () => {
+ const sequence = buildSequence();
+
+ it('moves exactly one position in either direction', () => {
+ expect(getPreviewNavigationTarget(sequence, 2, -1)).toEqual({ image: image('newest'), kind: 'image' });
+ expect(getPreviewNavigationTarget(sequence, 2, 1)).toEqual({ image: image('oldest'), kind: 'image' });
+ });
+
+ it('steps between the newest image and the placeholder in descending order', () => {
+ expect(getPreviewNavigationTarget(sequence, 1, -1)).toEqual({ kind: 'placeholder', placeholder });
+ expect(getPreviewNavigationTarget(sequence, 0, 1)).toEqual({ image: image('newest'), kind: 'image' });
+ });
+
+ it('steps between the oldest image and the placeholder in ascending order', () => {
+ const ascending = buildSequence({ imageOrderDir: 'ASC' });
+
+ expect(getPreviewNavigationTarget(ascending, 2, 1)).toEqual({ kind: 'placeholder', placeholder });
+ expect(getPreviewNavigationTarget(ascending, 3, -1)).toEqual({ image: image('oldest'), kind: 'image' });
+ });
+
+ it('clamps at both sequence boundaries', () => {
+ expect(getPreviewNavigationTarget(sequence, 0, -1)).toBeNull();
+ expect(getPreviewNavigationTarget(sequence, sequence.length - 1, 1)).toBeNull();
+ });
+
+ it('is a no-op for an unresolved cursor', () => {
+ expect(getPreviewNavigationTarget(sequence, -1, -1)).toBeNull();
+ expect(getPreviewNavigationTarget(sequence, -1, 1)).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts
new file mode 100644
index 0000000000..c9c68aab97
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts
@@ -0,0 +1,76 @@
+import type { GalleryOrderDir, GalleryQueuePlaceholder, GalleryView } from '@features/gallery/contracts';
+
+import { getGalleryPlaceholderInsertionIndex } from '@features/gallery/contracts';
+
+/**
+ * Pure navigation model for the preview widget's left/right stepping.
+ *
+ * The sequence is the current board's completed images plus, at most, the one
+ * placeholder that is actively generating, placed where the gallery grid would
+ * show it. Gallery selection and the live-follow preference remain the sources
+ * of truth; the cursor is re-resolved from them on every render, never stored.
+ */
+
+interface NavigableImage {
+ imageName: string;
+ starred?: boolean;
+}
+
+export type PreviewNavigationItem<TImage extends NavigableImage> =
+ | { kind: 'image'; image: TImage }
+ | { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };
+
+export const getPreviewNavigationSequence = <TImage extends NavigableImage>({
+ activePlaceholder,
+ boardId,
+ boardImages,
+ galleryView,
+ imageOrderDir,
+ starredFirst,
+}: {
+ /** The live slot from getGalleryGenerationSequence, or null. */
+ activePlaceholder: GalleryQueuePlaceholder | null;
+ /** The board backing boardImages — the selected image's own board. */
+ boardId: string;
+ /** Board images in the gallery's display order. */
+ boardImages: TImage[];
+ galleryView: GalleryView;
+ imageOrderDir: GalleryOrderDir;
+ starredFirst: boolean;
+}): PreviewNavigationItem<TImage>[] => {
+ const items: PreviewNavigationItem<TImage>[] = boardImages.map((image) => ({ image, kind: 'image' }));
+ const includePlaceholder =
+ activePlaceholder !== null && galleryView === 'images' && activePlaceholder.boardId === boardId;
+
+ if (!includePlaceholder) {
+ return items;
+ }
+
+ items.splice(getGalleryPlaceholderInsertionIndex(boardImages, imageOrderDir, starredFirst), 0, {
+ kind: 'placeholder',
+ placeholder: activePlaceholder,
+ });
+
+ return items;
+};
+
+export const getPreviewNavigationCursor = <TImage extends NavigableImage>(
+ sequence: PreviewNavigationItem<TImage>[],
+ { isFollowingLive, selectedImageName }: { isFollowingLive: boolean; selectedImageName: string | null }
+): number => {
+ if (isFollowingLive) {
+ return sequence.findIndex((item) => item.kind === 'placeholder');
+ }
+
+ if (selectedImageName === null) {
+ return -1;
+ }
+
+ return sequence.findIndex((item) => item.kind === 'image' && item.image.imageName === selectedImageName);
+};
+
+export const getPreviewNavigationTarget = <TImage extends NavigableImage>(
+ sequence: PreviewNavigationItem<TImage>[],
+ cursorIndex: number,
+ offset: -1 | 1
+): PreviewNavigationItem<TImage> | null => (cursorIndex === -1 ? null : (sequence[cursorIndex + offset] ?? null));
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index af1c4dd6d1..deb021f2ec 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -1767,13 +1767,42 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const updatedProject = getActiveProject(state);
const galleryValues = getProjectWidgetValues(updatedProject, 'gallery');
+ const expectedImage = {
+ ...createImage('gallery-image.png', queueItem.id),
+ boardId: 'none',
+ imageCategory: 'general',
+ starred: false,
+ };
expect(updatedProject.canvas.stagingArea.pendingImages).toEqual([]);
- expect(galleryValues.recentImages).toEqual([createImage('gallery-image.png', queueItem.id)]);
- expect(galleryValues.selectedImage).toEqual(createImage('gallery-image.png', queueItem.id));
+ expect(galleryValues.recentImages).toEqual([expectedImage]);
+ expect(galleryValues.selectedImage).toEqual(expectedImage);
expect(galleryValues.selectedImageName).toBe('gallery-image.png');
});
+ it('preserves the destination board on freshly routed Gallery results', () => {
+ let state = primeGenerate();
+
+ state = workbenchReducer(state, { boardId: 'board-1', type: 'selectGalleryBoard' });
+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });
+ state = submitGenerate(state);
+
+ const project = getActiveProject(state);
+ const queueItem = project.queue.items[0];
+ const image = createImage('board-image.png', queueItem.id);
+ state = workbenchReducer(state, {
+ images: [image],
+ projectId: project.id,
+ queueItemId: queueItem.id,
+ type: 'routeQueueItemResults',
+ });
+
+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImage).toMatchObject({
+ boardId: 'board-1',
+ imageName: image.imageName,
+ });
+ });
+
it('appends Gallery destination results for local fallback while backend owns boards', () => {
let state = primeGenerate();
@@ -1953,6 +1982,25 @@ describe('workbenchReducer Phase 5 generation flow', () => {
expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('selected.png');
});
+ it('preserves a manually selected image when later Gallery results arrive', () => {
+ let state = primeGenerate();
+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });
+ state = submitGenerate(state);
+
+ const project = getActiveProject(state);
+ const queueItem = project.queue.items[0];
+ const selectedImage = createImage('selected.png', 'backend-gallery');
+ state = workbenchReducer(state, { image: selectedImage, type: 'selectGalleryImage' });
+ state = workbenchReducer(state, {
+ images: [createImage('completed.png', queueItem.id)],
+ projectId: project.id,
+ queueItemId: queueItem.id,
+ type: 'routeQueueItemResults',
+ });
+
+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(selectedImage.imageName);
+ });
+
it('pauses live-follow for saved Gallery multi-selection and comparison intents', () => {
const primaryImage = createImage('primary.png', 'gallery');
const compareImage = createImage('compare.png', 'gallery');
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index a0fa8a093d..642aa83bbe 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -1,4 +1,3 @@
-import type { GallerySettings, GeneratedImageContract } from '@features/gallery/contracts';
import type { GenerateWidgetValues } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
import type { QueueCompiledSubmission, QueueHistoryItemStatus } from '@features/queue/contracts';
@@ -41,6 +40,13 @@ import type {
WidgetTypeId,
} from '@workbench/widgetContracts';
+import {
+ normalizeGalleryImage,
+ type GalleryImage,
+ type GallerySettings,
+ type GeneratedImageContract,
+} from '@features/gallery/contracts';
+
import type { WorkbenchQueueItem as QueueItem } from './queueHistoryContracts';
import { createNewCanvasStateV2, migrateCanvasStateToV2 } from './canvasMigration';
@@ -1711,8 +1717,15 @@ const updateGalleryWithResultImages = (project: Project, images: GeneratedImageC
const galleryValues = getWidgetValues(project, 'gallery');
const previousImages = getGalleryImages(galleryValues);
const previousImageNames = new Set(previousImages.map((image) => image.imageName));
- const newImages = images.filter((image) => !previousImageNames.has(image.imageName));
- const nextSelectedImage = newImages.at(-1);
+ const queueBoardIds = new Map(
+ project.queue.items.map((item) => [item.id, item.snapshot.galleryBoardId ?? 'none'] as const)
+ );
+ const newImages: GalleryImage[] = images
+ .filter((image) => !previousImageNames.has(image.imageName))
+ .map((image) => normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId)));
+ const shouldSelectIncomingImage =
+ project.settings.showProgressImagesInViewer || typeof galleryValues.selectedImageName !== 'string';
+ const nextSelectedImage = shouldSelectIncomingImage ? newImages.at(-1) : undefined;
return updateProjectWidgetValues(project, 'gallery', () => ({
...galleryValues,