Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(gallery): navigate in-progress, starred and listing as one sequence
Josh Corbett52f0a6fa2ad8
diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsxindex 11403abd30..aafe34edb8 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.browser.test.tsx@@ -32,6 +32,8 @@ vi.mock('@workbench/widgets/preview/livePreviewFollow', () => ({sessions: [],gallerySessions: [],pinnedSessionId: null,+ followedSessionId: null,+ follow: vi.fn(),pin: vi.fn(),showAll: vi.fn(),}),diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsxindex 74b7bb97a5..588bf60a1a 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx@@ -13,6 +13,8 @@ import { GalleryUiAdapterProvider } from './GalleryUiAdapter';let store: ReturnType<typeof createWorkbenchStore>;let adapter: GalleryUiAdapter;const noop = () => undefined;+const livePreviewFollow = vi.fn();+const openWorkbenchWidget = vi.fn();vi.mock('@features/gallery/react', () => ({GalleryUiProvider: ({ adapter: next, children }: { adapter: GalleryUiAdapter; children: ReactNode }) => {@@ -25,12 +27,14 @@ vi.mock('@workbench/widgets/preview/livePreviewFollow', () => ({sessions: [],gallerySessions: [],pinnedSessionId: null,+ followedSessionId: 'run:1',+ follow: livePreviewFollow,pin: vi.fn(),showAll: vi.fn(),}),}));vi.mock('@workbench/projects/useProjectFileActions', () => ({ useExportLibraryProject: () => noop }));-vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => noop }));+vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => openWorkbenchWidget }));vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(store.getSnapshot().activeProject),useWorkbenchCommands: () => store.commands,@@ -44,11 +48,35 @@ const renderAdapter = () => {const values = (projectId: string) => getProjectWidgetValues(store.queries.getProject(projectId)!, 'gallery');beforeEach(() => {+ vi.clearAllMocks();accountLifecycle.activate('gallery-adapter-test');store = createWorkbenchStore();});afterEach(() => accountLifecycle.invalidate());+describe('Gallery live-follow adapter', () => {+ it('passes the followed session through and reveals Preview only for a tile click', () => {+ const owner = renderAdapter();++ expect(owner.followedProgressSessionId).toBe('run:1');++ owner.followProgressSession('run:2', { revealPreview: false });+ expect(livePreviewFollow).toHaveBeenCalledExactlyOnceWith('run:2');+ expect(openWorkbenchWidget).not.toHaveBeenCalled();++ owner.followProgressSession('run:2', { revealPreview: true });+ expect(openWorkbenchWidget).toHaveBeenCalledExactlyOnceWith('preview');+ });++ it('ignores a follow retained across an account change', () => {+ const owner = renderAdapter();++ accountLifecycle.activate('gallery-adapter-test');+ owner.followProgressSession('run:2', { revealPreview: true });+ expect(livePreviewFollow).not.toHaveBeenCalled();+ });+});+describe('Gallery settings adapter ownership', () => {it('updates the captured active project through the Gallery command', () => {const owner = renderAdapter();diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex 6aa5fa729c..74bbec2d74 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -35,7 +35,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })liveFollowEnabled: project.settings.showProgressImagesInViewer,}));const livePreview = useLivePreviewFollow();- const { account, gallery, notifications, widgets } = useWorkbenchCommands();+ const { gallery, notifications, widgets } = useWorkbenchCommands();const queries = useWorkbenchQueries();const accountScope = captureAccountScope();const exportProject = useExportLibraryProject();@@ -66,13 +66,15 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })liveFollowEnabled,progressSessions: livePreview.gallerySessions,pinnedProgressSessionId: livePreview.pinnedSessionId,- followProgressSession: (sessionId) => {+ followedProgressSessionId: livePreview.followedSessionId,+ followProgressSession: (sessionId, { revealPreview }) => {if (!isAccountScopeCurrent(accountScope) || !queries.isActiveProject(projectId)) {return;}- account.updateProjectPreferences({ showProgressImagesInViewer: true });- livePreview.pin(sessionId);- openWorkbenchWidget('preview');+ livePreview.follow(sessionId);+ if (revealPreview) {+ openWorkbenchWidget('preview');+ }},notifications,projectId,@@ -83,7 +85,6 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })},}),[- account,accountScope,antialiasProgressImages,exportProject,diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex 4695193757..676cc64e8f 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -62,9 +62,13 @@ export {export {claimGalleryNavigationSequence,getGalleryDeletionSuccessor,+ getGalleryNavigationStep,+ getGallerySessionNavigationKey,getPersistedSelectedGalleryItemKeys,getSelectedGalleryImageFromValues,getSelectedGalleryItemFromValues,isGalleryNavigationCurrent,requestGalleryItemReveal,+ type GalleryNavigationDirection,+ type GalleryNavigationEntry,} from './core/selection';diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.test.tsindex ed7c7dfedc..78dd96563f 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.test.ts@@ -186,3 +186,86 @@ describe('getGalleryDeletionSuccessor', () => {expect(selection.getGalleryDeletionSuccessor([ref('a')], 'image:a', keys('a'))).toBeNull();});});++describe('getGalleryNavigationStep', () => {+ const item = (name: string, starred = false): GalleryItem => ({ ...imageItem, name, starred });+ const session = (id: string, navigable = true) => ({ id, kind: 'session' as const, navigable });+ const entry = (name: string, starred = false) => ({ item: item(name, starred), kind: 'item' as const });+ // Three columns: two in-progress rows (the second one a lone running tile+ // beside nothing), a strip of five (a full row plus a partial one), then+ // four listing items.+ const sections = [+ [session('p0'), session('p1', false), session('p2'), session('p3')],+ ['s0', 's1', 's2', 's3', 's4'].map((name) => entry(name, true)),+ ['r0', 'r1', 'r2', 'r3'].map((name) => entry(name)),+ ];+ const step = (cursorKey: string | null, direction: selection.GalleryNavigationDirection) => {+ const next = selection.getGalleryNavigationStep(sections, cursorKey, direction, 3);++ return next === null ? null : next.kind === 'session' ? next.id : next.item.name;+ };++ it('walks left and right across every seam, skipping tiles that cannot be followed', () => {+ expect(step('session:p3', 'right')).toBe('s0');+ expect(step('image:s0', 'left')).toBe('p3');+ expect(step('image:s4', 'right')).toBe('r0');+ expect(step('image:r0', 'left')).toBe('s4');+ expect(step('session:p0', 'right')).toBe('p2');+ expect(step('session:p2', 'left')).toBe('p0');+ expect(step('session:p0', 'left')).toBeNull();+ expect(step('image:r3', 'right')).toBeNull();+ });++ it('keeps the column across seams and clamps to a shorter row', () => {+ // r1 (column 1) rises onto the strip's partial row [s3, s4]; r2 clamps to its last cell.+ expect(step('image:r1', 'up')).toBe('s4');+ expect(step('image:r2', 'up')).toBe('s4');+ // s1 (column 1) rises past the partial in-progress row onto p3 (column 0).+ expect(step('image:s1', 'up')).toBe('p3');+ // s4 (column 1) descends to r1, not r0: the partial strip row does not shift the column.+ expect(step('image:s4', 'down')).toBe('r1');+ expect(step('image:s1', 'down')).toBe('s4');+ expect(step('session:p3', 'down')).toBe('s0');+ expect(step('image:r3', 'down')).toBeNull();+ expect(step('session:p0', 'up')).toBeNull();+ });++ it('lands on the nearest followable tile of a row, and skips a row with none', () => {+ // s1 (column 1) rising to the first in-progress row would land on p1, which is not running.+ expect(+ selection.getGalleryNavigationStep([sections[0]!.slice(0, 3), sections[1]!], 'image:s1', 'up', 3)+ ).toMatchObject({ id: 'p0' });+ expect(+ selection.getGalleryNavigationStep(+ [[session('p0', false), session('p1', false)], sections[1]!],+ 'image:s1',+ 'up',+ 3+ )+ ).toBeNull();+ });++ it('steps away from a cursor that is itself not followable, such as a settling session', () => {+ expect(step('session:p1', 'right')).toBe('p2');+ expect(step('session:p1', 'left')).toBe('p0');+ // The in-progress row below holds only p3, so the column clamps to it.+ expect(step('session:p1', 'down')).toBe('p3');+ });++ it('skips a row of waiting tiles that sits between two followable rows', () => {+ const waitingRow = [session('q0', false), session('q1', false), session('q2', false)];++ expect(+ selection.getGalleryNavigationStep([[session('p0')], waitingRow, sections[1]!], 'image:s0', 'up', 3)+ ).toMatchObject({ id: 'p0' });+ expect(+ selection.getGalleryNavigationStep([[session('p0')], waitingRow, sections[1]!], 'session:p0', 'down', 3)+ ).toMatchObject({ item: { name: 's0' } });+ });++ it('lands on the first followable entry when the cursor is off the sequence', () => {+ expect(step(null, 'down')).toBe('p0');+ expect(step('image:gone', 'left')).toBe('p0');+ expect(step(null, 'right')).toBe('p0');+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.tsindex cac198abd0..2835ed7008 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.ts@@ -197,3 +197,91 @@ export const claimGalleryNavigationSequence = (): number => ++navigationSequence/** False once a newer navigation has been claimed, which is when a slow hydrate must stand down. */export const isGalleryNavigationCurrent = (sequence: number): boolean => sequence === navigationSequence;++/*+ * Sectioned navigation. The gallery lays out three sections in one visual+ * order — the in-progress tiles, the starred strip, the listing — and Preview+ * walks the same order, so one sequence model serves both: left/right walk the+ * flat order across the seams, up/down keep the column across them. The cursor+ * is a key: a followed session's, or the selected item's.+ */++export type GalleryNavigationEntry =+ | { kind: 'item'; item: GalleryItem }+ | { kind: 'session'; id: string; navigable: boolean };++export type GalleryNavigationDirection = 'down' | 'left' | 'right' | 'up';++export const getGallerySessionNavigationKey = (sessionId: string): string => `session:${sessionId}`;++const getGalleryNavigationEntryKey = (entry: GalleryNavigationEntry): string =>+ entry.kind === 'item' ? toGalleryItemKey(entry.item) : getGallerySessionNavigationKey(entry.id);++const isNavigable = (entry: GalleryNavigationEntry | undefined): entry is GalleryNavigationEntry =>+ entry !== undefined && (entry.kind === 'item' || entry.navigable);++/**+ * The entry an arrow key lands on, or null when there is nowhere to go. Each+ * section chunks its own rows, so a vertical step across a seam keeps its+ * column instead of drifting by the previous section's partial last row; a+ * row whose landing cell is not navigable yields its nearest navigable cell,+ * and a row with none is skipped. Without a cursor, any key lands on the+ * first navigable entry.+ */+export const getGalleryNavigationStep = (+ sections: readonly (readonly GalleryNavigationEntry[])[],+ cursorKey: string | null,+ direction: GalleryNavigationDirection,+ columnCount = 1+): GalleryNavigationEntry | null => {+ const entries = sections.flat();+ const index =+ cursorKey === null ? -1 : entries.findIndex((entry) => getGalleryNavigationEntryKey(entry) === cursorKey);++ if (index === -1) {+ return entries.find(isNavigable) ?? null;+ }++ if (direction === 'left' || direction === 'right') {+ const step = direction === 'right' ? 1 : -1;++ for (let candidate = index + step; candidate >= 0 && candidate < entries.length; candidate += step) {+ if (isNavigable(entries[candidate])) {+ return entries[candidate]!;+ }+ }++ return null;+ }++ const rows: { length: number; start: number }[] = [];+ let sectionStart = 0;++ for (const section of sections) {+ for (let offset = 0; offset < section.length; offset += columnCount) {+ rows.push({ length: Math.min(columnCount, section.length - offset), start: sectionStart + offset });+ }++ sectionStart += section.length;+ }++ const rowIndex = rows.findIndex((row) => index >= row.start && index < row.start + row.length);+ const column = index - rows[rowIndex]!.start;+ const step = direction === 'down' ? 1 : -1;++ for (let target = rowIndex + step; target >= 0 && target < rows.length; target += step) {+ const row = rows[target]!;+ const landing = Math.min(column, row.length - 1);++ // Nearest navigable cell of the row by column distance, the left one on a tie.+ for (let distance = 0; distance < row.length; distance += 1) {+ for (const candidate of [landing - distance, landing + distance]) {+ if (candidate >= 0 && candidate < row.length && isNavigable(entries[row.start + candidate])) {+ return entries[row.start + candidate]!;+ }+ }+ }+ }++ return null;+};diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsindex 0591f9fb0e..f9f43c1363 100644--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -8,6 +8,7 @@ export {galleryItemNamesOptions,galleryItemsInfiniteOptions,galleryKeys,+ galleryStarredStripOptions,} from './data/queries';export type {CanonicalGalleryItemsFilter,diff --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 e2fa004b3e..c3281caffa 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@@ -19,8 +19,9 @@ import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';import { requestGalleryItemReveal } from '@features/gallery/core/selection';import { getGallerySettings } from '@features/gallery/core/settings';import { GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/react';-import { GALLERY_STARRED_SEPARATOR_HEIGHT_PX } from '@features/gallery/ui/galleryGridLayout';+import { GALLERY_PINNED_FOOTER_PX } from '@features/gallery/ui/galleryGridLayout';import { isGalleryImageDragData } from '@features/gallery/utility';+import { getFollowedProgressSession } from '@features/queue/contracts';import { parseDateTokens } from '@platform/search/dateTokens';import { accountLifecycle } from '@platform/state/accountLifecycle';import { getContrastRatio } from '@platform/ui/theme/contrastRatio.testing';@@ -338,7 +339,12 @@ const ContextMenuProbe = ({ target }: { target: CanonicalContextTarget }) => ();const NoopProvider = ({ children }: { children: ReactNode }) => children;-const createAdapter = (progressSessions: QueueProgressSession[]): GalleryUiAdapter =>+// Live-follow state travels as arguments so the compiler's memoization sees it change.+const createAdapter = (+ progressSessions: QueueProgressSession[],+ liveFollowEnabled: boolean,+ pinnedProgressSessionId: string | null+): GalleryUiAdapter =>({ItemActionsProvider: NoopProvider,ImageContextMenu: ContextMenuProbe,@@ -361,9 +367,12 @@ const createAdapter = (progressSessions: QueueProgressSession[]): GalleryUiAdapt},galleryValues: {},generateValues: {},- liveFollowEnabled: currentLiveFollowEnabled,+ liveFollowEnabled,progressSessions,- pinnedProgressSessionId: null,+ pinnedProgressSessionId,+ followedProgressSessionId: liveFollowEnabled+ ? (getFollowedProgressSession(progressSessions, pinnedProgressSessionId)?.id ?? null)+ : null,followProgressSession,notifications: { add: noop, reportError: noop },projectId: 'project-1',@@ -376,6 +385,7 @@ let root: Root | null = null;let queryClient: QueryClient | null = null;let currentGallery = createGallery();let currentLiveFollowEnabled = false;+let currentPinnedSessionId: string | null = null;let currentProgressSessions: QueueProgressSession[] = [];const followProgressSession = vi.fn();let currentStrip: GalleryStarredStrip = EMPTY_GALLERY_STARRED_STRIP;@@ -399,11 +409,15 @@ const Harness = ({background = 'bg',coMountPreviewSources = false,gallery,+ liveFollowEnabled,+ pinnedSessionId,progressSessions,}: {background?: 'bg' | 'bg.panel';coMountPreviewSources?: boolean;gallery: GalleryStateView;+ liveFollowEnabled: boolean;+ pinnedSessionId: string | null;progressSessions: QueueProgressSession[];}) => {const sensors = useSensors(@@ -427,7 +441,7 @@ const Harness = ({<I18nextProvider i18n={i18n}><ChakraProvider value={system}><QueryClientProvider client={queryClient!}>- <GalleryUiProvider adapter={createAdapter(progressSessions)}>+ <GalleryUiProvider adapter={createAdapter(progressSessions, liveFollowEnabled, pinnedSessionId)}><GalleryWidgetContext value={contextValue}><DndContext sensors={sensors}><DragMonitor />@@ -483,6 +497,8 @@ const renderGallery = async (background={background}coMountPreviewSources={coMountPreviewSources}gallery={gallery}+ liveFollowEnabled={currentLiveFollowEnabled}+ pinnedSessionId={currentPinnedSessionId}/>));@@ -520,6 +536,7 @@ beforeEach(() => {mocks.itemProgress = null;currentProgressSessions = [];currentLiveFollowEnabled = false;+ currentPinnedSessionId = null;mocks.progressFrame = null;currentStrip = EMPTY_GALLERY_STARRED_STRIP;queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });@@ -616,21 +633,23 @@ describe('GalleryImageGrid mixed item cells', () => {expect(getButton('Show all starred items').getBoundingClientRect().height).toBeLessThanOrEqual(24);});- it('keeps the starred label and grid together before a dedicated trailing gap', async () => {+ it('pins the strip in a ruled block above the listing, open or collapsed', async () => {setStrip([starred]);const gallery = createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS });await renderGallery(gallery);- const listRect = host?.querySelector('[role="list"]')?.getBoundingClientRect();+ const pinned = host!.querySelector<HTMLElement>('[data-gallery-pinned]')!;+ const listingTop = () => host!.querySelector('[data-gallery-section="regular"]')!.getBoundingClientRect().top;const headerRect = getButton('Collapse starred items').parentElement?.getBoundingClientRect();const starredRect = getButton('Select starred.png for preview').getBoundingClientRect();- const regularRect = getButton('Select regular.png for preview').getBoundingClientRect();- expect((headerRect?.top ?? 0) - (listRect?.top ?? 0)).toBeCloseTo(0, 0);+ expect(pinned.contains(getButton('Collapse starred items'))).toBe(true);+ expect(pinned.contains(getButton('Select starred.png for preview'))).toBe(true);+ expect(pinned.contains(getButton('Select regular.png for preview'))).toBe(false);expect(starredRect.top - (headerRect?.bottom ?? 0)).toBeLessThan(4);- // The trailing gap holds a hairline separator while the section is open.- expect(regularRect.top - starredRect.bottom).toBeCloseTo(8 + GALLERY_STARRED_SEPARATOR_HEIGHT_PX, 0);- expect(host?.querySelector('[data-gallery-starred-separator]')).not.toBeNull();+ // The block closes with a rule and a margin; the listing starts after them.+ expect(getComputedStyle(pinned).borderBottomWidth).toBe('1px');+ expect(listingTop() - pinned.getBoundingClientRect().bottom).toBeCloseTo(GALLERY_PINNED_FOOTER_PX - 1, 0);// The disclosure is a persisted setting, so collapsing goes through the// owner and comes back as the next render's settings.@@ -638,14 +657,11 @@ describe('GalleryImageGrid mixed item cells', () => {expect(actionMocks.updateSettings).toHaveBeenCalledExactlyOnceWith({ starredSectionCollapsed: true });await renderGallery({ ...gallery, settings: { ...DENSE_SETTINGS, starredSectionCollapsed: true } });+ const collapsedPinned = host!.querySelector<HTMLElement>('[data-gallery-pinned]')!;const collapsedHeaderRect = getButton('Expand starred items').parentElement?.getBoundingClientRect();- const collapsedRegularRect = getButton('Select regular.png for preview').getBoundingClientRect();- const collapsedSectionGap = collapsedRegularRect.top - (collapsedHeaderRect?.bottom ?? 0);- expect((collapsedHeaderRect?.top ?? 0) - (listRect?.top ?? 0)).toBeCloseTo(0, 0);- expect(collapsedSectionGap).toBeGreaterThanOrEqual(4);- expect(collapsedSectionGap).toBeLessThan(8);- expect(host?.querySelector('[data-gallery-starred-separator]')).toBeNull();+ expect(collapsedPinned.getBoundingClientRect().bottom - (collapsedHeaderRect?.bottom ?? 0)).toBeCloseTo(1, 0);+ expect(listingTop() - collapsedPinned.getBoundingClientRect().bottom).toBeCloseTo(GALLERY_PINNED_FOOTER_PX - 1, 0);});it('collapses only the strip cells, keeps the count, and omits the disclosure when the strip is empty', async () => {@@ -1229,10 +1245,14 @@ describe('GalleryImageGrid reveal requests', () => {// reveal here would silently drop it.expect(mocks.scrollToIndex).not.toHaveBeenCalled();+ const viewport = host!.querySelector<HTMLElement>('[data-part="viewport"]')!;+ const scrollTo = vi.spyOn(viewport, 'scrollTo');+await renderGallery({ ...gallery, settings: DENSE_SETTINGS });- expect(mocks.scrollToIndex).toHaveBeenCalledTimes(1);- // Row 0 is the header; the strip row is next.- expect(mocks.scrollToIndex).toHaveBeenCalledWith(1);+ // The strip is pinned above the listing, so the reveal scrolls to the top+ // of the viewport rather than to a listing row.+ expect(mocks.scrollToIndex).not.toHaveBeenCalled();+ expect(scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 0 });});/** A persisted off-page selection of deep.png with page-zero content loaded. */@@ -1422,9 +1442,99 @@ describe('shared gallery progress section', () => {expect(host?.querySelector('button[title^="Workflow A ·"]')).not.toBeNull();}await click(host!.querySelector<HTMLButtonElement>('button[title^="Workflow A ·"]')!);- expect(followProgressSession).toHaveBeenCalledWith('run:1');+ expect(followProgressSession).toHaveBeenCalledWith('run:1', { revealPreview: true });expect(host?.querySelectorAll('[role="listitem"]')).toHaveLength(currentGallery.items.length);});+ it('steps the arrow keys between the followed tile, the strip and the listing as one sequence', async () => {+ const starred = createItem('image', 'starred.png', { starred: true });+ const regular = createItem('image', 'regular.png');+ currentProgressSessions = [session, { ...session, id: 'run:2', itemIndex: 2, backendItemId: 11 }];+ currentLiveFollowEnabled = true;+ currentPinnedSessionId = 'run:2';+ setStrip([starred]);+ await renderGallery(createGallery({ items: [regular], selectedItemKey: null, selectedItemKeys: [] }));++ // Down from the second tile lands on the strip's only cell; right steps off the tiles into it too.+ registeredCommands.get('gallery.galleryNavDown')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(starred);+ registeredCommands.get('gallery.galleryNavRight')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(starred);+ registeredCommands.get('gallery.galleryNavLeft')?.();+ expect(followProgressSession).toHaveBeenLastCalledWith('run:1', { revealPreview: false });++ // From the strip, up and left follow a tile again; down and right reach the listing.+ currentLiveFollowEnabled = false;+ currentPinnedSessionId = null;+ await renderGallery(+ createGallery({ items: [regular], selectedItemKey: 'image:starred.png', selectedItemKeys: ['image:starred.png'] })+ );+ registeredCommands.get('gallery.galleryNavUp')?.();+ expect(followProgressSession).toHaveBeenLastCalledWith('run:1', { revealPreview: false });+ registeredCommands.get('gallery.galleryNavLeft')?.();+ expect(followProgressSession).toHaveBeenLastCalledWith('run:2', { revealPreview: false });+ registeredCommands.get('gallery.galleryNavDown')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(regular);+ registeredCommands.get('gallery.galleryNavRight')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(regular);+ expect(followProgressSession).toHaveBeenCalledTimes(3);+ });+ it('skips waiting tiles, which cannot be followed, and steps past a collapsed section', async () => {+ const starred = createItem('image', 'starred.png', { starred: true });+ currentProgressSessions = [+ session,+ { ...session, id: 'run:2', itemIndex: 2, backendItemId: null, state: 'queued' },+ ];+ currentLiveFollowEnabled = true;+ setStrip([starred]);+ await renderGallery(createGallery({ selectedItemKey: null, selectedItemKeys: [] }));++ registeredCommands.get('gallery.galleryNavRight')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(starred);+ expect(followProgressSession).not.toHaveBeenCalled();++ // A collapsed in-progress section shows no tiles, so the strip is the top of the sequence.+ currentLiveFollowEnabled = false;+ await renderGallery(+ createGallery({+ selectedItemKey: 'image:starred.png',+ selectedItemKeys: ['image:starred.png'],+ settings: { ...getGallerySettings({}), progressSectionCollapsed: true },+ })+ );+ registeredCommands.get('gallery.galleryNavLeft')?.();+ expect(followProgressSession).not.toHaveBeenCalled();+ expect(actionMocks.selectItem).toHaveBeenCalledTimes(1);+ });+ it('steps out of a starred selection the strip does not show instead of resetting', async () => {+ const shown = Array.from({ length: 12 }, (_, index) =>+ createItem('image', `starred-${index}.png`, { starred: true })+ );+ const hidden = createItem('image', 'starred-hidden.png', { starred: true });+ const regular = createItem('image', 'regular.png');+ setStrip([...shown, hidden], 13);+ await renderGallery(+ createGallery({+ items: [regular],+ selectedItemKey: 'image:starred-hidden.png',+ selectedItemKeys: ['image:starred-hidden.png'],+ settings: DENSE_SETTINGS,+ })+ );+ const shownCount = host!.querySelectorAll('[data-gallery-section="starred"] [role="listitem"]').length;+ expect(shownCount).toBeLessThan(13);++ registeredCommands.get('gallery.galleryNavRight')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(regular);+ registeredCommands.get('gallery.galleryNavLeft')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(shown[shownCount - 1]);++ // Under a collapsed disclosure the whole strip is hidden; the selection still steps into the listing.+ await renderGallery({ ...currentGallery, settings: { ...DENSE_SETTINGS, starredSectionCollapsed: true } });+ registeredCommands.get('gallery.galleryNavRight')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(regular);+ registeredCommands.get('gallery.galleryNavLeft')?.();+ expect(actionMocks.selectItem).toHaveBeenCalledTimes(3);+ });it('keeps the saved image selected while the queue only contains waiting slots', async () => {currentLiveFollowEnabled = true;currentProgressSessions = [{ ...session, state: 'queued' }];diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex 6ff9f6bb81..4031c3ed9a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -1,9 +1,11 @@import { Box, chakra, Flex, HStack, Icon, ScrollArea, Spinner, Stack, Text } from '@chakra-ui/react';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';-import { toGalleryItemKey, type GalleryItem } from '@features/gallery/core/items';+import { toGalleryItemKey, type GalleryItem, type GalleryItemKey } from '@features/gallery/core/items';import {getGalleryRevealRequest,+ getGallerySessionNavigationKey,subscribeGalleryRevealRequests,+ type GalleryNavigationEntry,type GalleryRevealRequest,} from '@features/gallery/core/selection';import { isDateBoardId } from '@features/gallery/data/backend';@@ -21,21 +23,24 @@ import {useSyncExternalStore,type DragEvent,type KeyboardEvent,+ type ReactNode,} from 'react';import { useVirtualizer } from 'react-hook-tanstack-virtual';import { useTranslation } from 'react-i18next';import {- buildGalleryGridNavigation,buildGalleryGridRows,+ chunkGalleryCellsIntoRows,GALLERY_GRID_GAP_PX,+ GALLERY_PINNED_FOOTER_PX,GALLERY_STARRED_HEADER_HEIGHT_PX,- GALLERY_STARRED_SEPARATOR_HEIGHT_PX,getGalleryCellSizePx,getGalleryColumnCount,- getGalleryGridRowHeightPx,- getGalleryGridRowIndexForItem,+ getGalleryGridRowIndexForItemKey,+ getGalleryPinnedHeightPx,getGalleryProgressLayout,+ getGalleryStarredLayout,+ getGalleryStarredStripItems,} from './galleryGridLayout';import { GalleryProgressSection } from './GalleryProgressSection';import { GalleryThumbnailCell } from './GalleryThumbnail';@@ -65,14 +70,12 @@ const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.d*/const GalleryStarredSectionHeader = ({isOpen,- offsetPx,onShowAll,onToggle,shownCount,total,}: {isOpen: boolean;- offsetPx: number;onShowAll: () => void;onToggle: () => void;shownCount: number;@@ -81,18 +84,7 @@ const GalleryStarredSectionHeader = ({const { t } = useTranslation();return (- <Flex- align="center"- gap="1"- h={`${GALLERY_STARRED_HEADER_HEIGHT_PX}px`}- left="0"- position="absolute"- px="1"- top="0"- transform={`translateY(${offsetPx}px)`}- w="full"- zIndex="1"- >+ <Flex align="center" gap="1" h={`${GALLERY_STARRED_HEADER_HEIGHT_PX}px`} px="1" w="full"><chakra.buttonaria-expanded={isOpen}aria-label={t(isOpen ? 'widgets.gallery.collapseStarredItems' : 'widgets.gallery.expandStarredItems')}@@ -147,6 +139,67 @@ const GalleryStarredSectionHeader = ({);};+/**+ * The pinned starred strip: bounded (three rows at most), so it renders as+ * plain rows above the virtualized listing rather than inside it. Its cells+ * sit between the in-progress tiles and the listing in the arrow-key+ * sequence, so the keys cross both seams.+ */+const GalleryStarredSection = ({+ cells,+ cellSizePx,+ columnCount,+ isOpen,+ renderCell,+ total,+ onShowAll,+ onToggle,+}: {+ cells: GalleryItem[];+ /** Rows take the listing's pitch explicitly, so the pinned block measures what the layout computed. */+ cellSizePx: number;+ columnCount: number;+ isOpen: boolean;+ renderCell: (item: GalleryItem) => ReactNode;+ total: number;+ onShowAll: () => void;+ onToggle: () => void;+}) => {+ const { t } = useTranslation();+ const rows = useMemo(() => chunkGalleryCellsIntoRows(cells, columnCount, 'starred'), [cells, columnCount]);++ return (+ <Box>+ <GalleryStarredSectionHeader+ isOpen={isOpen}+ shownCount={isOpen ? cells.length : 0}+ total={total}+ onShowAll={onShowAll}+ onToggle={onToggle}+ />+ {isOpen ? (+ <Box aria-label={t('widgets.gallery.starredItems')} role="list">+ {rows.map((row) => (+ <Box+ key={row.key}+ data-gallery-section="starred"+ display="grid"+ gap={`${GALLERY_GRID_GAP_PX}px`}+ gridTemplateColumns={`repeat(${columnCount}, minmax(0, 1fr))`}+ h={`${cellSizePx}px`}+ mb={`${GALLERY_GRID_GAP_PX}px`}+ role="presentation"+ w="full"+ >+ {row.cells.map(renderCell)}+ </Box>+ ))}+ </Box>+ ) : null}+ </Box>+ );+};+/*** The virtualized thumbnail grid. Column count comes from the measured* viewport width, so the grid is layout-blind: both shells render it the same@@ -155,13 +208,20 @@ const GalleryStarredSectionHeader = ({export const GalleryImageGrid = () => {const { t } = useTranslation();const { actions, gallery, isWindowTruncated, itemActions, region, starredStrip } = useGalleryWidget();- const { gallery: galleryCommands, ImageContextMenu, liveFollowEnabled, progressSessions } = useGalleryUi();+ const { gallery: galleryCommands, ImageContextMenu, followedProgressSessionId, 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, paginationMode, showImageDimensions, starredSectionCollapsed, thumbnailFit } =- gallery.settings;+ const {+ imageDensityPercent,+ paginationMode,+ progressSectionCollapsed,+ showImageDimensions,+ showPendingItems,+ starredSectionCollapsed,+ thumbnailFit,+ } = gallery.settings;const isStarredOpen = !starredSectionCollapsed;const {@@ -177,7 +237,7 @@ export const GalleryImageGrid = () => {} = useGalleryGridSelection();const columnCount = getGalleryColumnCount({ imageDensityPercent, widthPx: viewportWidth });- const isFollowingLive = liveFollowEnabled && progressSessions.some((session) => session.state !== 'queued');+ const isFollowingLive = followedProgressSessionId !== null;const isComparisonActive = gallery.isComparisonActive && !isFollowingLive;const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);const selectedBoardName = selectedBoard@@ -189,39 +249,60 @@ export const GalleryImageGrid = () => {const hasActiveSearch = gallery.searchTerm.trim() !== '';const isVirtualBoard = isDateBoardId(gallery.selectedBoardId);- const rows = useMemo(- () =>- buildGalleryGridRows({- columnCount,- isStarredOpen,- items: gallery.items,- starredItems: starredStrip.items,- starredTotal: starredStrip.total,- }),- [columnCount, gallery.items, isStarredOpen, starredStrip.items, starredStrip.total]- );- const navigation = useMemo(- () =>- buildGalleryGridNavigation({- columnCount,- isStarredOpen,- items: gallery.items,- starredItems: starredStrip.items,- }),- [columnCount, gallery.items, isStarredOpen, starredStrip.items]+ const rows = useMemo(() => buildGalleryGridRows(gallery.items, columnCount), [columnCount, gallery.items]);+ const starredCells = useMemo(+ () => getGalleryStarredStripItems(starredStrip.items, columnCount),+ [columnCount, starredStrip.items]);+ // The arrow keys' sections in visual order; a collapsed section has no+ // tiles to land on, so it contributes none. A starred selection the strip+ // does not show (beyond its three rows, or under a collapsed disclosure)+ // still belongs to the strip section, so the keys step out of it instead+ // of resetting — Preview places such a selection the same way.+ const isProgressOpen = showPendingItems && !progressSectionCollapsed;+ const navigationSections = useMemo((): GalleryNavigationEntry[][] => {+ const shownStripItems = isStarredOpen ? starredCells : [];+ const selectedKey = gallery.selectedItemKey;+ const isSelected = (item: GalleryItem) => toGalleryItemKey(item) === selectedKey;+ const hiddenStripSelection =+ selectedKey !== null && !shownStripItems.some(isSelected) && !gallery.items.some(isSelected)+ ? starredStrip.items.find(isSelected)+ : undefined;+ const stripEntries: GalleryNavigationEntry[] = shownStripItems.map((item) => ({ item, kind: 'item' }));++ if (hiddenStripSelection) {+ stripEntries.push({ item: hiddenStripSelection, kind: 'item' });+ }++ return [+ isProgressOpen+ ? progressSessions.map((session) => ({+ id: session.id,+ kind: 'session',+ navigable: session.state === 'running',+ }))+ : [],+ stripEntries,+ gallery.items.map((item) => ({ item, kind: 'item' })),+ ];+ }, [+ gallery.items,+ gallery.selectedItemKey,+ isProgressOpen,+ isStarredOpen,+ progressSessions,+ starredCells,+ starredStrip.items,+ ]);+ const cursorKey =+ followedProgressSessionId !== null+ ? getGallerySessionNavigationKey(followedProgressSessionId)+ : gallery.selectedItemKey;const rowCount = rows.length;const cellSizePx = getGalleryCellSizePx({ columnCount, widthPx: viewportWidth });const rowHeightPx = cellSizePx + GALLERY_GRID_GAP_PX;- const estimateRowSize = useCallback(- (index: number) => {- const row = rows[index];-- return row ? getGalleryGridRowHeightPx(row, rowHeightPx) : rowHeightPx;- },- [rowHeightPx, rows]- );+ const estimateRowSize = useCallback(() => rowHeightPx, [rowHeightPx]);const getRowKey = useCallback((index: number) => rows[index]?.key ?? index, [rows]);const getScrollElement = useCallback(() => viewportRef.current, []);@@ -229,13 +310,21 @@ export const GalleryImageGrid = () => {columns: columnCount,tileSize: cellSizePx,sessionCount: progressSessions.length,- visible: gallery.settings.showPendingItems,- collapsed: gallery.settings.progressSectionCollapsed,+ visible: showPendingItems,+ collapsed: progressSectionCollapsed,});- const progressHeight = progressLayout.height;+ const starredLayout = getGalleryStarredLayout({+ collapsed: !isStarredOpen,+ columns: columnCount,+ shownCount: starredCells.length,+ tileSize: cellSizePx,+ });+ // In progress and starred share one pinned block above the listing; the+ // virtualizer scrolls beneath it.+ const pinnedHeight = getGalleryPinnedHeightPx(progressLayout.height, starredLayout.height);const virtualizer = useVirtualizer({count: rowCount,- scrollMargin: progressHeight,+ scrollMargin: pinnedHeight,estimateSize: estimateRowSize,getItemKey: getRowKey,getScrollElement,@@ -250,24 +339,38 @@ export const GalleryImageGrid = () => {// an effect event, which always sees the latest render's closure, so a stable// identity would buy nothing and pinning the mutable virtualizer into a// dependency array defeats the compiler's own memoization.- /** Returns whether the item had a row to scroll to — a collapsed section has none. */- const scrollToItemIndex = (itemIndex: number): boolean => {- const rowIndex = getGalleryGridRowIndexForItem(rows, itemIndex);+ /** Returns whether the item had somewhere to scroll to — a collapsed strip has none. */+ const scrollToItemKey = (itemKey: GalleryItemKey): boolean => {+ const rowIndex = getGalleryGridRowIndexForItemKey(gallery.items, itemKey, columnCount);- if (rowIndex < 0) {- return false;+ if (rowIndex >= 0) {+ virtualizer.scrollToIndex(rowIndex);+ return true;}- virtualizer.scrollToIndex(rowIndex);- return true;+ // Strip cells sit in the pinned block at the top of the scroll content.+ if (isStarredOpen && starredCells.some((item) => toGalleryItemKey(item) === itemKey)) {+ viewportRef.current?.scrollTo({ top: 0 });+ return true;+ }++ return false;+ };+ const scrollToEntry = (entry: GalleryNavigationEntry) => {+ if (entry.kind === 'session') {+ viewportRef.current?.scrollTo({ top: 0 });+ } else {+ scrollToItemKey(toGalleryItemKey(entry.item));+ }};useGalleryGridHotkeys({actionSelectionRefs,columnCount,+ cursorKey,loadedItems,- navigation,- scrollToItemIndex,+ navigationSections,+ scrollToEntry,});// Reveals from outside the grid (the image map's click-to-reveal) must land@@ -305,14 +408,10 @@ export const GalleryImageGrid = () => {return;}- // A starred item lives in the strip, an unstarred one in the listing;- // the navigation list covers both.- const itemIndex = navigation.items.findIndex((item) => toGalleryItemKey(item) === pending.itemKey);-// Consumed only once it actually scrolled, so a reveal whose row has not// been built yet (a strip under a collapsed disclosure, a page still// loading) is honored on the next row-model change.- if (itemIndex >= 0 && scrollToItemIndex(itemIndex)) {+ if (scrollToItemKey(pending.itemKey)) {pendingRevealRef.current = null;return;@@ -321,7 +420,7 @@ export const GalleryImageGrid = () => {// The item may live on another paginated page: follow once per reveal, so// a reveal whose item never materializes cannot keep pulling the user back.if (- itemIndex < 0 &&+ !loadedItems.some((item) => toGalleryItemKey(item) === pending.itemKey) &&gallery.revealTargetPage !== null &&gallery.revealTargetPage !== gallery.page &&lastPageFollowedRevealToken !== pending.token@@ -331,6 +430,8 @@ export const GalleryImageGrid = () => {}});+ // Re-run on every change to what can be scrolled to — a page landing, the+ // strip opening — so a pending reveal settles as soon as its item can.useEffect(() => {if (revealRequest && revealRequest.token !== consumedRevealTokenRef.current) {consumedRevealTokenRef.current = revealRequest.token;@@ -338,7 +439,7 @@ export const GalleryImageGrid = () => {}settlePendingReveal();- }, [revealRequest, rows]);+ }, [revealRequest, navigationSections]);useLayoutEffect(() => {const viewport = viewportRef.current;@@ -379,7 +480,7 @@ export const GalleryImageGrid = () => {// layout effect keeps the stale frame from ever reaching the screen.useLayoutEffect(() => {measureVirtualizer();- }, [rowHeightPx, rows, progressHeight]);+ }, [rowHeightPx, rows, pinnedHeight]);const virtualRows = virtualizer.virtualItems;const lastVisibleRowIndex = virtualRows[virtualRows.length - 1]?.index ?? 0;@@ -469,6 +570,50 @@ export const GalleryImageGrid = () => {// Releasing the anchor puts the window back over the top of the listing.const handleReturnToBoardTop = useCallback(() => galleryCommands.setPage(0), [galleryCommands]);+ const renderCell = useCallback(+ (item: GalleryItem) => {+ const itemKey = toGalleryItemKey(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={item}+ onClick={handleThumbnailClick}+ onContextMenu={handleThumbnailContextMenu}+ onToggleStarred={handleToggleStarred}+ />+ );+ },+ [+ gallery.compareImageKey,+ gallery.selectedItemKey,+ getDragItems,+ handleThumbnailClick,+ handleThumbnailContextMenu,+ handleToggleStarred,+ isComparisonActive,+ isFollowingLive,+ region,+ selectedItemKeys,+ showImageDimensions,+ t,+ thumbnailFit,+ ]+ );+const anchoredWindowFirstItem = gallery.anchoredWindowPage * GALLERY_PAGE_SIZE + 1;return (@@ -500,7 +645,30 @@ export const GalleryImageGrid = () => {<ScrollArea.Root h="full" minH="0" size="xs" variant="hover" w="full"><ScrollArea.Viewport ref={viewportRef} h="full" outline="none" w="full"><ScrollArea.Content display="flex" flexDirection="column" minH="full">- <GalleryProgressSection layout={progressLayout} getScrollElement={getScrollElement} />+ {pinnedHeight > 0 ? (+ <Box+ borderBottomWidth="1px"+ borderColor="border.subtle"+ data-gallery-pinned+ flexShrink={0}+ mb={`${GALLERY_PINNED_FOOTER_PX - 1}px`}+ minW="0"+ >+ <GalleryProgressSection layout={progressLayout} getScrollElement={getScrollElement} />+ {starredCells.length > 0 ? (+ <GalleryStarredSection+ cells={starredCells}+ cellSizePx={cellSizePx}+ columnCount={columnCount}+ isOpen={isStarredOpen}+ renderCell={renderCell}+ total={starredStrip.total}+ onShowAll={handleShowAllStarred}+ onToggle={handleToggleStarredSection}+ />+ ) : null}+ </Box>+ ) : null}{isEmpty ? (gallery.isLoading || hasActiveSearch || isVirtualBoard || gallery.starredOnly ? (<Flex align="center" color="fg.muted" flex="1" justify="center" minH="8rem">@@ -513,7 +681,8 @@ export const GalleryImageGrid = () => {</Text></Flex>) : (- <Flex align="stretch" flex="1" minH="8rem" p="2">+ // No inset: the zone shares the thumbnails' outer edges.+ <Flex align="stretch" flex="1" minH="8rem"><input {...uploadInputProps} /><DropZonealignItems="center"@@ -537,44 +706,6 @@ export const GalleryImageGrid = () => {) : (<><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;- })}<Boxaria-label={t('widgets.gallery.itemsAriaLabel')}h="full"@@ -586,7 +717,7 @@ export const GalleryImageGrid = () => {{virtualRows.map((virtualRow) => {const row = rows[virtualRow.index];- if (!row || row.kind === 'starred-gap' || row.kind === 'starred-header') {+ if (!row) {return null;}@@ -601,35 +732,10 @@ export const GalleryImageGrid = () => {position="absolute"role="presentation"top="0"- transform={`translateY(${virtualRow.start - progressHeight}px)`}+ transform={`translateY(${virtualRow.start - pinnedHeight}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}- />- );- })}+ {row.cells.map(renderCell)}</Box>);})}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 366bfc1d31..555dc9238a 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@@ -16,6 +16,7 @@ import { page } from 'vitest/browser';import type { GalleryStateView } from './galleryStateView';import type { GalleryWidgetContextValue } from './GalleryWidgetContext';+import { GALLERY_PINNED_FOOTER_PX, GALLERY_STARRED_HEADER_HEIGHT_PX } from './galleryGridLayout';import { GalleryStackedLayout } from './GalleryStackedLayout';import { GalleryWideLayout } from './GalleryWideLayout';import { GalleryWidgetContext } from './GalleryWidgetContext';@@ -130,6 +131,7 @@ const adapter = {ImageContextMenu: () => null,progressSessions: [],pinnedProgressSessionId: null,+ followedProgressSessionId: null,liveFollowEnabled: false,followProgressSession: vi.fn(),antialiasProgressImages: false,@@ -220,7 +222,11 @@ describe('gallery layout shells', () => {);await renderLayout(GalleryStackedLayout);expect(panel.querySelector('[role="region"] button[aria-pressed]')).toBeNull();- expect(saved.getBoundingClientRect().top - viewport.getBoundingClientRect().top).toBeCloseTo(24, 0);+ // The collapsed disclosure row, then the pinned block's rule and margin.+ expect(saved.getBoundingClientRect().top - viewport.getBoundingClientRect().top).toBeCloseTo(+ GALLERY_STARRED_HEADER_HEIGHT_PX + GALLERY_PINNED_FOOTER_PX,+ 0+ );});it.each(['images', 'assets'] as const)(diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsxindex 11efef36c0..0912db860e 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsx@@ -126,7 +126,7 @@ const GalleryProgressGrid = ({getScrollElement(): HTMLDivElement | null;pinnedSessionId: string | null;liveFollowEnabled: boolean;- onFollow(id: string): void;+ onFollow(id: string, options: { revealPreview: boolean }): void;restoreFocus(): void;}) => {const { columns, tileSize, headerHeight, paddingBottom, rowCount, rowHeight } = layout;@@ -181,7 +181,7 @@ const GalleryProgressTile = ({size: number;fit: GalleryThumbnailFit;selected: boolean;- onFollow(id: string): void;+ onFollow(id: string, options: { revealPreview: boolean }): void;restoreFocus(): void;}) => {const { t } = useTranslation();@@ -207,7 +207,7 @@ const GalleryProgressTile = ({: progress?.message || t('widgets.gallery.progressPreparing');const follow = useCallback(() => {if (session.state === 'running') {- onFollow(session.id);+ onFollow(session.id, { revealPreview: true });}}, [onFollow, session.id, session.state]);const buttonRef = useCallback(@@ -228,6 +228,7 @@ const GalleryProgressTile = ({<chakra.buttonref={buttonRef}type="button"+ data-progress-tilefocusVisibleRing="inside"aria-label={`${label} · ${status}`}aria-pressed={selected && session.state !== 'queued'}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex ab5a8650e1..97128077f8 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -110,7 +110,10 @@ export interface GalleryUiAdapter {exportProject(projectId: string, projectName: string): void;progressSessions: QueueProgressSession[];pinnedProgressSessionId: string | null;- followProgressSession(sessionId: string): void;+ /** The session Preview is showing while it follows live; null otherwise. The arrow keys step from it. */+ followedProgressSessionId: string | null;+ /** Follow `sessionId` live; a tile click also reveals Preview, an arrow step must not move the layout. */+ followProgressSession(sessionId: string, options: { revealPreview: boolean }): void;liveFollowEnabled: boolean;widgets: {/** Open (or reveal) the Gallery widget; false when no region can host it. */diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex d03de4434f..c41bbace65 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -17,6 +17,7 @@ import { GalleryBoardDragMonitor } from './GalleryBoardDragMonitor';import { mergeGalleryLoadedItems } from './galleryGridLayout';import { GalleryLayout } from './GalleryLayout';import {+ getGalleryAnchoredWindowPage,getGalleryPage,getGalleryProjectBoardId,getGalleryRawSelectedBoardId,@@ -121,17 +122,17 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg}, [notifications, semanticError]);const { loadMore, selectedBoardId, total } = data;- const gallery = useMemo(- () => 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 anchored// mid-board (the banner promises a slice, not the top of the board).const starredStrip = useGalleryStarredStrip({- enabled: semanticQuery === null && !starredOnly && gallery.anchoredWindowPage === 0,+ enabled: semanticQuery === null && !starredOnly && getGalleryAnchoredWindowPage(galleryValues) === 0,filter: data.filter,});+ const gallery = useMemo(+ () => getGalleryStateView(galleryValues, data.boards, data.items, data.isLoadingItems, starredStrip.items),+ [data.boards, data.isLoadingItems, data.items, galleryValues, starredStrip.items]+ );const loadedItems = useMemo(() => mergeGalleryLoadedItems(starredStrip.items, gallery.items),[gallery.items, starredStrip.items]diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.tsindex 5885acb623..d0fbb76bf9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts@@ -3,17 +3,17 @@ import type { GalleryImageItem } from '@features/gallery/core/items';import { describe, expect, it } from 'vitest';import {- buildGalleryGridNavigation,buildGalleryGridRows,- getGalleryGridNavigationStep,GALLERY_GRID_GAP_PX,+ GALLERY_PINNED_FOOTER_PX,GALLERY_STARRED_HEADER_HEIGHT_PX,- GALLERY_STARRED_SEPARATOR_HEIGHT_PX,getGalleryCellSizePx,getGalleryColumnCount,getGalleryColumnCountForCell,- getGalleryGridRowHeightPx,- getGalleryGridRowIndexForItem,+ getGalleryGridRowIndexForItemKey,+ getGalleryPinnedHeightPx,+ getGalleryStarredLayout,+ getGalleryStarredStripItems,} from './galleryGridLayout';const createImageItem = (name: string, starred = false): GalleryImageItem => ({@@ -30,18 +30,7 @@ const createImageItem = (name: string, starred = false): GalleryImageItem => ({width: 512,});-const buildRows = (overrides: Partial<Parameters<typeof buildGalleryGridRows>[0]> = {}) =>- buildGalleryGridRows({- columnCount: 2,- isStarredOpen: true,- items: [],- starredItems: [],- starredTotal: 0,- ...overrides,- });--const cellNames = (rows: ReturnType<typeof buildRows>): string[][] =>- rows.flatMap((row) => (row.kind === 'cells' ? [row.cells.map((cell) => cell.item.name)] : []));+const buildRows = (items: GalleryImageItem[]) => buildGalleryGridRows(items, 2);describe('getGalleryColumnCountForCell', () => {it('rounds to the nearest whole cell and clamps to the caller bounds', () => {@@ -83,8 +72,18 @@ describe('getGalleryColumnCount', () => {it('clamps to a usable range at both extremes', () => {expect(getGalleryColumnCount({ imageDensityPercent: 100, widthPx: 40 })).toBe(2);- expect(getGalleryColumnCount({ imageDensityPercent: 100, widthPx: 8000 })).toBe(12);- expect(getGalleryColumnCount({ imageDensityPercent: 0, widthPx: 8000 })).toBe(12);+ expect(getGalleryColumnCount({ imageDensityPercent: 100, widthPx: 8000 })).toBe(48);+ expect(getGalleryColumnCount({ imageDensityPercent: 0, widthPx: 8000 })).toBe(42);+ });++ it('keeps density effective in a wide placement instead of pinning it at a column cap', () => {+ // A bottom panel around 1100px wide: every density step must still change the count.+ const counts = [0, 25, 50, 75, 100].map((percent) =>+ getGalleryColumnCount({ imageDensityPercent: percent, widthPx: 1100 })+ );++ expect(counts).toEqual([...counts].sort((a, b) => a - b));+ expect(new Set(counts).size).toBe(counts.length);});it('ignores out-of-range density instead of producing a nonsense count', () => {@@ -116,166 +115,45 @@ describe('getGalleryCellSizePx', () => {});describe('buildGalleryGridRows', () => {- it('chunks plain items into rows of the column count with no section chrome', () => {- const rows = buildRows({ items: ['a', 'b', 'c'].map((name) => createImageItem(name)) });+ it('chunks the listing into rows of the column count, keyed by their leading cell', () => {+ const rows = buildRows(['a', 'b', 'c'].map((name) => createImageItem(name)));- expect(rows.map((row) => row.kind)).toEqual(['cells', 'cells']);- expect(rows[0]?.kind === 'cells' && rows[0].cells.length).toBe(2);- expect(rows[1]?.kind === 'cells' && rows[1].cells.length).toBe(1);+ expect(rows.map((row) => row.cells.map((cell) => cell.name))).toEqual([['a', 'b'], ['c']]);+ expect(rows.map((row) => row.key)).toEqual(['regular:image:a', 'regular:image:c']);});- it('puts the starred strip in a header-led section above the unstarred listing', () => {- const starred = createImageItem('starred-1', true);- const rows = buildRows({- items: [createImageItem('regular-1'), createImageItem('regular-2')],- starredItems: [starred],- starredTotal: 1,- });-- expect(rows.map((row) => row.kind)).toEqual(['starred-header', 'cells', 'starred-gap', 'cells']);- expect(rows[0]?.kind === 'starred-header' && rows[0]).toMatchObject({ shownCount: 1, total: 1 });- expect(rows[1]?.kind === 'cells' && rows[1].section).toBe('starred');- expect(rows[2]?.kind === 'starred-gap' && rows[2].withSeparator).toBe(true);- expect(rows[3]?.kind === 'cells' && rows[3].section).toBe('regular');- expect(cellNames(rows)).toEqual([['starred-1'], ['regular-1', 'regular-2']]);- });-- it('caps the strip at three rows of the current column count and reports the backend total', () => {+ it('caps the strip at three rows of the current column count', () => {const starredItems = Array.from({ length: 7 }, (_, index) => createImageItem(`starred-${index}`, true));- const rows = buildRows({ starredItems, starredTotal: 9 });-- expect(rows[0]?.kind === 'starred-header' && rows[0]).toMatchObject({ shownCount: 6, total: 9 });- expect(rows.filter((row) => row.kind === 'cells' && row.section === 'starred')).toHaveLength(3);- expect(cellNames(rows).flat()).not.toContain('starred-6');- });-- it('renders no chrome when the strip is empty', () => {- const rows = buildRows({ items: [createImageItem('starred-1', true)], starredItems: [], starredTotal: 0 });-- expect(rows.map((row) => row.kind)).toEqual(['cells']);- });-- it('keeps the header but drops the starred rows and the separator while collapsed', () => {- const starred = createImageItem('starred-1', true);- const rows = buildRows({- isStarredOpen: false,- items: [createImageItem('regular-1')],- starredItems: [starred],- starredTotal: 1,- });- expect(rows.map((row) => row.kind)).toEqual(['starred-header', 'starred-gap', 'cells']);- expect(rows[0]?.kind === 'starred-header' && rows[0]).toMatchObject({ shownCount: 0, total: 1 });- expect(rows[1]?.kind === 'starred-gap' && rows[1].withSeparator).toBe(false);- });-- it('keeps regular row keys stable across a starred collapse so their cells are not recreated', () => {- const starred = createImageItem('starred-1', true);- const input = {- items: [createImageItem('regular-1'), createImageItem('regular-2')],- starredItems: [starred],- starredTotal: 1,- };- const regularKeys = (rows: ReturnType<typeof buildRows>) =>- rows.filter((row) => row.kind === 'cells' && row.section === 'regular').map((row) => row.key);-- expect(regularKeys(buildRows({ ...input, isStarredOpen: false }))).toEqual(regularKeys(buildRows(input)));- });-- it('numbers cells continuously from the strip into the listing, matching the navigation list', () => {- const starred = createImageItem('starred-1', true);- const input = {- columnCount: 2,- items: [createImageItem('regular-1'), createImageItem('regular-2')],- starredItems: [starred, createImageItem('starred-2', true)],- };- const openRows = buildRows({ ...input, starredTotal: 2 });- const openNavigation = buildGalleryGridNavigation({ ...input, isStarredOpen: true });- const indices = (rows: ReturnType<typeof buildRows>) =>- rows.flatMap((row) =>- row.kind === 'cells' ? row.cells.map((cell) => (cell.kind === 'item' ? cell.itemIndex : -1)) : []- );-- expect(indices(openRows)).toEqual([0, 1, 2, 3]);- expect(openNavigation.items.map((item) => item.name)).toEqual(['starred-1', 'starred-2', 'regular-1', 'regular-2']);- expect(openNavigation.regularStart).toBe(2);-- const collapsedNavigation = buildGalleryGridNavigation({ ...input, isStarredOpen: false });- expect(indices(buildRows({ ...input, isStarredOpen: false, starredTotal: 2 }))).toEqual([0, 1]);- expect(collapsedNavigation).toEqual({ items: input.items, regularStart: 0 });+ expect(getGalleryStarredStripItems(starredItems, 2).map((item) => item.name)).not.toContain('starred-6');+ expect(getGalleryStarredStripItems(starredItems, 2)).toHaveLength(6);});});-describe('getGalleryGridNavigationStep', () => {- // Five starred items at three columns: a full strip row plus a partial one- // above four listing items.- const navigation = buildGalleryGridNavigation({- columnCount: 3,- isStarredOpen: true,- items: ['r0', 'r1', 'r2', 'r3'].map((name) => createImageItem(name)),- starredItems: ['s0', 's1', 's2', 's3', 's4'].map((name) => createImageItem(name, true)),- });- const step = (from: number, direction: 'down' | 'left' | 'right' | 'up') =>- getGalleryGridNavigationStep(navigation, 3, from, direction);-- it('keeps the column when stepping down across the seam past a partial strip row', () => {- // s4 sits alone on the strip's second row (column 1); the cell below it is r1.- expect(step(4, 'down')).toBe(5 + 1);- // s1 (row 0, column 1) steps onto s4 (row 1, column 1).- expect(step(1, 'down')).toBe(4);- // s2 (row 0, column 2) has no cell below in the partial row; it lands on the row's last cell.- expect(step(2, 'down')).toBe(4);- });+describe('pinned sections layout', () => {+ it('sizes the starred strip by its disclosure row plus its open rows', () => {+ const open = getGalleryStarredLayout({ collapsed: false, columns: 2, shownCount: 3, tileSize: 96 });+ const collapsed = getGalleryStarredLayout({ collapsed: true, columns: 2, shownCount: 3, tileSize: 96 });- it('keeps the column when stepping up into the strip', () => {- // r2 (listing row 0, column 2) goes to the strip's last row, clamped to its last cell s4.- expect(step(5 + 2, 'up')).toBe(4);- // r0 (column 0) goes to s3.- expect(step(5, 'up')).toBe(3);+ expect(open.rowCount).toBe(2);+ expect(open.height).toBe(GALLERY_STARRED_HEADER_HEIGHT_PX + 2 * (96 + GALLERY_GRID_GAP_PX));+ expect(collapsed.height).toBe(GALLERY_STARRED_HEADER_HEIGHT_PX);+ expect(getGalleryStarredLayout({ collapsed: false, columns: 2, shownCount: 0, tileSize: 96 }).height).toBe(0);});- it('walks the flat sequence left and right and stays put at the edges', () => {- expect(step(4, 'right')).toBe(5);- expect(step(5, 'left')).toBe(4);- expect(step(0, 'left')).toBe(0);- expect(step(0, 'up')).toBe(0);- expect(step(8, 'right')).toBe(8);- expect(step(8, 'down')).toBe(8);- expect(step(5, 'down')).toBe(8);- });-});--describe('getGalleryGridRowHeightPx', () => {- it('sizes chrome rows by their own constants and cell rows by the shared row height', () => {- const starred = createImageItem('starred-1', true);- const items = { items: [createImageItem('regular-1')], starredItems: [starred], starredTotal: 1 };-- expect(buildRows(items).map((row) => getGalleryGridRowHeightPx(row, 100))).toEqual([- GALLERY_STARRED_HEADER_HEIGHT_PX,- 100,- GALLERY_STARRED_SEPARATOR_HEIGHT_PX,- 100,- ]);- expect(buildRows({ ...items, isStarredOpen: false }).map((row) => getGalleryGridRowHeightPx(row, 100))).toEqual([- GALLERY_STARRED_HEADER_HEIGHT_PX,- GALLERY_GRID_GAP_PX,- 100,- ]);+ it('closes the pinned block with its footer only when something is pinned', () => {+ expect(getGalleryPinnedHeightPx(0, 0)).toBe(0);+ expect(getGalleryPinnedHeightPx(40, 0)).toBe(40 + GALLERY_PINNED_FOOTER_PX);+ expect(getGalleryPinnedHeightPx(40, 124)).toBe(164 + GALLERY_PINNED_FOOTER_PX);});});-describe('getGalleryGridRowIndexForItem', () => {- it('finds the row holding a navigation index, across sections', () => {- const starred = createImageItem('starred-1', true);- const rows = buildRows({- items: [createImageItem('regular-1'), createImageItem('regular-2'), createImageItem('regular-3')],- starredItems: [starred],- starredTotal: 1,- });+describe('getGalleryGridRowIndexForItemKey', () => {+ it('finds the listing row holding an item; a strip item has no row', () => {+ const items = [createImageItem('regular-1'), createImageItem('regular-2'), createImageItem('regular-3')];- expect(getGalleryGridRowIndexForItem(rows, 0)).toBe(1);- expect(getGalleryGridRowIndexForItem(rows, 1)).toBe(3);- expect(getGalleryGridRowIndexForItem(rows, 3)).toBe(4);- expect(getGalleryGridRowIndexForItem(rows, 99)).toBe(-1);+ expect(getGalleryGridRowIndexForItemKey(items, 'image:starred-1', 2)).toBe(-1);+ expect(getGalleryGridRowIndexForItemKey(items, 'image:regular-1', 2)).toBe(0);+ expect(getGalleryGridRowIndexForItemKey(items, 'image:regular-3', 2)).toBe(1);});});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.tsindex 7ca0673166..e789dfd1db 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts@@ -1,14 +1,20 @@-import type { GalleryItem } from '@features/gallery/core/items';+import type { GalleryItem, GalleryItemKey } from '@features/gallery/core/items';import { toGalleryItemKey } from '@features/gallery/core/items';export const GALLERY_GRID_GAP_PX = 4;+/** The disclosure row of a pinned section (in progress, starred). */export const GALLERY_STARRED_HEADER_HEIGHT_PX = 24;-/** The gap row grows to hold a hairline rule while the starred section is open. */-export const GALLERY_STARRED_SEPARATOR_HEIGHT_PX = 13;+/** The pinned block's hairline rule plus the margin that separates it from the listing. */+export const GALLERY_PINNED_FOOTER_PX = 9;const GALLERY_MIN_COLUMN_COUNT = 2;-const GALLERY_MAX_COLUMN_COUNT = 12;+/**+ * High enough that the minimum cell size, not this cap, bounds a wide+ * placement: at 12 the bottom panel ignored the density slider below ~92px+ * cells, while the side panel kept shrinking.+ */+const GALLERY_MAX_COLUMN_COUNT = 48;/** Cell size the density slider interpolates between: 0% is largest, 100% smallest. */const GALLERY_MAX_CELL_PX = 192;@@ -61,46 +67,16 @@ 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 };-export type GalleryGridSection = 'regular' | 'starred';-export type GalleryGridRow =- | { cells: GalleryGridCell[]; key: string; kind: 'cells'; section: GalleryGridSection }- | { key: string; kind: 'starred-gap'; withSeparator: boolean }- | { key: string; kind: 'starred-header'; shownCount: number; total: number };+export type GalleryGridRow = { cells: GalleryItem[]; key: string; kind: 'cells'; section: GalleryGridSection };/** The starred strip shows at most this many rows at the current column count. */const GALLERY_STARRED_STRIP_MAX_ROWS = 3;-const getGalleryStarredStripItems = (starredItems: readonly GalleryItem[], columnCount: number): GalleryItem[] =>+export const getGalleryStarredStripItems = (starredItems: readonly GalleryItem[], columnCount: number): GalleryItem[] =>starredItems.slice(0, GALLERY_STARRED_STRIP_MAX_ROWS * columnCount);-/**- * The keyboard and scroll index space: the shown strip cells first, then the- * listing. The grid is unstarred-only, so no item occurs twice.- */-export interface GalleryGridNavigation {- items: GalleryItem[];- regularStart: number;-}--export const buildGalleryGridNavigation = ({- columnCount,- isStarredOpen,- items,- starredItems,-}: {- columnCount: number;- isStarredOpen: boolean;- items: readonly GalleryItem[];- starredItems: readonly GalleryItem[];-}): GalleryGridNavigation => {- const stripItems = isStarredOpen ? getGalleryStarredStripItems(starredItems, columnCount) : [];-- return { items: [...stripItems, ...items], regularStart: stripItems.length };-};-/*** Every item the grid has on hand — strip first, then the listing. The two* refetch independently, so an item can sit on both sides for a moment.@@ -118,56 +94,14 @@ export const mergeGalleryLoadedItems = (return [...starredItems, ...items.filter((item) => !seen.has(toGalleryItemKey(item)))];};-export type GalleryGridNavDirection = 'down' | 'left' | 'right' | 'up';--/**- * The next navigation index for an arrow key. Left/right walk the flat- * sequence; up/down move by visual row, and each section chunks its own rows,- * so a step across the seam keeps its column instead of drifting by the- * strip's partial last row. Clamped within each section's rows and to the- * ends of the sequence; a move that has nowhere to go returns `fromIndex`.- */-export const getGalleryGridNavigationStep = (- { items, regularStart }: GalleryGridNavigation,- columnCount: number,- fromIndex: number,- direction: GalleryGridNavDirection-): number => {- const lastIndex = items.length - 1;-- if (direction === 'left' || direction === 'right') {- return Math.min(lastIndex, Math.max(0, fromIndex + (direction === 'right' ? 1 : -1)));- }-- const stripRowCount = Math.ceil(regularStart / columnCount);- const listingCount = items.length - regularStart;- const listingRowCount = Math.ceil(listingCount / columnCount);- const sectionIndex = fromIndex < regularStart ? fromIndex : fromIndex - regularStart;- const row = (fromIndex < regularStart ? 0 : stripRowCount) + Math.floor(sectionIndex / columnCount);- const column = sectionIndex % columnCount;- const targetRow = row + (direction === 'down' ? 1 : -1);-- if (targetRow < 0 || targetRow >= stripRowCount + listingRowCount) {- return fromIndex;- }-- if (targetRow < stripRowCount) {- return Math.min(regularStart - 1, targetRow * columnCount + column);- }-- return Math.min(lastIndex, regularStart + (targetRow - stripRowCount) * columnCount + column);-};--const getGalleryGridCellKey = (cell: GalleryGridCell): string => toGalleryItemKey(cell.item);-/*** Rows are keyed by their leading cell rather than their index so that- * structural changes above a row (collapsing the starred section, a- * placeholder resolving) move the row without recreating it: the virtualizer- * and React both track the row by key, so its thumbnails keep their DOM.+ * structural changes above a row (a placeholder resolving, the strip+ * changing) move the row without recreating it: the virtualizer and React+ * both track the row by key, so its thumbnails keep their DOM.*/-const chunkGalleryCellsIntoRows = (- cells: GalleryGridCell[],+export const chunkGalleryCellsIntoRows = (+ cells: readonly GalleryItem[],columnCount: number,section: GalleryGridSection): GalleryGridRow[] => {@@ -178,7 +112,7 @@ const chunkGalleryCellsIntoRows = (rows.push({cells: rowCells,- key: `${section}:${getGalleryGridCellKey(rowCells[0]!)}`,+ key: `${section}:${toGalleryItemKey(rowCells[0]!)}`,kind: 'cells',section,});@@ -188,72 +122,24 @@ 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- * only saved items participate in navigation. Cell indices follow- * `buildGalleryGridNavigation`.+ * The listing's row model in one pure pass. The starred strip is pinned above+ * the virtualized listing (see `getGalleryStarredLayout`), so only the listing+ * chunks into rows.*/-export const buildGalleryGridRows = ({- columnCount,- isStarredOpen,- items,- starredItems,- starredTotal,-}: {- columnCount: number;- isStarredOpen: boolean;- items: readonly GalleryItem[];- starredItems: readonly GalleryItem[];- starredTotal: number;-}): GalleryGridRow[] => {- const stripItems = getGalleryStarredStripItems(starredItems, columnCount);- const shownCount = isStarredOpen ? stripItems.length : 0;- const starredCells: GalleryGridCell[] = stripItems.map((item, itemIndex) => ({ item, itemIndex, kind: 'item' }));- const regularItemCells: GalleryGridCell[] = items.map((item, index) => ({- item,- itemIndex: shownCount + index,- kind: 'item',- }));- const regularCells = regularItemCells;- const rows: GalleryGridRow[] = [];-- if (stripItems.length > 0) {- rows.push({ key: 'starred-header', kind: 'starred-header', shownCount, total: starredTotal });-- if (isStarredOpen) {- rows.push(...chunkGalleryCellsIntoRows(starredCells, columnCount, 'starred'));- }-- if (regularCells.length > 0) {- // A visible rule only while the starred cells are showing; collapsed, the- // header already separates the sections.- rows.push({ key: 'starred-gap', kind: 'starred-gap', withSeparator: isStarredOpen });- }- }-- rows.push(...chunkGalleryCellsIntoRows(regularCells, columnCount, 'regular'));-- return rows;-};--/** `cellRowHeightPx` is the thumbnail row height including its trailing gap. */-export const getGalleryGridRowHeightPx = (row: GalleryGridRow, cellRowHeightPx: number): number => {- if (row.kind === 'starred-header') {- return GALLERY_STARRED_HEADER_HEIGHT_PX;- }-- if (row.kind === 'starred-gap') {- return row.withSeparator ? GALLERY_STARRED_SEPARATOR_HEIGHT_PX : GALLERY_GRID_GAP_PX;- }+export const buildGalleryGridRows = (items: readonly GalleryItem[], columnCount: number): GalleryGridRow[] =>+ chunkGalleryCellsIntoRows(items, columnCount, 'regular');++/** The listing row holding `itemKey`; -1 for an item the listing does not hold (a strip item). */+export const getGalleryGridRowIndexForItemKey = (+ items: readonly GalleryItem[],+ itemKey: GalleryItemKey,+ columnCount: number+): number => {+ const index = items.findIndex((item) => toGalleryItemKey(item) === itemKey);- return cellRowHeightPx;+ return index < 0 ? -1 : Math.floor(index / columnCount);};-export const getGalleryGridRowIndexForItem = (rows: GalleryGridRow[], itemIndex: number): number =>- rows.findIndex(- (row) => row.kind === 'cells' && row.cells.some((cell) => cell.kind === 'item' && cell.itemIndex === itemIndex)- );-export const getGalleryProgressLayout = ({columns,tileSize,@@ -282,3 +168,32 @@ export const getGalleryProgressLayout = ({};};export type GalleryProgressLayout = ReturnType<typeof getGalleryProgressLayout>;++/** The pinned starred strip: its disclosure row plus, while open, its bounded rows. */+export const getGalleryStarredLayout = ({+ columns,+ tileSize,+ shownCount,+ collapsed,+}: {+ columns: number;+ tileSize: number;+ shownCount: number;+ collapsed: boolean;+}) => {+ const rowCount = Math.ceil(shownCount / columns);+ const rowHeight = tileSize + GALLERY_GRID_GAP_PX;++ return {+ rowCount,+ rowHeight,+ height: shownCount > 0 ? GALLERY_STARRED_HEADER_HEIGHT_PX + (collapsed ? 0 : rowCount * rowHeight) : 0,+ };+};++/**+ * In progress and starred share one pinned block above the listing, closed by+ * a rule and a margin; the virtualizer's scroll margin is the block's height.+ */+export const getGalleryPinnedHeightPx = (progressHeight: number, starredHeight: number): number =>+ progressHeight + starredHeight > 0 ? progressHeight + starredHeight + GALLERY_PINNED_FOOTER_PX : 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 90327f3145..1972207c25 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -282,6 +282,16 @@ describe('gallery state view', () => {expect(gallery.selectedItemKeys).toEqual(['image:selected.png']);});+ it('treats a selection in the starred strip as visible, though the listing does not hold it', () => {+ const starred = { ...createImageItem('starred.png'), starred: true };+ const values = { selectedImageName: 'image:starred.png' };++ expect(getGalleryStateView(values, boards, [createImageItem('regular.png')], false).selectedItemKey).toBeNull();+ expect(+ getGalleryStateView(values, boards, [createImageItem('regular.png')], false, [starred]).selectedItemKey+ ).toBe('image:starred.png');+ });+it('projects same-name images and videos independently by qualified key', () => {const image = createImageItem('shared');const video = createVideoItem('shared');diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex cccfa8b4ee..d719fb7270 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -190,11 +190,24 @@ export const getGalleryCompareImage = (values: Record<string, unknown>): GalleryselectedImageName: null,});+/** The infinite window's anchor page; 0 whenever the window covers the top of the listing. */+export const getGalleryAnchoredWindowPage = (values: Record<string, unknown>): number => {+ const page = getGalleryPage(values);++ return getGallerySettings(values).paginationMode === 'infinite' && page > 0 ? page : 0;+};++/**+ * `starredStripItems` are the strip the grid pins above the listing: a+ * starred selection lives there, never in the unstarred listing, and still+ * counts as visible.+ */export const getGalleryStateView = (values: Record<string, unknown>,backendBoards: GalleryBoard[],backendItems: GalleryItem[] | null,- isLoading: boolean+ isLoading: boolean,+ starredStripItems: readonly GalleryItem[] = []): GalleryStateView => {const localItems = getBoundedRecentImages(values.recentImages).map(legacyGeneratedImageToGalleryItem);const items = backendItems ?? (isLoading ? [] : localItems);@@ -205,8 +218,9 @@ export const getGalleryStateView = (: selectedItem? toGalleryItemKey(selectedItem): null;+ const isVisible = (item: GalleryItem) => toGalleryItemKey(item) === persistedSelectedItemKey;const visibleSelectedItemKey =- persistedSelectedItemKey && items.some((item) => toGalleryItemKey(item) === persistedSelectedItemKey)+ persistedSelectedItemKey && (items.some(isVisible) || starredStripItems.some(isVisible))? persistedSelectedItemKey: null;const selectedItemKeys = getPersistedSelectedGalleryItemKeys(values);@@ -234,7 +248,6 @@ export const getGalleryStateView = (compareImageKey !== visibleSelectedItemKey;const semanticImageQuery = getGallerySemanticImageQuery(values);const page = getGalleryPage(values);- const isAnchoredInfiniteWindow = settings.paginationMode === 'infinite' && page > 0;const selectedImageQuery = getGallerySelectedImageQuery(values);const revealTargetPage =settings.paginationMode === 'paginated' &&@@ -252,7 +265,7 @@ export const getGalleryStateView = (: null;return {- anchoredWindowPage: isAnchoredInfiniteWindow ? page : 0,+ anchoredWindowPage: getGalleryAnchoredWindowPage(values),boards,compareImageKey,galleryView,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 59f12143b9..654b7bf98d 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@@ -181,6 +181,7 @@ const adapter: GalleryUiAdapter = {liveFollowEnabled: false,progressSessions: [],pinnedProgressSessionId: null,+ followedProgressSessionId: null,followProgressSession: vi.fn(),notifications: {add: (...args: unknown[]) => mocks.notificationsAdd(...args),diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.tsindex 4fc0e990f5..1caa91568d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts@@ -1,12 +1,11 @@import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';+import type { GalleryNavigationDirection, GalleryNavigationEntry } from '@features/gallery/core/selection';-import { shouldStarSelection, toGalleryItemKey, toGalleryItemRef } from '@features/gallery/core/items';+import { shouldStarSelection, toGalleryItemRef } from '@features/gallery/core/items';+import { getGalleryNavigationStep } from '@features/gallery/core/selection';import { useEffect, useEffectEvent } from 'react';import { useTranslation } from 'react-i18next';-import type { GalleryGridNavDirection, GalleryGridNavigation } from './galleryGridLayout';--import { getGalleryGridNavigationStep } from './galleryGridLayout';import { useGalleryUi } from './GalleryUiContext';import { useGalleryWidget } from './GalleryWidgetContext';@@ -24,7 +23,7 @@ const GALLERY_HOTKEYS = [['gallery.deleteSelection', 'widgets.gallery.commands.deleteSelection', null, ['delete', 'backspace']],['gallery.starImage', 'widgets.gallery.commands.toggleStarImage', null, ['.']],['gallery.toggleStarredOnly', 'widgets.gallery.commands.toggleStarredOnly', null, []],-] as const satisfies readonly (readonly [string, string, GalleryGridNavDirection | null, readonly string[]])[];+] as const satisfies readonly (readonly [string, string, GalleryNavigationDirection | null, readonly string[]])[];/*** Registers the grid's commands and their default keys.@@ -36,36 +35,39 @@ const GALLERY_HOTKEYS = [export const useGalleryGridHotkeys = ({actionSelectionRefs,columnCount,+ cursorKey,loadedItems,- navigation,- scrollToItemIndex,+ navigationSections,+ scrollToEntry,}: {actionSelectionRefs: GalleryItemRef[];columnCount: number;+ /** Where the arrow keys step from: the followed session, else the selected item. */+ cursorKey: string | null;/** Everything on hand for star-state lookups, strip included. */loadedItems: readonly GalleryItem[];- /** The arrow-key index space: shown strip cells, then the listing. */- navigation: GalleryGridNavigation;- scrollToItemIndex: (itemIndex: number) => void;+ /** The arrow-key sections in visual order: in progress, the starred strip, the listing. */+ navigationSections: readonly (readonly GalleryNavigationEntry[])[];+ scrollToEntry: (entry: GalleryNavigationEntry) => void;}) => {const { t } = useTranslation();const { actions, gallery, itemActions, runtime } = useGalleryWidget();- const { gallery: galleryCommands } = useGalleryUi();+ const { followProgressSession, gallery: galleryCommands } = useGalleryUi();++ const navigate = useEffectEvent((direction: GalleryNavigationDirection) => {+ const entry = getGalleryNavigationStep(navigationSections, cursorKey, direction, columnCount);- const navigate = useEffectEvent((direction: GalleryGridNavDirection) => {- if (navigation.items.length === 0) {+ if (!entry) {return;}- const selectedIndex = navigation.items.findIndex((item) => toGalleryItemKey(item) === gallery.selectedItemKey);- const nextIndex =- selectedIndex === -1 ? 0 : getGalleryGridNavigationStep(navigation, columnCount, selectedIndex, direction);- const nextItem = navigation.items[nextIndex];-- if (nextItem && (nextIndex !== selectedIndex || selectedIndex === -1)) {- actions.selectItem(nextItem);- scrollToItemIndex(nextIndex);+ if (entry.kind === 'session') {+ followProgressSession(entry.id, { revealPreview: false });+ } else {+ actions.selectItem(entry.item);}++ scrollToEntry(entry);});const executeGalleryHotkey = useEffectEvent((commandId: string) => {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 88cc5aaa95..f467d3da1c 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@@ -100,6 +100,7 @@ const adapter: GalleryUiAdapter = {liveFollowEnabled: false,progressSessions: [],pinnedProgressSessionId: null,+ followedProgressSessionId: null,followProgressSession: vi.fn(),notifications: {add: (...args: unknown[]) => mocks.notificationsAdd(...args),diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.tsindex 3fe3c39c06..50d21ca008 100644--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts@@ -77,6 +77,7 @@ export {} from './data/events';export {+ getFollowedProgressSession,getQueueActiveSessions,getQueueProgressSessions,isGalleryProgressItem,diff --git a/invokeai/frontend/webv2/src/features/queue/core/activeSessions.test.ts b/invokeai/frontend/webv2/src/features/queue/core/activeSessions.test.tsindex f16e37458f..6528864f55 100644--- a/invokeai/frontend/webv2/src/features/queue/core/activeSessions.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/activeSessions.test.ts@@ -2,7 +2,12 @@ import { describe, expect, it } from 'vitest';import type { QueueItem } from './historyTypes';-import { getQueueActiveSessions, getQueueProgressSessions, isGalleryProgressItem } from './activeSessions';+import {+ getFollowedProgressSession,+ getQueueActiveSessions,+ getQueueProgressSessions,+ isGalleryProgressItem,+} from './activeSessions';const run = (id: string, backendItemIds: number[], destination: 'gallery' | 'canvas' = 'gallery'): QueueItem => ({id,@@ -105,3 +110,20 @@ describe('gallery batch progress slots', () => {}});});++describe('getFollowedProgressSession', () => {+ const sessions = [+ { id: 'queued', state: 'queued' as const },+ { id: 'settling', state: 'settling' as const },+ { id: 'running-1', state: 'running' as const },+ { id: 'running-2', state: 'running' as const },+ ];++ it('prefers the pinned session, then the first running, then the first settling, never a queued one', () => {+ expect(getFollowedProgressSession(sessions, 'running-2')?.id).toBe('running-2');+ expect(getFollowedProgressSession(sessions, null)?.id).toBe('running-1');+ expect(getFollowedProgressSession(sessions, 'gone')?.id).toBe('running-1');+ expect(getFollowedProgressSession(sessions.slice(0, 2), null)?.id).toBe('settling');+ expect(getFollowedProgressSession(sessions.slice(0, 1), null)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/core/activeSessions.ts b/invokeai/frontend/webv2/src/features/queue/core/activeSessions.tsindex 33401f340d..c6acf2320f 100644--- a/invokeai/frontend/webv2/src/features/queue/core/activeSessions.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/activeSessions.ts@@ -49,6 +49,20 @@ export const getQueueActiveSessions = (return sessions.sort((left, right) => left.backendItemId - right.backendItemId);};+/**+ * The session the live preview shows and the gallery highlights: the pinned+ * one, else the first running, else the first still settling; queued work is+ * never followed.+ */+export const getFollowedProgressSession = <T extends { id: string; state: QueueProgressSession['state'] }>(+ sessions: readonly T[],+ pinnedSessionId: string | null+): T | null =>+ sessions.find((session) => session.id === pinnedSessionId) ??+ sessions.find((session) => session.state === 'running') ??+ sessions.find((session) => session.state === 'settling') ??+ null;+/** A tile per unfinished batch slot, including work waiting to start. */export type QueueProgressSession = Omit<QueueActiveSession, 'backendItemId' | 'state'> & {backendItemId: number | null;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 a3ceb6e4c1..f5acb56a9a 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@@ -112,6 +112,8 @@ const mocks = vi.hoisted(() => {},},galleryItemFilters: [] as Array<{ boardId: string; starred?: boolean }>,+ galleryStripFetches: [] as Array<{ boardId: string; starred?: boolean }>,+ galleryStripItems: [] as Array<GalleryImageItem | GalleryVideoItem>,galleryItemPageOffsets: [] as number[],galleryItemWindowOffsets: [] as number[],galleryItemPages: [] as GalleryItemsPage[],@@ -179,6 +181,15 @@ vi.mock('@features/gallery/queries', () => ({flattenGalleryItemsData: (data: InfiniteData<GalleryItemsPage, number> | undefined) =>data?.pages.flatMap((page) => page.items) ?? [],galleryBoardsOptions: () => ({ queryFn: () => [], queryKey: ['test-boards'], staleTime: Infinity }),+ galleryStarredStripOptions: (query: { boardId: string; starred?: boolean }) => ({+ queryFn: () => {+ mocks.galleryStripFetches.push(query);++ return Promise.resolve({ items: mocks.galleryStripItems, total: mocks.galleryStripItems.length });+ },+ queryKey: ['test-strip', query.boardId, mocks.galleryStripItems.map((item) => item.name).join(',')],+ staleTime: Infinity,+ }),galleryItemsInfiniteOptions: (query: { boardId: string; orderDir?: 'ASC' | 'DESC'; starred?: boolean },window: { kind: 'anchor' | 'infinite' | 'page'; offset?: number } = { kind: 'infinite' }@@ -476,6 +487,7 @@ beforeEach(() => {delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).paginationMode;delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).semanticImageQuery;delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).selectedImageQuery;+ delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).starredOnly;mocks.project.widgetInstances.gallery.state.values.recentImages = mocks.recentImages;mocks.project.widgetInstances.gallery.state.values.selectedImage = {...mocks.recentImages[0],@@ -483,6 +495,8 @@ beforeEach(() => {};mocks.project.widgetInstances.gallery.state.values.selectedImageName = 'newest';mocks.galleryItemFilters.length = 0;+ mocks.galleryStripFetches.length = 0;+ mocks.galleryStripItems = [];mocks.galleryItemPageOffsets.length = 0;mocks.galleryItemWindowOffsets.length = 0;mocks.imageActionOptions = null;@@ -523,50 +537,108 @@ afterEach(async () => {});describe('preview keyboard navigation boundary', () => {- it('walks the unstarred listing the grid shows by default, and the starred one for a starred selection', async () => {+ it('walks the starred strip into the unstarred listing and back, as the grid lays them out', async () => {+ const starredTop = { ...createImageItem('starred-top', '2026-07-23T00:00:00.000Z'), starred: true };+ const starredNext = { ...createImageItem('starred-next', '2026-07-22T00:00:00.000Z'), starred: true };++ mocks.galleryStripItems = [starredTop, starredNext];+ setGalleryValues({+ selectedImage: { ...legacyImage('starred-next', '2026-07-22T00:00:00.000Z'), starred: true },+ selectedImageName: 'starred-next',+ });await render();+ // The listing stays the unstarred one; the strip supplies the starred neighbors.expect(mocks.galleryItemFilters.length).toBeGreaterThan(0);expect(mocks.galleryItemFilters.every((query) => query.starred === false)).toBe(true);+ await expect.poll(() => host?.textContent).toContain('2 of 4');+ expect(mocks.galleryStripFetches.length).toBeGreaterThan(0);- // A starred item lives in the grid's strip, so its neighbors are the- // other starred items, whatever listing the grid was showing.- mocks.galleryItemFilters.length = 0;+ await pressArrow('ArrowRight');+ expect(mocks.commands.gallery.selectItem).toHaveBeenLastCalledWith(+ expect.objectContaining({ name: 'newest' }),+ undefined,+ expect.any(Number),+ true+ );+ await pressArrow('ArrowLeft');+ expect(mocks.commands.gallery.selectItem).toHaveBeenLastCalledWith(+ expect.objectContaining({ name: 'starred-top' }),+ undefined,+ expect.any(Number),+ true+ );++ // Back from the listing's first item, left lands on the strip's last.+ setGalleryValues({ selectedImage: legacyImage('newest', '2026-07-21T00:00:00.000Z'), selectedImageName: 'newest' });+ await render();+ await pressArrow('ArrowLeft');+ expect(mocks.commands.gallery.selectItem).toHaveBeenLastCalledWith(+ expect.objectContaining({ name: 'starred-next' }),+ undefined,+ expect.any(Number),+ true+ );+ });++ it('shows an item just starred once, in the strip, until the listing refetch drops it', async () => {+ const justStarred = { ...createImageItem('newest', '2026-07-21T00:00:00.000Z'), starred: true };++ mocks.galleryStripItems = [justStarred];setGalleryValues({- recentImages: mocks.recentImages.map((image) =>- image.imageName === 'newest' ? { ...image, starred: true } : image- ),- selectedImage: { ...legacyImage('newest', '2026-07-23T00:00:00.000Z'), starred: true },+ recentImages: [],+ selectedImage: { ...legacyImage('newest', '2026-07-21T00:00:00.000Z'), starred: true },selectedImageName: 'newest',});await render();- expect(mocks.galleryItemFilters.length).toBeGreaterThan(0);- expect(mocks.galleryItemFilters.every((query) => query.starred === true)).toBe(true);+ await expect.poll(() => host?.textContent).toContain('1 of 2');+ await pressArrow('ArrowRight');+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ name: 'oldest' }),+ undefined,+ expect.any(Number),+ true+ );});- it('anchors a strip selection at the top of the starred listing, not at the grid page it was stamped with', async () => {- // Paginated mode, grid on page 2: the stamp says page 2 of the unstarred- // listing, but the clicked strip item sits at the top of the starred one.- const starredItem = { ...createImageItem('starred-top', '2026-07-23T00:00:00.000Z'), starred: true };- const starredNext = { ...createImageItem('starred-next', '2026-07-22T00:00:00.000Z'), starred: true };+ it('keeps a starred selection beyond the strip reachable, and drops the strip under the starred filter', async () => {+ const starredTop = { ...createImageItem('starred-top', '2026-07-23T00:00:00.000Z'), starred: true };+ const starredDeep = { ...createImageItem('starred-deep', '2026-07-01T00:00:00.000Z'), starred: true };+ mocks.galleryStripItems = [starredTop];setGalleryValues({- galleryPage: 2,- paginationMode: 'paginated',recentImages: [],- selectedImage: { ...legacyImage('starred-top', '2026-07-23T00:00:00.000Z'), starred: true },- selectedImageName: 'starred-top',- selectedImageQuery: { ...deepQuery, page: 2, paginationMode: 'paginated' },+ selectedImage: { ...legacyImage('starred-deep', '2026-07-01T00:00:00.000Z'), starred: true },+ selectedImageName: 'starred-deep',});- mocks.galleryItemPages = [{ items: [starredItem, starredNext], total: 2 }];-await render();- await pressArrow('ArrowRight');+ await pressArrow('ArrowLeft');+ expect(mocks.commands.gallery.selectItem).toHaveBeenLastCalledWith(+ expect.objectContaining({ name: 'starred-top' }),+ undefined,+ expect.any(Number),+ true+ );- expect(mocks.galleryItemWindowOffsets.every((offset) => offset === 0)).toBe(true);- expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(- expect.objectContaining({ name: 'starred-next' }),+ mocks.commands.gallery.selectItem.mockClear();+ mocks.galleryItemFilters.length = 0;+ mocks.galleryStripFetches.length = 0;+ mocks.galleryItemPages = [{ items: [starredTop, starredDeep], total: 2 }];+ setGalleryValues({+ recentImages: [],+ selectedImage: { ...legacyImage('starred-deep', '2026-07-01T00:00:00.000Z'), starred: true },+ selectedImageName: 'starred-deep',+ selectedImageQuery: { ...deepQuery, page: 0, starredOnly: true },+ starredOnly: true,+ });+ await render();+ await expect.poll(() => host?.textContent).toContain('2 of 2');+ expect(mocks.galleryStripFetches).toHaveLength(0);+ expect(mocks.galleryItemFilters.every((query) => query.starred === true)).toBe(true);+ await pressArrow('ArrowLeft');+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ name: 'starred-top' }),undefined,expect.any(Number),true@@ -1441,7 +1513,7 @@ describe('preview keyboard navigation boundary', () => {);});- it('does not insert live sessions into saved-image navigation', async () => {+ it('steps left off the first saved item onto the running session, following it', async () => {mocks.project.queue.items = [queueItem];mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });mocks.useProgressImage.mockReturnValue({@@ -1450,14 +1522,26 @@ describe('preview keyboard navigation boundary', () => {target: { itemIndex: 1, queueItemId: 'queue-item-live' },width: 64,});+ mocks.commands.account.updateProjectPreferences.mockImplementationOnce((settings: object) => {+ Object.assign(mocks.project.settings, settings);+ });await render();- await pressArrow('ArrowLeft');+ // Right has saved neighbors; only the leftmost step reaches the session.+ await pressArrow('ArrowRight');expect(mocks.commands.account.updateProjectPreferences).not.toHaveBeenCalled();- expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();+ setGalleryValues({ selectedImage: legacyImage('newest', '2026-07-21T00:00:00.000Z'), selectedImageName: 'newest' });+ await render();+ await pressArrow('ArrowLeft');+ expect(mocks.commands.account.updateProjectPreferences).toHaveBeenCalledExactlyOnceWith({+ showProgressImagesInViewer: true,+ });+ await rerender();+ expect(followControls.pinnedSessionId).toBe('queue-item-live:1');+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledTimes(1);});- it('disables saved-image arrow navigation while following live', async () => {+ it('steps right off the followed session onto the first saved item, and never onto waiting slots', 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) => ({@@ -1473,8 +1557,15 @@ describe('preview keyboard navigation boundary', () => {});await render();- await pressArrow('ArrowRight');+ await pressArrow('ArrowLeft');expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();+ await pressArrow('ArrowRight');+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ name: 'newest' }),+ undefined,+ expect.any(Number),+ true+ );});it('renders the live frame with the standard media chrome: footer up, no badge, item border', async () => {@@ -1514,9 +1605,15 @@ describe('preview keyboard navigation boundary', () => {mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });await render();+ // Stepping off the live session lands in the SAVED selection's listing, not the generating board's.await pressArrow('ArrowRight');- expect(mocks.commands.gallery.selectItem).not.toHaveBeenCalled();+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ boardId: 'none', name: 'newest' }),+ undefined,+ expect.any(Number),+ true+ );expect(mocks.galleryItemFilters.every((filter) => filter.boardId !== 'board-live')).toBe(true);});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 5ce27f901e..ff2e4e00a3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -188,9 +188,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const queueItems = useActiveProjectSelector((project) => project.queue.items);const previewValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'preview'));const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);- const { antialiasProgressImages, showProgressImagesInViewer } = useActiveProjectSelector(- (project) => project.settings- );+ const { antialiasProgressImages } = useActiveProjectSelector((project) => project.settings);const livePreview = useLivePreviewFollow();const { gallery, notifications, widgets } = useWorkbenchCommands();const queries = useWorkbenchQueries();@@ -218,8 +216,9 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {[livePreview.sessions]);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 activeGalleryPlaceholder =+ livePreview.sessions.find((session) => session.id === livePreview.followedSessionId) ?? null;+ const shouldFollowLive = activeGalleryPlaceholder !== null;const isComparing =!shouldFollowLive &&selectedItem?.kind === 'image' &&@@ -269,11 +268,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {navigate,navigationCursor,navigationQueryKey,- navigationSequence,selectPreviewItem,} = usePreviewNavigation({+ followedSessionId: activeGalleryPlaceholder?.id ?? null,+ followSession: livePreview.follow,isComparing,localItems,+ progressSessions: livePreview.gallerySessions,queueItems,selectGalleryItem: selectGalleryItemAtPage,selectedImageQuery,@@ -282,7 +283,6 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {galleryPaginationMode: getGallerySettings(galleryValues).paginationMode,selectedItemKey,semanticQuery: gallerySemanticQuery,- shouldFollowLive,});const [contextMenuTarget, setContextMenuTarget] = useState<ImageContextMenuTarget | null>(null);@@ -644,7 +644,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {<SelectedImagePreviewactionImage={actionImage}actions={imageActions}- boardItemCount={navigationSequence.length}+ boardItemCount={boardItems.length}density={density}filmstripItems={isFilmstripVisible && density !== 'minimal' ? boardItems : null}isItemCurrent={isItemCurrent}@@ -664,7 +664,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {<SelectedVideoPreviewactionImage={null}actions={imageActions}- boardItemCount={navigationSequence.length}+ boardItemCount={boardItems.length}density={density}filmstripItems={isFilmstripVisible && density !== 'minimal' ? boardItems : null}isItemCurrent={isItemCurrent}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsxindex d76b1ce4e3..cce8c53069 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx@@ -1,15 +1,28 @@import type { QueueActiveSession, QueueProgressSession } from '@features/queue/contracts';import type { ReactNode } from 'react';-import { getQueueActiveSessions, getQueueProgressSessions, isGalleryProgressItem } from '@features/queue/contracts';+import {+ getFollowedProgressSession,+ getQueueActiveSessions,+ getQueueProgressSessions,+ isGalleryProgressItem,+} from '@features/queue/contracts';import { useActiveProgressTargets, useFollowedProgressTargets } from '@features/queue/react';-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { createContext, use, useMemo, useState } from 'react';interface LivePreviewFollow {sessions: QueueActiveSession[];gallerySessions: QueueProgressSession[];pinnedSessionId: string | null;+ /**+ * The session on screen while live-follow is on — pinned, else the first+ * running, else the first settling, in the gallery's tile order — or null.+ * Gallery and Preview both step from it, so it is decided once, here.+ */+ followedSessionId: string | null;+ /** Turns live-follow on and pins `sessionId`: a tile click, or an arrow step onto a tile. */+ follow(sessionId: string): void;pin(sessionId: string): void;showAll(): void;}@@ -46,15 +59,22 @@ export const LivePreviewFollowProvider = ({ children }: { children: ReactNode })setSelection({ projectId, sessionId: null });}const pinnedSessionId = isStale ? null : selection.sessionId;+ const followedSessionId = enabled ? (getFollowedProgressSession(gallerySessions, pinnedSessionId)?.id ?? null) : null;+ const { account } = useWorkbenchCommands();const value = useMemo<LivePreviewFollow>(() => ({sessions,gallerySessions,pinnedSessionId,+ followedSessionId,+ follow: (sessionId) => {+ account.updateProjectPreferences({ showProgressImagesInViewer: true });+ setSelection({ projectId, sessionId });+ },pin: (sessionId) => setSelection({ projectId, sessionId }),showAll: () => setSelection({ projectId, sessionId: null }),}),- [sessions, gallerySessions, pinnedSessionId, projectId]+ [account, sessions, gallerySessions, followedSessionId, pinnedSessionId, projectId]);return <LivePreviewFollowContext value={value}>{children}</LivePreviewFollowContext>;};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex 3d024ad521..5f1c2546f0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -1,40 +1,45 @@import type { GalleryImageItem, GalleryItem, GalleryItemKey, GalleryView } from '@features/gallery';import type {GalleryItemsPage,+ GalleryNavigationEntry,GallerySemanticReference,getGallerySelectedImageQuery,} from '@features/gallery/contracts';-import type { QueueItem } from '@features/queue/contracts';+import type { GalleryItemsFilter } from '@features/gallery/queries';+import type { QueueItem, QueueProgressSession } from '@features/queue/contracts';import type { InfiniteData } from '@tanstack/react-query';import type { KeyboardEvent } from 'react';-import { compareGalleryItems, gallerySemanticReferenceKey, toGalleryItemKey } from '@features/gallery/contracts';+import {+ compareGalleryItems,+ gallerySemanticReferenceKey,+ getGalleryNavigationStep,+ getGallerySessionNavigationKey,+ toGalleryItemKey,+} from '@features/gallery/contracts';import {flattenGalleryItemsData,GALLERY_MAX_ROWS,GALLERY_PAGE_SIZE,galleryItemsInfiniteOptions,+ galleryStarredStripOptions,} from '@features/gallery/queries';import { parseDateTokens } from '@platform/search/dateTokens';-import { useInfiniteQuery } from '@tanstack/react-query';+import { useInfiniteQuery, useQuery } from '@tanstack/react-query';import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';-import type { PreviewNavigationItem } from './previewNavigation';--import {- getPreviewNavigationCursor,- getPreviewNavigationSequence,- getPreviewNavigationTarget,-} from './previewNavigation';-/*** Everything behind the preview's left/right stepping, in one place: the board* items query, the local/backend merge, the sequence + cursor, the navigate* action with its boundary-page fetch, and the neighbor prefetch. The view- * consumes the result; `previewNavigation.ts` keeps the pure sequence math.+ * consumes the result.*- * Gallery selection and the live-follow preference remain the sources of- * truth; nothing here stores a cursor.+ * The sequence is the gallery's own order — the in-progress sessions, the+ * starred strip, then the listing — so the arrows cross the grid's seams the+ * same way. One divergence: Preview walks the whole bounded strip query,+ * while the grid shows up to three rows of it (a width it alone knows) and+ * folds the rest behind "Show all". Gallery selection and the live-follow+ * preference remain the sources of truth; nothing here stores a cursor.*/const EMPTY_PREVIEW_ITEMS: GalleryItem[] = [];@@ -117,23 +122,30 @@ export const mergePreviewBoardItems = ();};+const toItemEntries = (items: readonly GalleryItem[]): GalleryNavigationEntry[] =>+ items.map((item) => ({ item, kind: 'item' }));+export interface PreviewNavigationState {+ /** Every saved item the arrows can reach, in order: the starred strip, then the listing. */boardItems: GalleryItem[];handleNavigationKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;isLoadingBoard: boolean;navigate: (offset: -1 | 1) => void;+ /** The selection's index in `boardItems`; -1 while following live or off the list. */navigationCursor: number;/** Identity of the backing query — the action context's filter identity. */navigationQueryKey: string;- navigationSequence: PreviewNavigationItem<GalleryItem>[];/** The page a selection of `item` is stamped with — see the action context's `getItemSelectionPage`. */getSelectionPage: (item: GalleryItem) => number;selectPreviewItem: (item: GalleryItem) => void;}export const usePreviewNavigation = ({+ followedSessionId,+ followSession,isComparing,localItems,+ progressSessions,queueItems,galleryPage,galleryPaginationMode,@@ -142,8 +154,10 @@ export const usePreviewNavigation = ({selectedItem,selectedItemKey,semanticQuery,- shouldFollowLive,}: {+ /** The live session on screen, when the preview is following one; the cursor sits on it. */+ followedSessionId: string | null;+ followSession: (sessionId: string) => 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. */@@ -151,6 +165,8 @@ export const usePreviewNavigation = ({isComparing: boolean;/** Recent local generations, already normalized to gallery items. */localItems: GalleryImageItem[];+ /** The gallery's in-progress tiles, in its order; only running ones can be stepped onto. */+ progressSessions: readonly QueueProgressSession[];queueItems: QueueItem[];selectGalleryItem: (item: GalleryItem, selectionPage: number) => void;selectedImageQuery: ReturnType<typeof getGallerySelectedImageQuery>;@@ -158,9 +174,7 @@ export const usePreviewNavigation = ({selectedItemKey: GalleryItemKey | null;/** The gallery's active similarity search, or null for the board listing. */semanticQuery: GallerySemanticReference | null;- shouldFollowLive: boolean;}): PreviewNavigationState => {- const hasSelectedItem = selectedItem !== null;const selectedImageSearch = useMemo(() => parseDateTokens(selectedImageQuery.searchTerm),[selectedImageQuery.searchTerm]@@ -168,13 +182,15 @@ export const usePreviewNavigation = ({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;+ // The grid partitions: its listing is unstarred-only, with the starred+ // items in the strip above it, unless the starred filter is on.+ const navigationStarredOnly = selectedImageQuery.starredOnly;// A ranked filmstrip follows the gallery's current search.const navigationSemanticQuery = semanticQuery;const navigationSemanticKey = gallerySemanticReferenceKey(navigationSemanticQuery);- const hasNavigationContext = hasSelectedItem;- const navigationContextKey = `${shouldFollowLive}:${selectedItemKey ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${selectedImageQuery.searchTerm}:${navigationStarredOnly}:${navigationSemanticKey}`;+ // Following live has a cursor too, so the listing loads for the step off it.+ const hasNavigationContext = selectedItem !== null || followedSessionId !== null;+ const navigationContextKey = `${followedSessionId ?? ''}:${selectedItemKey ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${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@@ -214,12 +230,8 @@ export const usePreviewNavigation = ({// Held sticky, the anchor outlived every one of them: a click on the newest// image at the top of the board left Preview walking rows 1800+ for a// selection at row 0.- // A strip selection is stamped with the grid's page, which indexes the- // unstarred listing; the strip is the top of the starred one.- const isStripSelection = navigationStarredOnly && !selectedImageQuery.starredOnly;- const navigationAnchorPage = isStripSelection- ? 0- : selectedImageQuery.paginationMode === 'paginated'+ const navigationAnchorPage =+ selectedImageQuery.paginationMode === 'paginated'? hasStaleNavigationAnchor? selectedImageQuery.page: navigationAnchor.page@@ -257,6 +269,19 @@ export const usePreviewNavigation = ({? ({ kind: 'anchor', offset: navigationAnchorPage * GALLERY_PAGE_SIZE } as const): ({ kind: 'infinite', offset: deepAnchorOffset } as const);+ const listingFilter = useMemo(+ (): GalleryItemsFilter => ({+ boardId: navigationBoardId,+ createdFrom: selectedImageSearch.range?.from,+ createdTo: selectedImageSearch.range?.to,+ galleryView: navigationGalleryView,+ orderDir: navigationOrderDir,+ searchTerm: selectedImageSearch.text,+ ...(navigationSemanticQuery ? { semanticQuery: navigationSemanticQuery } : {}),+ }),+ [navigationBoardId, navigationGalleryView, navigationOrderDir, navigationSemanticQuery, selectedImageSearch]+ );+const {data: boardItemsData,fetchNextPage: fetchNextBoardItemsPage,@@ -267,24 +292,32 @@ export const usePreviewNavigation = ({isFetchingNextPage: isFetchingNextBoardItemsPage,isFetchingPreviousPage: isFetchingPreviousBoardItemsPage,} = useInfiniteQuery({- ...galleryItemsInfiniteOptions(- {- boardId: navigationBoardId,- createdFrom: selectedImageSearch.range?.from,- createdTo: selectedImageSearch.range?.to,- galleryView: navigationGalleryView,- orderDir: navigationOrderDir,- searchTerm: selectedImageSearch.text,- ...(navigationSemanticQuery ? { semanticQuery: navigationSemanticQuery } : {}),- // The grid partitions: the listing is unstarred-only unless the- // selection was made under the starred filter.- starred: navigationStarredOnly,- },- navigationWindow- ),+ ...galleryItemsInfiniteOptions({ ...listingFilter, starred: navigationStarredOnly }, navigationWindow),enabled: hasNavigationContext,});+ // The strip the grid pins above its unstarred listing — the same bounded+ // query, so it is already cached whenever the gallery is open. As in the+ // grid, no strip applies to a ranked result, to the starred-only listing,+ // or to a window anchored mid-board.+ const hasStrip =+ hasNavigationContext && !navigationStarredOnly && navigationSemanticQuery === null && deepAnchorOffset === 0;+ const { data: stripData } = useQuery({ ...galleryStarredStripOptions(listingFilter), enabled: hasStrip });+ const stripItems = useMemo(() => {+ if (!hasStrip) {+ return EMPTY_PREVIEW_ITEMS;+ }++ const items = stripData?.items ?? EMPTY_PREVIEW_ITEMS;++ // A starred selection beyond the strip's bound (the grid hides it behind+ // "Show all") still belongs to the starred partition: it joins the strip+ // section so the arrows have somewhere to step from.+ return selectedItem?.starred && !items.some((item) => toGalleryItemKey(item) === selectedItemKey)+ ? [...items, selectedItem]+ : items;+ }, [hasStrip, selectedItem, selectedItemKey, stripData]);+const getSelectionPageIn = useCallback((item: GalleryItem, data: typeof boardItemsData): number => {const itemKey = toGalleryItemKey(item);@@ -310,9 +343,9 @@ export const usePreviewNavigation = ({// past a page boundary re-keys the query at the new row, the old entry// is discarded, and — a deep window being one-way — everything the user// just walked through is unreachable. An item the window does not hold- // at all (a recent the listing has not caught up with, the compare- // slot's image) is stamped at the top: that is where a recent lives,- // and the base window's reach is the best guess for anything else.+ // at all (a strip item, a recent the listing has not caught up with,+ // the compare slot's image) is stamped at the top: that is where those+ // live, and the base window's reach is the best guess for anything else.return navigationSemanticQuery !== null? 0: selectedImageQuery.paginationMode === 'paginated'@@ -392,12 +425,19 @@ export const usePreviewNavigation = ({[navigationBoardId, navigationGalleryView, navigationLocalItems, navigationOrderDir]);const previewLocalBoardItems = useMemo(() => {- if (!selectedItem || localBoardItems.some((item) => toGalleryItemKey(item) === selectedItemKey)) {- return localBoardItems;+ // A recent starred since it landed has moved to the strip.+ const listingLocalItems = hasStrip ? localBoardItems.filter((item) => !item.starred) : localBoardItems;++ if (+ !selectedItem ||+ (hasStrip && selectedItem.starred) ||+ listingLocalItems.some((item) => toGalleryItemKey(item) === selectedItemKey)+ ) {+ return listingLocalItems;}- return [selectedItem, ...localBoardItems];- }, [localBoardItems, selectedItem, selectedItemKey]);+ return [selectedItem, ...listingLocalItems];+ }, [hasStrip, 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.@@ -406,32 +446,62 @@ export const usePreviewNavigation = ({navigationSemanticQuery === null ? previewLocalBoardItems : selectedItem ? [selectedItem] : EMPTY_PREVIEW_ITEMS,[navigationSemanticQuery, previewLocalBoardItems, selectedItem]);+ // The listing and the strip refetch independently, so an item just starred+ // can sit on both sides for a moment; the strip keeps it.+ const stripKeys = useMemo(() => new Set(stripItems.map(toGalleryItemKey)), [stripItems]);+ const mergeListingItems = useCallback(+ (backendItems: GalleryItem[]) =>+ mergePreviewBoardItems(backendItems, previewMergeItems, navigationOrderDir, {+ isRanked: navigationSemanticQuery !== null,+ }).filter((item) => !stripKeys.has(toGalleryItemKey(item))),+ [navigationOrderDir, navigationSemanticQuery, previewMergeItems, stripKeys]+ );+ const listingItems = useMemo(+ () => (hasNavigationContext ? mergeListingItems(backendBoardItems) : EMPTY_PREVIEW_ITEMS),+ [backendBoardItems, hasNavigationContext, mergeListingItems]+ );const boardItems = useMemo(- () =>- !hasNavigationContext- ? EMPTY_PREVIEW_ITEMS- : mergePreviewBoardItems(backendBoardItems, previewMergeItems, navigationOrderDir, {- isRanked: navigationSemanticQuery !== null,- }),- [backendBoardItems, hasNavigationContext, navigationOrderDir, navigationSemanticQuery, previewMergeItems]+ () => (stripItems.length === 0 ? listingItems : [...stripItems, ...listingItems]),+ [listingItems, stripItems]);const isLoadingBoard = hasNavigationContext && isFetchingBoardItems;- const navigationSequence = useMemo(() => getPreviewNavigationSequence({ boardImages: boardItems }), [boardItems]);- const navigationCursor = getPreviewNavigationCursor(navigationSequence, {- isFollowingLive: shouldFollowLive,- selectedItemKey,- });+ const sessionEntries = useMemo(+ (): GalleryNavigationEntry[] =>+ progressSessions.map((session) => ({ id: session.id, kind: 'session', navigable: session.state === 'running' })),+ [progressSessions]+ );+ const stripEntries = useMemo(() => toItemEntries(stripItems), [stripItems]);+ const navigationSections = useMemo(+ () => [sessionEntries, stripEntries, toItemEntries(listingItems)],+ [listingItems, sessionEntries, stripEntries]+ );+ const cursorKey = followedSessionId !== null ? getGallerySessionNavigationKey(followedSessionId) : selectedItemKey;+ const navigationCursor =+ followedSessionId !== null || selectedItemKey === null+ ? -1+ : boardItems.findIndex((item) => toGalleryItemKey(item) === selectedItemKey);// One navigation action shared by the arrow keys and the footer buttons.- // Comparison and live following never step through saved images.+ // Comparison never steps through saved images.const navigate = useCallback((offset: -1 | 1) => {- if (isComparing || shouldFollowLive) {+ if (isComparing) {return;}- const target = getPreviewNavigationTarget(navigationSequence, navigationCursor, offset);+ const direction = offset === 1 ? 'right' : 'left';+ const stepTo = (entry: GalleryNavigationEntry | null, data: typeof boardItemsData) => {+ if (entry?.kind === 'session') {+ followSession(entry.id);+ } else if (entry) {+ stampSelection(entry.item, data);+ }+ };+ // Preview is the only surface that walks a paginated listing across+ // its pages, so at a loaded edge the next page wins over the strip+ // seam; the strip is reached from the listing's first page.const isAtLoadedBackendBoundary =+ followedSessionId === null &&selectedItemKey !== null &&(offset === 1? backendBoardItems.at(-1) !== undefined &&@@ -442,11 +512,7 @@ export const usePreviewNavigation = ({hasPreviousBoardItemsPage);if (!isAtLoadedBackendBoundary) {- if (!target) {- return;- }-- selectPreviewItem(target.item);+ stepTo(getGalleryNavigationStep(navigationSections, cursorKey, direction), boardItemsData);return;}@@ -461,44 +527,38 @@ export const usePreviewNavigation = ({return;}- const nextBackendBoardItems = flattenPreviewItems(result.data);- const nextBoardItems = mergePreviewBoardItems(nextBackendBoardItems, previewMergeItems, navigationOrderDir, {- isRanked: navigationSemanticQuery !== null,- });- const nextNavigationSequence = getPreviewNavigationSequence({ boardImages: nextBoardItems });- const nextNavigationCursor = getPreviewNavigationCursor(nextNavigationSequence, {- isFollowingLive: shouldFollowLive,- selectedItemKey,- });- const nextTarget = getPreviewNavigationTarget(nextNavigationSequence, nextNavigationCursor, offset);-- if (nextTarget?.kind === 'item') {- // Against the data just fetched: the item is not in the pages this- // render closed over, and a lookup there would read it as an item- // the window does not hold.- stampSelection(nextTarget.item, result.data);- }+ // Against the data just fetched: the item is not in the pages this+ // render closed over, and a lookup there would read it as an item+ // the window does not hold.+ const nextSections = [+ sessionEntries,+ stripEntries,+ toItemEntries(mergeListingItems(flattenPreviewItems(result.data))),+ ];++ stepTo(getGalleryNavigationStep(nextSections, cursorKey, direction), result.data);});},[backendBoardItems,+ boardItemsData,+ cursorKey,fetchNextBoardItemsPage,fetchPreviousBoardItemsPage,+ followedSessionId,+ followSession,hasNextBoardItemsPage,hasPreviousBoardItemsPage,isComparing,isFetchingNextBoardItemsPage,isFetchingPreviousBoardItemsPage,+ mergeListingItems,navigationContextKey,- navigationCursor,- navigationOrderDir,- navigationSemanticQuery,- navigationSequence,- previewMergeItems,+ navigationSections,selectedItemKey,- selectPreviewItem,- shouldFollowLive,+ sessionEntries,stampSelection,+ stripEntries,]);@@ -512,7 +572,7 @@ export const usePreviewNavigation = ({return;}- if (isComparing || shouldFollowLive) {+ if (isComparing) {return;}@@ -522,17 +582,15 @@ export const usePreviewNavigation = ({event.stopPropagation();navigate(event.key === 'ArrowLeft' ? -1 : 1);},- [isComparing, navigate, shouldFollowLive]+ [isComparing, navigate]);// Warm the browser cache for the sequence neighbors so arrow-key navigation// swaps without a decode flash.- const previousNeighbor = navigationSequence[navigationCursor - 1];- const nextNeighbor = navigationSequence[navigationCursor + 1];- const previousNeighborUrl =- previousNeighbor?.kind === 'item' && previousNeighbor.item.kind === 'image' ? previousNeighbor.item.fullUrl : null;- const nextNeighborUrl =- nextNeighbor?.kind === 'item' && nextNeighbor.item.kind === 'image' ? nextNeighbor.item.fullUrl : null;+ const previousNeighbor = navigationCursor === -1 ? undefined : boardItems[navigationCursor - 1];+ const nextNeighbor = navigationCursor === -1 ? undefined : boardItems[navigationCursor + 1];+ const previousNeighborUrl = previousNeighbor?.kind === 'image' ? previousNeighbor.fullUrl : null;+ const nextNeighborUrl = nextNeighbor?.kind === 'image' ? nextNeighbor.fullUrl : null;useEffect(() => {[previousNeighborUrl, nextNeighborUrl].forEach((url) => {@@ -549,7 +607,6 @@ export const usePreviewNavigation = ({navigate,navigationCursor,navigationQueryKey,- navigationSequence,getSelectionPage,selectPreviewItem,};