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
refactor(gallery): trim comment narration and consolidate tests
Josh Corbett69aed34b2a1d
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts b/invokeai/frontend/webv2/src/features/gallery/core/selection.tsindex 7464f5cf64..fedfe46294 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/selection.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/selection.ts@@ -97,11 +97,8 @@ export const getPersistedSelectedGalleryItemKeys = (galleryValues: Record<string};/**- * The item that should hold the selection after `primaryKey` is deleted: the- * next eligible entry in display order — the one that visually slides into- * the deleted slot — then, when nothing later survives, the nearest earlier- * entry. Earlier-first walking crosses the starred/regular section boundary- * under starred-first ordering, so later always wins.+ * Successor after deleting `primaryKey`: the next eligible entry in display+ * order, else the nearest earlier one — later-first stays out of the starred block.*/export const getGalleryDeletionSuccessor = (orderedRefs: readonly GalleryItemRef[],diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex 5a66423605..04b7a7b752 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -17,8 +17,7 @@ export const GALLERY_BOARD_PANEL_MIN_WIDTH_PX = 180;export const GALLERY_BOARD_PANEL_MAX_WIDTH_PX = 420;/**- * User-tunable gallery settings, persisted as plain entries in the gallery- * widget's `values` record so they survive workbench autosave/hydration —+ * User-tunable gallery settings, persisted in the widget's `values` record —* except `starredFirst`, which is derived, never stored.*/export interface GallerySettings {@@ -48,11 +47,8 @@ export interface GallerySettings {}/**- * Starred items form a dedicated grid section only under infinite pagination,- * where the window resets to the top of the listing on any board, search, or- * view change and fetching starred first keeps that section complete.- * Paginated pages are flat chronological slices: a starred-first order cut- * into fixed pages spills the section across page boundaries.+ * Starred items form a section only under infinite pagination; a starred-first+ * order cut into fixed pages spills the section across page boundaries.*/export const isGalleryStarredFirst = (paginationMode: GalleryPaginationMode): boolean => paginationMode === 'infinite';diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.tsindex 3a916aa4fb..82382ac948 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/types.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts@@ -1,9 +1,6 @@export interface GeneratedImageContract {- /**- * Backend creation timestamp, when known. `queuedAt` is the submission- * instant, which for a queued batch predates creation by the whole wait —- * ordering against backend rows must prefer this field.- */+ /** Backend creation timestamp, when known; `queuedAt` is the (earlier)+ * submission instant, so ordering must prefer this field. */createdAt?: string;height: number;imageName: string;diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.tsindex a77600ecf0..05a3f31554 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts@@ -293,15 +293,10 @@ const fetchSharedDateBoardNames = (};/**- * One read of a row range from the listing a filter names. The semantic/date- * dispatch and the shared name-list handling live here so the per-page- * queryFn and the invalidation-time window rebuild can never disagree about- * how a filter's rows are fetched. Semantic and date-board queries share one- * mechanism: the ordered name list is fetched once (shared across pages, both- * consumers, and the 60s stale window) and the range hydrates a slice of it —- * which keeps semantic ranks consistent across pages and keeps a dropped-file- * reference from re-uploading its blob on every fetch. Clamps to `limit`,- * distrusting the server exactly as the per-page path always has.+ * One range read of a filter's listing, shared by the per-page queryFn and+ * the window rebuild so the two cannot diverge. Name-list filters hydrate a+ * slice of one shared name fetch — re-running a semantic search re-uploads a+ * dropped file's blob. The result is clamped to `limit`.*/export const fetchGalleryItemsRange = async (client: QueryClient,diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.tsindex afef5cfbaa..3170100c5f 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts@@ -407,6 +407,7 @@ describe('Gallery window rebuild', () => {searchTerm: '',starredFirst: false,};+ const dateFilter: GalleryItemsFilter = { ...listFilter, boardId: 'by_date:2026-07-25' };const createPageItems = (prefix: string, count: number): GalleryItem[] =>Array.from({ length: count }, (_, index) => createItem(`${prefix}-${index}.png`));@@ -414,6 +415,17 @@ describe('Gallery window rebuild', () => {const observeItems = (client: QueryClient, filter: GalleryItemsFilter): (() => void) =>new InfiniteQueryObserver(client, galleryItemsInfiniteOptions(filter)).subscribe(() => undefined);+ /** A two-page stale window under `filter`, ready for an invalidation pass. */+ const setUpStaleWindow = (filter: GalleryItemsFilter = listFilter, pages?: GalleryItem[][]) => {+ const client = createClient();+ const key = galleryKeys.items(captureAccountScope(), canonicalizeGalleryItemsFilter(filter));+ const windowPages = pages ?? [createPageItems('stale-a', 60), createPageItems('stale-b', 60)];++ client.setQueryData(key, createData(windowPages));++ return { client, key, pages: windowPages };+ };+beforeEach(() => {accountLifecycle.activate('gallery-window-rebuild-test');vi.mocked(hydrateGalleryDateBoardItemPage).mockReset();@@ -422,10 +434,7 @@ describe('Gallery window rebuild', () => {});it('refreshes an observed multi-page window with one span request, leaving it fresh and in place', async () => {- const client = createClient();- const key = getItemsKey('board-1');-- client.setQueryData(key, createData([createPageItems('stale-a', 60), createPageItems('stale-b', 60)]));+ const { client, key } = setUpStaleWindow();const unsubscribe = observeItems(client, listFilter);vi.mocked(listGalleryItems).mockResolvedValue({ items: createPageItems('fresh', 100), total: 100 });@@ -447,11 +456,7 @@ describe('Gallery window rebuild', () => {});it('still collapses an unobserved multi-page window to its anchor page', async () => {- const client = createClient();- const key = getItemsKey('board-1');- const firstPage = createPageItems('stale-a', 60);-- client.setQueryData(key, createData([firstPage, createPageItems('stale-b', 60)]));+ const { client, key, pages } = setUpStaleWindow();await invalidateGalleryItems(client);@@ -459,16 +464,12 @@ describe('Gallery window rebuild', () => {expect(vi.mocked(listGalleryItems)).not.toHaveBeenCalled();expect(data.pageParams).toEqual([0]);- expect(data.pages[0]?.items).toBe(firstPage);+ expect(data.pages[0]?.items).toBe(pages[0]);expect(client.getQueryState(key)?.isInvalidated).toBe(true);});it('falls back to the collapse when the span request fails', async () => {- const client = createClient();- const key = getItemsKey('board-1');- const firstPage = createPageItems('stale-a', 60);-- client.setQueryData(key, createData([firstPage, createPageItems('stale-b', 60)]));+ const { client, key, pages } = setUpStaleWindow();const unsubscribe = observeItems(client, listFilter);vi.mocked(listGalleryItems).mockRejectedValue(new Error('offline'));@@ -479,21 +480,18 @@ describe('Gallery window rebuild', () => {expect(vi.mocked(listGalleryItems)).toHaveBeenCalledWith(expect.objectContaining({ limit: 120, offset: 0 }));expect(data.pageParams).toEqual([0]);- expect(data.pages[0]?.items).toBe(firstPage);+ expect(data.pages[0]?.items).toBe(pages[0]);unsubscribe();});it('discards a rebuild that lost to a concurrent cache write', async () => {- const client = createClient();- const key = getItemsKey('board-1');+ const { client, key } = setUpStaleWindow();const concurrentPage = [createItem('concurrent.png')];let unsubscribe: (() => void) | undefined;- client.setQueryData(key, createData([createPageItems('stale-a', 60), createPageItems('stale-b', 60)]));vi.mocked(listGalleryItems).mockImplementation(() => {client.setQueryData(key, createData([concurrentPage, [createItem('concurrent-b.png')]]));- // Deactivate before the trailing invalidation so it does not refetch- // through this self-writing mock; the collapse outcome stays inspectable.+ // Deactivate so the trailing invalidation cannot refetch through this mock.unsubscribe?.();return Promise.resolve({ items: createPageItems('fresh', 120), total: 120 });@@ -510,16 +508,7 @@ describe('Gallery window rebuild', () => {});it('rebuilds an observed date-board window through a fresh name list and one span hydration', async () => {- const client = createClient();- const dateFilter: GalleryItemsFilter = {- boardId: 'by_date:2026-07-25',- galleryView: 'images',- searchTerm: '',- starredFirst: false,- };- const key = galleryKeys.items(captureAccountScope(), canonicalizeGalleryItemsFilter(dateFilter));-- client.setQueryData(key, createData([createPageItems('stale-a', 60), createPageItems('stale-b', 60)]));+ const { client, key } = setUpStaleWindow(dateFilter);const unsubscribe = observeItems(client, dateFilter);vi.mocked(listGalleryDateBoardItemNames).mockResolvedValue({@@ -549,19 +538,14 @@ describe('Gallery window rebuild', () => {});it('bails to the collapse when a page fetch starts during the span read', async () => {- const client = createClient();- const key = getItemsKey('board-1');-- client.setQueryData(key, createData([createPageItems('stale-a', 60), createPageItems('stale-b', 60)]));-+ const { client, key } = setUpStaleWindow();const observer = new InfiniteQueryObserver(client, galleryItemsInfiniteOptions(listFilter));const unsubscribe = observer.subscribe(() => undefined);vi.mocked(listGalleryItems).mockImplementation(({ limit, offset }) => {if (limit === 120) {- // A user scroll lands while the span read is in flight. Its fetch- // snapshotted the pre-rebuild pages, so a swap now would be clobbered- // the moment it resolves — the rebuild must stand down.+ // A scroll mid-span-read snapshotted the old pages; a swap would be+ // clobbered when it resolves, so the rebuild must stand down.void observer.fetchNextPage();return Promise.resolve({ items: createPageItems('fresh', 120), total: 200 });@@ -579,18 +563,14 @@ describe('Gallery window rebuild', () => {await invalidateGalleryItems(client);const data = getData(client, key);- const names = data.pages.flatMap((page) => page.items.map((item) => item.name));- expect(names).not.toContain('fresh-0.png');+ expect(data.pages.flatMap((page) => page.items.map((item) => item.name))).not.toContain('fresh-0.png');expect(data.pageParams).toEqual([0]);unsubscribe();});it('keeps one empty page when the span comes back empty', async () => {- const client = createClient();- const key = getItemsKey('board-1');-- client.setQueryData(key, createData([createPageItems('stale-a', 60), createPageItems('stale-b', 60)]));+ const { client, key } = setUpStaleWindow();const unsubscribe = observeItems(client, listFilter);vi.mocked(listGalleryItems).mockResolvedValue({ items: [], total: 0 });@@ -606,18 +586,9 @@ describe('Gallery window rebuild', () => {});it('collapses a video-heavy name-hydrated window instead of re-reading every video', async () => {- const client = createClient();- const dateFilter: GalleryItemsFilter = {- boardId: 'by_date:2026-07-25',- galleryView: 'images',- searchTerm: '',- starredFirst: false,- };- const key = galleryKeys.items(captureAccountScope(), canonicalizeGalleryItemsFilter(dateFilter));const createVideos = (prefix: string): GalleryItem[] =>Array.from({ length: 60 }, (_, index) => createItem(`${prefix}-${index}.mp4`, 'board-1', false, 'video'));-- client.setQueryData(key, createData([createVideos('stale-a'), createVideos('stale-b')]));+ const { client, key } = setUpStaleWindow(dateFilter, [createVideos('stale-a'), createVideos('stale-b')]);const unsubscribe = observeItems(client, dateFilter);vi.mocked(listGalleryDateBoardItemNames).mockResolvedValue({ items: [], starredCount: 0, total: 0 });@@ -625,8 +596,7 @@ describe('Gallery window rebuild', () => {await invalidateGalleryItems(client);- // The collapsed window's own single-page refetch is fine; the span-sized- // re-read (which would fetch every video individually) must not happen.+ // The collapsed window may refetch one page; the span-sized re-read must not happen.expect(vi.mocked(hydrateGalleryDateBoardItemPage)).not.toHaveBeenCalledWith(expect.objectContaining({ limit: 120 }));@@ -635,15 +605,8 @@ describe('Gallery window rebuild', () => {});it('does not re-read a window watched only by a disabled observer', async () => {- const client = createClient();- const key = getItemsKey('board-1');-- client.setQueryData(key, createData([createPageItems('stale-a', 60), createPageItems('stale-b', 60)]));-- const observer = new InfiniteQueryObserver(client, {- ...galleryItemsInfiniteOptions(listFilter),- enabled: false,- });+ const { client, key } = setUpStaleWindow();+ const observer = new InfiniteQueryObserver(client, { ...galleryItemsInfiniteOptions(listFilter), enabled: false });const unsubscribe = observer.subscribe(() => undefined);await invalidateGalleryItems(client);diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex 91f647985f..7ecfbe5cea 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -362,12 +362,8 @@ const getGalleryWindowSpan = (};/**- * Refreshes an active multi-page window in place: one span-sized read- * re-covers the whole row range the window holds and its pages are swapped- * atomically, so rows never leave the screen. Returns false — leaving the- * caller to the collapse path — when the read fails or something else touched- * the entry meanwhile (the same last-writer-wins rule as the optimistic- * patches above).+ * Swaps an active window's pages atomically from one span-sized read. False+ * falls back to the collapse: the read failed or the entry changed meanwhile.*/const rebuildGalleryItemWindow = async (client: QueryClient, owner: AccountScope, query: Query): Promise<boolean> => {const filter = getGalleryItemsFilterFromKey(query.queryKey);@@ -383,9 +379,8 @@ const rebuildGalleryItemWindow = async (client: QueryClient, owner: AccountScopereturn false;}- // Name-hydrated windows fetch each video individually, so re-reading a- // video-heavy span on every mutation would dwarf what the collapse path- // ever cost. The window's current contents are the estimate.+ // Name-hydrated windows fetch videos one by one; re-reading a video-heavy+ // span every mutation would cost more than the collapse ever did.if ((filter.semantic !== undefined || isDateBoardId(filter.boardId)) &&before.pages.reduce((count, page) => count + page.items.filter((item) => item.kind === 'video').length, 0) >@@ -475,12 +470,9 @@ const runGalleryInvalidation = async (const rebuiltQueryHashes = new Set<string>();- // Refetching an infinite query replays every retained page, one request per- // page. An ACTIVE multi-page window instead refreshes with one span-sized- // read that swaps its pages atomically — collapsing it and letting the grid- // refill rearranged the rows under the user on every mutation. Windows- // nobody renders just collapse to their pinned page; the next mount- // refetches one page and can grow the window again.+ // An ACTIVE multi-page window swaps in one span read — collapsing it+ // rearranges the rows under the user; unwatched windows just collapse to+ // their pinned page and regrow on the next mount.for (const query of getGalleryItemListQueries(client, owner)) {const data = query.state.data;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 0dad294788..27992e8678 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@@ -1099,14 +1099,18 @@ describe('GalleryImageGrid reveal requests', () => {expect(mocks.scrollToIndex).toHaveBeenCalledTimes(1);});- it('follows the selection onto its paginated page when the revealed item is not loaded', async () => {- const gallery = createGallery({+ /** A persisted off-page selection of deep.png with page-zero content loaded. */+ const createOffPageGallery = (revealTargetPage: number | null) =>+ createGallery({items: [createItem('image', 'page-zero.png')],- revealTargetPage: 2,+ revealTargetPage,selectedItemKey: null,selectedItemKeys: ['image:deep.png'],});+ it('follows the selection onto its paginated page when the revealed item is not loaded', async () => {+ const gallery = createOffPageGallery(2);+await renderGallery(gallery);await interact(() => requestGalleryItemReveal('image:deep.png'));@@ -1125,12 +1129,7 @@ describe('GalleryImageGrid reveal requests', () => {});it('follows a reveal onto its page at most once, so a missing item cannot pull the user back', async () => {- const gallery = createGallery({- items: [createItem('image', 'page-zero.png')],- revealTargetPage: 2,- selectedItemKey: null,- selectedItemKeys: ['image:deep.png'],- });+ const gallery = createOffPageGallery(2);await renderGallery(gallery);await interact(() => requestGalleryItemReveal('image:deep.png'));@@ -1144,12 +1143,7 @@ describe('GalleryImageGrid reveal requests', () => {});it('does not page-follow a selection stamped for a different listing', async () => {- const gallery = createGallery({- items: [createItem('image', 'page-zero.png')],- revealTargetPage: null,- selectedItemKey: null,- selectedItemKeys: ['image:deep.png'],- });+ const gallery = createOffPageGallery(null);await renderGallery(gallery);await interact(() => requestGalleryItemReveal('image:deep.png'));@@ -1158,18 +1152,12 @@ describe('GalleryImageGrid reveal requests', () => {});it('retires a pending reveal once the persisted selection moves to another off-page item', async () => {- const gallery = createGallery({- items: [createItem('image', 'page-zero.png')],- revealTargetPage: null,- selectedItemKey: null,- selectedItemKeys: ['image:deep.png'],- });+ const gallery = createOffPageGallery(null);await renderGallery(gallery);await interact(() => requestGalleryItemReveal('image:deep.png'));- // An auto-selected fresh image replaces the persisted selection while- // both stay off-page (the visible key is null throughout).+ // An off-page auto-select replaces the persisted selection.await renderGallery({...gallery,items: [createItem('image', 'page-zero.png')],diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex 933246f5f4..07edac59ee 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -244,10 +244,8 @@ export const GalleryImageGrid = () => {return;}- // A different selection landing after the reveal (the user clicked- // something else) retires it — a late page load must not scroll away- // from what they chose. The persisted set covers off-page selections,- // whose visible key is null.+ // Another selection retires the reveal; the persisted set catches+ // off-page selections whose visible key is null.if ((gallery.selectedItemKey !== null && gallery.selectedItemKey !== pending.itemKey) ||(gallery.selectedItemKeys.length > 0 && !gallery.selectedItemKeys.includes(pending.itemKey))diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.tsindex 57fba20c1f..6d05717c04 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryBoardGroups.ts@@ -64,10 +64,8 @@ export const getGalleryBoardGroups = ({const dateBoards = showDates ? boards.filter((board) => board.kind === 'date' && matchesBoardSearch(board)) : [];const archivedBoards = showArchived ? regularBoards.filter((board) => board.archived) : [];- // Uncategorized is the one fixed system row, so it keeps a fixed seat at- // the top — as the legacy gallery pinned it — instead of drifting further- // down as boards accumulate. The pin holds during a search too: rows keep- // their familiar slots under a quick filter.+ // The one fixed system row keeps a fixed seat at the top (legacy-gallery+ // parity) instead of drifting down as boards accumulate.const yourBoards = [...(uncategorizedBoard && matchesBoardSearch(uncategorizedBoard) ? [uncategorizedBoard] : []),...(projectBoard && matchesBoardSearch(projectBoard) ? [projectBoard] : []),diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.tsindex 1452492043..cda6bc9f62 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts@@ -95,10 +95,9 @@ const chunkGalleryCellsIntoRows = (};/**- * The grid's whole row model in one pure pass: under a starred-first listing- * the starred items become a disclosure section above the regular items,- * while a flat listing chunks every item in order. Pending queue placeholders- * slot in at the position their images will land.+ * The grid's row model in one pure pass: a starred-first listing gets a+ * disclosure section, a flat one chunks in order, and placeholders slot in+ * where their images will land.*/export const buildGalleryGridRows = ({columnCount,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex be35a4a1af..239994a47b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -240,41 +240,23 @@ describe('gallery state view', () => {searchTerm: '',},};-- expect(getGalleryStateView(stamped, boards, [], false).revealTargetPage).toBe(2);- expect(getGalleryStateView(stamped, boards, [], false).page).toBe(0);- expect(- getGalleryStateView({ ...stamped, selectedBoardId: 'board-1' }, boards, [], false).revealTargetPage- ).toBeNull();- expect(- getGalleryStateView({ ...stamped, paginationMode: 'infinite' }, boards, [], false).revealTargetPage- ).toBeNull();- expect(+ const pageOf = (values: Record<string, unknown>, stamp: Record<string, unknown> = {}) =>getGalleryStateView(- { ...stamped, selectedImageQuery: { ...stamped.selectedImageQuery, galleryView: 'assets' } },+ { ...stamped, ...values, selectedImageQuery: { ...stamped.selectedImageQuery, ...stamp } },boards,[],false- ).revealTargetPage- ).toBeNull();- expect(- getGalleryStateView(- { ...stamped, selectedImageQuery: { ...stamped.selectedImageQuery, paginationMode: 'infinite' } },- boards,- [],- false- ).revealTargetPage- ).toBeNull();- expect(getGalleryStateView({ ...stamped, imageOrderDir: 'ASC' }, boards, [], false).revealTargetPage).toBeNull();- expect(getGalleryStateView({ ...stamped, searchTerm: 'cats' }, boards, [], false).revealTargetPage).toBeNull();- expect(- getGalleryStateView(- { ...stamped, semanticImageQuery: { imageName: 'ref.png', kind: 'image' } },- boards,- [],- false- ).revealTargetPage- ).toBeNull();+ ).revealTargetPage;++ expect(pageOf({})).toBe(2);+ expect(getGalleryStateView(stamped, boards, [], false).page).toBe(0);+ expect(pageOf({ selectedBoardId: 'board-1' })).toBeNull();+ expect(pageOf({ paginationMode: 'infinite' })).toBeNull();+ expect(pageOf({}, { galleryView: 'assets' })).toBeNull();+ expect(pageOf({}, { paginationMode: 'infinite' })).toBeNull();+ expect(pageOf({ imageOrderDir: 'ASC' })).toBeNull();+ expect(pageOf({ searchTerm: 'cats' })).toBeNull();+ expect(pageOf({ semanticImageQuery: { imageName: 'ref.png', kind: 'image' } })).toBeNull();});it('derives starred-first from the pagination mode: sectioned infinite window, flat paginated pages', () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex 81ab7108d4..6a0003a8a6 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -116,9 +116,8 @@ interface GalleryOrderImage {starred?: boolean;}-// Newest-first placeholders land where their images will: at the top of a-// flat listing, or just below the leading starred block of a starred-first-// one. Oldest-first listings take them at the end either way.+// Newest-first placeholders land at the top (below any leading starred+// block); oldest-first listings take them at the end.export const getGalleryPlaceholderInsertionIndex = (images: GalleryOrderImage[],imageOrderDir: GalleryOrderDir,@@ -381,12 +380,10 @@ const getVisibleGalleryQueuePlaceholders = (};/**- * Whether the current page or window can show where a NEW image will land.- * Placeholders stand in for images-to-come, so they render only there. In- * infinite mode that is the unanchored window (a deep reveal shows a slice- * nowhere near the landing). Newest-first pages land on page 0; oldest-first- * pages land at row `total` — unknowable until the total is, and on a page- * that does not exist yet when the last one is exactly full.+ * Whether this page/window can show where a NEW image lands (placeholders+ * render only there): page 0 for newest-first and the unanchored infinite+ * window; the row-`total` page for oldest-first — deliberately nonexistent+ * when the last page is exactly full, and unknowable without a total.*/const isGalleryWindowAtIncomingItemLanding = (settings: GallerySettings,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.tsindex 6e8983d308..b505ce47fe 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts@@ -157,10 +157,8 @@ describe('mergeGalleryItemWindow', () => {});it('places a completed batch image by its creation time, not the batch submission time', () => {- // A batch is submitted at T0 and its images complete one by one much- // later. Each overlaid recent must sort by when its image was actually- // created, or every fresh completion lands *below* its already-listed- // siblings until the backend refetch catches up, reshuffling the grid.+ // Overlaid recents must sort by creation time, or each fresh completion+ // lands below its already-listed siblings until the refetch catches up.const backendItems = [createBackendItem('batch-2.png', '2026-08-29 13:05:00.000'),createBackendItem('batch-1.png', '2026-08-29 13:04:00.000'),diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsxindex f6a9c946d7..eb6a1cfd71 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx@@ -889,6 +889,8 @@ const galleryItem = (kind: GalleryItem['kind'], name: string): GalleryItem => {describe('primary successor after confirmed deletion', () => {it('selects the next surviving item in display order — the one that takes the deleted slot', async () => {+ // Also what keeps deletion out of the leading starred block. Pinned at the+ // unit level in core/selection.test.ts.const before = galleryItem('video', 'before.mp4');const primary = galleryItem('image', 'primary.png');const after = galleryItem('image', 'after.png');@@ -912,36 +914,6 @@ describe('primary successor after confirmed deletion', () => {expect(mocks.gallerySelectItem).toHaveBeenCalledWith(after, 'project-1');});- it('does not jump into the leading starred block when deleting the first regular item', async () => {- // Ordered names lead with the starred section under infinite pagination;- // the successor must stay in the regular section the primary came from.- const starred = { ...galleryItem('image', 'starred.png'), starred: true };- const primary = galleryItem('image', 'primary.png');- const nextRegular = galleryItem('image', 'next-regular.png');- currentItemActionContext = {- filterIdentity: 'filter-a',- items: [starred, primary, nextRegular],- loadOrderedRefs: () =>- Promise.resolve([- { kind: 'image' as const, name: starred.name },- { kind: 'image' as const, name: primary.name },- { kind: 'image' as const, name: nextRegular.name },- ]),- selectedItemKey: 'image:primary.png',- };- mocks.itemDelete.mockResolvedValue({- affectedBoardIds: ['board-1'],- failed: [],- succeeded: [{ kind: 'image', name: primary.name }],- });-- await act(async () => {- await getItemActions().deleteItems([{ kind: 'image', name: primary.name }]);- });-- expect(mocks.gallerySelectItem).toHaveBeenCalledWith(nextRegular, 'project-1');- });-it('resolves an unloaded successor by qualified ref', async () => {const primary = galleryItem('image', 'primary.png');const before = galleryItem('image', 'before.png');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 c2746b2738..a9cd27c5e2 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@@ -1160,8 +1160,7 @@ describe('preview keyboard navigation boundary', () => {await render();await pressArrow('ArrowRight');- // Starred-first ordering would put starred-mid at the head and step onto- // oldest here; the paginated grid is flat, so its true neighbor wins.+ // Under starred-first the step would land on oldest; flat pages win.expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(expect.objectContaining({ kind: 'image', name: 'starred-mid' }),undefined,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex ae78191982..80297355e6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -188,9 +188,7 @@ export const usePreviewNavigation = ({shouldFollowLive && activePlaceholder ? activePlaceholder.boardId : selectedImageQuery.boardId;const navigationGalleryView = shouldFollowLive ? 'images' : selectedImageQuery.galleryView;const navigationOrderDir = shouldFollowLive ? imageOrderDir : selectedImageQuery.imageOrderDir;- // Following live means watching the gallery's own listing, so its mode —- // not the stamped one — decides the ordering, exactly as `imageOrderDir`- // substitutes above.+ // Live-follow watches the gallery's own listing, so its mode decides.const navigationStarredFirst = isGalleryStarredFirst(shouldFollowLive ? galleryPaginationMode : selectedImageQuery.paginationMode);