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
feat(gallery): share progress previews across boards
Josh Corbett85aa36630418
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex 4dd695b459..2a71877ec4 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -35,6 +35,8 @@ Platform State also owns reusable projections of broad external stores into refeThe queue pilot is the first migrated feature. Its private `QueueBackendPort` is the adapter seam; public callers use domain reads, commands, and production runtime factories from `@features/queue`. Private snake_case HTTP DTOs map explicitly to camelCase Queue read models before crossing that interface. TanStack Query owns the global backend queue read model, and non-React runtimes own reconciliation and realtime orchestration. Persisted per-project queue history remains in the Workbench aggregate.+Queue exposes board-independent active backend sessions, including preparation and result settlement. The Gallery progress section includes every unfinished batch slot, including queued work; Preview follows executing and settling sessions. Both use gallery-destination projections of the active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions do not participate in board counts, saved-image selection, or navigation. Saved outputs retain their actual backend board destinations; automatic result selection does not change the browsed board or its paging window.+Fonts owns its authenticated catalog, managed-library UI, and browser font-registration lifetime behind `@features/fonts`. App composes the session runtime; Canvas receives a font-resolution port and owns text geometry, rendering, and output readiness. Persisted text references and project-file remapping remain in Workbench. Launchpad font previews and Canvas share the same account lifetime; font binaries and browser registration names are not project state. The browser registry admits at most 64 faces and 128 MiB of font input data, including faces currently being parsed. Active references are protected from eviction; if they exhaust the budget, further loads fail until references are released. This bounds retained input, not browser-specific decoded font memory. Canvas reconciles active references only when the document forests or text draft source change.Font runtime composition and project-file option state travel in the existing shared route chunk. Catalog transport, the Fonts page, and project-file option dialogs load on demand. Missing-font recovery loads only for documents containing custom references. The locale asset plugin serves font-library strings as a separate namespace in development and production, loaded when the library or recovery UI opens; source translations remain in the canonical locale files. Text tool controls load when selected; their shared Canvas/Layer form and interaction dependencies remain grouped to avoid extra widget-activation requests. Catalog query keys have a lightweight public entry so invalidating an imported font does not pull the transport into startup.diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 0752c1a124..5498c69e47 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -469,7 +469,6 @@"source:src/features/fonts/launchpad.tsx","source:src/features/fonts/react.tsx","source:src/features/fonts/runtime.ts",- "source:src/features/gallery/contracts.ts","source:src/features/gallery/core/boardLabels.ts","source:src/features/gallery/core/image.ts","source:src/features/gallery/core/imagePaths.ts",@@ -597,6 +596,7 @@"source:src/features/nodes/index.ts","source:src/features/nodes/ui/NodesPage.tsx","source:src/features/queue/contracts.ts",+ "source:src/features/queue/core/activeSessions.ts","source:src/features/queue/core/deviceLabels.ts","source:src/features/queue/core/generationMeta.ts","source:src/features/queue/core/graphInputMedia.ts",@@ -1007,6 +1007,7 @@"source:src/workbench/widgets/layers/panes/editorPaneLayout.ts","source:src/workbench/widgets/manifests.ts","source:src/workbench/widgets/notifications/manifest.ts",+ "source:src/workbench/widgets/preview/livePreviewFollow.tsx","source:src/workbench/widgets/preview/manifest.ts","source:src/workbench/widgets/preview/previewSettings.ts","source:src/workbench/widgets/preview/settingsContribution.ts",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 4be31c74b9..6bf9d23c16 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -864,7 +864,6 @@"source:src/features/fonts/launchpad.tsx","source:src/features/fonts/react.tsx","source:src/features/fonts/runtime.ts",- "source:src/features/gallery/contracts.ts","source:src/features/gallery/core/boardLabels.ts","source:src/features/gallery/core/image.ts","source:src/features/gallery/core/imagePaths.ts",@@ -899,7 +898,7 @@"source:src/features/gallery/ui/GalleryItemSearch.tsx","source:src/features/gallery/ui/GalleryItemSortMenu.tsx","source:src/features/gallery/ui/GalleryLayout.tsx",- "source:src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx",+ "source:src/features/gallery/ui/GalleryProgressSection.tsx","source:src/features/gallery/ui/GallerySearchField.tsx","source:src/features/gallery/ui/GallerySelectionBar.tsx","source:src/features/gallery/ui/GallerySplitHandle.tsx",@@ -1098,6 +1097,7 @@"source:src/features/nodes/index.ts","source:src/features/nodes/ui/NodesPage.tsx","source:src/features/queue/contracts.ts",+ "source:src/features/queue/core/activeSessions.ts","source:src/features/queue/core/deviceLabels.ts","source:src/features/queue/core/generationMeta.ts","source:src/features/queue/core/graphInputMedia.ts",@@ -1512,7 +1512,6 @@"source:src/workbench/image-actions/imageRecall.ts","source:src/workbench/image-actions/index.ts","source:src/workbench/image-actions/recallParametersBridge.ts",- "source:src/workbench/image-actions/selectedImage.ts","source:src/workbench/image-actions/useDeletionConfirmation.tsx","source:src/workbench/image-actions/useFindGalleryItem.ts","source:src/workbench/image-actions/useImageActions.ts",@@ -1724,6 +1723,7 @@"source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx","source:src/workbench/widgets/preview/PreviewWidgetView.tsx","source:src/workbench/widgets/preview/implementation.ts",+ "source:src/workbench/widgets/preview/livePreviewFollow.tsx","source:src/workbench/widgets/preview/loupeGestures.ts","source:src/workbench/widgets/preview/manifest.ts","source:src/workbench/widgets/preview/previewCompareDnd.ts",@@ -1893,7 +1893,6 @@"source:src/features/fonts/launchpad.tsx","source:src/features/fonts/react.tsx","source:src/features/fonts/runtime.ts",- "source:src/features/gallery/contracts.ts","source:src/features/gallery/core/boardLabels.ts","source:src/features/gallery/core/image.ts","source:src/features/gallery/core/imagePaths.ts",@@ -1928,7 +1927,7 @@"source:src/features/gallery/ui/GalleryItemSearch.tsx","source:src/features/gallery/ui/GalleryItemSortMenu.tsx","source:src/features/gallery/ui/GalleryLayout.tsx",- "source:src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx",+ "source:src/features/gallery/ui/GalleryProgressSection.tsx","source:src/features/gallery/ui/GallerySearchField.tsx","source:src/features/gallery/ui/GallerySelectionBar.tsx","source:src/features/gallery/ui/GallerySplitHandle.tsx",@@ -2133,6 +2132,7 @@"source:src/features/nodes/index.ts","source:src/features/nodes/ui/NodesPage.tsx","source:src/features/queue/contracts.ts",+ "source:src/features/queue/core/activeSessions.ts","source:src/features/queue/core/deviceLabels.ts","source:src/features/queue/core/generationMeta.ts","source:src/features/queue/core/graphInputMedia.ts",@@ -2558,7 +2558,6 @@"source:src/workbench/image-actions/imageRecall.ts","source:src/workbench/image-actions/index.ts","source:src/workbench/image-actions/recallParametersBridge.ts",- "source:src/workbench/image-actions/selectedImage.ts","source:src/workbench/image-actions/useDeletionConfirmation.tsx","source:src/workbench/image-actions/useFindGalleryItem.ts","source:src/workbench/image-actions/useImageActions.ts",@@ -2912,6 +2911,7 @@"source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx","source:src/workbench/widgets/preview/PreviewWidgetView.tsx","source:src/workbench/widgets/preview/implementation.ts",+ "source:src/workbench/widgets/preview/livePreviewFollow.tsx","source:src/workbench/widgets/preview/loupeGestures.ts","source:src/workbench/widgets/preview/manifest.ts","source:src/workbench/widgets/preview/previewCompareDnd.ts",@@ -3092,7 +3092,6 @@"source:src/features/fonts/launchpad.tsx","source:src/features/fonts/react.tsx","source:src/features/fonts/runtime.ts",- "source:src/features/gallery/contracts.ts","source:src/features/gallery/core/boardLabels.ts","source:src/features/gallery/core/image.ts","source:src/features/gallery/core/imagePaths.ts",@@ -3127,7 +3126,7 @@"source:src/features/gallery/ui/GalleryItemSearch.tsx","source:src/features/gallery/ui/GalleryItemSortMenu.tsx","source:src/features/gallery/ui/GalleryLayout.tsx",- "source:src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx",+ "source:src/features/gallery/ui/GalleryProgressSection.tsx","source:src/features/gallery/ui/GallerySearchField.tsx","source:src/features/gallery/ui/GallerySelectionBar.tsx","source:src/features/gallery/ui/GallerySplitHandle.tsx",@@ -3326,6 +3325,7 @@"source:src/features/nodes/index.ts","source:src/features/nodes/ui/NodesPage.tsx","source:src/features/queue/contracts.ts",+ "source:src/features/queue/core/activeSessions.ts","source:src/features/queue/core/deviceLabels.ts","source:src/features/queue/core/generationMeta.ts","source:src/features/queue/core/graphInputMedia.ts",@@ -3807,7 +3807,6 @@"source:src/workbench/image-actions/imageRecall.ts","source:src/workbench/image-actions/index.ts","source:src/workbench/image-actions/recallParametersBridge.ts",- "source:src/workbench/image-actions/selectedImage.ts","source:src/workbench/image-actions/useDeletionConfirmation.tsx","source:src/workbench/image-actions/useFindGalleryItem.ts","source:src/workbench/image-actions/useImageActions.ts",@@ -4019,6 +4018,7 @@"source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx","source:src/workbench/widgets/preview/PreviewWidgetView.tsx","source:src/workbench/widgets/preview/implementation.ts",+ "source:src/workbench/widgets/preview/livePreviewFollow.tsx","source:src/workbench/widgets/preview/loupeGestures.ts","source:src/workbench/widgets/preview/manifest.ts","source:src/workbench/widgets/preview/previewCompareDnd.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex b2ae819f6f..c32fdba1e0 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2532,7 +2532,8 @@"videoRetry": "Retry","viewing": "Viewing","workflow": "Workflow",- "workflowJsonLabel": "Video workflow JSON"+ "workflowJsonLabel": "Video workflow JSON",+ "showAllActivePreviews": "Show all active previews"},"queue": {"allScopedItemsRequested": "All scoped queue items were requested.",@@ -3739,7 +3740,7 @@"settings": "Gallery settings","settingsGridSize": "Grid Size","settingsThumbnails": "Thumbnails",- "showPendingItems": "Show pending items",+ "showPendingItems": "Show in-progress section","sortBoardsAscending": "Sort boards ascending","sortBoardsBy": "Sort by","sortBoardsDescending": "Sort boards descending",@@ -3778,7 +3779,13 @@"backToBoardTop": "Back to top","windowLimit": "Showing the first {{count}} items. Narrow the search or switch to Pages to reach the rest.","windowLimitFrom": "Showing {{count}} items from item {{index}}. Narrow the search or switch to Pages to reach the rest.",- "boardOrder": "Board order"+ "boardOrder": "Board order",+ "inProgress": "In progress",+ "progressSession": "{{name}} · {{index}} of {{total}}",+ "progressQueued": "Queued",+ "progressPreparing": "Preparing",+ "progressSettling": "Finishing",+ "progressShared": "Active gallery runs across all boards"},"queueStatus": {"idle": "Queue idle",diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsxindex aece24120f..11403abd30 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx@@ -27,7 +27,15 @@ vi.mock('@features/gallery/react', () => ({return children;},}));-vi.mock('@features/queue/react', () => ({ useActiveProgressTarget: () => null }));+vi.mock('@workbench/widgets/preview/livePreviewFollow', () => ({+ useLivePreviewFollow: () => ({+ sessions: [],+ gallerySessions: [],+ pinnedSessionId: null,+ pin: vi.fn(),+ showAll: vi.fn(),+ }),+}));vi.mock('@workbench/projects/useProjectFileActions', () => ({ useExportLibraryProject: () => noop }));vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => noop }));vi.mock('./GalleryImageActionsBridge', () => ({diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsxindex 74d613d074..74b7bb97a5 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx@@ -20,7 +20,15 @@ vi.mock('@features/gallery/react', () => ({return children;},}));-vi.mock('@features/queue/react', () => ({ useActiveProgressTarget: () => null }));+vi.mock('@workbench/widgets/preview/livePreviewFollow', () => ({+ useLivePreviewFollow: () => ({+ sessions: [],+ gallerySessions: [],+ pinnedSessionId: null,+ pin: vi.fn(),+ showAll: vi.fn(),+ }),+}));vi.mock('@workbench/projects/useProjectFileActions', () => ({ useExportLibraryProject: () => noop }));vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => noop }));vi.mock('@workbench/WorkbenchContext', () => ({diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex aaa5d0516c..6aa5fa729c 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -2,11 +2,11 @@ import type { GalleryUiAdapter } from '@features/gallery/react';import type { ReactNode } from 'react';import { GalleryUiProvider } from '@features/gallery/react';-import { useActiveProgressTarget } from '@features/queue/react';import { useMountEffect } from '@platform/react/useMountEffect';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { useExportLibraryProject } from '@workbench/projects/useProjectFileActions';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import { useLivePreviewFollow } from '@workbench/widgets/preview/livePreviewFollow';import { getProjectWidgetInstance } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { lazy, useMemo } from 'react';@@ -25,24 +25,16 @@ const GalleryImageContextMenu = lazy(() =>* the Workbench aggregate. No second adapter is expected.*/export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode }) => {- const {- projectId,- projectName,- galleryValues,- generateValues,- queueItems,- antialiasProgressImages,- liveFollowEnabled,- } = useActiveProjectSelector((project) => ({- projectId: project.id,- projectName: project.name,- galleryValues: getProjectWidgetInstance(project, 'gallery')?.state?.values ?? EMPTY_WIDGET_VALUES,- generateValues: getProjectWidgetInstance(project, 'generate')?.state?.values ?? EMPTY_WIDGET_VALUES,- queueItems: project.queue.items,- antialiasProgressImages: project.settings.antialiasProgressImages,- liveFollowEnabled: project.settings.showProgressImagesInViewer,- }));- const liveProgressTarget = useActiveProgressTarget();+ const { projectId, projectName, galleryValues, generateValues, antialiasProgressImages, liveFollowEnabled } =+ useActiveProjectSelector((project) => ({+ projectId: project.id,+ projectName: project.name,+ galleryValues: getProjectWidgetInstance(project, 'gallery')?.state?.values ?? EMPTY_WIDGET_VALUES,+ generateValues: getProjectWidgetInstance(project, 'generate')?.state?.values ?? EMPTY_WIDGET_VALUES,+ antialiasProgressImages: project.settings.antialiasProgressImages,+ liveFollowEnabled: project.settings.showProgressImagesInViewer,+ }));+ const livePreview = useLivePreviewFollow();const { account, gallery, notifications, widgets } = useWorkbenchCommands();const queries = useWorkbenchQueries();const accountScope = captureAccountScope();@@ -57,9 +49,6 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })});const adapter = useMemo<GalleryUiAdapter>(() => ({- account: {- enableLiveFollow: () => account.updateProjectPreferences({ showProgressImagesInViewer: true }),- },antialiasProgressImages,exportProject,gallery: {@@ -75,11 +64,19 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })ItemActionsProvider: GalleryItemActionsAdapter,ImageContextMenu: GalleryImageContextMenu,liveFollowEnabled,- liveProgressTarget,+ progressSessions: livePreview.gallerySessions,+ pinnedProgressSessionId: livePreview.pinnedSessionId,+ followProgressSession: (sessionId) => {+ if (!isAccountScopeCurrent(accountScope) || !queries.isActiveProject(projectId)) {+ return;+ }+ account.updateProjectPreferences({ showProgressImagesInViewer: true });+ livePreview.pin(sessionId);+ openWorkbenchWidget('preview');+ },notifications,projectId,projectName,- queueItems,widgets: {openGallery: () => openWorkbenchWidget('gallery').ok,patchGalleryValues: (values) => widgets.patchValues('gallery', values),@@ -94,12 +91,11 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })galleryValues,generateValues,liveFollowEnabled,- liveProgressTarget,+ livePreview,notifications,openWorkbenchWidget,projectId,projectName,- queueItems,queries,widgets,]diff --git a/invokeai/frontend/webv2/src/app/workbenchPorts.test.tsx b/invokeai/frontend/webv2/src/app/workbenchPorts.test.tsxindex 0400fa3241..dbd0d5843c 100644--- a/invokeai/frontend/webv2/src/app/workbenchPorts.test.tsx+++ b/invokeai/frontend/webv2/src/app/workbenchPorts.test.tsx@@ -1,3 +1,4 @@+import { LivePreviewFollowProvider } from '@workbench/widgets/preview/livePreviewFollow';import { describe, expect, it } from 'vitest';import { GalleryUiAdapterProvider } from './GalleryUiAdapter';@@ -12,6 +13,7 @@ import { WorkflowUiAdapterProvider } from './WorkflowUiAdapter';describe('workbench UI port composition', () => {it('composes every feature adapter once in stable provider order', () => {expect(workbenchUiPortProviders).toEqual([+ LivePreviewFollowProvider,ModelsUiAdapterProvider,QueueUiAdapterProvider,GalleryUiAdapterProvider,diff --git a/invokeai/frontend/webv2/src/app/workbenchPorts.tsx b/invokeai/frontend/webv2/src/app/workbenchPorts.tsxindex 41a7e7b7f9..fc73cd76bf 100644--- a/invokeai/frontend/webv2/src/app/workbenchPorts.tsx+++ b/invokeai/frontend/webv2/src/app/workbenchPorts.tsx@@ -1,6 +1,7 @@import type { ProviderComponent } from '@platform/react/composeProviders';import { composeProviders } from '@platform/react/composeProviders';+import { LivePreviewFollowProvider } from '@workbench/widgets/preview/livePreviewFollow';import { GalleryUiAdapterProvider } from './GalleryUiAdapter';import { GenerationUiAdapterProvider } from './GenerationUiAdapter';@@ -11,6 +12,7 @@ import { VideoUiAdapterProvider } from './VideoUiAdapter';import { WorkflowUiAdapterProvider } from './WorkflowUiAdapter';export const workbenchUiPortProviders: ReadonlyArray<ProviderComponent> = [+ LivePreviewFollowProvider,ModelsUiAdapterProvider,QueueUiAdapterProvider,GalleryUiAdapterProvider,diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex e17dae3b2c..21e0890ad7 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -53,18 +53,11 @@ export {} from './core/settings';export {getGalleryCompareImage,- getGalleryCurrentItem,- getGalleryGenerationSequence,- getGalleryLiveSlots,getGalleryPage,getGallerySelectedImagePage,getGallerySelectedImageQuery,getGallerySemanticImageQuery,- getGalleryPlaceholderInsertionIndex,type GalleryCurrentItem,- type GalleryGenerationSequence,- type GalleryLiveTarget,- type GalleryQueuePlaceholder,type GallerySelectedImageQuery,} from './ui/galleryStateView';export {diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex 86958e21d7..1b04415c5b 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -38,6 +38,7 @@ export interface GallerySettings {*/showOtherProjectBoards: boolean;showPendingItems: boolean;+ progressSectionCollapsed: boolean;/** Disclosure of the starred strip at the top of the grid. */starredSectionCollapsed: boolean;thumbnailFit: GalleryThumbnailFit;@@ -58,6 +59,7 @@ export const DEFAULT_GALLERY_SETTINGS: GallerySettings = {showImageDimensions: false,showOtherProjectBoards: false,showPendingItems: true,+ progressSectionCollapsed: false,starredSectionCollapsed: false,thumbnailFit: 'square',};@@ -130,6 +132,7 @@ export const getGallerySettings = (values: Record<string, unknown>): GallerySetttypeof values.showPendingItems === 'boolean'? values.showPendingItems: DEFAULT_GALLERY_SETTINGS.showPendingItems,+ progressSectionCollapsed: values.progressSectionCollapsed === true,starredSectionCollapsed:typeof values.starredSectionCollapsed === 'boolean'? values.starredSectionCollapseddiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxindex 75a7c60b13..3d1b725e34 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -1,7 +1,9 @@/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-object-as-prop */import type { GalleryItem, GalleryItemRef } from '@features/gallery/contracts';import type { GalleryItemsFilter } from '@features/gallery/data/queries';+import type { QueueProgressSession } from '@features/queue/contracts';import type { StreamingImageSource } from '@platform/ui/streaming-image/streamingImageSource';+import type * as VirtualModule from 'react-hook-tanstack-virtual';import { Box, ChakraProvider } from '@chakra-ui/react';import {@@ -31,7 +33,7 @@ import { act, type ReactNode } 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';-import { userEvent } from 'vitest/browser';+import { page, userEvent } from 'vitest/browser';import type { GalleryStateView } from './galleryStateView';import type { GalleryActions, GalleryStarredStrip, GalleryWidgetContextValue } from './GalleryWidgetContext';@@ -42,6 +44,7 @@ import { GalleryWidgetContext } from './GalleryWidgetContext';import { EMPTY_GALLERY_STARRED_STRIP } from './useGalleryStarredStrip';const mocks = vi.hoisted(() => ({+ progressFrame: null as { dataUrl: string; width: number; height: number } | null,fetchNames: vi.fn(),measure: vi.fn(),scrollToIndex: vi.fn(),@@ -65,35 +68,45 @@ vi.mock('@features/gallery/data/queries', async (importOriginal) => ({}),}));-vi.mock('react-hook-tanstack-virtual', () => ({- useVirtualizer: (options: {- count: number;- estimateSize: (index: number) => number;- getScrollElement: () => Element | null;- overscan: number;- }) => {- mocks.virtualizerOptions.push(options);- const sizes = Array.from({ length: options.count }, (_, index) => options.estimateSize(index));- const starts = sizes.map((_, index) => sizes.slice(0, index).reduce((total, size) => total + size, 0));-- return {- measure: mocks.measure,- scrollToIndex: mocks.scrollToIndex,- totalSize: sizes.reduce((total, size) => total + size, 0),- virtualItems: Array.from({ length: options.count }, (_, index) => ({- end: (starts[index] ?? 0) + (sizes[index] ?? 0),- index,- key: index,- size: sizes[index] ?? 0,- start: starts[index] ?? 0,- })),- };- },-}));+vi.mock('react-hook-tanstack-virtual', async (importOriginal) => {+ const actual = await importOriginal<typeof VirtualModule>();+ return {+ useVirtualizer: (options: {+ count: number;+ horizontal?: boolean;+ scrollMargin?: number;+ estimateSize: (index: number) => number;+ getScrollElement: () => Element | null;+ overscan: number;+ }) => {+ if (options.overscan === 2) {+ return actual.useVirtualizer(options);+ }+ mocks.virtualizerOptions.push(options);+ const sizes = Array.from({ length: options.count }, (_, index) => options.estimateSize(index));+ const starts = sizes.map(+ (_, index) => (options.scrollMargin ?? 0) + sizes.slice(0, index).reduce((total, size) => total + size, 0)+ );++ return {+ measure: mocks.measure,+ scrollToIndex: mocks.scrollToIndex,+ totalSize: sizes.reduce((total, size) => total + size, 0),+ virtualItems: Array.from({ length: options.count }, (_, index) => ({+ end: (starts[index] ?? 0) + (sizes[index] ?? 0),+ index,+ key: index,+ size: sizes[index] ?? 0,+ start: starts[index] ?? 0,+ })),+ };+ },+ };+});vi.mock('@features/queue/react', () => ({- useQueueItemProgress: () => null,- useQueueItemProgressImage: () => null,+ useItemProgress: () => null,+ useQueueItemProgressImage: () => mocks.progressFrame,}));const i18n = createInstance();@@ -107,6 +120,12 @@ void i18n.use(initReactI18next).init({common: { generating: 'Generating' },widgets: {gallery: {+ inProgress: 'In progress',+ progressShared: 'Active gallery runs across all boards',+ progressPreparing: 'Preparing',+ progressQueued: 'Queued',+ progressSettling: 'Finishing',+ progressSession: '{{name}} · {{index}} of {{total}}',commands: {clearSelection: 'Clear selection',deleteSelection: 'Delete selection',@@ -228,7 +247,6 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateVisLoading: false,items,page: 0,- pendingPlaceholders: [],revealTargetPage: null,projectBoardId: null,searchTerm: '',@@ -320,11 +338,10 @@ const ContextMenuProbe = ({ target }: { target: CanonicalContextTarget }) => ();const NoopProvider = ({ children }: { children: ReactNode }) => children;-const createAdapter = (): GalleryUiAdapter =>+const createAdapter = (progressSessions: QueueProgressSession[]): GalleryUiAdapter =>({ItemActionsProvider: NoopProvider,ImageContextMenu: ContextMenuProbe,- account: { enableLiveFollow: noop },antialiasProgressImages: false,gallery: {clearSelection: noop,@@ -344,12 +361,13 @@ const createAdapter = (): GalleryUiAdapter =>},galleryValues: {},generateValues: {},- liveFollowEnabled: false,- liveProgressTarget: null,+ liveFollowEnabled: currentLiveFollowEnabled,+ progressSessions,+ pinnedProgressSessionId: null,+ followProgressSession,notifications: { add: noop, reportError: noop },projectId: 'project-1',projectName: 'Project',- queueItems: [],widgets: { openGallery: () => true, patchGalleryValues: noop },}) as unknown as GalleryUiAdapter;@@ -357,6 +375,9 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;let queryClient: QueryClient | null = null;let currentGallery = createGallery();+let currentLiveFollowEnabled = false;+let currentProgressSessions: QueueProgressSession[] = [];+const followProgressSession = vi.fn();let currentStrip: GalleryStarredStrip = EMPTY_GALLERY_STARRED_STRIP;let onDragStart = vi.fn();@@ -378,10 +399,12 @@ const Harness = ({background = 'bg',coMountPreviewSources = false,gallery,+ progressSessions,}: {background?: 'bg' | 'bg.panel';coMountPreviewSources?: boolean;gallery: GalleryStateView;+ progressSessions: QueueProgressSession[];}) => {const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),@@ -404,7 +427,7 @@ const Harness = ({<I18nextProvider i18n={i18n}><ChakraProvider value={system}><QueryClientProvider client={queryClient!}>- <GalleryUiProvider adapter={createAdapter()}>+ <GalleryUiProvider adapter={createAdapter(progressSessions)}><GalleryWidgetContext value={contextValue}><DndContext sensors={sensors}><DragMonitor />@@ -454,7 +477,14 @@ const renderGallery = async () => {currentGallery = gallery;await interact(() =>- root?.render(<Harness background={background} coMountPreviewSources={coMountPreviewSources} gallery={gallery} />)+ root?.render(+ <Harness+ progressSessions={currentProgressSessions}+ background={background}+ coMountPreviewSources={coMountPreviewSources}+ gallery={gallery}+ />+ ));};@@ -487,6 +517,9 @@ beforeEach(() => {vi.clearAllMocks();registeredCommands.clear();currentGallery = createGallery();+ currentProgressSessions = [];+ currentLiveFollowEnabled = false;+ mocks.progressFrame = null;currentStrip = EMPTY_GALLERY_STARRED_STRIP;queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });host = document.createElement('div');@@ -658,7 +691,7 @@ describe('GalleryImageGrid mixed item cells', () => {it('keeps showing the strip when every item on the board is starred', async () => {setStrip([starred]);- await renderGallery(createGallery({ items: [], pendingPlaceholders: [], settings: DENSE_SETTINGS }));+ await renderGallery(createGallery({ items: [], settings: DENSE_SETTINGS }));expect(getButton('Collapse starred items')).not.toBeNull();expect(host?.querySelector('button[aria-label="Select starred.png for preview"]')).not.toBeNull();@@ -1061,7 +1094,7 @@ describe('GalleryImageGrid upload drop zone', () => {});it('turns a true-empty, non-searching, non-virtual board into a click/drop upload target', async () => {- await renderGallery(createGallery({ items: [], pendingPlaceholders: [] }));+ await renderGallery(createGallery({ items: [] }));const target = host?.querySelector<HTMLElement>('[role="button"]');const input = host?.querySelector<HTMLInputElement>('input[type="file"]');@@ -1080,7 +1113,7 @@ describe('GalleryImageGrid upload drop zone', () => {});it('keeps the no-match message for a search with no results instead of the upload target', async () => {- await renderGallery(createGallery({ items: [], pendingPlaceholders: [], searchTerm: 'nope' }));+ await renderGallery(createGallery({ items: [], searchTerm: 'nope' }));expect(host?.textContent).toContain('No items');expect(host?.querySelector('[role="button"]')).toBeNull();@@ -1091,7 +1124,6 @@ describe('GalleryImageGrid upload drop zone', () => {createGallery({boards: [{ ...board, id: 'by_date:2026-07-30', kind: 'date' }],items: [],- pendingPlaceholders: [],selectedBoardId: 'by_date:2026-07-30',}));@@ -1099,23 +1131,23 @@ describe('GalleryImageGrid upload drop zone', () => {expect(host?.textContent).toContain('No items');expect(host?.querySelector('[role="button"]')).toBeNull();});+});+describe('GalleryImageGrid reveal requests', () => {it('reports the starred empty state instead of the upload target under the starred-only listing', async () => {- await renderGallery(createGallery({ items: [], pendingPlaceholders: [], starredOnly: true }));+ await renderGallery(createGallery({ items: [], starredOnly: true }));expect(host?.textContent).toContain('No starred items');expect(host?.querySelector('[role="button"]')).toBeNull();});it('keeps the loading message while an empty board is still loading', async () => {- await renderGallery(createGallery({ isLoading: true, items: [], pendingPlaceholders: [] }));+ await renderGallery(createGallery({ isLoading: true, items: [] }));expect(host?.textContent).toContain('Loading gallery');expect(host?.querySelector('[role="button"]')).toBeNull();});-});-describe('GalleryImageGrid reveal requests', () => {it('never scrolls on selection changes alone', async () => {// The selection also changes when a finished generation auto-selects its// image; scrolling on that would yank the grid out from under a browsing@@ -1362,3 +1394,143 @@ describe('GalleryImageGrid virtualization', () => {expect(host?.querySelector('[role="listitem"]')).toHaveStyle({ aspectRatio: '1 / 1' });});});++describe('shared gallery progress section', () => {+ const session: QueueProgressSession = {+ id: 'run:1',+ queueItemId: 'run',+ itemIndex: 1,+ backendItemId: 10,+ label: 'Workflow A',+ sourceId: 'workflow',+ width: 512,+ height: 768,+ itemCount: 1,+ state: 'running',+ };+ it('stays visible above empty and filtered boards and follows the clicked session', async () => {+ currentProgressSessions = [session];+ for (const boardState of [+ { selectedBoardId: 'board-other', items: [] },+ { searchTerm: 'unmatched', items: [] },+ { starredOnly: true, items: [] },+ { galleryView: 'assets' as const, items: [], isLoading: true },+ { page: 5, anchoredWindowPage: 5 },+ ]) {+ await renderGallery(createGallery(boardState));+ expect(host?.querySelector('button[title="Workflow A"]')).not.toBeNull();+ }+ await click(host!.querySelector<HTMLButtonElement>('button[title="Workflow A"]')!);+ expect(followProgressSession).toHaveBeenCalledWith('run:1');+ expect(host?.querySelectorAll('[role="listitem"]')).toHaveLength(currentGallery.items.length);+ });+ it('keeps the saved image selected while the queue only contains waiting slots', async () => {+ currentLiveFollowEnabled = true;+ currentProgressSessions = [{ ...session, state: 'queued' }];+ await renderGallery();+ const image = host!.querySelector<HTMLButtonElement>('[role="listitem"] button[aria-current="true"]');+ expect(image).not.toBeNull();+ expect(image!.getAttribute('aria-pressed')).toBe('true');+ });+ it('bounds mounted tiles for large batches and unmounts them when collapsed', async () => {+ currentProgressSessions = Array.from({ length: 1000 }, (_, index) => ({+ ...session,+ id: `run:${index + 1}`,+ itemCount: 1000,+ itemIndex: index + 1,+ state: 'queued',+ }));+ await renderGallery();+ const tiles = () => host!.querySelectorAll('[aria-label="In progress"] button[aria-pressed]');+ await expect.poll(() => tiles().length).toBeGreaterThan(0);+ expect(tiles().length).toBeLessThan(60);+ const contentId = host!.querySelector('[data-progress-disclosure]')!.getAttribute('aria-controls')!;+ const viewport = document.getElementById(contentId)!.closest<HTMLElement>('[data-part="viewport"]')!;+ await act(() => {+ viewport.scrollTop = viewport.scrollHeight;+ });+ await expect+ .poll(() => host!.querySelector('button[aria-label="Workflow A · 1000 of 1000 · Queued"]'))+ .not.toBeNull();+ expect(tiles().length).toBeLessThan(60);+ await renderGallery(createGallery({ settings: { ...DENSE_SETTINGS, progressSectionCollapsed: true } }));+ expect(tiles()).toHaveLength(0);+ });+ it('updates tile spacing when density changes without changing the batch', async () => {+ currentProgressSessions = [session, { ...session, id: 'run:2', itemIndex: 2 }];+ for (const imageDensityPercent of [100, 0, 100]) {+ await renderGallery(createGallery({ settings: { ...DENSE_SETTINGS, imageDensityPercent } }));+ await expect.poll(() => host!.querySelectorAll('[aria-label="In progress"] button[aria-pressed]').length).toBe(2);+ const tiles = host!.querySelectorAll<HTMLElement>('[aria-label="In progress"] button[aria-pressed]');+ expect(tiles[1]!.getBoundingClientRect().left - tiles[0]!.getBoundingClientRect().right).toBeCloseTo(4, 0);+ }+ });+ it('shows all three batch tiles while only the first is executing', async () => {+ host!.style.width = '320px';+ currentProgressSessions = [+ { ...session, itemCount: 3 },+ { ...session, id: 'run:2', itemIndex: 2, itemCount: 3, backendItemId: 11, state: 'queued' },+ { ...session, id: 'run:3', itemIndex: 3, itemCount: 3, backendItemId: 12, state: 'queued' },+ ];+ await renderGallery();+ const tiles = host!.querySelectorAll<HTMLButtonElement>('[aria-label="In progress"] button[aria-pressed]');+ expect(tiles).toHaveLength(3);+ expect(tiles[2]!.getBoundingClientRect().top).toBeGreaterThan(tiles[0]!.getBoundingClientRect().top);+ expect(tiles[2]!.getBoundingClientRect().left).toBeCloseTo(tiles[0]!.getBoundingClientRect().left, 0);+ expect(tiles[0]!.disabled).toBe(false);+ for (const tile of [tiles[1]!, tiles[2]!]) {+ expect(tile.disabled).toBe(true);+ expect(tile.textContent).toBe('');+ expect(tile.getAttribute('aria-label')).toContain('Queued');+ }+ });+ it('collapses independently and restores focus when the last session disappears', async () => {+ currentProgressSessions = [session];+ await renderGallery();+ await click(host!.querySelector<HTMLButtonElement>('[data-progress-disclosure]')!);+ expect(actionMocks.updateSettings).toHaveBeenCalledWith({ progressSectionCollapsed: true });+ await renderGallery(createGallery({ settings: { ...DENSE_SETTINGS, progressSectionCollapsed: true } }));+ expect(host?.querySelector('[data-progress-disclosure]')?.getAttribute('aria-expanded')).toBe('false');+ await renderGallery(createGallery());+ host!.querySelector<HTMLButtonElement>('button[title="Workflow A"]')!.focus();+ currentProgressSessions = [];+ mocks.progressFrame = null;+ await renderGallery();+ expect(host?.querySelector('[data-progress-disclosure]')).toBeNull();+ expect(host?.contains(document.activeElement)).toBe(true);+ });+ it('keeps concurrent progress separate from starred and saved items at narrow widths', async () => {+ await page.viewport(760, 580);+ const imageUrl = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96" fill="#587074"/><path d="M0 96L50 25L85 60L105 35L128 96" fill="#b7cbc8"/></svg>')}`;+ const items = ['Image A', 'Image B', 'Image C'].map((name) =>+ createItem('image', name, { fullUrl: imageUrl, thumbnailUrl: imageUrl })+ );+ mocks.progressFrame = { dataUrl: imageUrl, width: 128, height: 96 };+ currentProgressSessions = [+ session,+ { ...session, id: 'run:2', itemIndex: 2, backendItemId: 11, label: 'Workflow B' },+ { ...session, id: 'run:3', backendItemId: 12, label: 'A workflow with a long descriptive name' },+ ];+ setStrip([createItem('image', 'Starred image', { starred: true, fullUrl: imageUrl, thumbnailUrl: imageUrl })]);+ host!.style.width = '320px';+ await renderGallery(createGallery({ items }));+ expect(host!.scrollWidth).toBeLessThanOrEqual(host!.clientWidth);+ expect(host!.querySelectorAll('[aria-label="In progress"] button[aria-pressed]')).toHaveLength(3);+ for (const tile of host!.querySelectorAll<HTMLElement>('[aria-label="In progress"] button[aria-pressed]')) {+ expect(tile.textContent).toBe('');+ expect(tile.getBoundingClientRect().height).toBeCloseTo(tile.getBoundingClientRect().width, 0);+ expect(tile.getAttribute('aria-label')).toContain('Preparing');+ }+ await page.screenshot({ path: '../../../../artifacts/gallery-progress/narrow.png' });+ host!.style.width = '600px';+ await renderGallery(createGallery({ items }));+ await page.screenshot({ path: '../../../../artifacts/gallery-progress/wide.png' });+ });++ it('honors the existing hidden preference without changing board images', async () => {+ currentProgressSessions = [session];+ await renderGallery(createGallery({ settings: { ...DENSE_SETTINGS, showPendingItems: false } }));+ expect(host?.querySelector('[data-progress-disclosure]')).toBeNull();+ expect(host?.querySelectorAll('[role="listitem"]')).toHaveLength(currentGallery.items.length);+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex b8ff54cc12..a046274709 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -36,7 +36,7 @@ import {getGalleryGridRowHeightPx,getGalleryGridRowIndexForItem,} from './galleryGridLayout';-import { GalleryQueuePlaceholderCell } from './GalleryQueuePlaceholderCell';+import { GalleryProgressSection } from './GalleryProgressSection';import { GalleryThumbnailCell } from './GalleryThumbnail';import { useGalleryUi } from './GalleryUiContext';import { useGalleryWidget } from './GalleryWidgetContext';@@ -154,19 +154,13 @@ const GalleryStarredSectionHeader = ({export const GalleryImageGrid = () => {const { t } = useTranslation();const { actions, gallery, isWindowTruncated, itemActions, region, starredStrip } = useGalleryWidget();- const { account, antialiasProgressImages, gallery: galleryCommands, ImageContextMenu } = useGalleryUi();+ const { gallery: galleryCommands, ImageContextMenu, liveFollowEnabled, progressSessions } = useGalleryUi();const [isDropActive, setIsDropActive] = useState(false);const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(region) ?? 0);const dragDepthRef = useRef(0);const viewportRef = useRef<HTMLDivElement | null>(null);- const {- imageDensityPercent,- imageOrderDir,- paginationMode,- showImageDimensions,- starredSectionCollapsed,- thumbnailFit,- } = gallery.settings;+ const { imageDensityPercent, paginationMode, showImageDimensions, starredSectionCollapsed, thumbnailFit } =+ gallery.settings;const isStarredOpen = !starredSectionCollapsed;const {@@ -182,7 +176,7 @@ export const GalleryImageGrid = () => {} = useGalleryGridSelection();const columnCount = getGalleryColumnCount({ imageDensityPercent, widthPx: viewportWidth });- const isFollowingLive = gallery.currentItem?.kind === 'placeholder';+ const isFollowingLive = liveFollowEnabled && progressSessions.some((session) => session.state !== 'queued');const isComparisonActive = gallery.isComparisonActive;const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);const selectedBoardName = selectedBoard@@ -190,8 +184,7 @@ export const GalleryImageGrid = () => {: t('widgets.gallery.selectedBoardFallback');// The listing is unstarred-only, so a board whose items are all starred// still has the strip to show.- const isEmpty =- gallery.items.length === 0 && gallery.pendingPlaceholders.length === 0 && starredStrip.items.length === 0;+ const isEmpty = gallery.items.length === 0 && starredStrip.items.length === 0;const hasActiveSearch = gallery.searchTerm.trim() !== '';const isVirtualBoard = isDateBoardId(gallery.selectedBoardId);@@ -199,22 +192,12 @@ export const GalleryImageGrid = () => {() =>buildGalleryGridRows({columnCount,- imageOrderDir,isStarredOpen,items: gallery.items,- pendingPlaceholders: gallery.pendingPlaceholders,starredItems: starredStrip.items,starredTotal: starredStrip.total,}),- [- columnCount,- gallery.items,- gallery.pendingPlaceholders,- imageOrderDir,- isStarredOpen,- starredStrip.items,- starredStrip.total,- ]+ [columnCount, gallery.items, isStarredOpen, starredStrip.items, starredStrip.total]);const navigation = useMemo(() =>@@ -241,8 +224,16 @@ export const GalleryImageGrid = () => {const getRowKey = useCallback((index: number) => rows[index]?.key ?? index, [rows]);const getScrollElement = useCallback(() => viewportRef.current, []);+ const progressHeight =+ gallery.settings.showPendingItems && progressSessions.length > 0+ ? GALLERY_STARRED_HEADER_HEIGHT_PX ++ (gallery.settings.progressSectionCollapsed+ ? 0+ : Math.ceil(progressSessions.length / columnCount) * rowHeightPx + 8)+ : 0;const virtualizer = useVirtualizer({count: rowCount,+ scrollMargin: progressHeight,estimateSize: estimateRowSize,getItemKey: getRowKey,getScrollElement,@@ -386,7 +377,7 @@ export const GalleryImageGrid = () => {// layout effect keeps the stale frame from ever reaching the screen.useLayoutEffect(() => {measureVirtualizer();- }, [rowHeightPx, rows]);+ }, [rowHeightPx, rows, progressHeight]);const virtualRows = virtualizer.virtualItems;const lastVisibleRowIndex = virtualRows[virtualRows.length - 1]?.index ?? 0;@@ -452,10 +443,6 @@ export const GalleryImageGrid = () => {[openUploadPicker]);- const handleShowProgressImages = useCallback(() => {- account.enableLiveFollow();- }, [account]);-const handleToggleStarredSection = useCallback(() => actions.updateSettings({ starredSectionCollapsed: isStarredOpen }),[actions, isStarredOpen]@@ -483,198 +470,187 @@ export const GalleryImageGrid = () => {const anchoredWindowFirstItem = gallery.anchoredWindowPage * GALLERY_PAGE_SIZE + 1;return (- <Box- ref={syncRangeInteractionContext}- flex="1"- h="full"- maxW="full"- minH="0"- minW="0"- position="relative"- w="full"- onDragEnter={handleDragEnter}- onDragLeave={handleDragLeave}- onDragOver={handleDragOver}- onDrop={handleDrop}- >- {gallery.anchoredWindowPage > 0 ? (- <Flex align="center" bg="bg.panel" gap="2" justify="space-between" px="2" py="1">- <Text color="fg.muted" fontSize="2xs" truncate>- {t('widgets.gallery.windowAnchored', { index: anchoredWindowFirstItem })}- </Text>- <Button flexShrink={0} size="2xs" variant="ghost" onClick={handleReturnToBoardTop}>- {t('widgets.gallery.backToBoardTop')}- </Button>- </Flex>- ) : null}- {isEmpty ? (- gallery.isLoading || hasActiveSearch || isVirtualBoard || gallery.starredOnly ? (- <Flex align="center" color="fg.muted" h="full" justify="center" minH="8rem">- <Text fontSize="xs">- {gallery.isLoading- ? t('widgets.gallery.loadingBackendGallery')- : gallery.starredOnly && gallery.semanticImageQuery === null- ? t('widgets.gallery.noStarredItemsMatch')- : t('widgets.gallery.noImagesMatch')}+ <Stack flex="1" gap="0" h="full" minH="0" minW="0" w="full">+ <Box+ ref={syncRangeInteractionContext}+ flex="1"+ h="full"+ maxW="full"+ minH="0"+ minW="0"+ position="relative"+ w="full"+ onDragEnter={handleDragEnter}+ onDragLeave={handleDragLeave}+ onDragOver={handleDragOver}+ onDrop={handleDrop}+ >+ {gallery.anchoredWindowPage > 0 ? (+ <Flex align="center" bg="bg.panel" gap="2" justify="space-between" px="2" py="1">+ <Text color="fg.muted" fontSize="2xs" truncate>+ {t('widgets.gallery.windowAnchored', { index: anchoredWindowFirstItem })}</Text>+ <Button flexShrink={0} size="2xs" variant="ghost" onClick={handleReturnToBoardTop}>+ {t('widgets.gallery.backToBoardTop')}+ </Button></Flex>- ) : (- <Flex align="stretch" h="full" minH="8rem" p="2">- <input {...uploadInputProps} />- <DropZone- alignItems="center"- display="flex"- flex="1"- fontSize="xs"- isOver={isDropActive}- justifyContent="center"- role="button"- tabIndex={0}- onClick={openUploadPicker}- onKeyDown={handleUploadKeyDown}- >- <Stack align="center" gap="1">- <Icon as={UploadIcon} boxSize="4" color="fg.subtle" />- <Text color="fg.muted">{t('widgets.gallery.emptyBoardUploadHint')}</Text>- </Stack>- </DropZone>- </Flex>- )- ) : (+ ) : null}<ScrollArea.Root h="full" minH="0" size="xs" variant="hover" w="full"><ScrollArea.Viewport ref={viewportRef} h="full" outline="none" w="full">- <ScrollArea.Content>- <Box h={`${virtualizer.totalSize}px`} position="relative" w="full">- {virtualRows.map((virtualRow) => {- const row = rows[virtualRow.index];-- if (row?.kind === 'starred-header') {- return (- <GalleryStarredSectionHeader- key={virtualRow.key}- isOpen={isStarredOpen}- offsetPx={virtualRow.start}- shownCount={row.shownCount}- total={row.total}- onShowAll={handleShowAllStarred}- onToggle={handleToggleStarredSection}- />- );- }-- return row?.kind === 'starred-gap' && row.withSeparator ? (- <Flex- key={virtualRow.key}- aria-hidden="true"- data-gallery-starred-separator- align="center"- h={`${GALLERY_STARRED_SEPARATOR_HEIGHT_PX}px`}- left="0"- // The starred row above already carries its trailing grid- // gap; centering over the remaining height keeps the rule- // equidistant from both thumbnail edges.- pb={`${GALLERY_GRID_GAP_PX}px`}+ <ScrollArea.Content display="flex" flexDirection="column" minH="full">+ <GalleryProgressSection columns={columnCount} tileSize={cellSizePx} getScrollElement={getScrollElement} />+ {isEmpty ? (+ gallery.isLoading || hasActiveSearch || isVirtualBoard || gallery.starredOnly ? (+ <Flex align="center" color="fg.muted" flex="1" justify="center" minH="8rem">+ <Text fontSize="xs">+ {gallery.isLoading+ ? t('widgets.gallery.loadingBackendGallery')+ : gallery.starredOnly && gallery.semanticImageQuery === null+ ? t('widgets.gallery.noStarredItemsMatch')+ : t('widgets.gallery.noImagesMatch')}+ </Text>+ </Flex>+ ) : (+ <Flex align="stretch" flex="1" minH="8rem" p="2">+ <input {...uploadInputProps} />+ <DropZone+ alignItems="center"+ display="flex"+ flex="1"+ fontSize="xs"+ isOver={isDropActive}+ justifyContent="center"+ role="button"+ tabIndex={0}+ onClick={openUploadPicker}+ onKeyDown={handleUploadKeyDown}+ >+ <Stack align="center" gap="1">+ <Icon as={UploadIcon} boxSize="4" color="fg.subtle" />+ <Text color="fg.muted">{t('widgets.gallery.emptyBoardUploadHint')}</Text>+ </Stack>+ </DropZone>+ </Flex>+ )+ ) : (+ <>+ <Box h={`${virtualizer.totalSize}px`} position="relative" w="full">+ {virtualRows.map((virtualRow) => {+ const row = rows[virtualRow.index];++ if (row?.kind === 'starred-header') {+ return (+ <GalleryStarredSectionHeader+ key={virtualRow.key}+ isOpen={isStarredOpen}+ offsetPx={virtualRow.start - progressHeight}+ shownCount={row.shownCount}+ total={row.total}+ onShowAll={handleShowAllStarred}+ onToggle={handleToggleStarredSection}+ />+ );+ }++ return row?.kind === 'starred-gap' && row.withSeparator ? (+ <Flex+ key={virtualRow.key}+ aria-hidden="true"+ data-gallery-starred-separator+ align="center"+ h={`${GALLERY_STARRED_SEPARATOR_HEIGHT_PX}px`}+ left="0"+ // The starred row above already carries its trailing grid+ // gap; centering over the remaining height keeps the rule+ // equidistant from both thumbnail edges.+ pb={`${GALLERY_GRID_GAP_PX}px`}+ position="absolute"+ top="0"+ transform={`translateY(${virtualRow.start - progressHeight}px)`}+ w="full"+ >+ <Box bg="border.subtle" h="1px" w="full" />+ </Flex>+ ) : null;+ })}+ <Box+ aria-label={t('widgets.gallery.itemsAriaLabel')}+ h="full"+ inset="0"position="absolute"- top="0"- transform={`translateY(${virtualRow.start}px)`}+ role="list"w="full">- <Box bg="border.subtle" h="1px" w="full" />+ {virtualRows.map((virtualRow) => {+ const row = rows[virtualRow.index];++ if (!row || row.kind === 'starred-gap' || row.kind === 'starred-header') {+ return null;+ }++ return (+ <Box+ key={virtualRow.key}+ data-gallery-section={row.section}+ display="grid"+ gap={`${GALLERY_GRID_GAP_PX}px`}+ gridTemplateColumns={`repeat(${columnCount}, minmax(0, 1fr))`}+ left="0"+ position="absolute"+ role="presentation"+ top="0"+ transform={`translateY(${virtualRow.start - progressHeight}px)`}+ w="full"+ >+ {row.cells.map((cell) => {+ const itemKey = toGalleryItemKey(cell.item);++ return (+ <GalleryThumbnailCell+ key={itemKey}+ alwaysShowDimensions={showImageDimensions}+ dragScope={region}+ compareRole={+ isComparisonActive && itemKey === gallery.selectedItemKey+ ? t('widgets.preview.viewing')+ : isComparisonActive && itemKey === gallery.compareImageKey+ ? t('widgets.preview.compare')+ : null+ }+ fit={thumbnailFit}+ getDragItems={getDragItems}+ isPrimary={!isFollowingLive && itemKey === gallery.selectedItemKey}+ isSelected={!isFollowingLive && selectedItemKeys.has(itemKey)}+ item={cell.item}+ onClick={handleThumbnailClick}+ onContextMenu={handleThumbnailContextMenu}+ onToggleStarred={handleToggleStarred}+ />+ );+ })}+ </Box>+ );+ })}+ </Box>+ </Box>+ {paginationMode === 'infinite' && gallery.isLoading && gallery.items.length > 0 && (+ <Flex align="center" justify="center" py="2">+ <Spinner color="fg.subtle" size="xs" /></Flex>- ) : null;- })}- <Box- aria-label={t('widgets.gallery.itemsAriaLabel')}- h="full"- inset="0"- position="absolute"- role="list"- w="full"- >- {virtualRows.map((virtualRow) => {- const row = rows[virtualRow.index];-- if (!row || row.kind === 'starred-gap' || row.kind === 'starred-header') {- return null;- }-- return (- <Box- key={virtualRow.key}- data-gallery-section={row.section}- display="grid"- gap={`${GALLERY_GRID_GAP_PX}px`}- gridTemplateColumns={`repeat(${columnCount}, minmax(0, 1fr))`}- left="0"- position="absolute"- role="presentation"- top="0"- transform={`translateY(${virtualRow.start}px)`}- w="full"- >- {row.cells.map((cell) => {- if (cell.kind === 'placeholder') {- return (- <GalleryQueuePlaceholderCell- 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}- />- );- }-- const itemKey = toGalleryItemKey(cell.item);-- return (- <GalleryThumbnailCell- key={itemKey}- alwaysShowDimensions={showImageDimensions}- dragScope={region}- compareRole={- isComparisonActive && itemKey === gallery.selectedItemKey- ? t('widgets.preview.viewing')- : isComparisonActive && itemKey === gallery.compareImageKey- ? t('widgets.preview.compare')- : null- }- fit={thumbnailFit}- getDragItems={getDragItems}- isPrimary={!isFollowingLive && itemKey === gallery.selectedItemKey}- isSelected={!isFollowingLive && selectedItemKeys.has(itemKey)}- item={cell.item}- onClick={handleThumbnailClick}- onContextMenu={handleThumbnailContextMenu}- onToggleStarred={handleToggleStarred}- />- );- })}- </Box>- );- })}- </Box>- </Box>- {paginationMode === 'infinite' && gallery.isLoading && gallery.items.length > 0 && (- <Flex align="center" justify="center" py="2">- <Spinner color="fg.subtle" size="xs" />- </Flex>- )}- {paginationMode === 'infinite' && !gallery.isLoading && isWindowTruncated && (- <Flex align="center" justify="center" py="3">- <Text color="fg.subtle" fontSize="xs" textAlign="center">- {gallery.anchoredWindowPage > 0- ? t('widgets.gallery.windowLimitFrom', {- count: gallery.items.length,- index: anchoredWindowFirstItem,- })- : t('widgets.gallery.windowLimit', { count: gallery.items.length })}- </Text>- </Flex>+ )}+ {paginationMode === 'infinite' && !gallery.isLoading && isWindowTruncated && (+ <Flex align="center" justify="center" py="3">+ <Text color="fg.subtle" fontSize="xs" textAlign="center">+ {gallery.anchoredWindowPage > 0+ ? t('widgets.gallery.windowLimitFrom', {+ count: gallery.items.length,+ index: anchoredWindowFirstItem,+ })+ : t('widgets.gallery.windowLimit', { count: gallery.items.length })}+ </Text>+ </Flex>+ )}+ </>)}</ScrollArea.Content></ScrollArea.Viewport>@@ -682,28 +658,28 @@ export const GalleryImageGrid = () => {<ScrollArea.Thumb /></ScrollArea.Scrollbar></ScrollArea.Root>- )}- {isDropActive && (- <DropZone- alignItems="center"- display="flex"- flexDirection="column"- gap="2"- inset="0"- isOver- justifyContent="center"- pointerEvents="none"- position="absolute"- variant="overlay"- zIndex="1"- >- <UploadIcon size="20" />- <Text fontSize="xs" fontWeight="600">- {t('widgets.gallery.dropMediaToUploadToBoard', { name: selectedBoardName })}- </Text>- </DropZone>- )}- <ImageContextMenu boards={gallery.boards} target={activeContextMenuTarget} onClose={handleCloseContextMenu} />- </Box>+ {isDropActive && (+ <DropZone+ alignItems="center"+ display="flex"+ flexDirection="column"+ gap="2"+ inset="0"+ isOver+ justifyContent="center"+ pointerEvents="none"+ position="absolute"+ variant="overlay"+ zIndex="1"+ >+ <UploadIcon size="20" />+ <Text fontSize="xs" fontWeight="600">+ {t('widgets.gallery.dropMediaToUploadToBoard', { name: selectedBoardName })}+ </Text>+ </DropZone>+ )}+ <ImageContextMenu boards={gallery.boards} target={activeContextMenuTarget} onClose={handleCloseContextMenu} />+ </Box>+ </Stack>);};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsxindex 05edd1d705..80de4a88ba 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx@@ -11,6 +11,7 @@ import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';import type { GalleryStateView } from './galleryStateView';import type { GalleryWidgetContextValue } from './GalleryWidgetContext';@@ -21,7 +22,7 @@ import { GalleryWidgetContext } from './GalleryWidgetContext';import { EMPTY_GALLERY_STARRED_STRIP } from './useGalleryStarredStrip';vi.mock('@features/queue/react', () => ({- useQueueItemProgress: () => null,+ useItemProgress: () => null,useQueueItemProgressImage: () => null,}));@@ -55,7 +56,9 @@ const createItem = (name: string) => ({kind: 'image' as const,name,starred: false,- thumbnailUrl: `/thumb/${name}`,+ thumbnailUrl: `data:image/svg+xml,${encodeURIComponent(+ '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#547c83"/></svg>'+ )}`,width: 64,});@@ -126,7 +129,10 @@ const contextBase = {const adapter = {ImageContextMenu: () => null,- account: { enableLiveFollow: vi.fn() },+ progressSessions: [],+ pinnedProgressSessionId: null,+ liveFollowEnabled: false,+ followProgressSession: vi.fn(),antialiasProgressImages: false,widgets: { openGallery: vi.fn(() => true), patchGalleryValues: vi.fn() },} as unknown as GalleryUiAdapter;@@ -157,6 +163,7 @@ const renderLayout = async (Layout: typeof GalleryStackedLayout | typeof GallerybeforeEach(() => {vi.clearAllMocks();setGallery(gallery);+ adapter.progressSessions = [];host = document.createElement('div');host.style.cssText = 'height:600px;left:0;position:fixed;top:0;width:900px;';document.body.append(host);@@ -173,6 +180,79 @@ afterEach(async () => {});describe('gallery layout shells', () => {+ it('wraps progress into matching gallery columns inside the same vertical viewport', async () => {+ host!.style.width = '560px';+ adapter.progressSessions = Array.from({ length: 4 }, (_, index) => ({+ id: `batch:${index + 1}`,+ queueItemId: 'batch',+ backendItemId: index + 1,+ itemIndex: index + 1,+ itemCount: 4,+ label: 'Batch',+ sourceId: 'workflow',+ width: 512,+ height: 512,+ state: 'queued',+ }));+ setGallery(+ createGallery({ settings: { ...DEFAULT_GALLERY_SETTINGS, boardPanelCollapsed: true, imageDensityPercent: 0 } })+ );+ await renderLayout(GalleryStackedLayout);+ const panel = host!.querySelector<HTMLElement>('[role="tabpanel"]')!;+ await expect.poll(() => panel.querySelectorAll('[role="region"] button[aria-pressed]').length).toBe(4);+ const tiles = panel.querySelectorAll<HTMLElement>('[role="region"] button[aria-pressed]');+ const saved = panel.querySelector<HTMLElement>('[role="listitem"]')!;+ const viewport = panel.querySelector<HTMLElement>('[data-part="viewport"]')!;+ expect(panel.querySelectorAll('[data-part="viewport"]')).toHaveLength(1);+ expect(viewport.contains(tiles[0]!)).toBe(true);+ expect(tiles[0]!.getBoundingClientRect().width).toBeCloseTo(saved.getBoundingClientRect().width, 0);+ expect(tiles[3]!.getBoundingClientRect().top).toBeGreaterThan(tiles[0]!.getBoundingClientRect().top);+ expect(saved.getBoundingClientRect().top).toBeGreaterThanOrEqual(tiles[3]!.getBoundingClientRect().bottom);+ expect(viewport.scrollWidth).toBe(viewport.clientWidth);+ setGallery(+ createGallery({+ settings: {+ ...DEFAULT_GALLERY_SETTINGS,+ boardPanelCollapsed: true,+ imageDensityPercent: 0,+ progressSectionCollapsed: true,+ },+ })+ );+ await renderLayout(GalleryStackedLayout);+ expect(panel.querySelector('[role="region"] button[aria-pressed]')).toBeNull();+ expect(saved.getBoundingClientRect().top - viewport.getBoundingClientRect().top).toBeCloseTo(24, 0);+ });++ it.each(['images', 'assets'] as const)(+ 'fills the stacked %s panel with media or its empty upload picker',+ async (galleryView) => {+ await page.viewport(760, 680);+ host!.style.width = '560px';+ for (const items of [[createItem('visible.png')], []]) {+ setGallery(+ createGallery({ galleryView, items, settings: { ...DEFAULT_GALLERY_SETTINGS, boardPanelCollapsed: true } })+ );+ await renderLayout(GalleryStackedLayout);+ const panel = host!.querySelector<HTMLElement>('[role="tabpanel"]')!;+ const grid = panel.firstElementChild as HTMLElement;+ expect(grid.getBoundingClientRect().width).toBeCloseTo(panel.getBoundingClientRect().width, 0);+ if (items.length) {+ await expect.poll(() => panel.querySelector('[role="listitem"]')).not.toBeNull();+ const viewport = panel.querySelector<HTMLElement>('[data-part="viewport"]')!;+ expect(viewport.clientWidth).toBeGreaterThan(500);+ expect(viewport.clientHeight).toBeGreaterThan(100);+ } else {+ const picker = panel.querySelector<HTMLElement>('[role="button"]')!;+ expect(picker.getBoundingClientRect().width).toBeGreaterThan(panel.clientWidth - 24);+ }+ await page.screenshot({+ path: `../../../../artifacts/gallery-progress/stacked-${galleryView}-${items.length ? 'media' : 'empty'}.png`,+ });+ }+ }+ );+it('keeps the center gallery scroll area above the selection actions', async () => {const items = Array.from({ length: 80 }, (_, index) => createItem(`image-${index}.png`));diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsxnew file mode 100644index 0000000000..32d3b2fbed--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsx@@ -0,0 +1,252 @@+import type { QueueProgressSession } from '@features/queue/contracts';++import { Box, chakra, Icon, Skeleton, Text } from '@chakra-ui/react';+import { getDeterminateProgressPercent } from '@features/queue/contracts';+import { useItemProgress, useQueueItemProgressImage } from '@features/queue/react';+import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';+import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';+import { ChevronRightIcon, HourglassIcon } from 'lucide-react';+import { useCallback, useId, useRef } from 'react';+import { useVirtualizer } from 'react-hook-tanstack-virtual';+import { useTranslation } from 'react-i18next';++import { GALLERY_GRID_GAP_PX, GALLERY_STARRED_HEADER_HEIGHT_PX } from './galleryGridLayout';+import { useGalleryUi } from './GalleryUiContext';+import { useGalleryWidget } from './GalleryWidgetContext';++export const GalleryProgressSection = ({+ columns,+ tileSize,+ getScrollElement,+}: {+ columns: number;+ tileSize: number;+ getScrollElement(): HTMLDivElement | null;+}) => {+ const { t } = useTranslation();+ const { progressSessions, pinnedProgressSessionId, liveFollowEnabled, followProgressSession } = useGalleryUi();+ const { actions, gallery } = useGalleryWidget();+ const { progressSectionCollapsed, showPendingItems } = gallery.settings;+ const rootRef = useRef<HTMLDivElement | null>(null);+ const contentId = useId();+ const restoreFocus = useCallback(() => {+ const root = rootRef.current;+ (root?.querySelector<HTMLButtonElement>('[data-progress-disclosure]') ?? root)?.focus({ preventScroll: true });+ }, []);+ const disclosureRef = useCallback(+ (element: HTMLButtonElement | null) => {+ if (!element) {+ return;+ }+ return () => {+ if (document.activeElement === element) {+ queueMicrotask(restoreFocus);+ }+ };+ },+ [restoreFocus]+ );+ const toggleCollapsed = useCallback(+ () => actions.updateSettings({ progressSectionCollapsed: !progressSectionCollapsed }),+ [actions, progressSectionCollapsed]+ );+ const visible = showPendingItems && progressSessions.length > 0;++ return (+ <Box ref={rootRef} aria-label={t('widgets.gallery.inProgress')} flexShrink={0} minW="0" role="region" tabIndex={-1}>+ {visible ? (+ <>+ <chakra.button+ ref={disclosureRef}+ display="flex"+ alignItems="center"+ aria-controls={contentId}+ aria-expanded={!progressSectionCollapsed}+ type="button"+ focusVisibleRing="inside"+ data-progress-disclosure+ gap="1"+ h={`${GALLERY_STARRED_HEADER_HEIGHT_PX}px`}+ py="0"+ px="1"+ textAlign="start"+ title={t('widgets.gallery.progressShared')}+ w="full"+ onClick={toggleCollapsed}+ >+ <Icon+ as={ChevronRightIcon}+ boxSize="3"+ transform={progressSectionCollapsed ? undefined : 'rotate(90deg)'}+ />+ <Icon as={HourglassIcon} boxSize="3" />+ <Text fontSize="2xs" fontWeight="600" letterSpacing="wide" lineHeight="1" textTransform="uppercase">+ {t('widgets.gallery.inProgress')}+ </Text>+ <Text color="fg.muted" fontSize="xs" fontVariantNumeric="tabular-nums">+ · {progressSessions.length}+ </Text>+ </chakra.button>+ <Box id={contentId} hidden={progressSectionCollapsed}>+ {!progressSectionCollapsed ? (+ <GalleryProgressGrid+ key={`${columns}:${tileSize}`}+ sessions={progressSessions}+ size={tileSize}+ columns={columns}+ getScrollElement={getScrollElement}+ pinnedSessionId={pinnedProgressSessionId}+ liveFollowEnabled={liveFollowEnabled}+ onFollow={followProgressSession}+ restoreFocus={restoreFocus}+ />+ ) : null}+ </Box>+ </>+ ) : null}+ </Box>+ );+};++const GalleryProgressGrid = ({+ sessions,+ size,+ columns,+ getScrollElement,+ pinnedSessionId,+ liveFollowEnabled,+ onFollow,+ restoreFocus,+}: {+ sessions: QueueProgressSession[];+ size: number;+ columns: number;+ getScrollElement(): HTMLDivElement | null;+ pinnedSessionId: string | null;+ liveFollowEnabled: boolean;+ onFollow(id: string): void;+ restoreFocus(): void;+}) => {+ const rowHeight = size + GALLERY_GRID_GAP_PX;+ const rowCount = Math.ceil(sessions.length / columns);+ const estimateSize = useCallback(() => rowHeight, [rowHeight]);+ const getItemKey = useCallback((index: number) => sessions[index * columns]!.id, [sessions, columns]);+ const virtualizer = useVirtualizer({+ count: rowCount,+ getScrollElement,+ estimateSize,+ getItemKey,+ scrollMargin: GALLERY_STARRED_HEADER_HEIGHT_PX,+ overscan: 2,+ });+ return (+ <Box minW="0" pb="2">+ <Box position="relative" h={`${virtualizer.totalSize}px`} w="full">+ {virtualizer.virtualItems.map((row) => (+ <Box+ key={row.key}+ position="absolute"+ top={`${row.start - GALLERY_STARRED_HEADER_HEIGHT_PX}px`}+ left="0"+ display="grid"+ gridTemplateColumns={`repeat(${columns}, minmax(0, 1fr))`}+ gap={`${GALLERY_GRID_GAP_PX}px`}+ w="full"+ >+ {sessions.slice(row.index * columns, (row.index + 1) * columns).map((session) => (+ <GalleryProgressTile+ key={session.id}+ session={session}+ size={size}+ selected={liveFollowEnabled && (pinnedSessionId === null || pinnedSessionId === session.id)}+ onFollow={onFollow}+ restoreFocus={restoreFocus}+ />+ ))}+ </Box>+ ))}+ </Box>+ </Box>+ );+};++const GalleryProgressTile = ({+ session,+ size,+ selected,+ onFollow,+ restoreFocus,+}: {+ session: QueueProgressSession;+ size: number;+ selected: boolean;+ onFollow(id: string): void;+ restoreFocus(): void;+}) => {+ const { t } = useTranslation();+ const { antialiasProgressImages } = useGalleryUi();+ const image = useQueueItemProgressImage(session.queueItemId, session.itemIndex);+ const progress = useItemProgress(session.backendItemId);+ const percentage = getDeterminateProgressPercent(progress?.percentage);+ const label =+ session.itemCount > 1+ ? t('widgets.gallery.progressSession', {+ name: session.label,+ index: session.itemIndex,+ total: session.itemCount,+ })+ : session.label;+ const status =+ session.state === 'queued'+ ? t('widgets.gallery.progressQueued')+ : session.state === 'settling'+ ? t('widgets.gallery.progressSettling')+ : percentage !== null+ ? `${percentage}%`+ : progress?.message || t('widgets.gallery.progressPreparing');+ const follow = useCallback(() => onFollow(session.id), [onFollow, session.id]);+ const buttonRef = useCallback(+ (element: HTMLButtonElement | null) => {+ if (!element) {+ return;+ }+ return () => {+ if (document.activeElement === element) {+ queueMicrotask(restoreFocus);+ }+ };+ },+ [restoreFocus]+ );++ return (+ <chakra.button+ ref={buttonRef}+ type="button"+ focusVisibleRing="inside"+ aria-label={`${label} · ${status}`}+ aria-pressed={selected && session.state !== 'queued'}+ disabled={session.state === 'queued'}+ borderColor={selected && session.state !== 'queued' ? 'accent.solid' : 'border.subtle'}+ borderWidth="1px"+ flexShrink={0}+ minW="0"+ overflow="hidden"+ rounded="md"+ textAlign="start"+ title={label}+ w={`${size}px`}+ onClick={follow}+ >+ <StreamingImageFrame+ aspectRatio={1}+ fit="contain"+ liveImage={progressImageToStreamingSource(image)}+ shouldAntialiasLiveImage={antialiasProgressImages}+ w="full"+ >+ <Skeleton h="full" w="full" />+ </StreamingImageFrame>+ </chakra.button>+ );+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryQueuePlaceholderCell.tsxdeleted file mode 100644index 1986049b72..0000000000--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryQueuePlaceholderCell.tsx+++ /dev/null@@ -1,95 +0,0 @@-import type { GalleryThumbnailFit } from '@features/gallery/core/settings';--import { Box, Flex, ProgressCircle, Skeleton } from '@chakra-ui/react';-import { useQueueItemProgress, useQueueItemProgressImage } from '@features/queue/react';-import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';-import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';-import { useTranslation } from 'react-i18next';--import type { GalleryQueuePlaceholder } from './galleryStateView';--/** Grid tile standing in for an in-flight queue item bound for the current board. */-export const GalleryQueuePlaceholderCell = ({- antialiasProgressImages,- fit,- isSelected,- placeholder,- onClick,-}: {- antialiasProgressImages: boolean;- fit: GalleryThumbnailFit;- isSelected: boolean;- placeholder: GalleryQueuePlaceholder;- onClick: () => void;-}) => {- const { t } = useTranslation();- const progressImage = useQueueItemProgressImage(placeholder.queueItemId, placeholder.itemIndex);- const progress = useQueueItemProgress(placeholder.queueItemId);- const isActive = progress?.activeItemIndex === placeholder.itemIndex;- const percentage = typeof progress?.percentage === 'number' ? Math.round(progress.percentage * 100) : null;-- return (- <Box aspectRatio={1} minW="0" role="listitem" w="full">- <Box- as="button"- aria-label={t('widgets.preview.showInProgressDiffusion')}- aria-pressed={isSelected}- bg="bg"- borderColor={isSelected ? 'accent.solid' : 'border.subtle'}- borderWidth={isSelected ? '2px' : '1px'}- h="full"- overflow="hidden"- position="relative"- rounded="md"- w="full"- onClick={onClick}- >- <StreamingImageFrame- fit={fit === 'aspect' ? 'contain' : 'cover'}- h="full"- liveImage={progressImageToStreamingSource(progressImage)}- shouldAntialiasLiveImage={antialiasProgressImages}- w="full"- >- <Skeleton h="full" w="full" />- </StreamingImageFrame>- {isActive ? <GalleryPlaceholderCircularProgress percentage={percentage} /> : null}- </Box>- </Box>- );-};--const GalleryPlaceholderCircularProgress = ({ percentage }: { percentage: number | null }) => {- const { t } = useTranslation();-- return (- <Flex- align="center"- alignItems="center"- inset="0"- justify="center"- pointerEvents="none"- position="absolute"- zIndex="1"- >- <ProgressCircle.Root- aria-label={- percentage === null- ? t('widgets.gallery.generationProgress')- : t('widgets.gallery.generationProgressPercent', { percentage })- }- bg="bg/85"- borderWidth={1}- p={0.5}- rounded="full"- size="xs"- value={percentage}- >- <ProgressCircle.Circle>- <ProgressCircle.Track />- <ProgressCircle.Range />- </ProgressCircle.Circle>- </ProgressCircle.Root>- </Flex>- );-};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex c00688fe16..ab5a8650e1 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -1,12 +1,10 @@import type { GalleryImageItem, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery/contracts';import type { GallerySettings } from '@features/gallery/core/settings';import type { GalleryBoard, GalleryBoardDeletionResult, GalleryImage, GalleryView } from '@features/gallery/core/types';-import type { QueueItem } from '@features/queue/contracts';+import type { QueueProgressSession } from '@features/queue/contracts';import { createContext, use, type ComponentType, type ReactNode } from 'react';-import type { GalleryLiveTarget } from './galleryStateView';-export interface GalleryItemActions {deleteItems(items: GalleryItemRef[]): Promise<void>;downloadItem(item: GalleryItem): Promise<void>;@@ -98,7 +96,6 @@ export interface GalleryWidgetProps {export interface GalleryUiAdapter {ItemActionsProvider: ComponentType<GalleryItemActionsOptions & { children: ReactNode }>;ImageContextMenu: ComponentType<GalleryItemContextMenuProps>;- account: { enableLiveFollow(): void };antialiasProgressImages: boolean;gallery: GalleryCommandsPort;galleryValues: Record<string, unknown>;@@ -111,9 +108,10 @@ export interface GalleryUiAdapter {* board because a board menu can offer this for any project's board, not only the open one.*/exportProject(projectId: string, projectName: string): void;- queueItems: QueueItem[];+ progressSessions: QueueProgressSession[];+ pinnedProgressSessionId: string | null;+ followProgressSession(sessionId: string): void;liveFollowEnabled: boolean;- liveProgressTarget: GalleryLiveTarget | null;widgets: {/** Open (or reveal) the Gallery widget; false when no region can host it. */openGallery(): boolean;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex c4aede887c..d03de4434f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -76,12 +76,9 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidggallery: galleryCommands,galleryValues,generateValues,- liveFollowEnabled,- liveProgressTarget,notifications,projectId,projectName,- queueItems,ItemActionsProvider,} = useGalleryUi();const galleryView = getGalleryView(galleryValues);@@ -125,17 +122,8 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgconst { loadMore, selectedBoardId, total } = data;const gallery = useMemo(- () =>- getGalleryStateView(- galleryValues,- data.boards,- data.items,- data.isLoadingItems,- queueItems,- liveFollowEnabled,- liveProgressTarget- ),- [data.boards, data.isLoadingItems, data.items, galleryValues, liveFollowEnabled, liveProgressTarget, queueItems]+ () => getGalleryStateView(galleryValues, data.boards, data.items, data.isLoadingItems),+ [data.boards, data.isLoadingItems, data.items, galleryValues]);// No strip under a ranked result (no starred filter applies), under the// starred-only listing (it would repeat the grid), or in a window anchoreddiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.tsindex 69b106ed72..5885acb623 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts@@ -2,8 +2,6 @@ import type { GalleryImageItem } from '@features/gallery/core/items';import { describe, expect, it } from 'vitest';-import type { GalleryQueuePlaceholder } from './galleryStateView';-import {buildGalleryGridNavigation,buildGalleryGridRows,@@ -32,34 +30,18 @@ const createImageItem = (name: string, starred = false): GalleryImageItem => ({width: 512,});-const createPlaceholder = (id: string): GalleryQueuePlaceholder => ({- backendItemId: null,- boardId: 'none',- height: 1024,- id,- itemIndex: 0,- queueItemId: `queue-${id}`,- width: 1024,-});-const buildRows = (overrides: Partial<Parameters<typeof buildGalleryGridRows>[0]> = {}) =>buildGalleryGridRows({columnCount: 2,- imageOrderDir: 'DESC',isStarredOpen: true,items: [],- pendingPlaceholders: [],starredItems: [],starredTotal: 0,...overrides,});const cellNames = (rows: ReturnType<typeof buildRows>): string[][] =>- rows.flatMap((row) =>- row.kind === 'cells'- ? [row.cells.map((cell) => (cell.kind === 'item' ? cell.item.name : `placeholder:${cell.placeholder.id}`))]- : []- );+ rows.flatMap((row) => (row.kind === 'cells' ? [row.cells.map((cell) => cell.item.name)] : []));describe('getGalleryColumnCountForCell', () => {it('rounds to the nearest whole cell and clamps to the caller bounds', () => {@@ -200,30 +182,6 @@ describe('buildGalleryGridRows', () => {expect(regularKeys(buildRows({ ...input, isStarredOpen: false }))).toEqual(regularKeys(buildRows(input)));});- it('gives every row a unique key across the header, strip, gap, placeholder, and listing rows', () => {- const starred = createImageItem('starred-1', true);- const rows = buildRows({- items: [createImageItem('regular-1'), createImageItem('regular-2')],- pendingPlaceholders: [createPlaceholder('slot-1')],- starredItems: [starred],- starredTotal: 1,- });- const keys = rows.map((row) => row.key);-- expect(new Set(keys).size).toBe(keys.length);- });-- it('slots placeholders ahead of regular items for newest-first ordering and after them otherwise', () => {- const items = [createImageItem('regular-1')];- const pendingPlaceholders = [createPlaceholder('slot-1')];-- const newestFirst = buildRows({ items, pendingPlaceholders });- expect(newestFirst[0]?.kind === 'cells' && newestFirst[0].cells[0]?.kind).toBe('placeholder');-- const oldestFirst = buildRows({ imageOrderDir: 'ASC', items, pendingPlaceholders });- expect(oldestFirst[0]?.kind === 'cells' && oldestFirst[0].cells[0]?.kind).toBe('item');- });-it('numbers cells continuously from the strip into the listing, matching the navigation list', () => {const starred = createImageItem('starred-1', true);const input = {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.tsindex 35e57b9aa4..6b7990cc78 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts@@ -1,12 +1,7 @@import type { GalleryItem } from '@features/gallery/core/items';-import type { GalleryOrderDir } from '@features/gallery/core/types';import { toGalleryItemKey } from '@features/gallery/core/items';-import type { GalleryQueuePlaceholder } from './galleryStateView';--import { getGalleryPlaceholderInsertionIndex } from './galleryStateView';-export const GALLERY_GRID_GAP_PX = 4;export const GALLERY_STARRED_HEADER_HEIGHT_PX = 24;/** The gap row grows to hold a hairline rule while the starred section is open. */@@ -66,9 +61,7 @@ export const getGalleryColumnCount = ({export const getGalleryCellSizePx = ({ columnCount, widthPx }: { columnCount: number; widthPx: number }): number =>widthPx > 0 ? Math.max(1, (widthPx - GALLERY_GRID_GAP_PX * (columnCount - 1)) / columnCount) : 96;-export type GalleryGridCell =- | { kind: 'item'; item: GalleryItem; itemIndex: number }- | { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };+export type GalleryGridCell = { kind: 'item'; item: GalleryItem; itemIndex: number };export type GalleryGridSection = 'regular' | 'starred';@@ -165,8 +158,7 @@ export const getGalleryGridNavigationStep = (return Math.min(lastIndex, regularStart + (targetRow - stripRowCount) * columnCount + column);};-const getGalleryGridCellKey = (cell: GalleryGridCell): string =>- cell.kind === 'placeholder' ? `placeholder:${cell.placeholder.id}` : toGalleryItemKey(cell.item);+const getGalleryGridCellKey = (cell: GalleryGridCell): string => toGalleryItemKey(cell.item);/*** Rows are keyed by their leading cell rather than their index so that@@ -198,23 +190,19 @@ const chunkGalleryCellsIntoRows = (/*** The grid's row model in one pure pass: the bounded starred strip gets a* disclosure section above the listing, the listing chunks in order, and- * placeholders slot in where their images will land. Cell indices follow+ * only saved items participate in navigation. Cell indices follow* `buildGalleryGridNavigation`.*/export const buildGalleryGridRows = ({columnCount,- imageOrderDir,isStarredOpen,items,- pendingPlaceholders,starredItems,starredTotal,}: {columnCount: number;- imageOrderDir: GalleryOrderDir;isStarredOpen: boolean;items: readonly GalleryItem[];- pendingPlaceholders: readonly GalleryQueuePlaceholder[];starredItems: readonly GalleryItem[];starredTotal: number;}): GalleryGridRow[] => {@@ -226,16 +214,7 @@ export const buildGalleryGridRows = ({itemIndex: shownCount + index,kind: 'item',}));- const placeholderCells: GalleryGridCell[] = pendingPlaceholders.map((placeholder) => ({- kind: 'placeholder',- placeholder,- }));- const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(items.length, imageOrderDir);- const regularCells = [- ...regularItemCells.slice(0, placeholderInsertionIndex),- ...placeholderCells,- ...regularItemCells.slice(placeholderInsertionIndex),- ];+ const regularCells = regularItemCells;const rows: GalleryGridRow[] = [];if (stripItems.length > 0) {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex cfafe663e6..90327f3145 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -1,14 +1,10 @@import type { GalleryImageItem, GalleryItem, GalleryVideoItem } from '@features/gallery/core/items';import type { GalleryBoard, GeneratedImageContract } from '@features/gallery/core/types';-import type { QueueHistoryItemStatus, QueueItem } from '@features/queue/contracts';import { describe, expect, it } from 'vitest';import {getBoardCounts,- getGalleryCurrentItem,- getGalleryGenerationSequence,- getGalleryLiveSlots,getGallerySelectedBoardId,getGallerySelectedImageQuery,getGallerySemanticImageQuery,@@ -73,50 +69,6 @@ const createVideoItem = (name: string): GalleryVideoItem => ({thumbnailUrl: `/api/v1/videos/i/${name}/thumbnail`,});-const createQueueItem = ({- backendItemIds,- batchCount = 1,- boardId = 'none',- completedBackendItemIds,- cancelledBackendItemIds,- destination = 'gallery',- status = 'pending',- localId,-}: {- backendItemIds?: number[];- batchCount?: number;- boardId?: string;- completedBackendItemIds?: number[];- cancelledBackendItemIds?: number[];- destination?: 'gallery' | 'canvas';- status?: QueueHistoryItemStatus;- localId?: string;-}): QueueItem => ({- backendItemIds,- cancellable: true,- cancelledBackendItemIds,- completedBackendItemIds,- id: localId ?? `queue-item-${status}-${boardId}`,- snapshot: {- backendSubmission: {- batchCount,- graph: { edges: [], id: 'gallery-placeholder-graph', nodes: {} },- kind: 'workflow',- },- destination,- filterIntermediateResults: false,- galleryBoardId: boardId,- graph: { id: 'gallery-placeholder-graph', label: 'Gallery placeholder' },- presentation: { batchCount, height: 768, width: 512 },- sourceId: 'workflow',- submittedAt: '2026-06-09T00:00:00.000Z',- },- status,-});--const getPendingPlaceholders = (queueItems: QueueItem[], values: Record<string, unknown>) =>- getGalleryStateView(values, boards, [], false, queueItems).pendingPlaceholders;-describe('gallery state view', () => {it('preserves a selected backend board id while boards are still loading', () => {const values = { selectedBoardId: 'board-1' };@@ -209,6 +161,7 @@ describe('gallery state view', () => {showImageDimensions: false,showOtherProjectBoards: false,showPendingItems: true,+ progressSectionCollapsed: false,starredSectionCollapsed: false,thumbnailFit: 'square',});@@ -367,331 +320,14 @@ describe('gallery state view', () => {kind: 'image',});});-- it('threads the parsed semantic reference into the view and hides pending placeholders while ranked', () => {- const queueItems = [createQueueItem({ batchCount: 2, boardId: 'board-1', status: 'pending' })];- const withSemantic = getGalleryStateView(+ it('threads persisted semantic references into the board view', () => {+ const ranked = getGalleryStateView({ selectedBoardId: 'board-1', semanticImageQuery: 'ref.png' },boards,[],- false,- queueItems- );-- // Legacy persisted shape: a bare image name.- expect(withSemantic.semanticImageQuery).toEqual({ imageName: 'ref.png', kind: 'image' });- // A ranked result has no chronological insertion point for images-to-come.- expect(withSemantic.pendingPlaceholders).toEqual([]);-- const withoutSemantic = getGalleryStateView({ selectedBoardId: 'board-1' }, boards, [], false, queueItems);-- expect(withoutSemantic.semanticImageQuery).toBe(null);- expect(withoutSemantic.pendingPlaceholders.length).toBeGreaterThan(0);- });-- it('creates placeholders for in-flight gallery queue items on the viewed board', () => {- const queueItems = [- createQueueItem({ batchCount: 2, boardId: 'board-1', status: 'pending' }),- createQueueItem({ backendItemIds: [11, 12, 13], boardId: 'board-1', status: 'running' }),- ];- const placeholders = getPendingPlaceholders(queueItems, { imageOrderDir: 'ASC', selectedBoardId: 'board-1' });-- expect(placeholders).toHaveLength(5);- expect(placeholders[0]).toMatchObject({- height: 768,- itemIndex: 1,- queueItemId: 'queue-item-running-board-1',- width: 512,- });- });-- it('skips completed backend item slots when creating placeholders', () => {- const queueItems = [- createQueueItem({- backendItemIds: [11, 12, 13],- boardId: 'board-1',- completedBackendItemIds: [11],- status: 'running',- }),- ];-- const placeholders = getPendingPlaceholders(queueItems, { imageOrderDir: 'ASC', selectedBoardId: 'board-1' });-- expect(placeholders.map((placeholder) => placeholder.itemIndex)).toEqual([2, 3]);- });-- it('resolves the live slot from the exact denoising target instead of the newest submitted batch', () => {- const newerBatch = createQueueItem({- backendItemIds: [21, 22],- boardId: 'board-1',- localId: 'newer-batch',- status: 'running',- });- const activeEarlierBatch = createQueueItem({- backendItemIds: [11, 12],- boardId: 'board-1',- completedBackendItemIds: [11],- localId: 'active-earlier-batch',- status: 'running',- });-- expect(- getGalleryGenerationSequence([newerBatch, activeEarlierBatch], {- itemIndex: 2,- queueItemId: activeEarlierBatch.id,- }).liveSlot- ).toMatchObject({- boardId: 'board-1',- itemIndex: 2,- queueItemId: activeEarlierBatch.id,- });- });-- it('flattens pending slots from multiple batches into one global execution order', () => {- const newerBatch = createQueueItem({- backendItemIds: [21, 22],- boardId: 'board-1',- localId: 'newer-batch',- status: 'running',- });- const earlierBatch = createQueueItem({- backendItemIds: [11, 12],- boardId: 'board-1',- localId: 'earlier-batch',- status: 'running',- });-- const sequence = getGalleryGenerationSequence([newerBatch, earlierBatch], null);-- expect(sequence.chronologicalSlots.map((slot) => slot.id)).toEqual([- 'earlier-batch:0',- 'earlier-batch:1',- 'newer-batch:0',- 'newer-batch:1',- ]);- 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],- boardId: 'board-1',- localId: 'newer-batch',- status: 'running',- });- const earlierBatch = createQueueItem({- backendItemIds: [11, 12],- boardId: 'board-1',- localId: 'earlier-batch',- status: 'running',- });-- const placeholders = getPendingPlaceholders([newerBatch, earlierBatch], {- imageOrderDir: 'DESC',- selectedBoardId: 'board-1',- });-- expect(placeholders.map((slot) => slot.id)).toEqual([- 'newer-batch:1',- 'newer-batch:0',- 'earlier-batch:1',- 'earlier-batch:0',- ]);- });-- it('uses one derived current item while live-follow is active', () => {- const placeholder = {- backendItemId: null,- boardId: 'board-1',- height: 768,- id: 'queue-item:0',- itemIndex: 1,- queueItemId: 'queue-item',- width: 512,- };-- expect(- getGalleryCurrentItem({- activePlaceholder: placeholder,- isComparisonActive: false,- liveFollowEnabled: true,- selectedItemKey: 'image:saved.png',- })- ).toEqual({ kind: 'placeholder', placeholder });- expect(- getGalleryCurrentItem({- activePlaceholder: placeholder,- isComparisonActive: false,- liveFollowEnabled: false,- selectedItemKey: 'image:saved.png',- })- ).toEqual({ itemKey: 'image:saved.png', kind: 'item' });- });-- it('keeps the visible image selected when the active placeholder belongs to another board', () => {- const image = { ...createImageItem('selected.png'), boardId: 'board-1' } as const;- const activeItem = createQueueItem({ boardId: 'board-2', localId: 'active-other-board', status: 'running' });- const gallery = getGalleryStateView(- { selectedBoardId: 'board-1', selectedImageName: 'image:selected.png' },- boards,- [image],- false,- [activeItem],- true,- { itemIndex: 1, queueItemId: activeItem.id }- );-- expect(gallery.currentItem).toEqual({ itemKey: 'image:selected.png', kind: 'item' });- });-- it('skips cancelled backend item slots when creating placeholders', () => {- const queueItems = [- createQueueItem({- backendItemIds: [11, 12, 13],- boardId: 'board-1',- cancelledBackendItemIds: [12],- completedBackendItemIds: [11],- status: 'running',- }),- ];-- const placeholders = getPendingPlaceholders(queueItems, { imageOrderDir: 'ASC', selectedBoardId: 'board-1' });-- expect(placeholders.map((placeholder) => placeholder.itemIndex)).toEqual([3]);- });-- it('does not create placeholders for other boards, finished items, or canvas runs', () => {- const queueItems = [- createQueueItem({ boardId: 'board-2', status: 'pending' }),- createQueueItem({ boardId: 'board-1', status: 'completed' }),- createQueueItem({ boardId: 'board-1', destination: 'canvas', status: 'pending' }),- ];-- expect(getPendingPlaceholders(queueItems, { selectedBoardId: 'board-1' })).toEqual([]);- });-- it('hides placeholders while searching, browsing assets, or filtering to starred items', () => {- const queueItems = [createQueueItem({ boardId: 'none', status: 'pending' })];-- expect(getPendingPlaceholders(queueItems, { searchTerm: 'cat', selectedBoardId: 'none' })).toEqual([]);- expect(getPendingPlaceholders(queueItems, { selectedBoardId: 'none', starredOnly: true })).toEqual([]);- expect(- getGalleryStateView({ selectedBoardId: 'none', starredOnly: true }, boards, [], false, queueItems).currentItem- ).toBeNull();- expect(getPendingPlaceholders(queueItems, { galleryView: 'assets', selectedBoardId: 'none' })).toEqual([]);- expect(- getGalleryStateView({ selectedBoardId: 'none' }, boards, [], false, queueItems).pendingPlaceholders- ).toHaveLength(1);- });-- it('hides only pending placeholders when the persisted setting is disabled', () => {- const queueItems = [createQueueItem({ boardId: 'none', status: 'pending' })];- const image = createImageItem('completed.png');- const gallery = getGalleryStateView(- { selectedBoardId: 'none', showPendingItems: false },- boards,- [image],- false,- queueItems+ false);-- expect(gallery.pendingPlaceholders).toEqual([]);- expect((gallery as typeof gallery & { items?: GalleryItem[] }).items).toEqual([image]);- expect(gallery.settings.showPendingItems).toBe(false);- });-- it('shows placeholders only on the paginated page where new images land', () => {- const queueItems = [createQueueItem({ boardId: 'none', status: 'pending' })];- const getPlaceholders = (values: Record<string, unknown>) =>- getGalleryStateView(- { paginationMode: 'paginated', selectedBoardId: 'none', ...values },- boards,- [],- false,- queueItems- ).pendingPlaceholders;-- // Newest-first: new images land on page 0.- expect(getPlaceholders({ galleryPage: 0 })).toHaveLength(1);- expect(getPlaceholders({ galleryPage: 2 })).toHaveLength(0);-- // Oldest-first: they land at row `total`, which needs the known total.- expect(getPlaceholders({ galleryPage: 2, galleryTotalImages: 150, imageOrderDir: 'ASC' })).toHaveLength(1);- expect(getPlaceholders({ galleryPage: 0, galleryTotalImages: 150, imageOrderDir: 'ASC' })).toHaveLength(0);- expect(getPlaceholders({ galleryPage: 0, imageOrderDir: 'ASC' })).toHaveLength(0);-- // An exactly-full last page means the image lands on a page that does not- // exist yet, which no current page can show.- expect(getPlaceholders({ galleryPage: 1, galleryTotalImages: 120, imageOrderDir: 'ASC' })).toHaveLength(0);- });-- it('hides placeholders while an infinite window is anchored mid-board', () => {- const queueItems = [createQueueItem({ boardId: 'none', status: 'pending' })];-- expect(- getGalleryStateView({ galleryPage: 11, selectedBoardId: 'none' }, boards, [], false, queueItems)- .pendingPlaceholders- ).toHaveLength(0);- });-});--describe('getGalleryLiveSlots', () => {- const slot = (queueItemId: string, itemIndex: number, backendItemId: number | null) => ({- backendItemId,- boardId: 'none',- height: 512,- id: `${queueItemId}:${itemIndex - 1}`,- itemIndex,- queueItemId,- width: 512,- });-- it('returns nothing when no session is live', () => {- expect(getGalleryLiveSlots([slot('queue-1', 1, 10)], [])).toEqual([]);- });-- it('returns one slot per live target', () => {- const slots = [slot('queue-1', 1, 10), slot('queue-1', 2, 11), slot('queue-1', 3, 12)];-- expect(- getGalleryLiveSlots(slots, [- { itemIndex: 1, queueItemId: 'queue-1' },- { itemIndex: 3, queueItemId: 'queue-1' },- ])- ).toEqual([slots[0], slots[2]]);- });-- it('orders tiles chronologically, not by the order sessions started reporting', () => {- // Tiles must keep a stable position, so ordering follows the chronological slot- // list (sorted by backend item id) rather than the target list.- const slots = [slot('queue-1', 1, 10), slot('queue-1', 2, 11)];-- expect(- getGalleryLiveSlots(slots, [- { itemIndex: 2, queueItemId: 'queue-1' },- { itemIndex: 1, queueItemId: 'queue-1' },- ])- ).toEqual([slots[0], slots[1]]);- });-- it('ignores targets with no matching slot', () => {- expect(getGalleryLiveSlots([slot('queue-1', 1, 10)], [{ itemIndex: 4, queueItemId: 'queue-9' }])).toEqual([]);+ expect(ranked.semanticImageQuery).toEqual({ imageName: 'ref.png', kind: 'image' });+ expect(getGalleryStateView({ selectedBoardId: 'board-1' }, boards, [], false).semanticImageQuery).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex d059dcdec6..2734acd4d1 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -1,5 +1,4 @@import type { GalleryBoard, GalleryImage, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';-import type { QueueItem } from '@features/queue/contracts';import {legacyGeneratedImageToGalleryItem,@@ -7,7 +6,6 @@ import {type GalleryItem,type GalleryItemKey,} from '@features/gallery/core/items';-import { GALLERY_PAGE_SIZE } from '@features/gallery/core/paging';import { getBoundedRecentImages } from '@features/gallery/core/recentImages';import {getPersistedSelectedGalleryItemKeys,@@ -19,7 +17,6 @@ import {type GallerySemanticReference,} from '@features/gallery/core/semanticImageQuery';import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';-import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';/*** Stand-in shown before any board has loaded. `name` is intentionally empty:@@ -38,40 +35,7 @@ const UNCATEGORIZED_BOARD: GalleryBoard = {videoCount: 0,};-/**- * A grid cell standing in for an image that an in-flight queue item will- * deliver to the currently viewed board once generation completes.- */-export interface GalleryQueuePlaceholder {- boardId: string;- id: string;- queueItemId: string;- itemIndex: number;- width: number;- height: number;- /**- * The backend queue item id, once the slot has been claimed by one — null while the- * submission is still local-only. Progress keyed by *local* id cannot distinguish- * two slots of the same batch running on two GPUs, so surfaces that need per-session- * facts (which GPU is rendering this tile) resolve them through this id.- */- backendItemId: number | null;-}--export interface GalleryLiveTarget {- queueItemId: string;- itemIndex: number;-}--export interface GalleryGenerationSequence {- chronologicalSlots: GalleryQueuePlaceholder[];- liveSlot: GalleryQueuePlaceholder | null;-}--export type GalleryCurrentItem =- | { kind: 'item'; itemKey: GalleryItemKey }- | { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder }- | null;+export type GalleryCurrentItem = { kind: 'item'; itemKey: GalleryItemKey } | null;export interface GalleryStateView {/**@@ -91,7 +55,6 @@ export interface GalleryStateView {isLoading: boolean;/** The grid's current page in paginated mode; the window anchor otherwise. */page: number;- pendingPlaceholders: GalleryQueuePlaceholder[];projectBoardId: string | null;/*** The selection's stamped paginated page, when the stamp names the listing@@ -109,125 +72,6 @@ export interface GalleryStateView {starredOnly: boolean;}-interface SortableGalleryQueueSlot {- backendItemId: number | null;- placeholder: GalleryQueuePlaceholder;- submittedAt: string;-}--// Newest-first placeholders land at the top; oldest-first listings take them at the end.-export const getGalleryPlaceholderInsertionIndex = (itemCount: number, imageOrderDir: GalleryOrderDir): number =>- imageOrderDir === 'DESC' ? 0 : itemCount;--export const getGalleryGenerationSequence = (- queueItems: QueueItem[],- liveTarget: GalleryLiveTarget | null-): GalleryGenerationSequence => {- const sortableSlots: SortableGalleryQueueSlot[] = [];-- for (const item of queueItems) {- if ((item.status !== 'pending' && 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 ?? []);- const slotCount = item.backendItemIds?.length ?? getQueueItemSnapshotBatchCount(item);-- for (let index = 0; index < slotCount; index += 1) {- const backendItemId = item.backendItemIds?.[index] ?? null;-- if (- backendItemId !== null &&- (completedBackendItemIds.has(backendItemId) || cancelledBackendItemIds.has(backendItemId))- ) {- continue;- }-- sortableSlots.push({- backendItemId,- placeholder: {- backendItemId,- boardId,- height,- id: `${item.id}:${index}`,- itemIndex: index + 1,- queueItemId: item.id,- width,- },- submittedAt: item.snapshot.submittedAt,- });- }- }-- sortableSlots.sort((a, b) => {- if (a.backendItemId !== null && b.backendItemId !== null) {- 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.queueItemId.localeCompare(b.placeholder.queueItemId) ||- a.placeholder.itemIndex - b.placeholder.itemIndex- );- });-- const chronologicalSlots = sortableSlots.map(({ placeholder }) => placeholder);- const liveSlot = liveTarget- ? (chronologicalSlots.find(- (slot) => slot.queueItemId === liveTarget.queueItemId && slot.itemIndex === liveTarget.itemIndex- ) ?? null)- : null;-- return { chronologicalSlots, liveSlot };-};--/**- * The slots for every concurrently-running session, in chronological order.- *- * Multi-GPU runs one session per GPU, so more than one slot can be live at once.- * Ordering comes from `chronologicalSlots` (sorted by backend item id) rather than- * from the order the targets happened to start reporting, so tiles keep a stable- * left-to-right position for as long as they run.- */-export const getGalleryLiveSlots = (- chronologicalSlots: GalleryQueuePlaceholder[],- liveTargets: readonly GalleryLiveTarget[]-): GalleryQueuePlaceholder[] =>- liveTargets.length === 0- ? []- : chronologicalSlots.filter((slot) =>- liveTargets.some((target) => target.queueItemId === slot.queueItemId && target.itemIndex === slot.itemIndex)- );--export const getGalleryCurrentItem = ({- activePlaceholder,- isComparisonActive,- liveFollowEnabled,- selectedItemKey,-}: {- activePlaceholder: GalleryQueuePlaceholder | null;- isComparisonActive: boolean;- liveFollowEnabled: boolean;- selectedItemKey: GalleryItemKey | null;-}): GalleryCurrentItem => {- if (liveFollowEnabled && !isComparisonActive && activePlaceholder) {- return { kind: 'placeholder', placeholder: activePlaceholder };- }-- return selectedItemKey ? { itemKey: selectedItemKey, kind: 'item' } : null;-};-export const getGalleryView = (values: Record<string, unknown>): GalleryView =>values.galleryView === 'assets' ? 'assets' : 'images';@@ -349,50 +193,11 @@ export const getGalleryCompareImage = (values: Record<string, unknown>): GalleryselectedImageName: null,});-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 = chronologicalSlots.filter((placeholder) => placeholder.boardId === selectedBoardId);-- return imageOrderDir === 'DESC' ? [...placeholders].reverse() : placeholders;-};--/**- * Whether this page/window can show where a NEW image lands (placeholders- * render only there): page 0 for newest-first and the unanchored infinite- * window; the row-`total` page for oldest-first — deliberately nonexistent- * when the last page is exactly full, and unknowable without a total.- */-const isGalleryWindowAtIncomingItemLanding = (- settings: GallerySettings,- page: number,- totalImages: number | null-): boolean => {- if (settings.paginationMode === 'infinite' || settings.imageOrderDir === 'DESC') {- return page === 0;- }-- return totalImages !== null && page === Math.floor(totalImages / GALLERY_PAGE_SIZE);-};-export const getGalleryStateView = (values: Record<string, unknown>,backendBoards: GalleryBoard[],backendItems: GalleryItem[] | null,- isLoading: boolean,- queueItems: QueueItem[] = [],- liveFollowEnabled = false,- liveTarget: GalleryLiveTarget | null = null+ isLoading: boolean): GalleryStateView => {const localItems = getBoundedRecentImages(values.recentImages).map(legacyGeneratedImageToGalleryItem);const items = backendItems ?? (isLoading ? [] : localItems);@@ -430,32 +235,12 @@ export const getGalleryStateView = (visibleSelectedItemKey?.startsWith('image:') === true &&compareImageKey !== null &&compareImageKey !== visibleSelectedItemKey;- const generationSequence = getGalleryGenerationSequence(queueItems, liveTarget);- // A ranked similarity result has no chronological insertion point, so- // pending placeholders (which stand in for images-to-come) are hidden while- // a semantic query is active — exactly as they are for a text search, and- // for the starred-only filter, which a fresh generation never matches.const semanticImageQuery = getGallerySemanticImageQuery(values);const page = getGalleryPage(values);const isAnchoredInfiniteWindow = settings.paginationMode === 'infinite' && page > 0;- const showsIncomingItemLanding = isGalleryWindowAtIncomingItemLanding(settings, page, getGalleryTotalImages(values));- const visibleActivePlaceholder =- settings.showPendingItems &&- galleryView === 'images' &&- searchTerm.trim() === '' &&- semanticImageQuery === null &&- !starredOnly &&- showsIncomingItemLanding- ? generationSequence.liveSlot?.boardId === selectedBoardId- ? generationSequence.liveSlot- : null- : null;- const currentItem = getGalleryCurrentItem({- activePlaceholder: visibleActivePlaceholder,- isComparisonActive,- liveFollowEnabled,- selectedItemKey: visibleSelectedItemKey,- });+ const currentItem: GalleryCurrentItem = visibleSelectedItemKey+ ? { kind: 'item', itemKey: visibleSelectedItemKey }+ : null;const selectedImageQuery = getGallerySelectedImageQuery(values);const revealTargetPage =settings.paginationMode === 'paginated' &&@@ -482,15 +267,6 @@ export const getGalleryStateView = (items,isLoading,page,- pendingPlaceholders:- settings.showPendingItems && semanticImageQuery === null && !starredOnly && showsIncomingItemLanding- ? getVisibleGalleryQueuePlaceholders(generationSequence.chronologicalSlots, {- galleryView,- imageOrderDir: settings.imageOrderDir,- searchTerm,- selectedBoardId,- })- : [],projectBoardId: getGalleryProjectBoardId(values),revealTargetPage,searchTerm,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex 8b9f668f6f..59f12143b9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -157,7 +157,6 @@ const noop = vi.fn();const adapter: GalleryUiAdapter = {ItemActionsProvider: NoopProvider,ImageContextMenu: NoopContextMenu,- account: { enableLiveFollow: noop },antialiasProgressImages: false,exportProject: vi.fn(),gallery: {@@ -180,14 +179,15 @@ const adapter: GalleryUiAdapter = {galleryValues: {},generateValues: {},liveFollowEnabled: false,- liveProgressTarget: null,+ progressSessions: [],+ pinnedProgressSessionId: null,+ followProgressSession: vi.fn(),notifications: {add: (...args: unknown[]) => mocks.notificationsAdd(...args),reportError: (...args: unknown[]) => mocks.notificationsReportError(...args),},projectId: 'project-1',projectName: 'Project',- queueItems: [],widgets: { openGallery: () => true, patchGalleryValues },};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsxindex 9cffbd59c8..88cc5aaa95 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx@@ -76,7 +76,6 @@ const NoopProvider = ({ children }: { children: ReactNode }) => children;const adapter: GalleryUiAdapter = {ItemActionsProvider: NoopProvider,ImageContextMenu: () => null,- account: { enableLiveFollow: noop },antialiasProgressImages: false,exportProject: vi.fn(),gallery: {@@ -99,14 +98,15 @@ const adapter: GalleryUiAdapter = {galleryValues: {},generateValues: {},liveFollowEnabled: false,- liveProgressTarget: null,+ progressSessions: [],+ pinnedProgressSessionId: null,+ followProgressSession: vi.fn(),notifications: {add: (...args: unknown[]) => mocks.notificationsAdd(...args),reportError: (...args: unknown[]) => mocks.notificationsReportError(...args),},projectId: 'project-1',projectName: 'Project',- queueItems: [],widgets: { openGallery: () => true, patchGalleryValues: noop },};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsxindex b32c05062a..1091d3498e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx@@ -189,3 +189,7 @@ describe('preview floating Invoke control', () => {expect(executeCommand).not.toHaveBeenCalled();});});++vi.mock('./livePreviewFollow', () => ({+ useLivePreviewFollow: () => ({ sessions: [], pinnedSessionId: null, pin: vi.fn(), showAll: vi.fn() }),+}));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsxindex eb35bdcabe..944dacaffb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx@@ -1,7 +1,6 @@import type { WidgetViewProps } from '@workbench/widgetContracts';import { Box, HStack, Icon } from '@chakra-ui/react';-import { useProgressImage } from '@features/queue/react';import { IconButton, ToggleIconButton, Tooltip } from '@platform/ui';import { useInvocationState } from '@workbench/shell/topbar/useInvocationState';import { getProjectWidgetValues } from '@workbench/widgetState';@@ -10,6 +9,7 @@ import { GalleryThumbnailsIcon, HourglassIcon, SparklesIcon } from 'lucide-reactimport { useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { useLivePreviewFollow } from './livePreviewFollow';import { PreviewActionStrip } from './PreviewActionStrip';import { usePreviewHeaderContext } from './previewHeaderStore';import { getPreviewFilmstripVisible } from './previewSettings';@@ -28,8 +28,9 @@ import { getPreviewFilmstripVisible } from './previewSettings';*/export const PreviewHeaderActions = ({ region, runtime }: WidgetViewProps) => {const { t } = useTranslation();+ const livePreview = useLivePreviewFollow();const showProgressImagesInViewer = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);- const hasProgressImage = useProgressImage() !== null;+ const hasProgressImage = livePreview.sessions.length > 0;const { actionItem, actions, copyCurrentVideoFrame, isVideoFrameCopyAvailable, openItemMenu, openVideoDetails } =usePreviewHeaderContext();const isFilmstripVisible = useActiveProjectSelector((project) =>@@ -40,10 +41,10 @@ export const PreviewHeaderActions = ({ region, runtime }: WidgetViewProps) => {? t('widgets.preview.hideInProgressDiffusion'): t('widgets.preview.showInProgressDiffusion');const filmstripLabel = isFilmstripVisible ? t('widgets.preview.hideFilmstrip') : t('widgets.preview.showFilmstrip');- const toggleProgressImages = useCallback(- () => account.updateProjectPreferences({ showProgressImagesInViewer: !showProgressImagesInViewer }),- [account, showProgressImagesInViewer]- );+ const toggleProgressImages = useCallback(() => {+ livePreview.showAll();+ account.updateProjectPreferences({ showProgressImagesInViewer: !showProgressImagesInViewer });+ }, [account, livePreview, showProgressImagesInViewer]);const toggleFilmstrip = useCallback(() => widgets.patchValues('preview', { filmstripVisible: !isFilmstripVisible }),[isFilmstripVisible, widgets]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsxindex 8e492862ba..434c070aff 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx@@ -491,6 +491,10 @@ describe('Multi-session live preview tiles', () => {const placeholder = {backendItemId: 1,boardId: 'none',+ label: 'Generate',+ sourceId: 'generate' as const,+ itemCount: 1,+ state: 'running' as const,height: 512,id: 'queue-1:0',itemIndex: 0,@@ -557,3 +561,7 @@ describe('Multi-session live preview tiles', () => {expect(captionInsideFrame).toBeNull();});});++vi.mock('./livePreviewFollow', () => ({+ useLivePreviewFollow: () => ({ sessions: [], pinnedSessionId: null, pin: vi.fn(), showAll: vi.fn() }),+}));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.tsxindex 343e9613fc..7d053ec776 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx@@ -9,12 +9,15 @@ import { requestGalleryItemReveal } from '@features/gallery/contracts';import { QueryClient, QueryClientProvider, type InfiniteData } from '@tanstack/react-query';import { system } from '@theme/system';import i18next from 'i18next';-import { act } from 'react';+import { act, useCallback } 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';+import { LivePreviewFollowProvider, useLivePreviewFollow } from './livePreviewFollow';+const queueItem: QueueItem = {+ backendItemIds: [1],cancellable: true,id: 'queue-item-live',snapshot: {@@ -91,6 +94,7 @@ const mocks = vi.hoisted(() => {widgets: { patchValues: vi.fn() },},project: {+ id: 'project-1',queue: { items: [] as unknown[] },settings: { antialiasProgressImages: false, showProgressImagesInViewer: false },widgetInstances: {@@ -122,7 +126,7 @@ const mocks = vi.hoisted(() => {},recentImages,bridgeProgressImage: null as unknown,- runningProgressTargets: undefined as unknown[] | undefined,+ runningProgressTargets: undefined as { queueItemId: string; itemIndex: number }[] | undefined,slotProgressImage: undefined as unknown,useActiveProgressTarget: vi.fn(() => null as unknown),useProgressImage: vi.fn(() => null as unknown),@@ -140,7 +144,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({}));const mockProgressTargets = () => {- const target = mocks.useActiveProgressTarget();+ const target = mocks.useActiveProgressTarget() as { queueItemId: string; itemIndex: number } | null;return target ? [target] : [];};@@ -149,7 +153,12 @@ vi.mock('@features/queue/react', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),useActiveProgressTarget: () => mocks.useActiveProgressTarget(),useActiveProgressTargets: () => mocks.runningProgressTargets ?? mockProgressTargets(),- useFollowedProgressTargets: () => mockProgressTargets(),+ useFollowedProgressTargets: () =>+ [...(mocks.runningProgressTargets ?? []), ...mockProgressTargets()].filter(+ (target, index, all) =>+ all.findIndex((other) => other.queueItemId === target.queueItemId && other.itemIndex === target.itemIndex) ===+ index+ ),useProgressImage: () => mocks.useProgressImage(),useQueueItemBridgeProgressImage: () => mocks.bridgeProgressImage,// The slot's own frame: derived from the "latest" mock by target unless a test overrides it.@@ -309,6 +318,15 @@ let root: Root | null = null;let queryClient: QueryClient | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+let followControls: ReturnType<typeof useLivePreviewFollow>;+const FollowProbe = () => {+ const controls = useLivePreviewFollow();+ const ref = useCallback(() => {+ followControls = controls;+ }, [controls]);+ return <span ref={ref} />;+};+const renderTree = async (client: QueryClient) => {await act(async () => {root?.render(@@ -316,7 +334,10 @@ const renderTree = async (client: QueryClient) => {<ChakraProvider value={system}><QueryClientProvider client={client}><DndContext>- <PreviewWidgetView instance={instance} manifest={manifest} region="center" runtime={runtime} />+ <LivePreviewFollowProvider>+ <FollowProbe />+ <PreviewWidgetView instance={instance} manifest={manifest} region="center" runtime={runtime} />+ </LivePreviewFollowProvider></DndContext></QueryClientProvider></ChakraProvider>@@ -1420,7 +1441,7 @@ describe('preview keyboard navigation boundary', () => {);});- it('enables live-follow when stepping onto the active placeholder', async () => {+ it('does not insert live sessions into saved-image navigation', async () => {mocks.project.queue.items = [queueItem];mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });mocks.useProgressImage.mockReturnValue({@@ -1431,18 +1452,12 @@ describe('preview keyboard navigation boundary', () => {});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.account.updateProjectPreferences).not.toHaveBeenCalled();expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();});- it('keeps arrow navigation working while following live', async () => {+ it('disables saved-image arrow navigation 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) => ({@@ -1458,17 +1473,8 @@ describe('preview keyboard navigation boundary', () => {});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.selectItem).toHaveBeenCalledTimes(1);- expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(- expect.objectContaining({ kind: 'image', name: 'newest' }),- undefined,- expect.any(Number),- true- );+ expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();});it('renders the live frame with the standard media chrome: footer up, no badge, item border', async () => {@@ -1494,7 +1500,7 @@ describe('preview keyboard navigation boundary', () => {expect(host?.querySelector<HTMLImageElement>('img[src^="data:image/png"]')).not.toBeNull();});- it('uses the active placeholder board while following live, even before an image frame arrives', async () => {+ it('keeps board navigation in its saved-image context while another board generates', async () => {const liveBoardImage = {...mocks.project.widgetInstances.gallery.state.values.recentImages[0],boardId: 'board-live',@@ -1512,12 +1518,8 @@ describe('preview keyboard navigation boundary', () => {await render();await pressArrow('ArrowRight');- expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(- expect.objectContaining({ boardId: 'board-live', kind: 'image', name: 'live-board-image' }),- undefined,- expect.any(Number),- true- );+ expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();+ expect(mocks.galleryItemFilters.every((filter) => filter.boardId !== 'board-live')).toBe(true);});it('keeps following a completed slot while its result is still routing', async () => {@@ -1599,6 +1601,47 @@ describe('preview keyboard navigation boundary', () => {expect(host?.querySelector<HTMLImageElement>('img[src="data:image/png;base64,slot-one"]')).toBeNull();});+ it('pins one concurrent session, returns to overview, and continues after the pinned session settles', async () => {+ mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2] }];+ mocks.project.settings.showProgressImagesInViewer = true;+ mocks.runningProgressTargets = [+ { queueItemId: queueItem.id, itemIndex: 1 },+ { queueItemId: queueItem.id, itemIndex: 2 },+ ];+ mocks.slotProgressImage = { dataUrl: 'data:image/png;base64,live', width: 64, height: 64 };+ await render();+ expect(host?.querySelectorAll('img[src^="data:image/png"]')).toHaveLength(2);+ await act(() => followControls.pin('queue-item-live:2'));+ expect(host?.querySelectorAll('img[src^="data:image/png"]')).toHaveLength(1);+ expect(followControls.pinnedSessionId).toBe('queue-item-live:2');+ await act(() => followControls.showAll());+ expect(host?.querySelectorAll('img[src^="data:image/png"]')).toHaveLength(2);+ await act(() => followControls.pin('queue-item-live:2'));+ mocks.runningProgressTargets = [{ queueItemId: queueItem.id, itemIndex: 1 }];+ await rerender();+ expect(followControls.pinnedSessionId).toBeNull();+ expect(host?.querySelectorAll('img[src^="data:image/png"]')).toHaveLength(1);+ });++ it('keeps live previews available during similarity search and temporary comparison override', async () => {+ mocks.project.queue.items = [queueItem];+ mocks.project.settings.showProgressImagesInViewer = true;+ mocks.runningProgressTargets = [{ queueItemId: queueItem.id, itemIndex: 1 }];+ mocks.slotProgressImage = { dataUrl: 'data:image/png;base64,live', width: 64, height: 64 };+ const values = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;+ values.semanticImageQuery = { kind: 'text', query: 'blue sky' };+ values.compareImage = mocks.recentImages[1];+ await render();+ expect(host?.querySelectorAll('img[src^="data:image/png"]')).toHaveLength(1);+ await act(() => followControls.pin('queue-item-live:1'));+ mocks.project.id = 'project-2';+ mocks.project.queue.items = [];+ await rerender();+ expect(followControls.pinnedSessionId).toBeNull();+ expect(followControls.sessions).toEqual([]);+ mocks.project.id = 'project-1';+ });+it('orders local images oldest-first when the gallery is ascending', async () => {(mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).imageOrderDir = 'ASC';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 082f1c9e2b..8e241b3ff1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -1,5 +1,5 @@import type { SystemStyleObject } from '@chakra-ui/react';-import type { QueueItem } from '@features/queue/contracts';+import type { QueueActiveSession, QueueItem } from '@features/queue/contracts';import type { WidgetViewProps } from '@workbench/widgetContracts';import { Box, Flex, SimpleGrid, Stack, Text } from '@chakra-ui/react';@@ -15,8 +15,6 @@ import {} from '@features/gallery';import {getGalleryCompareImage,- getGalleryGenerationSequence,- getGalleryLiveSlots,getGalleryPage,getGallerySelectedImageQuery,getGallerySemanticImageQuery,@@ -30,7 +28,6 @@ import {requestGalleryItemReveal,toGalleryItemKey,toGalleryItemRef,- type GalleryQueuePlaceholder,} from '@features/gallery/contracts';import { galleryBoardsOptions } from '@features/gallery/queries';import { createGenerateFormValuesSelector } from '@features/generation/react';@@ -38,13 +35,12 @@ import { getDeterminateProgressPercent } from '@features/queue/contracts';import { useDeviceLabel } from '@features/queue/devices';import {consumeQueueItemSwapProgressImage,- useActiveProgressTargets,- useFollowedProgressTargets,useItemProgress,useQueueItemBridgeProgressImage,useQueueItemProgressImage,useQueueItemSwapProgressImage,} from '@features/queue/react';+import { Button } from '@platform/ui';import {imageUrlToStreamingSource,progressImageToStreamingSource,@@ -73,6 +69,7 @@ import { useTranslation } from 'react-i18next';import type { PreviewLoupeControls } from './usePreviewLoupe';+import { useLivePreviewFollow } from './livePreviewFollow';import { PreviewCompare } from './PreviewCompare';import { resolvePreviewCompareDrop } from './previewCompareDnd';import { usePreviewDensity, type PreviewDensity } from './previewDensity';@@ -194,9 +191,8 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const { antialiasProgressImages, showProgressImagesInViewer } = useActiveProjectSelector((project) => project.settings);- const runningProgressTargets = useActiveProgressTargets();- const followedProgressTargets = useFollowedProgressTargets();- const { account, gallery, notifications, widgets } = useWorkbenchCommands();+ const livePreview = useLivePreviewFollow();+ const { gallery, notifications, widgets } = useWorkbenchCommands();const queries = useWorkbenchQueries();const { density, rootRef } = usePreviewDensity(region);const recentImages = galleryValues.recentImages;@@ -206,7 +202,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const comparisonMode = getPreviewComparisonMode(previewValues);const displayBoardId = selectedItem?.boardId ?? 'none';const hasSelectedItem = selectedItem !== null;- const { imageOrderDir } = getGallerySettings(galleryValues);const selectedImageQuery = getGallerySelectedImageQuery(galleryValues);// The gallery's live similarity search: when one is active the grid shows a// ranked result set, and navigation has to walk that same list. Memoized on@@ -219,40 +214,29 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {);const selectedItemKey = selectedItem ? toGalleryItemKey(selectedItem) : null;const isComparing =+ !showProgressImagesInViewer &&selectedItem?.kind === 'image' &&compareImage !== null &&toGalleryItemKey({ kind: 'image', name: compareImage.imageName }) !== selectedItemKey;- const generationSequence = useMemo(() => getGalleryGenerationSequence(queueItems, null), [queueItems]);- // Multi-GPU runs one session per GPU, so several slots can be live at once. One- // live slot keeps the existing single-frame preview; two or more are tiled.- // Running slots only: a slot settling after completion must not turn a- // single-GPU batch into a two-tile grid at every item boundary.const liveGalleryPlaceholders = useMemo(- () => getGalleryLiveSlots(generationSequence.chronologicalSlots, runningProgressTargets),- [generationSequence.chronologicalSlots, runningProgressTargets]+ () => livePreview.sessions.filter((session) => session.state === 'running'),+ [livePreview.sessions]);- // The slot to follow: the oldest running one, else the oldest settling one. A- // completed slot stays followed until its result routing lands, and routing- // removes its placeholder first — so the followed set is filtered against the- // placeholders that exist rather than trusting a single target that may have- // just vanished. That routing window is where Preview used to fall back onto- // the previous selection before the finished image was selected. A running- // slot wins over a settling one so a concurrent session's live stream is- // never hidden behind a static frame.- const activeGalleryPlaceholder = useMemo(- () =>- liveGalleryPlaceholders[0] ??- getGalleryLiveSlots(generationSequence.chronologicalSlots, followedProgressTargets)[0] ??- null,- [followedProgressTargets, generationSequence.chronologicalSlots, liveGalleryPlaceholders]- );- // Not while a similarity search is active: the grid hides pending items- // there entirely, so following the generation would put Preview on a tile- // the grid is not showing and, worse, hand the arrows the board listing- // while the grid shows a ranking.- const shouldFollowLive =- showProgressImagesInViewer && activeGalleryPlaceholder !== null && !isComparing && gallerySemanticQuery === null;+ const pinnedSession = livePreview.sessions.find((session) => session.id === livePreview.pinnedSessionId);+ const activeGalleryPlaceholder = pinnedSession ?? liveGalleryPlaceholders[0] ?? livePreview.sessions[0] ?? null;+ const shouldFollowLive = showProgressImagesInViewer && activeGalleryPlaceholder !== null;const { t } = useTranslation();+ const navigationBoundaryRef = useRef<HTMLDivElement | null>(null);+ const overviewButtonRef = useCallback((element: HTMLButtonElement | null) => {+ if (!element) {+ return;+ }+ return () => {+ if (document.activeElement === element) {+ queueMicrotask(() => navigationBoundaryRef.current?.focus({ preventScroll: true }));+ }+ };+ }, []);const loupeControlsRef = useRef<PreviewLoupeControls | null>(null);const videoControllerRef = useRef<PreviewVideoFrameController | null>(null);const [copyAvailableItemKey, setCopyAvailableItemKey] = useState<GalleryItemKey | null>(null);@@ -269,10 +253,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {t('widgets.gallery.unknownBoard'));- const enableLiveFollow = useCallback(- () => account.updateProjectPreferences({ showProgressImagesInViewer: true }),- [account]- );const selectGalleryItemAtPage = useCallback((item: GalleryItem, selectionPage: number) => {gallery.selectItem(item, undefined, selectionPage, true);@@ -292,9 +272,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {navigationSequence,selectPreviewItem,} = usePreviewNavigation({- activePlaceholder: activeGalleryPlaceholder,- enableLiveFollow,- imageOrderDir,isComparing,localItems,queueItems,@@ -605,7 +582,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {{/* Single always-mounted keyboard boundary: DOM focus survives swapsbetween the live, selected, and compare branches, so arrownavigation keeps working across them. */}+ {shouldFollowLive && pinnedSession ? (+ <Button ref={overviewButtonRef} alignSelf="start" size="2xs" variant="ghost" onClick={livePreview.showAll}>+ {t('widgets.preview.showAllActivePreviews')}+ </Button>+ ) : null}<Stack+ ref={navigationBoundaryRef}aria-label={t('widgets.labels.preview')}gap="0"h="full"@@ -616,19 +599,19 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {w="full"onKeyDown={handleNavigationKeyDown}>- {shouldFollowLive && liveGalleryPlaceholders.length > 1 ? (+ {shouldFollowLive && !pinnedSession && liveGalleryPlaceholders.length > 1 ? (<LivePreviewTilesplaceholders={liveGalleryPlaceholders}shouldAntialiasProgressImage={antialiasProgressImages}/>) : shouldFollowLive && activeGalleryPlaceholder ? (<LivePreview- boardItemCount={navigationSequence.length}+ boardItemCount={0}density={density}filmstripItems={isFilmstripVisible && density !== 'minimal' ? boardItems : null}isLoadingBoard={isLoadingBoard}placeholder={activeGalleryPlaceholder}- selectedIndex={navigationCursor}+ selectedIndex={-1}shouldAntialiasProgressImage={antialiasProgressImages}onNext={selectNextItem}onPrevious={selectPreviousItem}@@ -933,7 +916,7 @@ const LivePreview = ({density: PreviewDensity;filmstripItems: GalleryItem[] | null;isLoadingBoard: boolean;- placeholder: GalleryQueuePlaceholder;+ placeholder: QueueActiveSession;selectedIndex: number;shouldAntialiasProgressImage: boolean;onNext: () => void;@@ -1010,7 +993,7 @@ export const LivePreviewTile = ({placeholder,shouldAntialiasProgressImage,}: {- placeholder: GalleryQueuePlaceholder;+ placeholder: QueueActiveSession;shouldAntialiasProgressImage: boolean;}) => {const { t } = useTranslation();@@ -1070,7 +1053,7 @@ export const LivePreviewTiles = ({placeholders,shouldAntialiasProgressImage,}: {- placeholders: GalleryQueuePlaceholder[];+ placeholders: QueueActiveSession[];shouldAntialiasProgressImage: boolean;}) => (<SimpleGrid gap="2" h="full" minH="0" columns={placeholders.length > 2 ? 2 : placeholders.length}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsxnew file mode 100644index 0000000000..d76b1ce4e3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx@@ -0,0 +1,68 @@+import type { QueueActiveSession, QueueProgressSession } from '@features/queue/contracts';+import type { ReactNode } from 'react';++import { getQueueActiveSessions, getQueueProgressSessions, isGalleryProgressItem } from '@features/queue/contracts';+import { useActiveProgressTargets, useFollowedProgressTargets } from '@features/queue/react';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { createContext, use, useMemo, useState } from 'react';++interface LivePreviewFollow {+ sessions: QueueActiveSession[];+ gallerySessions: QueueProgressSession[];+ pinnedSessionId: string | null;+ pin(sessionId: string): void;+ showAll(): void;+}++const LivePreviewFollowContext = createContext<LivePreviewFollow | null>(null);++/** Owned by the mounted Workbench, never persisted with project documents. */+export const LivePreviewFollowProvider = ({ children }: { children: ReactNode }) => {+ const { projectId, items, enabled } = useActiveProjectSelector((project) => ({+ projectId: project.id,+ items: project.queue.items,+ enabled: project.settings.showProgressImagesInViewer,+ }));+ const running = useActiveProgressTargets();+ const followed = useFollowedProgressTargets();+ const sessions = useMemo(+ () => getQueueActiveSessions(items.filter(isGalleryProgressItem), running, followed),+ [items, running, followed]+ );+ const gallerySessions = useMemo(+ () => getQueueProgressSessions(items.filter(isGalleryProgressItem), sessions),+ [items, sessions]+ );+ const [selection, setSelection] = useState<{ projectId: string; sessionId: string | null }>({+ projectId,+ sessionId: null,+ });+ const isStale =+ selection.projectId !== projectId ||+ !enabled ||+ (selection.sessionId !== null &&+ !sessions.some((session) => session.id === selection.sessionId && session.state === 'running'));+ if (isStale && (selection.sessionId !== null || selection.projectId !== projectId)) {+ setSelection({ projectId, sessionId: null });+ }+ const pinnedSessionId = isStale ? null : selection.sessionId;+ const value = useMemo<LivePreviewFollow>(+ () => ({+ sessions,+ gallerySessions,+ pinnedSessionId,+ pin: (sessionId) => setSelection({ projectId, sessionId }),+ showAll: () => setSelection({ projectId, sessionId: null }),+ }),+ [sessions, gallerySessions, pinnedSessionId, projectId]+ );+ return <LivePreviewFollowContext value={value}>{children}</LivePreviewFollowContext>;+};++export const useLivePreviewFollow = (): LivePreviewFollow => {+ const context = use(LivePreviewFollowContext);+ if (!context) {+ throw new Error('Live preview requires its Workbench provider.');+ }+ return context;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.tsindex 474d4a0226..e00ea60bb9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts@@ -1,158 +1,31 @@-import type { GalleryItemKind, GalleryItemKey, GalleryQueuePlaceholder } from '@features/gallery/contracts';-import { describe, expect, it } from 'vitest';import {getPreviewNavigationCursor,getPreviewNavigationSequence,getPreviewNavigationTarget,- type PreviewNavigationItem,} from './previewNavigation';-interface TestItem {- kind: GalleryItemKind;- name: string;- starred?: boolean;-}--const placeholder: GalleryQueuePlaceholder = {- backendItemId: null,- boardId: 'none',- height: 1024,- id: 'queue-1:1',- itemIndex: 1,- queueItemId: 'queue-1',- width: 1024,-};--const item = (kind: GalleryItemKind, name: string, starred = false): TestItem => ({ kind, name, starred });--const keys = (sequence: PreviewNavigationItem<TestItem>[]): string[] =>- sequence.map((entry) => (entry.kind === 'item' ? `${entry.item.kind}:${entry.item.name}` : 'placeholder'));--const buildSequence = (overrides: Partial<Parameters<typeof getPreviewNavigationSequence<TestItem>>[0]> = {}) =>- getPreviewNavigationSequence<TestItem>({- activePlaceholder: placeholder,- boardId: 'none',- boardImages: [item('image', 'newest'), item('video', 'middle'), item('image', 'oldest')],- galleryView: 'images',- imageOrderDir: 'DESC',- ...overrides,- });--describe('getPreviewNavigationSequence', () => {- it('places the placeholder at the newest position in descending order', () => {- expect(keys(buildSequence())).toEqual(['placeholder', 'image:newest', 'video:middle', 'image:oldest']);- });-- it('places the placeholder at the latest chronological position in ascending order', () => {- expect(keys(buildSequence({ imageOrderDir: 'ASC' }))).toEqual([- 'image:newest',- 'video:middle',- 'image:oldest',- 'placeholder',- ]);- });-- it('places the placeholder first in a descending listing even when starred items lead it', () => {- expect(- keys(- buildSequence({- boardImages: [item('image', 'starred-newest', true), item('image', 'older')],- })- )- ).toEqual(['placeholder', 'image:starred-newest', 'image:older']);- });-- it('excludes the placeholder when it belongs to another board or the assets view', () => {- expect(keys(buildSequence({ boardId: 'board-2' }))).toEqual(['image:newest', 'video:middle', 'image:oldest']);- expect(keys(buildSequence({ galleryView: 'assets' }))).toEqual(['image:newest', 'video:middle', 'image:oldest']);- });-- it('returns only completed media items when there is no active placeholder', () => {- expect(keys(buildSequence({ activePlaceholder: null }))).toEqual(['image:newest', 'video:middle', 'image:oldest']);- });-- it('keeps same-name images and videos as independent navigation entries', () => {- expect(- keys(- buildSequence({- activePlaceholder: null,- boardImages: [item('image', 'shared'), item('video', 'shared')],- })- )- ).toEqual(['image:shared', 'video:shared']);- });-});--describe('getPreviewNavigationCursor', () => {- const sequence = buildSequence();-- it('resolves to the placeholder while following live', () => {- expect(getPreviewNavigationCursor(sequence, { isFollowingLive: true, selectedItemKey: 'video:middle' })).toBe(0);- });-- it('resolves the selected media kind and name otherwise', () => {- expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedItemKey: 'video:middle' })).toBe(2);-- const sameName = buildSequence({- activePlaceholder: null,- boardImages: [item('image', 'shared'), item('video', 'shared')],- });- expect(getPreviewNavigationCursor(sameName, { isFollowingLive: false, selectedItemKey: 'image:shared' })).toBe(0);- expect(getPreviewNavigationCursor(sameName, { isFollowingLive: false, selectedItemKey: 'video:shared' })).toBe(1);- });-- it('is unresolved when the selected item is absent from the sequence', () => {- expect(- getPreviewNavigationCursor(sequence, {- isFollowingLive: false,- selectedItemKey: 'image:missing' as GalleryItemKey,- })- ).toBe(-1);- expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedItemKey: null })).toBe(-1);- });-});--describe('getPreviewNavigationTarget', () => {- const sequence = buildSequence();-- it('moves exactly one position in either direction', () => {- expect(getPreviewNavigationTarget(sequence, 2, -1)).toEqual({- item: item('image', 'newest'),- kind: 'item',- });- expect(getPreviewNavigationTarget(sequence, 2, 1)).toEqual({- item: item('image', 'oldest'),- kind: 'item',- });- });-- it('steps between the newest item and the placeholder in descending order', () => {- expect(getPreviewNavigationTarget(sequence, 1, -1)).toEqual({ kind: 'placeholder', placeholder });- expect(getPreviewNavigationTarget(sequence, 0, 1)).toEqual({- item: item('image', 'newest'),- kind: 'item',- });- });-- it('steps between the oldest item 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({- item: item('image', 'oldest'),- kind: 'item',- });- });-- it('clamps at both sequence boundaries', () => {+const images = [+ { kind: 'image' as const, name: 'same-name' },+ { kind: 'video' as const, name: 'same-name' },+ { kind: 'image' as const, name: 'older' },+];++describe('saved-image preview navigation', () => {+ it('preserves the board order and distinguishes same-name media', () => {+ const sequence = getPreviewNavigationSequence({ boardImages: images });+ const cursor = getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedItemKey: 'video:same-name' });+ expect(getPreviewNavigationTarget(sequence, cursor, -1)?.item).toEqual(images[0]);+ expect(getPreviewNavigationTarget(sequence, cursor, 1)?.item).toEqual(images[2]);expect(getPreviewNavigationTarget(sequence, 0, -1)).toBeNull();- expect(getPreviewNavigationTarget(sequence, sequence.length - 1, 1)).toBeNull();+ expect(getPreviewNavigationTarget(sequence, 2, 1)).toBeNull();});-- it('is a no-op for an unresolved cursor', () => {- expect(getPreviewNavigationTarget(sequence, -1, -1)).toBeNull();- expect(getPreviewNavigationTarget(sequence, -1, 1)).toBeNull();+ it('has no board cursor while following a live session or without a saved selection', () => {+ const sequence = getPreviewNavigationSequence({ boardImages: images });+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: true, selectedItemKey: 'video:same-name' })).toBe(+ -1+ );+ expect(getPreviewNavigationCursor(sequence, { isFollowingLive: false, selectedItemKey: null })).toBe(-1);});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.tsindex 84321ba471..c7b195c358 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts@@ -1,69 +1,26 @@-import type {- GalleryItemKind,- GalleryItemKey,- GalleryOrderDir,- GalleryQueuePlaceholder,- GalleryView,-} from '@features/gallery/contracts';+import type { GalleryItemKey } from '@features/gallery/contracts';-import { getGalleryPlaceholderInsertionIndex, toGalleryItemKey } 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.- */+import { toGalleryItemKey } from '@features/gallery/contracts';interface NavigableItem {- kind: GalleryItemKind;+ kind: 'image' | 'video';name: string;}+export type PreviewNavigationItem<TItem extends NavigableItem> = { kind: 'item'; item: TItem };-export type PreviewNavigationItem<TItem extends NavigableItem> =- | { kind: 'item'; item: TItem }- | { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };-+/** Saved-image navigation never assigns a live session to a board. */export const getPreviewNavigationSequence = <TItem extends NavigableItem>({- activePlaceholder,- boardId,boardImages,- galleryView,- imageOrderDir,}: {- /** The live slot from getGalleryGenerationSequence, or null. */- activePlaceholder: GalleryQueuePlaceholder | null;- /** The board backing boardImages — the selected item's own board. */- boardId: string;- /** Board items in the gallery's display order. */boardImages: TItem[];- galleryView: GalleryView;- imageOrderDir: GalleryOrderDir;-}): PreviewNavigationItem<TItem>[] => {- const items: PreviewNavigationItem<TItem>[] = boardImages.map((item) => ({ item, kind: 'item' }));- const includePlaceholder =- activePlaceholder !== null && galleryView === 'images' && activePlaceholder.boardId === boardId;-- if (!includePlaceholder) {- return items;- }-- items.splice(getGalleryPlaceholderInsertionIndex(boardImages.length, imageOrderDir), 0, {- kind: 'placeholder',- placeholder: activePlaceholder,- });-- return items;-};+}): PreviewNavigationItem<TItem>[] => boardImages.map((item) => ({ kind: 'item', item }));export const getPreviewNavigationCursor = <TItem extends NavigableItem>(sequence: PreviewNavigationItem<TItem>[],{ isFollowingLive, selectedItemKey }: { isFollowingLive: boolean; selectedItemKey: GalleryItemKey | null }): number => {if (isFollowingLive) {- return sequence.findIndex((item) => item.kind === 'placeholder');+ return -1;}if (selectedItemKey === null) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex c872b6f758..3d024ad521 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -1,6 +1,5 @@import type { GalleryImageItem, GalleryItem, GalleryItemKey, GalleryView } from '@features/gallery';import type {- GalleryQueuePlaceholder,GalleryItemsPage,GallerySemanticReference,getGallerySelectedImageQuery,@@ -133,9 +132,6 @@ export interface PreviewNavigationState {}export const usePreviewNavigation = ({- activePlaceholder,- enableLiveFollow,- imageOrderDir,isComparing,localItems,queueItems,@@ -148,16 +144,10 @@ export const usePreviewNavigation = ({semanticQuery,shouldFollowLive,}: {- /** The live slot from getGalleryGenerationSequence, or null. */- activePlaceholder: GalleryQueuePlaceholder | null;- /** Turns the live-follow preference back on (stepping onto the placeholder). */- enableLiveFollow: () => void;/** The page the gallery grid is on; a ranked list mirrors it (see below). */galleryPage: number;/** The gallery's own pagination mode, likewise mirrored by a ranked list. */galleryPaginationMode: 'infinite' | 'paginated';- /** The gallery's own sort settings, used while following live. */- imageOrderDir: 'ASC' | 'DESC';isComparing: boolean;/** Recent local generations, already normalized to gallery items. */localItems: GalleryImageItem[];@@ -175,27 +165,17 @@ export const usePreviewNavigation = ({() => parseDateTokens(selectedImageQuery.searchTerm),[selectedImageQuery.searchTerm]);- const navigationBoardId =- shouldFollowLive && activePlaceholder ? activePlaceholder.boardId : selectedImageQuery.boardId;- const navigationGalleryView = shouldFollowLive ? 'images' : selectedImageQuery.galleryView;- const navigationOrderDir = shouldFollowLive ? imageOrderDir : selectedImageQuery.imageOrderDir;- // The grid partitions starred items into its strip, so Preview walks the- // list the selected item belongs to: the starred one for a starred item or- // under the starred filter, the unstarred listing otherwise. Following live- // means watching the board a (never starred) result lands in, so the- // filter is dropped for that mode as the search is.- const navigationStarredOnly = !shouldFollowLive && (selectedImageQuery.starredOnly || selectedItem?.starred === true);- // Read from the gallery's CURRENT search, not from a copy stamped onto the- // selection: the chip is a view mode, and Preview has to follow it the- // moment it is set or cleared or it walks a list that is no longer on- // screen. Following live means watching the board a generation is landing- // in, which no ranked result set describes, so the search is dropped for- // that mode exactly as the board's own search term is.- const navigationSemanticQuery = shouldFollowLive ? null : semanticQuery;+ const navigationBoardId = selectedImageQuery.boardId;+ const navigationGalleryView = selectedImageQuery.galleryView;+ const navigationOrderDir = selectedImageQuery.imageOrderDir;+ // Navigate the saved selection's listing even while live progress overlays it.+ const navigationStarredOnly = selectedImageQuery.starredOnly || selectedItem?.starred === true;+ // A ranked filmstrip follows the gallery's current search.+ const navigationSemanticQuery = semanticQuery;const navigationSemanticKey = gallerySemanticReferenceKey(navigationSemanticQuery);- const hasNavigationContext = shouldFollowLive || hasSelectedItem;+ const hasNavigationContext = hasSelectedItem;const navigationContextKey = `${shouldFollowLive}:${selectedItemKey ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${selectedImageQuery.searchTerm}:${navigationStarredOnly}:${navigationSemanticKey}`;- const navigationQueryKey = `${shouldFollowLive}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.searchTerm}:${navigationStarredOnly}:${navigationSemanticKey}`;+ const navigationQueryKey = `${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.searchTerm}:${navigationStarredOnly}:${navigationSemanticKey}`;// Lets a boundary fetch that resolves after the user has moved on compare the// context it started in against the one now on screen, and drop its stale@@ -244,7 +224,7 @@ export const usePreviewNavigation = ({? selectedImageQuery.page: navigationAnchor.page: selectedImageQuery.page;- const isPaginatedWindow = !shouldFollowLive && selectedImageQuery.paginationMode === 'paginated';+ const isPaginatedWindow = selectedImageQuery.paginationMode === 'paginated';// A selection deeper than the base window's reach (a deep reveal from the// image map) anchors navigation at its own page — walking from offset 0// could never arrive at the cursor. Such a window is a slice from the@@ -254,7 +234,6 @@ export const usePreviewNavigation = ({// anchor must stay where the selection was made, and the exclusions below// that hinge on "is this window mid-board?" are all derived from it.const deepAnchorOffset =- !shouldFollowLive &&!isPaginatedWindow &&navigationSemanticQuery === null &&navigationAnchorPage * GALLERY_PAGE_SIZE >= GALLERY_MAX_ROWS@@ -267,9 +246,8 @@ export const usePreviewNavigation = ({// shorter than the board, on an empty one whose only member is the anchored// selection, leaving both arrows with nowhere to step. Setting a search also// resets the grid's page, which the stamped record never sees.- const navigationWindow = shouldFollowLive- ? ({ kind: 'infinite' } as const)- : navigationSemanticQuery !== null+ const navigationWindow =+ navigationSemanticQuery !== null? galleryPaginationMode === 'paginated'? ({ kind: 'anchor', offset: galleryPage * GALLERY_PAGE_SIZE } as const): // In infinite mode the grid's page IS its window offset, so mirroring@@ -292,11 +270,11 @@ export const usePreviewNavigation = ({...galleryItemsInfiniteOptions({boardId: navigationBoardId,- createdFrom: shouldFollowLive ? undefined : selectedImageSearch.range?.from,- createdTo: shouldFollowLive ? undefined : selectedImageSearch.range?.to,+ createdFrom: selectedImageSearch.range?.from,+ createdTo: selectedImageSearch.range?.to,galleryView: navigationGalleryView,orderDir: navigationOrderDir,- searchTerm: shouldFollowLive ? '' : selectedImageSearch.text,+ searchTerm: selectedImageSearch.text,...(navigationSemanticQuery ? { semanticQuery: navigationSemanticQuery } : {}),// The grid partitions: the listing is unstarred-only unless the// selection was made under the starred filter.@@ -379,17 +357,14 @@ export const usePreviewNavigation = ({// top is not theirs to join; the grid draws the same line for its own// window. There, only in-flight work and the selection merge.const hasActiveSearch =- navigationStarredOnly ||- (!shouldFollowLive && (selectedImageSearch.text.trim() !== '' || selectedImageSearch.range !== undefined));+ navigationStarredOnly || selectedImageSearch.text.trim() !== '' || selectedImageSearch.range !== undefined;if (!hasActiveSearch && !isPaginatedWindow && deepAnchorOffset === 0) {return localItems;}const refreshingSelectedSourceId =- !shouldFollowLive && isFetchingBoardItems && selectedItem?.kind === 'image'- ? selectedItem.sourceQueueItemId- : null;+ isFetchingBoardItems && selectedItem?.kind === 'image' ? selectedItem.sourceQueueItemId : null;return localItems.filter((item) =>@@ -405,7 +380,6 @@ export const usePreviewNavigation = ({optimisticQueueItemIds,selectedImageSearch,selectedItem,- shouldFollowLive,]);const localBoardItems = useMemo(() =>@@ -418,16 +392,12 @@ export const usePreviewNavigation = ({[navigationBoardId, navigationGalleryView, navigationLocalItems, navigationOrderDir]);const previewLocalBoardItems = useMemo(() => {- if (- shouldFollowLive ||- !selectedItem ||- localBoardItems.some((item) => toGalleryItemKey(item) === selectedItemKey)- ) {+ if (!selectedItem || localBoardItems.some((item) => toGalleryItemKey(item) === selectedItemKey)) {return localBoardItems;}return [selectedItem, ...localBoardItems];- }, [localBoardItems, selectedItem, selectedItemKey, shouldFollowLive]);+ }, [localBoardItems, selectedItem, selectedItemKey]);const backendBoardItems = useMemo(() => flattenPreviewItems(boardItemsData), [boardItemsData]);// Recents belong to a board listing; a ranked list gets only the selection,// and only as the cursor anchor described in mergePreviewBoardItems.@@ -446,37 +416,17 @@ export const usePreviewNavigation = ({[backendBoardItems, hasNavigationContext, navigationOrderDir, navigationSemanticQuery, previewMergeItems]);const isLoadingBoard = hasNavigationContext && isFetchingBoardItems;- const navigationSequence = useMemo(- () =>- getPreviewNavigationSequence({- // A ranked result set has no chronological insertion point, so the- // generating placeholder is left out — matching the gallery grid,- // which hides pending items while a similarity search is active.- activePlaceholder: navigationSemanticQuery ? null : activePlaceholder,- boardId: navigationBoardId,- boardImages: boardItems,- galleryView: navigationGalleryView,- imageOrderDir: navigationOrderDir,- }),- [- activePlaceholder,- boardItems,- navigationBoardId,- navigationGalleryView,- navigationOrderDir,- navigationSemanticQuery,- ]- );+ const navigationSequence = useMemo(() => getPreviewNavigationSequence({ boardImages: boardItems }), [boardItems]);const navigationCursor = getPreviewNavigationCursor(navigationSequence, {isFollowingLive: shouldFollowLive,selectedItemKey,});// One navigation action shared by the arrow keys and the footer buttons.- // Compare mode stays inert and never exposes the placeholder.+ // Comparison and live following never step through saved images.const navigate = useCallback((offset: -1 | 1) => {- if (isComparing) {+ if (isComparing || shouldFollowLive) {return;}@@ -496,11 +446,7 @@ export const usePreviewNavigation = ({return;}- if (target.kind === 'item') {- selectPreviewItem(target.item);- } else {- enableLiveFollow();- }+ selectPreviewItem(target.item);return;}@@ -519,16 +465,7 @@ export const usePreviewNavigation = ({const nextBoardItems = mergePreviewBoardItems(nextBackendBoardItems, previewMergeItems, navigationOrderDir, {isRanked: navigationSemanticQuery !== null,});- const nextNavigationSequence = getPreviewNavigationSequence({- // Same exclusion as the render path: a ranked list has no- // chronological slot for the generating placeholder, and inserting- // one here would step onto a tile the sequence never showed.- activePlaceholder: navigationSemanticQuery ? null : activePlaceholder,- boardId: navigationBoardId,- boardImages: nextBoardItems,- galleryView: navigationGalleryView,- imageOrderDir: navigationOrderDir,- });+ const nextNavigationSequence = getPreviewNavigationSequence({ boardImages: nextBoardItems });const nextNavigationCursor = getPreviewNavigationCursor(nextNavigationSequence, {isFollowingLive: shouldFollowLive,selectedItemKey,@@ -540,15 +477,11 @@ export const usePreviewNavigation = ({// render closed over, and a lookup there would read it as an item// the window does not hold.stampSelection(nextTarget.item, result.data);- } else if (nextTarget?.kind === 'placeholder') {- enableLiveFollow();}});},[- activePlaceholder,backendBoardItems,- enableLiveFollow,fetchNextBoardItemsPage,fetchPreviousBoardItemsPage,hasNextBoardItemsPage,@@ -556,10 +489,8 @@ export const usePreviewNavigation = ({isComparing,isFetchingNextBoardItemsPage,isFetchingPreviousBoardItemsPage,- navigationBoardId,navigationContextKey,navigationCursor,- navigationGalleryView,navigationOrderDir,navigationSemanticQuery,navigationSequence,@@ -581,7 +512,7 @@ export const usePreviewNavigation = ({return;}- if (isComparing) {+ if (isComparing || shouldFollowLive) {return;}@@ -591,7 +522,7 @@ export const usePreviewNavigation = ({event.stopPropagation();navigate(event.key === 'ArrowLeft' ? -1 : 1);},- [isComparing, navigate]+ [isComparing, navigate, shouldFollowLive]);// Warm the browser cache for the sequence neighbors so arrow-key navigation