Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(gallery): partition starred items into a bounded strip
Josh Corbett6eda7c9c0d52
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 174b26ec8e..7388b19e2f 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3377,7 +3377,8 @@"navigationRight": "Gallery navigation right","navigationUp": "Gallery navigation up","selectAllOnPage": "Select all gallery images on page",- "toggleStarImage": "Toggle gallery image star"+ "toggleStarImage": "Toggle gallery image star",+ "toggleStarredOnly": "Toggle gallery starred-only filter"},"clearClusterSearch": "Clear cluster filter","clearImageSearch": "Clear image similarity search",@@ -3468,6 +3469,7 @@"newest": "Newest","noBoardsMatchSearch": "No boards match this search.","noImagesMatch": "No items match this board, tab, or search.",+ "noStarredItemsMatch": "No starred items match this board, tab, or search.","oldest": "Oldest","otherProjectBoards": "Other projects' boards","pagination": "Pagination",@@ -3542,7 +3544,12 @@"sortBoardsDescending": "Sort boards descending","sortBy": "Sort by","starImage": "Star {{name}}",+ "showAllStarred": "Show all",+ "showAllStarredItems": "Show all starred items","starredItems": "Starred",+ "starredOnly": "Starred only",+ "starredOnlyTooltip": "Show only starred items",+ "starredOnlyUnavailable": "The starred filter does not apply to similarity results","starSelection": "Star selection","statusChip_one": "Gallery: {{count}} item","statusChip_other": "Gallery: {{count}} items",diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex 72e1ecacaf..64d7c870bb 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -47,7 +47,6 @@ export {export {DEFAULT_GALLERY_SETTINGS,getGallerySettings,- isGalleryStarredFirst,type GalleryPaginationMode,type GallerySettings,type GalleryThumbnailFit,diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.test.tsindex b2f82ad943..5eb461fe15 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.test.ts@@ -227,17 +227,6 @@ describe('gallery item ordering', () => {expect(sorted.map((item) => item.name)).toEqual(['legacy.png', 'backend.png']);});- it('keeps starred items first regardless of timestamp shape', () => {- const starredOlderBackend = { ...sqliteItem, createdAt: '2026-08-29 02:28:40.566', starred: true };- const unstarredNewerOverlay = { ...overlayItem, createdAt: '2026-08-29T13:01:20.649Z' };-- const sorted = [unstarredNewerOverlay, starredOlderBackend].sort((a, b) =>- compareGalleryItems(a, b, { orderDir: 'DESC', starredFirst: true })- );-- expect(sorted.map((item) => item.name)).toEqual(['backend.png', 'legacy.png']);- });-it('falls through to the kind tie-breaker when the two shapes name the same instant', () => {const image = { ...sqliteItem, createdAt: '2026-08-29 13:01:20.649' };const video = { ...image, durationSeconds: 2, kind: 'video' as const, name: 'backend.png' };diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.tsindex d02a867a34..6cdc34e1f5 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/items.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.ts@@ -95,16 +95,12 @@ const compareSqliteBinaryText = (a: string, b: string): number => (a === b ? 0 :const compareCreatedAt = (a: string, b: string): number =>compareSqliteBinaryText(normalizeServerTimestamp(a), normalizeServerTimestamp(b));-/** Mirrors the backend's starred/time/kind/name order for mixed gallery items. */+/** Mirrors the backend's time/kind/name order for mixed gallery items. */export const compareGalleryItems = (a: GalleryItem,b: GalleryItem,- { orderDir = 'DESC', starredFirst = false }: { orderDir?: GalleryOrderDir; starredFirst?: boolean }+ { orderDir = 'DESC' }: { orderDir?: GalleryOrderDir } = {}): number => {- if (starredFirst && a.starred !== b.starred) {- return a.starred ? -1 : 1;- }-const direction = orderDir === 'ASC' ? 1 : -1;const chronologicalOrder = compareCreatedAt(a.createdAt, b.createdAt);diff --git a/invokeai/frontend/webv2/src/features/gallery/core/paging.ts b/invokeai/frontend/webv2/src/features/gallery/core/paging.tsindex 7a4a56e2eb..9901fadaaf 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/paging.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/paging.ts@@ -2,3 +2,5 @@export const GALLERY_PAGE_SIZE = 60;export const GALLERY_MAX_INFINITE_PAGES = 10;export const GALLERY_MAX_ROWS = GALLERY_PAGE_SIZE * GALLERY_MAX_INFINITE_PAGES;+/** The bounded starred strip: three rows at the grid's twelve-column maximum. */+export const GALLERY_STARRED_STRIP_LIMIT = 36;diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex 20f29b5456..86958e21d7 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -16,10 +16,7 @@ export const GALLERY_MIN_GRID_HEIGHT_PX = 128;export const GALLERY_BOARD_PANEL_MIN_WIDTH_PX = 180;export const GALLERY_BOARD_PANEL_MAX_WIDTH_PX = 420;-/**- * User-tunable gallery settings, persisted in the widget's `values` record —- * except `starredFirst`, which is derived, never stored.- */+/** User-tunable gallery settings, persisted in the widget's `values` record. */export interface GallerySettings {boardOrderBy: GalleryBoardOrderBy;boardOrderDir: GalleryOrderDir;@@ -41,17 +38,11 @@ export interface GallerySettings {*/showOtherProjectBoards: boolean;showPendingItems: boolean;- /** Derived from `paginationMode` — see `isGalleryStarredFirst`. */- starredFirst: boolean;+ /** Disclosure of the starred strip at the top of the grid. */+ starredSectionCollapsed: boolean;thumbnailFit: GalleryThumbnailFit;}-/**- * 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';-export const DEFAULT_GALLERY_SETTINGS: GallerySettings = {boardOrderBy: 'created_at',boardOrderDir: 'DESC',@@ -67,7 +58,7 @@ export const DEFAULT_GALLERY_SETTINGS: GallerySettings = {showImageDimensions: false,showOtherProjectBoards: false,showPendingItems: true,- starredFirst: isGalleryStarredFirst('infinite'),+ starredSectionCollapsed: false,thumbnailFit: 'square',};@@ -139,7 +130,10 @@ export const getGallerySettings = (values: Record<string, unknown>): GallerySetttypeof values.showPendingItems === 'boolean'? values.showPendingItems: DEFAULT_GALLERY_SETTINGS.showPendingItems,- starredFirst: isGalleryStarredFirst(paginationMode),+ starredSectionCollapsed:+ typeof values.starredSectionCollapsed === 'boolean'+ ? values.starredSectionCollapsed+ : DEFAULT_GALLERY_SETTINGS.starredSectionCollapsed,thumbnailFit: values.thumbnailFit === 'aspect' ? 'aspect' : DEFAULT_GALLERY_SETTINGS.thumbnailFit,};};diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.tsindex 6191e06b07..fae0b77069 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts@@ -439,7 +439,7 @@ describe('listGalleryItems', () => {orderDir: 'ASC',searchTerm: ' summer clip ',signal: controller.signal,- starredFirst: true,+ starred: true,});const [url, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];@@ -454,7 +454,9 @@ describe('listGalleryItems', () => {expect(params.get('limit')).toBe('17');expect(params.get('offset')).toBe('34');expect(params.get('order_dir')).toBe('ASC');- expect(params.get('starred_first')).toBe('true');+ expect(params.get('starred')).toBe('true');+ // The backend defaults to starred-first; the grid must pin it off.+ expect(params.get('starred_first')).toBe('false');expect(params.get('search_term')).toBe('summer clip');expect(init.signal).toBe(controller.signal);});diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 2c3baf4199..66a430e515 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -572,7 +572,6 @@ const listPaletteDateBoardImageNames = async ({orderDir,searchTerm,signal,- starredFirst,}: {boardId: string;createdFrom?: string;@@ -581,7 +580,6 @@ const listPaletteDateBoardImageNames = async ({orderDir: GalleryOrderDir;searchTerm: string;signal?: AbortSignal;- starredFirst: boolean;}): Promise<PaletteDateBoardImageNames> => {// Palette results remain intentionally image-only, but derive from the// polymorphic item_names endpoint so no webv2 path regresses to image_names.@@ -593,7 +591,6 @@ const listPaletteDateBoardImageNames = async ({orderDir,searchTerm,signal,- starredFirst,});const imageNames = result.items.filter((ref) => ref.kind === 'image').map((ref) => ref.name);@@ -605,7 +602,6 @@ const listPaletteDateBoardImageNames = async ({export interface GalleryItemNames {items: GalleryItemRef[];- starredCount: number;total: number;}@@ -617,16 +613,12 @@ interface GalleryItemNamesRequest {orderDir: GalleryOrderDir;searchTerm: string;signal?: AbortSignal;- starredFirst: boolean;+ /** true = only starred items, false = only unstarred; absent = all. */+ starred?: boolean;}-const mapGalleryItemNames = (body: {- items: GalleryItemRef[];- starred_count: number;- total_count: number;-}): GalleryItemNames => ({+const mapGalleryItemNames = (body: { items: GalleryItemRef[]; total_count: number }): GalleryItemNames => ({items: body.items,- starredCount: normalizeTotal(body.starred_count, 0),total: normalizeTotal(body.total_count, body.items.length),});@@ -638,7 +630,7 @@ export const listGalleryItemNames = async ({orderDir,searchTerm,signal,- starredFirst,+ starred,}: GalleryItemNamesRequest): Promise<GalleryItemNames> => {const query = toSearchParams({board_id: boardId,@@ -648,13 +640,15 @@ export const listGalleryItemNames = async ({is_intermediate: false,order_dir: orderDir,search_term: searchTerm.trim() || undefined,- starred_first: starredFirst,+ starred,+ // The backend defaults to starred-first; the grid orders chronologically+ // and carries starred items in its own strip.+ starred_first: false,});- const body = await apiFetchJson<{- items: GalleryItemRef[];- starred_count: number;- total_count: number;- }>(`/api/v1/gallery/items/names?${query}`, { signal });+ const body = await apiFetchJson<{ items: GalleryItemRef[]; total_count: number }>(+ `/api/v1/gallery/items/names?${query}`,+ { signal }+ );return mapGalleryItemNames(body);};@@ -667,28 +661,26 @@ export const listGalleryDateBoardItemNames = async ({orderDir,searchTerm,signal,- starredFirst,+ starred,}: GalleryItemNamesRequest): Promise<GalleryItemNames> => {if ((createdFrom !== undefined || createdTo !== undefined) &&!isTimestampInRange(getDateFromBoardId(boardId), { from: createdFrom, to: createdTo })) {- return { items: [], starredCount: 0, total: 0 };+ return { items: [], total: 0 };}const query = toSearchParams({categories: galleryView === 'assets' ? assetCategories : imageCategories,order_dir: orderDir,search_term: searchTerm.trim() || undefined,- starred_first: starredFirst,- });- const body = await apiFetchJson<{- items: GalleryItemRef[];- starred_count: number;- total_count: number;- }>(`/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/item_names?${query}`, {- signal,+ starred,+ starred_first: false,});+ const body = await apiFetchJson<{ items: GalleryItemRef[]; total_count: number }>(+ `/api/v1/virtual_boards/by_date/${encodeURIComponent(getDateFromBoardId(boardId))}/item_names?${query}`,+ { signal }+ );return mapGalleryItemNames(body);};@@ -777,7 +769,8 @@ interface GalleryListRequest {orderDir?: GalleryOrderDir;searchTerm: string;signal?: AbortSignal;- starredFirst?: boolean;+ /** true = only starred items, false = only unstarred; absent = all. */+ starred?: boolean;}interface GalleryItemsRequest extends GalleryListRequest {@@ -795,7 +788,7 @@ export const listGalleryItems = async ({orderDir = 'DESC',searchTerm,signal,- starredFirst = false,+ starred,}: GalleryItemsRequest): Promise<GalleryItemsPage> => {const query = toSearchParams({board_id: boardId,@@ -807,7 +800,8 @@ export const listGalleryItems = async ({offset,order_dir: orderDir,search_term: searchTerm.trim() || undefined,- starred_first: starredFirst,+ starred,+ starred_first: false,});const body = await apiFetchJson<{items: BackendGalleryItemDTO[];@@ -888,7 +882,7 @@ export const searchGallerySemantic = async (* The ranked result set as item refs, in relevance order. Pages hydrate* slices of this list (`hydrateGalleryDateBoardItemPage`), and range* selection / deletion neighbors read it directly. Semantic results are- * image-only and carry no starred information.+ * image-only.*/export const listSemanticGalleryItemNames = async ({query,@@ -905,7 +899,6 @@ export const listSemanticGalleryItemNames = async ({return {items: imageNames.map((name) => ({ kind: 'image', name })),- starredCount: 0,total: imageNames.length,};}@@ -914,7 +907,6 @@ export const listSemanticGalleryItemNames = async ({return {items: results.map((result) => ({ kind: 'image', name: result.imageName })),- starredCount: 0,total: results.length,};};@@ -929,7 +921,6 @@ export const listPaletteImages = async ({orderDir = 'DESC',searchTerm,signal,- starredFirst = false,}: GalleryListRequest): Promise<GalleryImagesPage> => {if (isDateBoardId(boardId)) {const names = await listPaletteDateBoardImageNames({@@ -940,7 +931,6 @@ export const listPaletteImages = async ({orderDir,searchTerm,signal,- starredFirst,});return hydratePaletteDateBoardImagePage({ ...names, limit, offset, signal });@@ -956,7 +946,7 @@ export const listPaletteImages = async ({offset,order_dir: orderDir,search_term: searchTerm.trim() || undefined,- starred_first: starredFirst,+ starred_first: false,});const body = await apiFetchJson<ListImagesResponse | BackendImageDTO[]>(`/api/v1/images/?${query}`, { signal });const items = Array.isArray(body) ? body : (body.items ?? []);diff --git a/invokeai/frontend/webv2/src/features/gallery/data/dateBoardItemHydration.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/dateBoardItemHydration.test.tsindex 969e080a86..36b8a4d399 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/dateBoardItemHydration.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/dateBoardItemHydration.test.ts@@ -77,18 +77,19 @@ describe('Gallery item names and date hydration', () => {galleryView: 'images',orderDir: 'DESC',searchTerm: '',- starredFirst: true,+ starred: true,})).resolves.toEqual({items: [{ kind: 'video', name: 'clip.mp4' },{ kind: 'image', name: 'still.png' },],- starredCount: 1,total: 2,});expect(mocks.apiFetchJson.mock.calls[0]?.[0]).toContain('/by_date/2026-07-30/item_names?');+ expect(mocks.apiFetchJson.mock.calls[0]?.[0]).toContain('starred=true');+ expect(mocks.apiFetchJson.mock.calls[0]?.[0]).toContain('starred_first=false');expect(mocks.apiFetchJson.mock.calls[0]?.[0]).not.toContain('image_names');});@@ -102,7 +103,6 @@ describe('Gallery item names and date hydration', () => {galleryView: 'images',orderDir: 'DESC',searchTerm: ' portrait ',- starredFirst: false,});const url = mocks.apiFetchJson.mock.calls[0]?.[0] as string;diff --git a/invokeai/frontend/webv2/src/features/gallery/data/itemQueryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/itemQueryCache.test.tsindex 20133ae4db..37f6b2b22a 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/itemQueryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/itemQueryCache.test.ts@@ -88,7 +88,7 @@ describe('Qualified gallery cache patches', () => {});client.setQueryData(itemsKey, createData([createItem('image', 'one')]));- client.setQueryData(namesKey, { items: [{ kind: 'image', name: 'one' }], starredCount: 0, total: 1 });+ client.setQueryData(namesKey, { items: [{ kind: 'image', name: 'one' }], total: 1 });client.setQueryData(boardsKey, []);await Promise.all([invalidateGallery(client), invalidateGallery(client), invalidateGallery(client)]);diff --git a/invokeai/frontend/webv2/src/features/gallery/data/mixedQueries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/mixedQueries.test.tsindex ece4f4a0c2..5c72527b77 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/mixedQueries.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/mixedQueries.test.ts@@ -32,7 +32,6 @@ const baseFilter: GalleryItemsFilter = {galleryView: 'images',orderDir: 'DESC',searchTerm: ' portrait ',- starredFirst: true,};const createItem = (kind: 'image' | 'video', name: string): GalleryItem =>@@ -70,7 +69,7 @@ describe('Mixed gallery queries', () => {accountLifecycle.activate('task-4-query-test');vi.clearAllMocks();backend.listGalleryItems.mockResolvedValue({ items: [], total: 0 });- backend.listGalleryItemNames.mockResolvedValue({ items: [], starredCount: 0, total: 0 });+ backend.listGalleryItemNames.mockResolvedValue({ items: [], total: 0 });});afterEach(() => {diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.tsindex a987efa350..eed180a5ac 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts@@ -22,10 +22,14 @@ import {flattenGalleryItemsData,GALLERY_MAX_ROWS,GALLERY_PAGE_SIZE,+ GALLERY_STARRED_STRIP_LIMIT,galleryBoardsOptions,galleryItemNamesOptions,galleryItemsInfiniteOptions,+ galleryStarredStripOptions,getGalleryItemListQueries,+ getGalleryItemsFilterFromKey,+ isGalleryStarredStripQueryKey,canonicalizeGalleryItemsFilter,type GalleryItemsFilter,} from './queries';@@ -75,7 +79,6 @@ const baseFilter: GalleryItemsFilter = {galleryView: 'images',orderDir: 'DESC',searchTerm: 'portrait',- starredFirst: true,};describe('Gallery item query read model', () => {@@ -153,7 +156,6 @@ describe('Gallery item query read model', () => {};const rankedNames = {items: [{ kind: 'image', name: 'ranked.png' }],- starredCount: 0,total: 1,};@@ -345,7 +347,7 @@ describe('Gallery item query read model', () => {it('fetches one date-board ref list while hydrating multiple fixed pages', async () => {const queryClient = createQueryClient();const refs = Array.from({ length: 180 }, (_, index) => ({ kind: 'image' as const, name: `date-${index}` }));- backend.listGalleryDateBoardItemNames.mockResolvedValue({ items: refs, starredCount: 0, total: refs.length });+ backend.listGalleryDateBoardItemNames.mockResolvedValue({ items: refs, total: refs.length });backend.hydrateGalleryDateBoardItemPage.mockImplementation(({ limit, offset, total }: { limit: number; offset: number; total: number }) =>Promise.resolve(createPage({ count: limit, offset, prefix: 'date', total }))@@ -367,7 +369,6 @@ describe('Gallery item query read model', () => {backend.listGalleryDateBoardItemNames.mockResolvedValueOnce({items: [{ kind: 'image', name: 'refreshed' }, ...refs],- starredCount: 0,total: refs.length + 1,});await invalidateGalleryItems(queryClient);@@ -381,12 +382,10 @@ describe('Gallery item query read model', () => {it('does not cancel a shared date-name request when one list consumer is cancelled', async () => {const queryClient = createQueryClient();let namesSignal: AbortSignal | undefined;- let resolveNames:- | ((value: { items: { kind: 'image'; name: string }[]; starredCount: number; total: number }) => void)- | undefined;+ let resolveNames: ((value: { items: { kind: 'image'; name: string }[]; total: number }) => void) | undefined;backend.listGalleryDateBoardItemNames.mockImplementation(({ signal }: { signal: AbortSignal }) =>- new Promise<{ items: { kind: 'image'; name: string }[]; starredCount: number; total: number }>((resolve) => {+ new Promise<{ items: { kind: 'image'; name: string }[]; total: number }>((resolve) => {namesSignal = signal;resolveNames = resolve;})@@ -406,7 +405,7 @@ describe('Gallery item query read model', () => {await queryClient.cancelQueries({ exact: true, queryKey: pageOptions.queryKey });expect(namesSignal?.aborted).toBe(false);- resolveNames?.({ items: [{ kind: 'image', name: 'shared-date-0' }], starredCount: 0, total: 1 });+ resolveNames?.({ items: [{ kind: 'image', name: 'shared-date-0' }], total: 1 });await expect(infiniteRequest).resolves.toMatchObject({pages: [{ items: [{ name: 'shared-date-0' }], total: 1 }],});@@ -419,7 +418,7 @@ describe('canonicalizeGalleryItemsFilter under a semantic query', () => {it('ignores the controls a ranked result set does not answer to', () => {// The semantic branch sends only the reference, so board, view, order,- // starred-first and the date range change nothing about the response.+ // the starred filter and the date range change nothing about the response.// While they stayed in the key, clicking a board minted a fresh key and// re-ran the search — re-uploading the dropped blob, or making the server// re-download a remote URL, to render byte-identical results.@@ -434,7 +433,7 @@ describe('canonicalizeGalleryItemsFilter under a semantic query', () => {{ boardId: 'board-b' },{ galleryView: 'assets' as const },{ orderDir: 'ASC' as const },- { starredFirst: true },+ { starred: true },{ createdFrom: '2026-01-01' },]) {expect(@@ -473,4 +472,72 @@ describe('canonicalizeGalleryItemsFilter under a semantic query', () => {expect(onBoardA).not.toEqual(onBoardB);});++ it('keys the starred filter only when it is set', () => {+ const unfiltered = canonicalizeGalleryItemsFilter({ boardId: 'board-a', galleryView: 'images', searchTerm: '' });+ const starredOnly = canonicalizeGalleryItemsFilter({+ boardId: 'board-a',+ galleryView: 'images',+ searchTerm: '',+ starred: true,+ });++ expect(unfiltered).not.toHaveProperty('starred');+ expect(starredOnly).toEqual({ ...unfiltered, starred: true });+ });+});++describe('galleryStarredStripOptions', () => {+ beforeEach(() => {+ backend.hydrateGalleryDateBoardItemPage.mockReset();+ backend.isDateBoardId.mockReset();+ backend.listGalleryDateBoardItemNames.mockReset();+ backend.listGalleryItems.mockReset();+ accountLifecycle.activate('strip-query-test');+ backend.isDateBoardId.mockImplementation((boardId: string) => boardId.startsWith('by_date:'));+ });++ it('reads one bounded starred-only range under the listing key family', async () => {+ const queryClient = createQueryClient();+ backend.listGalleryItems.mockResolvedValue(createPage({ count: 2, offset: 0, total: 9 }));++ const options = galleryStarredStripOptions(baseFilter);+ const page = await queryClient.fetchQuery(options);++ expect(page.total).toBe(9);+ // The strip lives in the list key family (so account-wide invalidation+ // and mutation patching reach it) under the listing's filter plus `starred`.+ expect(getGalleryItemListQueries(queryClient).map((query) => query.queryKey)).toEqual([options.queryKey]);+ expect(getGalleryItemsFilterFromKey(options.queryKey)).toEqual({+ ...canonicalizeGalleryItemsFilter(baseFilter),+ starred: true,+ });+ expect(isGalleryStarredStripQueryKey(options.queryKey)).toBe(true);+ expect(isGalleryStarredStripQueryKey(galleryItemsInfiniteOptions(baseFilter).queryKey)).toBe(false);+ expect(backend.listGalleryItems).toHaveBeenCalledOnce();+ expect(backend.listGalleryItems.mock.calls[0]?.[0]).toMatchObject({+ boardId: 'board-1',+ limit: GALLERY_STARRED_STRIP_LIMIT,+ offset: 0,+ starred: true,+ });+ });++ it('routes a date board through its starred-only name list', async () => {+ const queryClient = createQueryClient();+ const refs = [{ kind: 'image' as const, name: 'starred-0' }];+ backend.listGalleryDateBoardItemNames.mockResolvedValue({ items: refs, total: 1 });+ backend.hydrateGalleryDateBoardItemPage.mockResolvedValue(createPage({ count: 1, offset: 0, total: 1 }));++ await queryClient.fetchQuery(galleryStarredStripOptions({ ...baseFilter, boardId: 'by_date:2026-07-18' }));++ expect(backend.listGalleryDateBoardItemNames.mock.calls[0]?.[0]).toMatchObject({+ boardId: 'by_date:2026-07-18',+ starred: true,+ });+ expect(backend.hydrateGalleryDateBoardItemPage).toHaveBeenCalledWith(+ expect.objectContaining({ items: refs, limit: GALLERY_STARRED_STRIP_LIMIT, offset: 0 })+ );+ expect(backend.listGalleryItems).not.toHaveBeenCalled();+ });});diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.tsindex 0c6458d9b9..b6cb2a8f6a 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts@@ -4,7 +4,12 @@ import type { GalleryBoardOrderBy, GalleryOrderDir, GalleryView } from '@featureimport type { AccountScope } from '@platform/state/accountLifecycle';import { toGalleryItemKey } from '@features/gallery/core/items';-import { GALLERY_MAX_INFINITE_PAGES, GALLERY_MAX_ROWS, GALLERY_PAGE_SIZE } from '@features/gallery/core/paging';+import {+ GALLERY_MAX_INFINITE_PAGES,+ GALLERY_MAX_ROWS,+ GALLERY_PAGE_SIZE,+ GALLERY_STARRED_STRIP_LIMIT,+} from '@features/gallery/core/paging';import { toGallerySemanticQuery } from '@features/gallery/core/semanticImageQuery';import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';import {@@ -28,7 +33,7 @@ import {listSemanticGalleryItemNames,} from './backend';-export { GALLERY_MAX_INFINITE_PAGES, GALLERY_MAX_ROWS, GALLERY_PAGE_SIZE };+export { GALLERY_MAX_INFINITE_PAGES, GALLERY_MAX_ROWS, GALLERY_PAGE_SIZE, GALLERY_STARRED_STRIP_LIMIT };export interface GalleryBoardsQuery {includeArchived?: boolean;@@ -59,7 +64,8 @@ export interface GalleryItemsFilter {* apply to a ranked result set.*/semanticQuery?: GallerySemanticReference | null;- starredFirst?: boolean;+ /** true = only starred items, false = only unstarred; absent = all. */+ starred?: boolean;}export interface CanonicalGalleryItemsFilter {@@ -71,7 +77,7 @@ export interface CanonicalGalleryItemsFilter {searchTerm: string;/** Label-free semantic reference: a file query is keyed by its registry id. */semantic?: GallerySemanticQuery;- starredFirst: boolean;+ starred?: boolean;}/**@@ -98,7 +104,13 @@ type GalleryItemsInfiniteQueryKey = readonly [type GalleryItemsAnchorQueryKey = readonly [...GalleryItemsInfiniteQueryKey, 'anchor' | 'infinite', number];-export type GalleryItemsListQueryKey = GalleryItemsAnchorQueryKey | GalleryItemsInfiniteQueryKey;+/** The bounded starred strip: one `GalleryItemsPage`, not an infinite window. */+type GalleryItemsStripQueryKey = readonly [...GalleryItemsInfiniteQueryKey, 'strip'];++export type GalleryItemsListQueryKey =+ | GalleryItemsAnchorQueryKey+ | GalleryItemsInfiniteQueryKey+ | GalleryItemsStripQueryKey;const canonicalizeBoardsQuery = (query: GalleryBoardsQuery): CanonicalGalleryBoardsQuery => ({includeArchived: query.includeArchived ?? false,@@ -113,9 +125,9 @@ export const canonicalizeGalleryItemsFilter = (filter: GalleryItemsFilter): Canoif (semantic) {// A ranked result set answers to the reference alone: the semantic branch// of `galleryItemNamesOptionsForOwner` sends only the query, so board,- // view, order, starred-first and the date range change nothing about the- // response. Keeping them in the key made clicking a board — or toggling- // starred-first, or switching the images/assets tab — mint a fresh key and+ // view, order, the starred filter and the date range change nothing about+ // the response. Keeping them in the key made clicking a board — or toggling+ // the starred filter, or switching the images/assets tab — mint a fresh key and// re-run the search for byte-identical results, which for a dropped file// means re-uploading the blob and for a URL reference means the server// re-downloads the remote image. Pinned rather than omitted so the shape@@ -127,7 +139,6 @@ export const canonicalizeGalleryItemsFilter = (filter: GalleryItemsFilter): CanoorderDir: 'DESC',searchTerm: '',semantic,- starredFirst: false,};}@@ -138,7 +149,7 @@ export const canonicalizeGalleryItemsFilter = (filter: GalleryItemsFilter): CanogalleryView: filter.galleryView,orderDir: filter.orderDir ?? 'DESC',searchTerm: filter.searchTerm.trim(),- starredFirst: filter.starredFirst ?? false,+ ...(filter.starred !== undefined ? { starred: filter.starred } : {}),};};@@ -179,6 +190,8 @@ export const galleryKeys = {window: GalleryItemsWindow = { kind: 'infinite' }): GalleryItemsListQueryKey =>[...galleryKeys.itemListsForAccount(owner), filter, ...getWindowKey(window)] as GalleryItemsListQueryKey,+ starredStrip: (owner: AccountScope, filter: CanonicalGalleryItemsFilter): GalleryItemsStripQueryKey =>+ [...galleryKeys.itemListsForAccount(owner), filter, 'strip'] as const,itemNamesRoot: () => [...galleryKeys.itemsRoot(), 'names'] as const,itemNamesForAccount: (owner: AccountScope) => [...galleryKeys.itemNamesRoot(), getAccountKey(owner)] as const,itemNames: (owner: AccountScope, filter: CanonicalGalleryItemsFilter) =>@@ -412,6 +425,29 @@ export const galleryItemsInfiniteOptions = (});};+/**+ * The starred strip shares the list key family (and so the account-wide+ * invalidation and mutation patching) with the listing it sits above, keyed+ * on that listing's filter plus `starred: true`.+ */+export const galleryStarredStripOptions = (inputFilter: GalleryItemsFilter) => {+ const owner = captureAccountScope();+ const filter: CanonicalGalleryItemsFilter = { ...canonicalizeGalleryItemsFilter(inputFilter), starred: true };++ return queryOptions({+ queryFn: ({ client, signal }) =>+ fetchGalleryItemsRange(client, owner, filter, {+ limit: GALLERY_STARRED_STRIP_LIMIT,+ offset: 0,+ signal: AbortSignal.any([signal, owner.signal]),+ }),+ queryKey: galleryKeys.starredStrip(owner, filter),+ staleTime: 60_000,+ });+};++export const isGalleryStarredStripQueryKey = (queryKey: QueryKey): boolean => queryKey[5] === 'strip';+export const flattenGalleryItemsData = (data: InfiniteData<GalleryItemsPage, number> | undefined): GalleryItem[] => {if (!data) {return [];diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.tsindex 084a445812..4babc96255 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts@@ -20,6 +20,7 @@ import {} from './queries';import {getGalleryItemBoardIdsFromCaches,+ getGalleryItemStarredFromCaches,invalidateGallery,invalidateGalleryItems,patchGalleryBoardCaches,@@ -90,16 +91,8 @@ const createData = (pages: GalleryItem[][]): GalleryItemsData => {};};-const getItemsKey = (boardId: string, owner: AccountScope = captureAccountScope(), starredFirst = false) =>- galleryKeys.items(- owner,- canonicalizeGalleryItemsFilter({- boardId,- galleryView: 'images',- searchTerm: '',- starredFirst,- })- );+const getItemsKey = (boardId: string, owner: AccountScope = captureAccountScope()) =>+ galleryKeys.items(owner, canonicalizeGalleryItemsFilter({ boardId, galleryView: 'images', searchTerm: '' }));const getData = (client: QueryClient, queryKey: ReturnType<typeof getItemsKey>): GalleryItemsData => {const data = client.getQueryData<GalleryItemsData>(queryKey);@@ -156,10 +149,41 @@ describe('Gallery item cache patches', () => {expect(rolledBack.pages[0]?.items[1]).toBe(samePageUntouched);});- it('patches star state immediately when the active list sorts starred items first', () => {+ it('drops a starred item from the unstarred listing window and decrements its total', () => {+ const client = createClient();+ const target = createItem('target.png');+ const other = createItem('other.png');+ const key = galleryKeys.items(+ captureAccountScope(),+ canonicalizeGalleryItemsFilter({ boardId: 'board-1', galleryView: 'images', searchTerm: '', starred: false })+ );++ client.setQueryData(key, createData([[target, other]]));+ const rollback = patchGalleryItemCaches(client, {+ kind: 'star',+ result: getResult([{ kind: 'image', name: target.name }]),+ starred: true,+ });++ expect(getData(client, key).pages[0]).toEqual({ items: [other], total: 1 });++ rollback();++ expect(getData(client, key).pages[0]).toEqual({ items: [target, other], total: 2 });+ });++ it('flips star state in place in a ranked window, which lists by similarity rather than by flag', () => {const client = createClient();const target = createItem('target.png');- const key = getItemsKey('board-1', captureAccountScope(), true);+ const key = galleryKeys.items(+ captureAccountScope(),+ canonicalizeGalleryItemsFilter({+ boardId: 'board-1',+ galleryView: 'images',+ searchTerm: '',+ semanticQuery: { imageName: 'ref.png', kind: 'image' },+ })+ );client.setQueryData(key, createData([[target]]));@@ -261,6 +285,110 @@ describe('Gallery item cache patches', () => {expect(after.pages.map((page) => page.total)).toEqual([2]);});+ describe('starred strip entries', () => {+ const getStripKey = (boardId: string) =>+ galleryKeys.starredStrip(+ captureAccountScope(),+ canonicalizeGalleryItemsFilter({ boardId, galleryView: 'images', searchTerm: '', starred: true })+ );+ const getStrip = (client: QueryClient, key: ReturnType<typeof getStripKey>): GalleryItemsPage => {+ const page = client.getQueryData<GalleryItemsPage>(key);++ if (!page) {+ throw new Error('missing strip');+ }++ return page;+ };++ it('drops an unstarred item and its count at once, and rolls the strip back', () => {+ const client = createClient();+ const target = createItem('target.png', 'board-1', true);+ const other = createItem('other.png', 'board-1', true);+ const key = getStripKey('board-1');+ const before: GalleryItemsPage = { items: [target, other], total: 5 };++ client.setQueryData(key, before);+ const rollback = patchGalleryItemCaches(client, {+ kind: 'star',+ result: getResult([{ kind: 'image', name: target.name }]),+ starred: false,+ });++ expect(getStrip(client, key)).toEqual({ items: [other], total: 4 });++ rollback();++ expect(getStrip(client, key)).toEqual(before);+ });++ it('leaves the strip to the refetch when an item is starred', () => {+ const client = createClient();+ const key = getStripKey('board-1');+ const before: GalleryItemsPage = { items: [createItem('starred.png', 'board-1', true)], total: 1 };++ client.setQueryData(key, before);+ patchGalleryItemCaches(client, {+ kind: 'star',+ result: getResult([{ kind: 'image', name: 'newly-starred.png' }]),+ starred: true,+ });++ expect(getStrip(client, key)).toEqual(before);+ });++ it('removes deleted items and items moved off the board, keeping ones moved within all-boards views', () => {+ const client = createClient();+ const deleted = createItem('deleted.png', 'board-1', true);+ const moved = createItem('moved.png', 'board-1', true, 'video');+ const kept = createItem('kept.png', 'board-1', true);+ const boardKey = getStripKey('board-1');+ const allKey = getStripKey(ALL_READABLE_BOARDS_ID);++ client.setQueryData(boardKey, { items: [deleted, moved, kept], total: 3 });+ client.setQueryData(allKey, { items: [deleted, moved, kept], total: 3 });+ patchGalleryItemCaches(client, { kind: 'delete', result: getResult([{ kind: 'image', name: deleted.name }]) });+ patchGalleryItemCaches(client, {+ boardId: 'board-2',+ kind: 'move',+ result: getResult([{ kind: 'video', name: moved.name }]),+ });++ expect(getStrip(client, boardKey)).toEqual({ items: [kept], total: 1 });+ expect(getStrip(client, allKey)).toEqual({ items: [{ ...moved, boardId: 'board-2' }, kept], total: 2 });+ });++ it('drops an unstarred item from a starred-only listing window too, not just the strip', () => {+ const client = createClient();+ const target = createItem('target.png', 'board-1', true);+ const other = createItem('other.png', 'board-1', true);+ const key = galleryKeys.items(+ captureAccountScope(),+ canonicalizeGalleryItemsFilter({ boardId: 'board-1', galleryView: 'images', searchTerm: '', starred: true })+ );++ client.setQueryData(key, createData([[target, other]]));+ patchGalleryItemCaches(client, {+ kind: 'star',+ result: getResult([{ kind: 'image', name: target.name }]),+ starred: false,+ });++ expect(getData(client, key).pages[0]).toEqual({ items: [other], total: 1 });+ });++ it('reads prior starred flags from the strip for rollback', () => {+ const client = createClient();+ const stripOnly = createItem('strip-only.png', 'board-1', true);++ client.setQueryData(getStripKey('board-1'), { items: [stripOnly], total: 1 });++ expect(getGalleryItemStarredFromCaches(client, [{ kind: 'image', name: stripOnly.name }])).toEqual(+ new Map([['image:strip-only.png', true]])+ );+ });+ });+it('does not let rollback clobber a later concurrent cache update', () => {const client = createClient();const target = createItem('target.png');@@ -406,7 +534,6 @@ describe('Gallery window rebuild', () => {boardId: 'board-1',galleryView: 'images',searchTerm: '',- starredFirst: false,};const dateFilter: GalleryItemsFilter = { ...listFilter, boardId: 'by_date:2026-07-25' };@@ -514,7 +641,6 @@ describe('Gallery window rebuild', () => {vi.mocked(listGalleryDateBoardItemNames).mockResolvedValue({items: createPageItems('fresh', 130).map(({ kind, name }) => ({ kind, name })),- starredCount: 0,total: 130,});vi.mocked(hydrateGalleryDateBoardItemPage).mockResolvedValue({@@ -592,7 +718,7 @@ describe('Gallery window rebuild', () => {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 });+ vi.mocked(listGalleryDateBoardItemNames).mockResolvedValue({ items: [], total: 0 });vi.mocked(hydrateGalleryDateBoardItemPage).mockResolvedValue({ items: [], total: 0 });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 7ecfbe5cea..08fa4d7864 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -22,6 +22,7 @@ import {galleryKeys,getGalleryItemListQueries,getGalleryItemsFilterFromKey,+ isGalleryStarredStripQueryKey,type CanonicalGalleryItemsFilter,} from './queries';@@ -30,9 +31,12 @@ export type GalleryItemCachePatch =| { boardId: string; kind: 'move'; result: GalleryItemMutationResult }| { kind: 'star'; result: GalleryItemMutationResult; starred: boolean };+/** A list window's pages, or the starred strip's single page. */+type GalleryItemsCacheData = InfiniteData<GalleryItemsPage, number> | GalleryItemsPage;+interface ItemCacheRollbackEntry {- after: InfiniteData<GalleryItemsPage, number>;- before: InfiniteData<GalleryItemsPage, number>;+ after: GalleryItemsCacheData;+ before: GalleryItemsCacheData;queryKey: QueryKey;}@@ -46,6 +50,23 @@ const isGalleryItemsData = (value: unknown): value is InfiniteData<GalleryItemsPreturn Array.isArray(data.pages) && Array.isArray(data.pageParams);};+const isGalleryItemsPage = (value: unknown): value is GalleryItemsPage =>+ typeof value === 'object' &&+ value !== null &&+ Array.isArray((value as { items?: unknown }).items) &&+ typeof (value as { total?: unknown }).total === 'number';++/** The pages a list-family cache entry holds, whichever shape it is. */+const getCachedPages = (query: Query): GalleryItemsPage[] => {+ const data = query.state.data;++ if (isGalleryItemsData(data)) {+ return data.pages;+ }++ return isGalleryStarredStripQueryKey(query.queryKey) && isGalleryItemsPage(data) ? [data] : [];+};+const mapPageItems = (page: GalleryItemsPage,mapItem: (item: GalleryItem) => GalleryItem | null,@@ -76,6 +97,29 @@ const mapPageItems = (};};+/**+ * Whether a patch takes matching items out of a listing with this filter.+ * Ranked similarity windows are board-agnostic (a move never changes+ * membership); a starred-only listing — the strip, or the grid under the+ * starred filter — loses an item the moment it is unstarred.+ */+const patchRemovesItems = (filter: CanonicalGalleryItemsFilter, patch: GalleryItemCachePatch): boolean => {+ if (patch.kind === 'delete') {+ return true;+ }++ if (patch.kind === 'star') {+ return filter.starred !== undefined && filter.starred !== patch.starred;+ }++ return (+ filter.semantic === undefined &&+ filter.boardId !== ALL_READABLE_BOARDS_ID &&+ filter.boardId !== patch.boardId &&+ !isDateBoardId(filter.boardId)+ );+};+const patchItemPage = (page: GalleryItemsPage,filter: CanonicalGalleryItemsFilter,@@ -83,61 +127,39 @@ const patchItemPage = (itemKeys: ReadonlySet<GalleryItemKey>,removedItemCount: number): GalleryItemsPage => {- if (patch.kind === 'star') {- return mapPageItems(page, (item) => {- if (!itemKeys.has(toGalleryItemKey(item)) || item.starred === patch.starred) {- return item;- }-- return { ...item, starred: patch.starred };- });- }-- if (patch.kind === 'delete') {+ if (patchRemovesItems(filter, patch)) {return mapPageItems(page, (item) => (itemKeys.has(toGalleryItemKey(item)) ? null : item), removedItemCount);}- // Ranked similarity windows are board-agnostic: moving an image to another- // board never changes its membership in the result set.- const keepsMovedItems =- filter.semantic !== undefined ||- filter.boardId === ALL_READABLE_BOARDS_ID ||- filter.boardId === patch.boardId ||- isDateBoardId(filter.boardId);-- return mapPageItems(- page,- (item) => {- if (!itemKeys.has(toGalleryItemKey(item))) {- return item;- }+ return mapPageItems(page, (item) => {+ if (!itemKeys.has(toGalleryItemKey(item))) {+ return item;+ }- if (!keepsMovedItems) {- return null;- }+ if (patch.kind === 'star') {+ return item.starred === patch.starred ? item : { ...item, starred: patch.starred };+ }+ if (patch.kind === 'move') {return item.boardId === patch.boardId ? item : { ...item, boardId: patch.boardId };- },- keepsMovedItems ? 0 : removedItemCount- );+ }++ return item;+ });};+const countRemovedItems = (page: GalleryItemsPage, itemKeys: ReadonlySet<GalleryItemKey>): number =>+ page.items.filter((item) => itemKeys.has(toGalleryItemKey(item))).length;+const patchItemsInfiniteData = (data: InfiniteData<GalleryItemsPage, number>,filter: CanonicalGalleryItemsFilter,patch: GalleryItemCachePatch,itemKeys: ReadonlySet<GalleryItemKey>): InfiniteData<GalleryItemsPage, number> => {- const removesItems =- patch.kind === 'delete' ||- (patch.kind === 'move' &&- filter.semantic === undefined &&- filter.boardId !== ALL_READABLE_BOARDS_ID &&- filter.boardId !== patch.boardId &&- !isDateBoardId(filter.boardId));const removedItemKeys = new Set<GalleryItemKey>();- if (removesItems) {+ if (patchRemovesItems(filter, patch)) {for (const page of data.pages) {for (const item of page.items) {const key = toGalleryItemKey(item);@@ -160,6 +182,27 @@ const patchItemsInfiniteData = (return changed ? { ...data, pages } : data;};+const patchItemsCacheData = (+ query: Query,+ filter: CanonicalGalleryItemsFilter,+ patch: GalleryItemCachePatch,+ itemKeys: ReadonlySet<GalleryItemKey>+): { after: GalleryItemsCacheData; before: GalleryItemsCacheData } | null => {+ const before = query.state.data;++ if (isGalleryItemsData(before)) {+ return { after: patchItemsInfiniteData(before, filter, patch, itemKeys), before };+ }++ // A newly starred item is left to the trailing refetch, which knows where+ // it belongs chronologically in the strip.+ if (isGalleryStarredStripQueryKey(query.queryKey) && isGalleryItemsPage(before)) {+ return { after: patchItemPage(before, filter, patch, itemKeys, countRemovedItems(before, itemKeys)), before };+ }++ return null;+};+/*** Applies only backend-confirmed successes. Failed refs are intentionally* ignored, and kind-qualified keys prevent same-name images/videos colliding.@@ -181,23 +224,17 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCaconst rollbackEntries: ItemCacheRollbackEntry[] = [];for (const query of getGalleryItemListQueries(client)) {- const before = query.state.data;const filter = getGalleryItemsFilterFromKey(query.queryKey);+ const patched = filter ? patchItemsCacheData(query, filter, patch, itemKeys) : null;- if (!filter || !isGalleryItemsData(before)) {- continue;- }-- const after = patchItemsInfiniteData(before, filter, patch, itemKeys);-- if (after === before) {+ if (!patched || patched.after === patched.before) {continue;}- const applied = client.setQueryData<InfiniteData<GalleryItemsPage, number>>(query.queryKey, after);+ const applied = client.setQueryData<GalleryItemsCacheData>(query.queryKey, patched.after);if (applied) {- rollbackEntries.push({ after: applied, before, queryKey: query.queryKey });+ rollbackEntries.push({ after: applied, before: patched.before, queryKey: query.queryKey });}}@@ -205,7 +242,7 @@ export const patchGalleryItemCaches = (client: QueryClient, patch: GalleryItemCarollbackClusterMembers?.();rollBackUnclaimedEntries(rollbackEntries,- (entry) => client.getQueryData<InfiniteData<GalleryItemsPage, number>>(entry.queryKey),+ (entry) => client.getQueryData<GalleryItemsCacheData>(entry.queryKey),(entry) => client.setQueryData(entry.queryKey, entry.before));};@@ -228,13 +265,7 @@ export const getGalleryItemBoardIdsFromCaches = (break;}- const data = query.state.data;-- if (!isGalleryItemsData(data)) {- continue;- }-- for (const page of data.pages) {+ for (const page of getCachedPages(query)) {for (const item of page.items) {const key = toGalleryItemKey(item);@@ -266,13 +297,7 @@ export const getGalleryItemStarredFromCaches = (break;}- const data = query.state.data;-- if (!isGalleryItemsData(data)) {- continue;- }-- for (const page of data.pages) {+ for (const page of getCachedPages(query)) {for (const item of page.items) {const key = toGalleryItemKey(item);diff --git a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.tsindex 8ec0cf681b..a085339821 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts@@ -128,7 +128,6 @@ describe('listSemanticGalleryItemNames', () => {{ kind: 'image', name: 'first.png' },{ kind: 'image', name: 'second.png' },],- starredCount: 0,total: 2,});});@@ -142,7 +141,6 @@ describe('listSemanticGalleryItemNames', () => {{ kind: 'image', name: 'near.png' },{ kind: 'image', name: 'far.png' },],- starredCount: 0,total: 2,});// An evicted key (another cluster registered, or a reload) degrades to an@@ -151,7 +149,6 @@ describe('listSemanticGalleryItemNames', () => {registerImageCluster(['other.png'], 'newer');await expect(listSemanticGalleryItemNames({ query: { clusterId, kind: 'cluster' } })).resolves.toEqual({items: [],- starredCount: 0,total: 0,});expect(mocks.apiFetchJson).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsxindex 61b3f1b5b3..b257010d22 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx@@ -88,6 +88,7 @@ const createGallery = (settings: Partial<GallerySettings> = {}): GalleryStateVieselectedItemKey: null,selectedItemKeys: [],settings: { ...DEFAULT_GALLERY_SETTINGS, showArchivedBoards: true, showDateBoards: true, ...settings },+ starredOnly: false,...({} as Record<string, never>),}) as GalleryStateView;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 789420d4f6..75a7c60b13 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@@ -34,10 +34,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';import type { GalleryStateView } from './galleryStateView';-import type { GalleryActions, GalleryWidgetContextValue } from './GalleryWidgetContext';+import type { GalleryActions, GalleryStarredStrip, GalleryWidgetContextValue } from './GalleryWidgetContext';+import { mergeGalleryLoadedItems } from './galleryGridLayout';import { GalleryImageGrid } from './GalleryImageGrid';import { GalleryWidgetContext } from './GalleryWidgetContext';+import { EMPTY_GALLERY_STARRED_STRIP } from './useGalleryStarredStrip';const mocks = vi.hoisted(() => ({fetchNames: vi.fn(),@@ -114,12 +116,16 @@ void i18n.use(initReactI18next).init({navigationUp: 'Up',selectAllOnPage: 'Select all',toggleStarImage: 'Toggle star',+ toggleStarredOnly: 'Toggle starred filter',},generationProgress: 'Generation progress',generationProgressPercent: 'Generation {{percentage}}%',itemsAriaLabel: 'Gallery items',loadingBackendGallery: 'Loading gallery',noImagesMatch: 'No items',+ noStarredItemsMatch: 'No starred items',+ showAllStarred: 'Show all',+ showAllStarredItems: 'Show all starred items',collapseStarredItems: 'Collapse starred items',dropMediaToUploadToBoard: 'Drop media to {{name}}',emptyBoardUploadHint: 'Drop media here or click to upload',@@ -199,12 +205,11 @@ const createFilter = (gallery: GalleryStateView): GalleryItemsFilter => {galleryView: gallery.galleryView,orderDir: gallery.settings.imageOrderDir,searchTerm: parse.text,- starredFirst: gallery.settings.starredFirst,};};-/** Infinite-mode settings — the only mode where the starred section renders. */-const SECTIONED_SETTINGS = { ...getGallerySettings({}), imageDensityPercent: 0 };+/** Infinite-mode settings at the sparsest density, so few columns fit the harness. */+const DENSE_SETTINGS = { ...getGallerySettings({}), imageDensityPercent: 0 };const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateView => {const items = overrides.items ?? [@@ -232,6 +237,7 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateVselectedItemKeys: ['image:first.png'],semanticImageQuery: null,settings: { ...getGallerySettings({ paginationMode: 'paginated' }), imageDensityPercent: 0 },+ starredOnly: false,...overrides,};};@@ -241,7 +247,9 @@ const actionMocks = {selectItem: vi.fn(),selectItemRange: vi.fn(),setCompareItem: vi.fn(),+ setStarredOnly: vi.fn(),toggleItemInSelection: vi.fn(),+ updateSettings: vi.fn(),};const imageActionMocks = {deleteItems: vi.fn(),@@ -284,10 +292,11 @@ const createActions = (): GalleryActions =>selectProjectBoard: vi.fn(),setCompareItem: actionMocks.setCompareItem,setSearchTerm: noop,+ setStarredOnly: actionMocks.setStarredOnly,setView: noop,toggleImageInSelection: actionMocks.toggleItemInSelection,toggleItemInSelection: actionMocks.toggleItemInSelection,- updateSettings: noop,+ updateSettings: actionMocks.updateSettings,uploadFiles: vi.fn(),}) as unknown as GalleryActions;@@ -348,7 +357,13 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;let queryClient: QueryClient | null = null;let currentGallery = createGallery();+let currentStrip: GalleryStarredStrip = EMPTY_GALLERY_STARRED_STRIP;let onDragStart = vi.fn();++/** The strip the next renders show; `total` defaults to the item count. */+const setStrip = (items: GalleryItem[], total = items.length) => {+ currentStrip = { items, total };+};(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const DragMonitor = () => {@@ -378,9 +393,11 @@ const Harness = ({gallery,itemActions: imageActionMocks,isWindowTruncated: false,+ loadedItems: mergeGalleryLoadedItems(currentStrip.items, gallery.items),projectName: 'Project',region: 'right',runtime,+ starredStrip: currentStrip,} as unknown as GalleryWidgetContextValue;return (@@ -470,6 +487,7 @@ beforeEach(() => {vi.clearAllMocks();registeredCommands.clear();currentGallery = createGallery();+ currentStrip = EMPTY_GALLERY_STARRED_STRIP;queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });host = document.createElement('div');host.style.cssText = 'height:480px;left:20px;position:fixed;top:20px;width:600px;';@@ -488,14 +506,16 @@ afterEach(async () => {});describe('GalleryImageGrid mixed item cells', () => {- it('separates starred items into an expanded disclosure above regular items', async () => {- await renderGallery(- createGallery({- items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],- settings: SECTIONED_SETTINGS,- })+ const starred = createItem('image', 'starred.png', { starred: true });+ const sectionOrder = () =>+ Array.from(host?.querySelectorAll('[data-gallery-section]') ?? []).map((row) =>+ row.getAttribute('data-gallery-section'));+ it('puts the starred strip in an expanded disclosure above the unstarred listing', async () => {+ setStrip([starred]);+ await renderGallery(createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS }));+const trigger = getButton('Collapse starred items');const starredSection = host?.querySelector('[data-gallery-section="starred"]');const regularSection = host?.querySelector('[data-gallery-section="regular"]');@@ -505,19 +525,28 @@ describe('GalleryImageGrid mixed item cells', () => {expect(trigger.closest('[role="list"]')).toBeNull();expect(starredSection?.querySelector('button[aria-label="Select starred.png for preview"]')).not.toBeNull();expect(regularSection?.querySelector('button[aria-label="Select regular.png for preview"]')).not.toBeNull();- expect(- Array.from(host?.querySelectorAll('[data-gallery-section]') ?? []).map((row) =>- row.getAttribute('data-gallery-section')- )- ).toEqual(['starred', 'regular']);+ expect(host?.querySelectorAll('button[aria-label="Select starred.png for preview"]')).toHaveLength(1);+ expect(sectionOrder()).toEqual(['starred', 'regular']);+ // Every starred item is on screen, so there is nothing more to show.+ expect(host?.querySelector('button[aria-label="Show all starred items"]')).toBeNull();+ });++ it('offers Show all when the board holds more starred items than the strip, switching to the starred listing', async () => {+ setStrip([starred], 7);+ await renderGallery(createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS }));++ const trigger = getButton('Collapse starred items');+ expect([...trigger.querySelectorAll<HTMLElement>('span')].some((span) => span.textContent === '7')).toBe(true);++ await click(getButton('Show all starred items'));++ expect(actionMocks.setStarredOnly).toHaveBeenCalledExactlyOnceWith(true);});it.each(['bg', 'bg.panel'] as const)('keeps the starred count readable on the %s surface', async (background) => {+ setStrip([starred]);await renderGallery(- createGallery({- items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],- settings: SECTIONED_SETTINGS,- }),+ createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS }),false,background);@@ -541,27 +570,22 @@ describe('GalleryImageGrid mixed item cells', () => {});it('matches board disclosure chrome while retaining the star marker', async () => {- await renderGallery(- createGallery({- items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],- settings: SECTIONED_SETTINGS,- })- );+ setStrip([starred], 3);+ await renderGallery(createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS }));const trigger = getButton('Collapse starred items');const header = trigger.parentElement;expect(header?.getBoundingClientRect().height).toBe(24);expect(trigger.querySelector('svg.lucide-star')).not.toBeNull();+ // The Show all control shares the row without growing it.+ expect(getButton('Show all starred items').getBoundingClientRect().height).toBeLessThanOrEqual(24);});it('keeps the starred label and grid together before a dedicated trailing gap', async () => {- await renderGallery(- createGallery({- items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],- settings: SECTIONED_SETTINGS,- })- );+ setStrip([starred]);+ const gallery = createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS });+ await renderGallery(gallery);const listRect = host?.querySelector('[role="list"]')?.getBoundingClientRect();const headerRect = getButton('Collapse starred items').parentElement?.getBoundingClientRect();@@ -574,7 +598,11 @@ describe('GalleryImageGrid mixed item cells', () => {expect(regularRect.top - starredRect.bottom).toBeCloseTo(8 + GALLERY_STARRED_SEPARATOR_HEIGHT_PX, 0);expect(host?.querySelector('[data-gallery-starred-separator]')).not.toBeNull();+ // The disclosure is a persisted setting, so collapsing goes through the+ // owner and comes back as the next render's settings.await click(getButton('Collapse starred items'));+ expect(actionMocks.updateSettings).toHaveBeenCalledExactlyOnceWith({ starredSectionCollapsed: true });+ await renderGallery({ ...gallery, settings: { ...DENSE_SETTINGS, starredSectionCollapsed: true } });const collapsedHeaderRect = getButton('Expand starred items').parentElement?.getBoundingClientRect();const collapsedRegularRect = getButton('Select regular.png for preview').getBoundingClientRect();@@ -586,42 +614,118 @@ describe('GalleryImageGrid mixed item cells', () => {expect(host?.querySelector('[data-gallery-starred-separator]')).toBeNull();});- it('collapses only the starred items and omits the disclosure when no stars are loaded', async () => {+ it('collapses only the strip cells, keeps the count, and omits the disclosure when the strip is empty', async () => {+ setStrip([starred], 4);await renderGallery(createGallery({- items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],- settings: SECTIONED_SETTINGS,+ items: [createItem('image', 'regular.png')],+ settings: { ...DENSE_SETTINGS, starredSectionCollapsed: true },}));- await click(getButton('Collapse starred items'));+ const trigger = getButton('Expand starred items');- expect(getButton('Expand starred items').getAttribute('aria-expanded')).toBe('false');+ expect(trigger.getAttribute('aria-expanded')).toBe('false');+ expect([...trigger.querySelectorAll<HTMLElement>('span')].some((span) => span.textContent === '4')).toBe(true);expect(host?.querySelector('button[aria-label="Select starred.png for preview"]')).toBeNull();expect(host?.querySelector('button[aria-label="Select regular.png for preview"]')).not.toBeNull();+ // Collapsed, nothing is shown, so Show all still leads to the rest.+ expect(host?.querySelector('button[aria-label="Show all starred items"]')).not.toBeNull();- await renderGallery(createGallery({ items: [createItem('image', 'regular.png')], settings: SECTIONED_SETTINGS }));+ await click(trigger);+ expect(actionMocks.updateSettings).toHaveBeenLastCalledWith({ starredSectionCollapsed: false });++ setStrip([]);+ await renderGallery(createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS }));expect(host?.querySelector('button[aria-label="Expand starred items"]')).toBeNull();expect(host?.querySelector('button[aria-label="Collapse starred items"]')).toBeNull();});- it('renders starred items inline with no section on flat paginated pages', async () => {+ it('shows the strip on paginated pages too, and no chrome when the strip is empty', async () => {+ setStrip([starred]);+ await renderGallery(createGallery({ items: [createItem('image', 'regular.png')] }));++ expect(host?.querySelector('button[aria-label="Collapse starred items"]')).not.toBeNull();+ expect(sectionOrder()).toEqual(['starred', 'regular']);++ setStrip([]);+ await renderGallery(createGallery({ items: [createItem('image', 'regular.png')] }));++ expect(host?.querySelector('button[aria-label="Collapse starred items"]')).toBeNull();+ expect(sectionOrder()).toEqual(['regular']);+ });++ it('keeps showing the strip when every item on the board is starred', async () => {+ setStrip([starred]);+ await renderGallery(createGallery({ items: [], pendingPlaceholders: [], settings: DENSE_SETTINGS }));++ expect(getButton('Collapse starred items')).not.toBeNull();+ expect(host?.querySelector('button[aria-label="Select starred.png for preview"]')).not.toBeNull();+ expect(host?.querySelector('[role="button"]')).toBeNull();+ expect(host?.textContent).not.toContain('Drop media');+ });++ it('caps the strip at three rows of the current column count', async () => {+ const starredItems = Array.from({ length: 40 }, (_, index) =>+ createItem('image', `starred-${index}.png`, { starred: true })+ );+ setStrip(starredItems, 40);+ await renderGallery(createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS }));++ const stripRows = host?.querySelectorAll('[data-gallery-section="starred"]') ?? [];+ const stripCells = host?.querySelectorAll('[data-gallery-section="starred"] [role="listitem"]').length ?? 0;+ const columnCount = stripRows[0]?.querySelectorAll('[role="listitem"]').length ?? 0;++ expect(stripRows).toHaveLength(3);+ expect(columnCount).toBeGreaterThan(0);+ expect(stripCells).toBe(3 * columnCount);+ expect(host?.querySelector('button[aria-label="Show all starred items"]')).not.toBeNull();+ });++ it('walks the arrow keys from the strip into the listing and back across the seam', async () => {+ const regular = createItem('image', 'regular.png');+ setStrip([starred]);await renderGallery(createGallery({- items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],+ items: [regular],+ selectedItemKey: 'image:starred.png',+ selectedItemKeys: ['image:starred.png'],+ settings: DENSE_SETTINGS,}));- expect(host?.querySelector('button[aria-label="Collapse starred items"]')).toBeNull();- expect(- Array.from(host?.querySelectorAll('[data-gallery-section]') ?? []).map((row) =>- row.getAttribute('data-gallery-section')- )- ).toEqual(['regular']);- expect(- host?.querySelector('[data-gallery-section="regular"] button[aria-label="Select starred.png for preview"]')- ).not.toBeNull();+ registeredCommands.get('gallery.galleryNavRight')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(regular);++ await renderGallery({+ ...currentGallery,+ selectedItemKey: 'image:regular.png',+ selectedItemKeys: ['image:regular.png'],+ });+ registeredCommands.get('gallery.galleryNavLeft')?.();+ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(starred);+ });++ it('stars from the strip for a selection the listing window has not loaded', async () => {+ setStrip([starred]);+ await renderGallery(+ createGallery({+ items: [createItem('image', 'regular.png')],+ selectedItemKey: 'image:starred.png',+ selectedItemKeys: ['image:starred.png'],+ settings: DENSE_SETTINGS,+ })+ );++ registeredCommands.get('gallery.starImage')?.();+ expect(imageActionMocks.setItemsStarred).toHaveBeenCalledWith([{ kind: 'image', name: 'starred.png' }], false);++ await click(getButton('Unstar starred.png'));+ expect(imageActionMocks.setItemsStarred).toHaveBeenCalledTimes(2);++ registeredCommands.get('gallery.toggleStarredOnly')?.();+ expect(actionMocks.setStarredOnly).toHaveBeenCalledExactlyOnceWith(true);});it('renders same-name media independently and gives a video a static accessible poster', async () => {@@ -866,7 +970,7 @@ describe('GalleryImageGrid range selection', () => {];it('does not load names on render and lazily selects the backend-ordered mixed range on Shift-click', async () => {- mocks.fetchNames.mockResolvedValue({ items: orderedRefs, starredCount: 0, total: orderedRefs.length });+ mocks.fetchNames.mockResolvedValue({ items: orderedRefs, total: orderedRefs.length });const gallery = createGallery({ items: rangeItems });await renderGallery(gallery);@@ -888,13 +992,8 @@ describe('GalleryImageGrid range selection', () => {galleryView: gallery.galleryView,orderDir: gallery.settings.imageOrderDir,searchTerm: '',- starredFirst: gallery.settings.starredFirst,};- queryClient?.setQueryData(getNamesKey(filter), {- items: orderedRefs,- starredCount: 0,- total: orderedRefs.length,- });+ queryClient?.setQueryData(getNamesKey(filter), { items: orderedRefs, total: orderedRefs.length });await renderGallery(gallery);await click(getButton('Select last.png for preview'), { shiftKey: true });@@ -904,7 +1003,7 @@ describe('GalleryImageGrid range selection', () => {});it('ignores a names response after the filter identity changes', async () => {- let resolveNames: ((value: { items: GalleryItemRef[]; starredCount: number; total: number }) => void) | null = null;+ let resolveNames: ((value: { items: GalleryItemRef[]; total: number }) => void) | null = null;mocks.fetchNames.mockReturnValue(new Promise((resolve) => {resolveNames = resolve;@@ -915,13 +1014,13 @@ describe('GalleryImageGrid range selection', () => {await renderGallery(gallery);await click(getButton('Select last.png for preview'), { shiftKey: true });await renderGallery({ ...gallery, searchTerm: 'different filter' });- await interact(() => resolveNames?.({ items: orderedRefs, starredCount: 0, total: orderedRefs.length }));+ await interact(() => resolveNames?.({ items: orderedRefs, total: orderedRefs.length }));expect(actionMocks.selectItemRange).not.toHaveBeenCalled();});it('ignores a names response after the account epoch changes', async () => {- let resolveNames: ((value: { items: GalleryItemRef[]; starredCount: number; total: number }) => void) | null = null;+ let resolveNames: ((value: { items: GalleryItemRef[]; total: number }) => void) | null = null;mocks.fetchNames.mockReturnValue(new Promise((resolve) => {resolveNames = resolve;@@ -931,7 +1030,7 @@ describe('GalleryImageGrid range selection', () => {await renderGallery(createGallery({ items: rangeItems }));await click(getButton('Select last.png for preview'), { shiftKey: true });accountLifecycle.activate('other-grid-user');- await interact(() => resolveNames?.({ items: orderedRefs, starredCount: 0, total: orderedRefs.length }));+ await interact(() => resolveNames?.({ items: orderedRefs, total: orderedRefs.length }));expect(actionMocks.selectItemRange).not.toHaveBeenCalled();});@@ -1001,6 +1100,13 @@ describe('GalleryImageGrid upload drop zone', () => {expect(host?.querySelector('[role="button"]')).toBeNull();});+ it('reports the starred empty state instead of the upload target under the starred-only listing', async () => {+ await renderGallery(createGallery({ items: [], pendingPlaceholders: [], starredOnly: true }));++ expect(host?.textContent).toContain('No starred items');+ expect(host?.querySelector('[role="button"]')).toBeNull();+ });+it('keeps the loading message while an empty board is still loading', async () => {await renderGallery(createGallery({ isLoading: true, items: [], pendingPlaceholders: [] }));@@ -1074,24 +1180,26 @@ describe('GalleryImageGrid reveal requests', () => {expect(mocks.scrollToIndex).not.toHaveBeenCalled();});- it('keeps a reveal pending while its item has no row, then scrolls when one appears', async () => {- // A starred item under a collapsed Starred section is loaded but has no- // row to scroll to; consuming the reveal there would silently drop it.+ it('reveals a starred item in the strip, and keeps the reveal pending while the strip is collapsed', async () => {const starred = createItem('image', 'starred.png', { starred: true });+ setStrip([starred]);const gallery = createGallery({- items: [starred, createItem('image', 'regular.png')],+ items: [createItem('image', 'regular.png')],selectedItemKey: 'image:starred.png',selectedItemKeys: ['image:starred.png'],- settings: SECTIONED_SETTINGS,+ settings: { ...DENSE_SETTINGS, starredSectionCollapsed: true },});await renderGallery(gallery);- await click(getButton('Collapse starred items'));await interact(() => requestGalleryItemReveal('image:starred.png'));+ // Loaded but row-less under the collapsed disclosure: consuming the+ // reveal here would silently drop it.expect(mocks.scrollToIndex).not.toHaveBeenCalled();- await click(getButton('Expand starred items'));+ 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);});/** A persisted off-page selection of deep.png with page-zero content loaded. */@@ -1204,10 +1312,9 @@ describe('GalleryImageGrid virtualization', () => {});it('re-measures when the row model changes without a resize, and only then', async () => {- const gallery = createGallery({- items: [createItem('image', 'starred.png', { starred: true }), createItem('image', 'regular.png')],- settings: SECTIONED_SETTINGS,- });+ const starred = createItem('image', 'starred.png', { starred: true });+ setStrip([starred]);+ const gallery = createGallery({ items: [createItem('image', 'regular.png')], settings: DENSE_SETTINGS });await renderGallery(gallery);@@ -1215,7 +1322,7 @@ describe('GalleryImageGrid virtualization', () => {// explicit measure() the virtualizer would keep serving the expanded// offsets — the new rows would paint below a stale starred-sized hole.mocks.measure.mockClear();- await click(getButton('Collapse starred items'));+ await renderGallery({ ...gallery, settings: { ...DENSE_SETTINGS, starredSectionCollapsed: true } });expect(mocks.measure).toHaveBeenCalled();// Swapping the item list (e.g. the media/assets view switch) is the same@@ -1236,7 +1343,7 @@ describe('GalleryImageGrid virtualization', () => {await renderGallery(createGallery({items,- settings: SECTIONED_SETTINGS,+ settings: DENSE_SETTINGS,}));await vi.waitFor(() => expect(actionMocks.loadMore).toHaveBeenCalled());diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex acac399612..b8ff54cc12 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -26,6 +26,7 @@ import { useVirtualizer } from 'react-hook-tanstack-virtual';import { useTranslation } from 'react-i18next';import {+ buildGalleryGridNavigation,buildGalleryGridRows,GALLERY_GRID_GAP_PX,GALLERY_STARRED_HEADER_HEIGHT_PX,@@ -56,23 +57,32 @@ let lastPageFollowedRevealToken = 0;const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');-/** The disclosure row above the starred items, styled to match board rows. */+/**+ * The disclosure row above the starred strip, styled to match board rows.+ * "Show all" appears only while the board holds more starred items than the+ * strip shows; it switches the listing to the starred-only filter.+ */const GalleryStarredSectionHeader = ({isOpen,- itemCount,offsetPx,+ onShowAll,onToggle,+ shownCount,+ total,}: {isOpen: boolean;- itemCount: number;offsetPx: number;+ onShowAll: () => void;onToggle: () => void;+ shownCount: number;+ total: number;}) => {const { t } = useTranslation();return (<Flexalign="center"+ gap="1"h={`${GALLERY_STARRED_HEADER_HEIGHT_PX}px`}left="0"position="absolute"@@ -103,7 +113,7 @@ const GalleryStarredSectionHeader = ({transition="transform var(--wb-motion-duration-medium) ease"/><Icon as={StarIcon} boxSize="3" fill="currentColor" />- <HStack gap="1">+ <HStack gap="1" minW="0"><Textas="span"fontSize="2xs"@@ -116,10 +126,22 @@ const GalleryStarredSectionHeader = ({{t('widgets.gallery.starredItems')}</Text><Text as="span" color="currentColor" fontSize="2xs" fontVariantNumeric="tabular-nums" lineHeight="1">- {itemCount}+ {total}</Text></HStack></chakra.button>+ {total > shownCount ? (+ <Button+ aria-label={t('widgets.gallery.showAllStarredItems')}+ color="fg.muted"+ flexShrink={0}+ size="2xs"+ variant="ghost"+ onClick={onShowAll}+ >+ {t('widgets.gallery.showAllStarred')}+ </Button>+ ) : null}</Flex>);};@@ -131,15 +153,21 @@ const GalleryStarredSectionHeader = ({*/export const GalleryImageGrid = () => {const { t } = useTranslation();- const { actions, gallery, isWindowTruncated, itemActions, region } = useGalleryWidget();+ const { actions, gallery, isWindowTruncated, itemActions, region, starredStrip } = useGalleryWidget();const { account, antialiasProgressImages, gallery: galleryCommands, ImageContextMenu } = useGalleryUi();const [isDropActive, setIsDropActive] = useState(false);- const [isStarredOpen, setIsStarredOpen] = useState(true);const [viewportWidth, setViewportWidth] = useState(() => viewportWidthCache.get(region) ?? 0);const dragDepthRef = useRef(0);const viewportRef = useRef<HTMLDivElement | null>(null);- const { imageDensityPercent, imageOrderDir, paginationMode, showImageDimensions, starredFirst, thumbnailFit } =- gallery.settings;+ const {+ imageDensityPercent,+ imageOrderDir,+ paginationMode,+ showImageDimensions,+ starredSectionCollapsed,+ thumbnailFit,+ } = gallery.settings;+ const isStarredOpen = !starredSectionCollapsed;const {actionSelectionRefs,@@ -148,6 +176,7 @@ export const GalleryImageGrid = () => {handleCloseContextMenu,handleThumbnailClick,handleThumbnailContextMenu,+ loadedItems,selectedItemKeys,syncRangeInteractionContext,} = useGalleryGridSelection();@@ -159,7 +188,10 @@ export const GalleryImageGrid = () => {const selectedBoardName = selectedBoard? getGalleryBoardLabel(selectedBoard, t): t('widgets.gallery.selectedBoardFallback');- const isEmpty = gallery.items.length === 0 && gallery.pendingPlaceholders.length === 0;+ // The listing is unstarred-only, so a board whose items are all starred+ // still has the strip to show.+ const isEmpty =+ gallery.items.length === 0 && gallery.pendingPlaceholders.length === 0 && starredStrip.items.length === 0;const hasActiveSearch = gallery.searchTerm.trim() !== '';const isVirtualBoard = isDateBoardId(gallery.selectedBoardId);@@ -171,9 +203,28 @@ export const GalleryImageGrid = () => {isStarredOpen,items: gallery.items,pendingPlaceholders: gallery.pendingPlaceholders,- starredFirst,+ starredItems: starredStrip.items,+ starredTotal: starredStrip.total,}),- [columnCount, gallery.items, gallery.pendingPlaceholders, imageOrderDir, isStarredOpen, starredFirst]+ [+ columnCount,+ gallery.items,+ gallery.pendingPlaceholders,+ imageOrderDir,+ isStarredOpen,+ starredStrip.items,+ starredStrip.total,+ ]+ );+ const navigation = useMemo(+ () =>+ buildGalleryGridNavigation({+ columnCount,+ isStarredOpen,+ items: gallery.items,+ starredItems: starredStrip.items,+ }),+ [columnCount, gallery.items, isStarredOpen, starredStrip.items]);const rowCount = rows.length;@@ -218,7 +269,13 @@ export const GalleryImageGrid = () => {return true;};- useGalleryGridHotkeys({ actionSelectionRefs, columnCount, scrollToItemIndex });+ useGalleryGridHotkeys({+ actionSelectionRefs,+ columnCount,+ loadedItems,+ navigation,+ scrollToItemIndex,+ });// Reveals from outside the grid (the image map's click-to-reveal) must land// in view. This listens to the explicit reveal channel, NOT the selection:@@ -255,12 +312,13 @@ export const GalleryImageGrid = () => {return;}- const itemIndex = gallery.items.findIndex((item) => toGalleryItemKey(item) === pending.itemKey);+ // 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: the item can be loaded and- // still have no row — a starred item under a collapsed Starred section —- // and clearing on the attempt alone would silently drop the reveal- // instead of honoring it when the section is expanded again.+ // 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)) {pendingRevealRef.current = null;@@ -398,9 +456,21 @@ export const GalleryImageGrid = () => {account.enableLiveFollow();}, [account]);- const handleToggleStarredSection = useCallback(() => {- setIsStarredOpen((isOpen) => !isOpen);- }, []);+ const handleToggleStarredSection = useCallback(+ () => actions.updateSettings({ starredSectionCollapsed: isStarredOpen }),+ [actions, isStarredOpen]+ );++ // Show all removes the header it lives in; focus moves first, to the+ // toolbar control that reports (and undoes) the filter, so keyboard users+ // are not dropped on the document body.+ const handleShowAllStarred = useCallback(() => {+ viewportRef.current+ ?.closest('[role="tabpanel"]')+ ?.parentElement?.querySelector<HTMLElement>('[data-gallery-starred-filter-toggle]')+ ?.focus();+ actions.setStarredOnly(true);+ }, [actions]);const handleToggleStarred = useCallback((item: GalleryItem) => void itemActions.setItemsStarred([{ kind: item.kind, name: item.name }], !item.starred),@@ -438,10 +508,14 @@ export const GalleryImageGrid = () => {</Flex>) : null}{isEmpty ? (- gallery.isLoading || hasActiveSearch || isVirtualBoard ? (+ gallery.isLoading || hasActiveSearch || isVirtualBoard || gallery.starredOnly ? (<Flex align="center" color="fg.muted" h="full" justify="center" minH="8rem"><Text fontSize="xs">- {gallery.isLoading ? t('widgets.gallery.loadingBackendGallery') : t('widgets.gallery.noImagesMatch')}+ {gallery.isLoading+ ? t('widgets.gallery.loadingBackendGallery')+ : gallery.starredOnly && gallery.semanticImageQuery === null+ ? t('widgets.gallery.noStarredItemsMatch')+ : t('widgets.gallery.noImagesMatch')}</Text></Flex>) : (@@ -479,8 +553,10 @@ export const GalleryImageGrid = () => {<GalleryStarredSectionHeaderkey={virtualRow.key}isOpen={isStarredOpen}- itemCount={row.itemCount}offsetPx={virtualRow.start}+ shownCount={row.shownCount}+ total={row.total}+ onShowAll={handleShowAllStarred}onToggle={handleToggleStarredSection}/>);@@ -536,42 +612,48 @@ export const GalleryImageGrid = () => {transform={`translateY(${virtualRow.start}px)`}w="full">- {row.cells.map((cell) =>- cell.kind === 'placeholder' ? (- <GalleryQueuePlaceholderCell- key={cell.placeholder.id}- antialiasProgressImages={antialiasProgressImages}- fit={thumbnailFit}- isSelected={- gallery.currentItem?.kind === 'placeholder' &&- gallery.currentItem.placeholder.id === cell.placeholder.id- }- placeholder={cell.placeholder}- onClick={handleShowProgressImages}- />- ) : (+ {row.cells.map((cell) => {+ if (cell.kind === 'placeholder') {+ return (+ <GalleryQueuePlaceholderCell+ key={cell.placeholder.id}+ antialiasProgressImages={antialiasProgressImages}+ fit={thumbnailFit}+ isSelected={+ gallery.currentItem?.kind === 'placeholder' &&+ gallery.currentItem.placeholder.id === cell.placeholder.id+ }+ placeholder={cell.placeholder}+ onClick={handleShowProgressImages}+ />+ );+ }++ const itemKey = toGalleryItemKey(cell.item);++ return (<GalleryThumbnailCell- key={toGalleryItemKey(cell.item)}+ key={itemKey}alwaysShowDimensions={showImageDimensions}dragScope={region}compareRole={- isComparisonActive && toGalleryItemKey(cell.item) === gallery.selectedItemKey+ isComparisonActive && itemKey === gallery.selectedItemKey? t('widgets.preview.viewing')- : isComparisonActive && toGalleryItemKey(cell.item) === gallery.compareImageKey+ : isComparisonActive && itemKey === gallery.compareImageKey? t('widgets.preview.compare'): null}fit={thumbnailFit}getDragItems={getDragItems}- isPrimary={!isFollowingLive && toGalleryItemKey(cell.item) === gallery.selectedItemKey}- isSelected={!isFollowingLive && selectedItemKeys.has(toGalleryItemKey(cell.item))}+ isPrimary={!isFollowingLive && itemKey === gallery.selectedItemKey}+ isSelected={!isFollowingLive && selectedItemKeys.has(itemKey)}item={cell.item}onClick={handleThumbnailClick}onContextMenu={handleThumbnailContextMenu}onToggleStarred={handleToggleStarred}/>- )- )}+ );+ })}</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 c928bf3e08..05edd1d705 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@@ -18,6 +18,7 @@ import type { GalleryWidgetContextValue } from './GalleryWidgetContext';import { GalleryStackedLayout } from './GalleryStackedLayout';import { GalleryWideLayout } from './GalleryWideLayout';import { GalleryWidgetContext } from './GalleryWidgetContext';+import { EMPTY_GALLERY_STARRED_STRIP } from './useGalleryStarredStrip';vi.mock('@features/queue/react', () => ({useQueueItemProgress: () => null,@@ -72,7 +73,9 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}) =>selectedBoardId: 'dogs',selectedItemKey: 'image:a.png',selectedItemKeys: ['image:a.png', 'image:b.png'],+ semanticImageQuery: null,settings: DEFAULT_GALLERY_SETTINGS,+ starredOnly: false,...overrides,}) as unknown as GalleryStateView;@@ -88,6 +91,7 @@ const createContextValue = () =>({...contextBase,gallery: activeGallery,+ loadedItems: activeGallery.items,region: 'center',}) as unknown as GalleryWidgetContextValue;@@ -98,6 +102,7 @@ const contextBase = {selectBoard: vi.fn(),selectProjectBoard: vi.fn(),setSearchTerm: vi.fn(),+ setStarredOnly: vi.fn(),setView: vi.fn(),updateSettings: vi.fn(),uploadFiles: vi.fn(),@@ -105,6 +110,7 @@ const contextBase = {filter: { boardId: 'dogs', galleryView: 'images', searchTerm: '' },gallery,isWindowTruncated: false,+ starredStrip: EMPTY_GALLERY_STARRED_STRIP,itemActions: {deleteItems: vi.fn(),downloadItems: vi.fn(),@@ -272,6 +278,66 @@ describe('gallery layout shells', () => {}});+ it('offers the starred-only filter in both shells, pressed while active and disabled under a ranked query', async () => {+ for (const Layout of [GalleryStackedLayout, GalleryWideLayout]) {+ setGallery(createGallery({ starredOnly: false }));+ await renderLayout(Layout);++ const toggle = host?.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.starredOnly"]');++ expect(toggle, 'starred filter toggle did not render in the toolbar').not.toBeNull();+ expect(toggle?.getAttribute('aria-pressed')).toBe('false');++ await act(() => {+ toggle?.click();+ });+ expect(contextBase.actions.setStarredOnly).toHaveBeenLastCalledWith(true);++ setGallery(createGallery({ starredOnly: true }));+ await renderLayout(Layout);+ expect(+ host+ ?.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.starredOnly"]')+ ?.getAttribute('aria-pressed')+ ).toBe('true');++ setGallery(createGallery({ semanticImageQuery: { imageName: 'ref.png', kind: 'image' }, starredOnly: true }));+ await renderLayout(Layout);++ const ranked = host?.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.starredOnly"]');++ // Inert but focusable, so the tooltip can say why it does not apply.+ expect(ranked?.getAttribute('aria-disabled')).toBe('true');+ expect(ranked?.disabled).toBe(false);+ expect(ranked?.getAttribute('aria-pressed')).toBe('false');+ (contextBase.actions.setStarredOnly as ReturnType<typeof vi.fn>).mockClear();+ await act(() => {+ ranked?.click();+ });+ expect(contextBase.actions.setStarredOnly).not.toHaveBeenCalled();+ }+ });++ it('moves focus to the toolbar toggle when Show all removes the strip header', async () => {+ const starredItem = { ...createItem('starred.png'), starred: true };++ contextBase.starredStrip = { items: [starredItem], total: 9 };+ setGallery(createGallery({ items: [createItem('a.png')], starredOnly: false }));+ await renderLayout(GalleryWideLayout);++ const showAll = host?.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.showAllStarredItems"]');++ expect(showAll, 'Show all did not render').not.toBeNull();+ showAll?.focus();+ await act(() => {+ showAll?.click();+ });++ expect(contextBase.actions.setStarredOnly).toHaveBeenLastCalledWith(true);+ expect(document.activeElement?.getAttribute('aria-label')).toBe('widgets.gallery.starredOnly');+ contextBase.starredStrip = EMPTY_GALLERY_STARRED_STRIP;+ });+it('hides the board column and its handle in both shells when collapsed', async () => {setGallery(createGallery({ settings: { ...DEFAULT_GALLERY_SETTINGS, boardPanelCollapsed: true } }));diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsxindex 477d6ecc9a..17eb3421dd 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.browser.test.tsx@@ -12,8 +12,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { GalleryStateView } from './galleryStateView';import type { GalleryWidgetContextValue } from './GalleryWidgetContext';+import { mergeGalleryLoadedItems } from './galleryGridLayout';import { GallerySelectionBar } from './GallerySelectionBar';import { GalleryWidgetContext } from './GalleryWidgetContext';+import { EMPTY_GALLERY_STARRED_STRIP } from './useGalleryStarredStrip';vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -94,8 +96,17 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const renderBar = async (gallery: GalleryStateView) => {- const contextValue = { gallery, itemActions } as unknown as GalleryWidgetContextValue;+const renderBar = async (+ gallery: GalleryStateView,+ starredStrip: { items: GalleryItem[]; total: number } | null = null+) => {+ const strip = starredStrip ?? EMPTY_GALLERY_STARRED_STRIP;+ const contextValue = {+ gallery,+ itemActions,+ loadedItems: mergeGalleryLoadedItems(strip.items, gallery.items),+ starredStrip: strip,+ } as unknown as GalleryWidgetContextValue;await act(() =>root?.render(@@ -172,6 +183,16 @@ describe('GallerySelectionBar', () => {expect(itemActions.setItemsStarred).toHaveBeenCalledWith(expect.anything(), false);});+ it('reads star state from the strip for a selection the listing window has not loaded', async () => {+ await renderBar(createGallery({ items: [] }), {+ items: [createItem('a.png', true), createItem('b.png', true)],+ total: 2,+ });+ await click(getButton('widgets.gallery.unstarSelection'));++ expect(itemActions.setItemsStarred).toHaveBeenCalledWith(expect.anything(), false);+ });+it('downloads and deletes the selection', async () => {const gallery = createGallery();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsxindex f0713353de..7bf73b06e8 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySelectionBar.tsx@@ -23,7 +23,7 @@ const MOVE_MENU_POSITIONING = { placement: 'top-end' } as const;*/export const GallerySelectionBar = () => {const { t } = useTranslation();- const { gallery, itemActions } = useGalleryWidget();+ const { gallery, itemActions, loadedItems } = useGalleryWidget();const moveTriggerIds = useMenuTriggerIds();const selectedItemKeys = gallery.selectedItemKeys;const selectionCount = selectedItemKeys.length;@@ -32,10 +32,7 @@ export const GallerySelectionBar = () => {// Star acts on the whole selection: only "unstar all" when every selected// item is already starred, matching the `.` hotkey.- const shouldStar = useMemo(- () => shouldStarSelection(gallery.items, selectedItemRefs),- [gallery.items, selectedItemRefs]- );+ const shouldStar = useMemo(() => shouldStarSelection(loadedItems, selectedItemRefs), [loadedItems, selectedItemRefs]);const moveTargets = useMemo(() =>@@ -51,8 +48,8 @@ export const GallerySelectionBar = () => {);const handleDownload = useCallback(- () => void itemActions.downloadItems(selectedItemRefs, gallery.items),- [gallery.items, itemActions, selectedItemRefs]+ () => void itemActions.downloadItems(selectedItemRefs, loadedItems),+ [itemActions, loadedItems, selectedItemRefs]);const handleDelete = useCallback(diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsxindex f7a1c963b3..c708af60df 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx@@ -14,6 +14,7 @@ import { GalleryItemSearch } from './GalleryItemSearch';import { GalleryItemSortMenu } from './GalleryItemSortMenu';import { GallerySelectionBar } from './GallerySelectionBar';import { GALLERY_SPLIT_HANDLE_SIZE_PX, GallerySplitHandle } from './GallerySplitHandle';+import { GalleryStarredFilterToggle } from './GalleryStarredFilterToggle';import { GalleryUploadButton } from './GalleryUploadButton';import { GalleryViewTabs } from './GalleryViewTabs';import { useGalleryWidget } from './GalleryWidgetContext';@@ -125,6 +126,7 @@ export const GalleryStackedLayout = () => {<HStack gap="1" minW="0"><GalleryViewTabs idBase={viewTabsIdBase} /><Spacer />+ <GalleryStarredFilterToggle /><GalleryItemSortMenu /><GalleryUploadButtonboards={gallery.boards}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStarredFilterToggle.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStarredFilterToggle.tsxnew file mode 100644index 0000000000..8a8e2d8866--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStarredFilterToggle.tsx@@ -0,0 +1,39 @@+import { ToggleIconButton } from '@platform/ui/Button';+import { StarIcon } from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useGalleryWidget } from './GalleryWidgetContext';++/**+ * Restricts the listing to starred items. Inert (but still focusable, so the+ * tooltip can explain why) under a ranked similarity result, which the+ * starred filter does not apply to.+ */+export const GalleryStarredFilterToggle = () => {+ const { t } = useTranslation();+ const { actions, gallery } = useGalleryWidget();+ const isRanked = gallery.semanticImageQuery !== null;+ const handleCheckedChange = useCallback(+ (checked: boolean) => {+ if (!isRanked) {+ actions.setStarredOnly(checked);+ }+ },+ [actions, isRanked]+ );++ return (+ <ToggleIconButton+ aria-disabled={isRanked || undefined}+ checked={gallery.starredOnly && !isRanked}+ data-gallery-starred-filter-toggle+ flexShrink={0}+ icon={StarIcon}+ label={t('widgets.gallery.starredOnly')}+ size="xs"+ tooltip={t(isRanked ? 'widgets.gallery.starredOnlyUnavailable' : 'widgets.gallery.starredOnlyTooltip')}+ onCheckedChange={handleCheckedChange}+ />+ );+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex 89ecc5e88e..c00688fe16 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -65,9 +65,10 @@ export interface GalleryCommandsPort {setPage(page: number): void;setPageInfo(totalImages: number): void;setSearchTerm(searchTerm: string): void;+ setStarredOnly(starredOnly: boolean): void;setView(view: GalleryView): void;toggleItemSelection(item: GalleryItem, nextPrimaryItem: GalleryItem | null): void;- updateSettings(settings: Partial<Omit<GallerySettings, 'starredFirst'>>): void;+ updateSettings(settings: Partial<GallerySettings>): void;}export interface GalleryNotificationsPort {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsxindex a295caa1d9..e7a5fd6330 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx@@ -10,6 +10,7 @@ import { GalleryItemSearch } from './GalleryItemSearch';import { GalleryItemSortMenu } from './GalleryItemSortMenu';import { GallerySelectionBar } from './GallerySelectionBar';import { GallerySplitHandle } from './GallerySplitHandle';+import { GalleryStarredFilterToggle } from './GalleryStarredFilterToggle';import { GalleryUploadButton } from './GalleryUploadButton';import { GalleryViewTabs } from './GalleryViewTabs';import { useGalleryWidget } from './GalleryWidgetContext';@@ -71,6 +72,7 @@ export const GalleryWideLayout = () => {<Box flex="1" maxW="22rem" minW="9rem"><GalleryItemSearch /></Box>+ <GalleryStarredFilterToggle /><GalleryItemSortMenu /><GalleryUploadButtonboards={gallery.boards}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex 249b95b07b..f4880df489 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -30,15 +30,24 @@ export interface GalleryActions {selectItemRange: (items: GalleryItemRef[], primaryItem: GalleryItem) => void;setCompareItem: (image: GalleryImageItem | null) => void;setSearchTerm: (searchTerm: string) => void;+ /** Restricts (or releases) the listing to starred items; resets the page like a search. */+ setStarredOnly: (starredOnly: boolean) => void;/** Sets (or clears) the image-similarity query shown as a chip in the search field. */setSemanticImageQuery: (reference: GallerySemanticReference | null) => void;setView: (galleryView: GalleryView) => void;toggleItemInSelection: (item: GalleryItem, nextPrimaryItem: GalleryItem | null) => void;- updateSettings: (settings: Partial<Omit<GallerySettings, 'starredFirst'>>) => void;+ updateSettings: (settings: Partial<GallerySettings>) => void;/** Resolves with the confirmed uploads; empty when nothing landed. */uploadFiles: (files: File[]) => Promise<GalleryItem[]>;}+/** The bounded starred strip above the listing; empty whenever it does not apply. */+export interface GalleryStarredStrip {+ items: GalleryItem[];+ /** Starred items under the same filter, per the backend; 0 until known. */+ total: number;+}+export interface GalleryWidgetContextValue {gallery: GalleryStateView;actions: GalleryActions;@@ -51,6 +60,9 @@ export interface GalleryWidgetContextValue {itemActions: GalleryItemActions;/** The infinite window is full and the board holds images it cannot reach. */isWindowTruncated: boolean;+ /** Everything on hand — strip first, then the listing, without repeats — for lookups by key. */+ loadedItems: GalleryItem[];+ starredStrip: GalleryStarredStrip;projectName: string;/** Placement, used only to scope cached viewport measurements. */region: GalleryWidgetProps['region'];diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex d72e087d8b..f663465228 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -1,5 +1,7 @@+import type { GalleryItem } from '@features/gallery/core/items';import type { GalleryItemsFilter } from '@features/gallery/data/queries';+import { toGalleryItemRef } from '@features/gallery/core/items';import { getBoundedRecentImages } from '@features/gallery/core/recentImages';import { getGallerySettings } from '@features/gallery/core/settings';import { GALLERY_PAGE_SIZE, galleryItemNamesOptions } from '@features/gallery/data/queries';@@ -12,6 +14,7 @@ import { useTranslation } from 'react-i18next';import type { GalleryStateView } from './galleryStateView';import { GalleryBoardDragMonitor } from './GalleryBoardDragMonitor';+import { mergeGalleryLoadedItems } from './galleryGridLayout';import { GalleryLayout } from './GalleryLayout';import {getGalleryPage,@@ -19,6 +22,7 @@ import {getGalleryRawSelectedBoardId,getGallerySearchTerm,getGallerySemanticImageQuery,+ getGalleryStarredOnly,getGalleryStateView,getGalleryTotalImages,getGalleryView,@@ -30,9 +34,15 @@ import {type GalleryWidgetProps,type GalleryWidgetRuntime,} from './GalleryUiContext';-import { GalleryWidgetContext, type GalleryActions, type GalleryWidgetContextValue } from './GalleryWidgetContext';+import {+ GalleryWidgetContext,+ type GalleryActions,+ type GalleryStarredStrip,+ type GalleryWidgetContextValue,+} from './GalleryWidgetContext';import { useGalleryActions } from './useGalleryActions';import { useGalleryData } from './useGalleryData';+import { useGalleryStarredStrip } from './useGalleryStarredStrip';export const shouldPublishGalleryTotal = ({knownTotalImages,@@ -76,6 +86,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg} = useGalleryUi();const galleryView = getGalleryView(galleryValues);const searchTerm = getGallerySearchTerm(galleryValues);+ const starredOnly = getGalleryStarredOnly(galleryValues);const recentImages = useMemo(() => getBoundedRecentImages(galleryValues.recentImages), [galleryValues.recentImages]);const page = getGalleryPage(galleryValues);const knownTotalImages = getGalleryTotalImages(galleryValues);@@ -91,6 +102,8 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgselectedBoardId: getGalleryRawSelectedBoardId(galleryValues),semanticQuery,settings,+ // The grid partitions: starred items live in the strip above it.+ starred: starredOnly,});// A failed similarity search renders exactly like an empty one ("no images@@ -124,6 +137,17 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg),[data.boards, data.isLoadingItems, data.items, galleryValues, liveFollowEnabled, liveProgressTarget, queueItems]);+ // 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,+ filter: data.filter,+ });+ const loadedItems = useMemo(+ () => mergeGalleryLoadedItems(starredStrip.items, gallery.items),+ [gallery.items, starredStrip.items]+ );const lastPublishedTotalRef = useRef<number | null>(null);const itemActionFilterIdentity = useMemo(() => JSON.stringify(data.filter), [data.filter]);const loadOrderedItemRefs = useCallback(@@ -132,9 +156,10 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgconst result = await queryClient.fetchQuery(galleryItemNamesOptions(data.filter));signal.throwIfAborted();- return result.items;+ // Navigation order: the strip's starred items, then the listing.+ return [...starredStrip.items.map(toGalleryItemRef), ...result.items];},- [data.filter, queryClient]+ [data.filter, queryClient, starredStrip.items]);const itemActionContextRef = useRef<GalleryItemActionContext | null>(null);const galleryLocationRef = useRef({ galleryView, selectedBoardId });@@ -212,7 +237,8 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidg}, [galleryCommands, page, total]);if (region === 'bottom' && presentation !== 'expanded') {- return <GalleryStatusChip count={total ?? gallery.items.length} />;+ // The listing total is unstarred-only; the strip's total is the rest.+ return <GalleryStatusChip count={(total ?? gallery.items.length) + starredStrip.total} />;}return (@@ -227,9 +253,11 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgfilter={data.filter}gallery={gallery}isWindowTruncated={data.isWindowTruncated}+ loadedItems={loadedItems}projectName={projectName}region={region}runtime={runtime}+ starredStrip={starredStrip}/></ItemActionsProvider>);@@ -240,22 +268,37 @@ const GalleryWidgetContent = ({filter,gallery,isWindowTruncated,+ loadedItems,projectName,region,runtime,+ starredStrip,}: {actions: GalleryActions;filter: GalleryItemsFilter;gallery: GalleryStateView;isWindowTruncated: boolean;+ loadedItems: GalleryItem[];projectName: string;region: GalleryWidgetProps['region'];runtime: GalleryWidgetRuntime;+ starredStrip: GalleryStarredStrip;}) => {const itemActions = useGalleryItemActions();const contextValue = useMemo<GalleryWidgetContextValue>(- () => ({ actions, filter, gallery, isWindowTruncated, itemActions, projectName, region, runtime }),- [actions, filter, gallery, isWindowTruncated, itemActions, projectName, region, runtime]+ () => ({+ actions,+ filter,+ gallery,+ isWindowTruncated,+ itemActions,+ loadedItems,+ projectName,+ region,+ runtime,+ starredStrip,+ }),+ [actions, filter, gallery, isWindowTruncated, itemActions, loadedItems, projectName, region, runtime, starredStrip]);return (diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.tsindex 0b5a3c0e8f..69b106ed72 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.test.ts@@ -5,7 +5,9 @@ import { describe, expect, it } from 'vitest';import type { GalleryQueuePlaceholder } from './galleryStateView';import {+ buildGalleryGridNavigation,buildGalleryGridRows,+ getGalleryGridNavigationStep,GALLERY_GRID_GAP_PX,GALLERY_STARRED_HEADER_HEIGHT_PX,GALLERY_STARRED_SEPARATOR_HEIGHT_PX,@@ -47,10 +49,18 @@ const buildRows = (overrides: Partial<Parameters<typeof buildGalleryGridRows>[0]isStarredOpen: true,items: [],pendingPlaceholders: [],- starredFirst: true,+ starredItems: [],+ starredTotal: 0,...overrides,});+const cellNames = (rows: ReturnType<typeof buildRows>): string[][] =>+ rows.flatMap((row) =>+ row.kind === 'cells'+ ? [row.cells.map((cell) => (cell.kind === 'item' ? cell.item.name : `placeholder:${cell.placeholder.id}`))]+ : []+ );+describe('getGalleryColumnCountForCell', () => {it('rounds to the nearest whole cell and clamps to the caller bounds', () => {const bounds = { max: 8, min: 3, targetCellPx: 72 };@@ -132,42 +142,71 @@ describe('buildGalleryGridRows', () => {expect(rows[1]?.kind === 'cells' && rows[1].cells.length).toBe(1);});- it('lifts starred items into a header-led section above the regular items', () => {+ 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('starred-1', true), createImageItem('regular-2')],+ 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].itemCount).toBe(1);+ 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', () => {+ 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 items = [createImageItem('starred-1', true), createImageItem('regular-1')];- const rows = buildRows({ isStarredOpen: false, items });+ 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 items = [createImageItem('starred-1', true), createImageItem('regular-1'), createImageItem('regular-2')];- const openKeys = buildRows({ items })- .filter((row) => row.kind === 'cells' && row.section === 'regular')- .map((row) => row.key);- const collapsedKeys = buildRows({ isStarredOpen: false, items })- .filter((row) => row.kind === 'cells' && row.section === 'regular')- .map((row) => row.key);-- expect(collapsedKeys).toEqual(openKeys);+ 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('gives every row a unique key', () => {+ it('gives every row a unique key across the header, strip, gap, placeholder, and listing rows', () => {+ const starred = createImageItem('starred-1', true);const rows = buildRows({- items: [createImageItem('starred-1', true), createImageItem('regular-1'), createImageItem('regular-2')],+ items: [createImageItem('regular-1'), createImageItem('regular-2')],pendingPlaceholders: [createPlaceholder('slot-1')],+ starredItems: [starred],+ starredTotal: 1,});const keys = rows.map((row) => row.key);@@ -185,46 +224,81 @@ describe('buildGalleryGridRows', () => {expect(oldestFirst[0]?.kind === 'cells' && oldestFirst[0].cells[0]?.kind).toBe('item');});- it('keeps starred items inline with no section chrome in a flat listing', () => {- const rows = buildRows({- items: [createImageItem('starred-1', true), createImageItem('regular-1'), createImageItem('regular-2')],- pendingPlaceholders: [createPlaceholder('slot-1')],- starredFirst: false,- });+ 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(rows.map((row) => row.kind)).toEqual(['cells', 'cells']);- expect(rows[0]?.kind === 'cells' && rows[0].cells[0]?.kind).toBe('placeholder');- expect(rows[0]?.kind === 'cells' && rows[0].cells[1]?.kind === 'item' && rows[0].cells[1].item.name).toBe(- 'starred-1'- );+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);});- it('never mixes starred and regular cells in one row', () => {- const rows = buildRows({- columnCount: 3,- items: [createImageItem('starred-1', true), createImageItem('regular-1'), createImageItem('regular-2')],- });+ 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);+ });- for (const row of rows) {- if (row.kind === 'cells') {- expect(row.cells.length).toBeLessThanOrEqual(3);- }- }- expect(rows.filter((row) => row.kind === 'cells')).toHaveLength(2);+ 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 items = [createImageItem('starred-1', true), createImageItem('regular-1')];+ 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([+ expect(buildRows(items).map((row) => getGalleryGridRowHeightPx(row, 100))).toEqual([GALLERY_STARRED_HEADER_HEIGHT_PX,100,GALLERY_STARRED_SEPARATOR_HEIGHT_PX,100,]);- expect(buildRows({ isStarredOpen: false, items }).map((row) => getGalleryGridRowHeightPx(row, 100))).toEqual([+ expect(buildRows({ ...items, isStarredOpen: false }).map((row) => getGalleryGridRowHeightPx(row, 100))).toEqual([GALLERY_STARRED_HEADER_HEIGHT_PX,GALLERY_GRID_GAP_PX,100,@@ -233,14 +307,17 @@ describe('getGalleryGridRowHeightPx', () => {});describe('getGalleryGridRowIndexForItem', () => {- it('finds the row holding an item by its index in the source list, across sections', () => {+ it('finds the row holding a navigation index, across sections', () => {+ const starred = createImageItem('starred-1', true);const rows = buildRows({- items: [createImageItem('regular-1'), createImageItem('starred-1', true), createImageItem('regular-2')],+ items: [createImageItem('regular-1'), createImageItem('regular-2'), createImageItem('regular-3')],+ starredItems: [starred],+ starredTotal: 1,});- // Item 1 is starred, so it lives in the starred row despite its list position.- expect(getGalleryGridRowIndexForItem(rows, 1)).toBe(1);- expect(getGalleryGridRowIndexForItem(rows, 2)).toBe(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);});});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.tsindex a6110f8114..35e57b9aa4 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryGridLayout.ts@@ -75,7 +75,95 @@ export type GalleryGridSection = 'regular' | 'starred';export type GalleryGridRow =| { cells: GalleryGridCell[]; key: string; kind: 'cells'; section: GalleryGridSection }| { key: string; kind: 'starred-gap'; withSeparator: boolean }- | { itemCount: number; key: string; kind: 'starred-header' };+ | { key: string; kind: 'starred-header'; shownCount: number; total: number };++/** 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[] =>+ 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.+ */+export const mergeGalleryLoadedItems = (+ starredItems: readonly GalleryItem[],+ items: readonly GalleryItem[]+): GalleryItem[] => {+ if (starredItems.length === 0) {+ return items as GalleryItem[];+ }++ const seen = new Set(starredItems.map(toGalleryItemKey));++ 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 =>cell.kind === 'placeholder' ? `placeholder:${cell.placeholder.id}` : toGalleryItemKey(cell.item);@@ -108,9 +196,10 @@ const chunkGalleryCellsIntoRows = (};/**- * 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.+ * The grid's row model in one pure pass: the bounded starred strip gets a+ * disclosure section above the listing, the listing chunks in order, and+ * placeholders slot in where their images will land. Cell indices follow+ * `buildGalleryGridNavigation`.*/export const buildGalleryGridRows = ({columnCount,@@ -118,35 +207,30 @@ export const buildGalleryGridRows = ({isStarredOpen,items,pendingPlaceholders,- starredFirst,+ starredItems,+ starredTotal,}: {columnCount: number;imageOrderDir: GalleryOrderDir;isStarredOpen: boolean;- items: GalleryItem[];- pendingPlaceholders: GalleryQueuePlaceholder[];- starredFirst: boolean;+ items: readonly GalleryItem[];+ pendingPlaceholders: readonly GalleryQueuePlaceholder[];+ starredItems: readonly GalleryItem[];+ starredTotal: number;}): GalleryGridRow[] => {- const regularItemCells: GalleryGridCell[] = [];- const regularItems: GalleryItem[] = [];- const starredItemCells: GalleryGridCell[] = [];-- items.forEach((item, itemIndex) => {- const cell: GalleryGridCell = { item, itemIndex, kind: 'item' };-- if (starredFirst && item.starred) {- starredItemCells.push(cell);- } else {- regularItemCells.push(cell);- regularItems.push(item);- }- });-+ 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 placeholderCells: GalleryGridCell[] = pendingPlaceholders.map((placeholder) => ({kind: 'placeholder',placeholder,}));- const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(regularItems, imageOrderDir, starredFirst);+ const placeholderInsertionIndex = getGalleryPlaceholderInsertionIndex(items.length, imageOrderDir);const regularCells = [...regularItemCells.slice(0, placeholderInsertionIndex),...placeholderCells,@@ -154,11 +238,11 @@ export const buildGalleryGridRows = ({];const rows: GalleryGridRow[] = [];- if (starredItemCells.length > 0) {- rows.push({ itemCount: starredItemCells.length, key: 'starred-header', kind: 'starred-header' });+ if (stripItems.length > 0) {+ rows.push({ key: 'starred-header', kind: 'starred-header', shownCount, total: starredTotal });if (isStarredOpen) {- rows.push(...chunkGalleryCellsIntoRows(starredItemCells, columnCount, 'starred'));+ rows.push(...chunkGalleryCellsIntoRows(starredCells, columnCount, 'starred'));}if (regularCells.length > 0) {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex a1ab0c2408..93fce51494 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -10,6 +10,7 @@ import {getGalleryGenerationSequence,getGalleryLiveSlots,getGallerySelectedBoardId,+ getGallerySelectedImageQuery,getGallerySemanticImageQuery,getGalleryStateView,} from './galleryStateView';@@ -185,8 +186,13 @@ describe('gallery state view', () => {});});- it('parses persisted gallery settings with safe defaults and ignores a persisted starredFirst', () => {- const gallery = getGalleryStateView({ boardOrderBy: 'board_name', starredFirst: false }, boards, [], false);+ it('parses persisted gallery settings with safe defaults', () => {+ const gallery = getGalleryStateView(+ { boardOrderBy: 'board_name', starredSectionCollapsed: 'yes' },+ boards,+ [],+ false+ );expect(gallery.settings).toEqual({boardOrderBy: 'board_name',@@ -203,9 +209,12 @@ describe('gallery state view', () => {showImageDimensions: false,showOtherProjectBoards: false,showPendingItems: true,- starredFirst: true,+ starredSectionCollapsed: false,thumbnailFit: 'square',});+ expect(+ getGalleryStateView({ starredSectionCollapsed: true }, boards, [], false).settings.starredSectionCollapsed+ ).toBe(true);});it('exposes comparison state only while an image selection differs from the compare image', () => {@@ -241,6 +250,7 @@ describe('gallery state view', () => {page: 2,paginationMode: 'paginated',searchTerm: '',+ starredOnly: false,},};const pageOf = (values: Record<string, unknown>, stamp: Record<string, unknown> = {}) =>@@ -259,12 +269,22 @@ describe('gallery state view', () => {expect(pageOf({}, { paginationMode: 'infinite' })).toBeNull();expect(pageOf({ imageOrderDir: 'ASC' })).toBeNull();expect(pageOf({ searchTerm: 'cats' })).toBeNull();+ expect(pageOf({ starredOnly: true })).toBeNull();+ expect(pageOf({ starredOnly: true }, { starredOnly: true })).toBe(2);expect(pageOf({ semanticImageQuery: { imageName: 'ref.png', kind: 'image' } })).toBeNull();});- it('derives starred-first from the pagination mode: sectioned infinite window, flat paginated pages', () => {- expect(getGalleryStateView({ paginationMode: 'infinite' }, boards, [], false).settings.starredFirst).toBe(true);- expect(getGalleryStateView({ paginationMode: 'paginated' }, boards, [], false).settings.starredFirst).toBe(false);+ it('reads the starred-only filter as a strict boolean and stamps it on the selection query', () => {+ expect(getGalleryStateView({ starredOnly: true }, boards, [], false).starredOnly).toBe(true);+ expect(getGalleryStateView({ starredOnly: 'true' }, boards, [], false).starredOnly).toBe(false);+ expect(getGalleryStateView({}, boards, [], false).starredOnly).toBe(false);++ // The stamp wins over the live value: navigation walks the listing the+ // selection was made in, not the one the grid has since switched to.+ expect(+ getGallerySelectedImageQuery({ selectedImageQuery: { starredOnly: true }, starredOnly: false })+ ).toMatchObject({ starredOnly: true });+ expect(getGallerySelectedImageQuery({ starredOnly: true })).toMatchObject({ starredOnly: true });});it('qualifies legacy names and preserves ordered mixed-media selection keys', () => {@@ -559,10 +579,14 @@ describe('gallery state view', () => {expect(getPendingPlaceholders(queueItems, { selectedBoardId: 'board-1' })).toEqual([]);});- it('hides placeholders while searching or browsing assets', () => {+ it('hides placeholders while searching, browsing assets, or filtering to starred items', () => {const queueItems = [createQueueItem({ boardId: 'none', status: 'pending' })];expect(getPendingPlaceholders(queueItems, { searchTerm: 'cat', selectedBoardId: 'none' })).toEqual([]);+ expect(getPendingPlaceholders(queueItems, { selectedBoardId: 'none', starredOnly: true })).toEqual([]);+ expect(+ getGalleryStateView({ selectedBoardId: 'none', starredOnly: true }, boards, [], false, queueItems).currentItem+ ).toBeNull();expect(getPendingPlaceholders(queueItems, { galleryView: 'assets', selectedBoardId: 'none' })).toEqual([]);expect(getGalleryStateView({ selectedBoardId: 'none' }, boards, [], false, queueItems).pendingPlaceholdersdiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex f413f25c1a..24db5dde6d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -105,6 +105,8 @@ export interface GalleryStateView {/** Active image-similarity query, rendered as a chip in place of the search text. */semanticImageQuery: GallerySemanticReference | null;settings: GallerySettings;+ /** The listing is restricted to starred items. */+ starredOnly: boolean;}interface SortableGalleryQueueSlot {@@ -113,29 +115,9 @@ interface SortableGalleryQueueSlot {submittedAt: string;}-interface GalleryOrderImage {- starred?: boolean;-}--// 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,- starredFirst: boolean-): number => {- if (imageOrderDir !== 'DESC') {- return images.length;- }-- if (!starredFirst) {- return 0;- }-- const firstUnstarredIndex = images.findIndex((image) => !image.starred);-- return firstUnstarredIndex === -1 ? images.length : firstUnstarredIndex;-};+// Newest-first placeholders land at the top; oldest-first listings take them at the end.+export const getGalleryPlaceholderInsertionIndex = (itemCount: number, imageOrderDir: GalleryOrderDir): number =>+ imageOrderDir === 'DESC' ? 0 : itemCount;export const getGalleryGenerationSequence = (queueItems: QueueItem[],@@ -252,6 +234,9 @@ export const getGalleryView = (values: Record<string, unknown>): GalleryView =>export const getGallerySearchTerm = (values: Record<string, unknown>): string =>typeof values.searchTerm === 'string' ? values.searchTerm : '';+/** The starred-only listing filter; a session value kept beside `searchTerm`. */+export const getGalleryStarredOnly = (values: Record<string, unknown>): boolean => values.starredOnly === true;+export const getGallerySemanticImageQuery = (values: Record<string, unknown>): GallerySemanticReference | null =>parseGallerySemanticReference(values.semanticImageQuery);@@ -311,6 +296,7 @@ export interface GallerySelectedImageQuery {page: number;paginationMode: 'infinite' | 'paginated';searchTerm: string;+ starredOnly: boolean;}export const getGallerySelectedImageQuery = (values: Record<string, unknown>): GallerySelectedImageQuery => {@@ -344,6 +330,7 @@ export const getGallerySelectedImageQuery = (values: Record<string, unknown>): G? query.paginationMode: settings.paginationMode,searchTerm: query && typeof query.searchTerm === 'string' ? query.searchTerm : String(values.searchTerm ?? ''),+ starredOnly: query && typeof query.starredOnly === 'boolean' ? query.starredOnly : getGalleryStarredOnly(values),};};@@ -424,6 +411,7 @@ export const getGalleryStateView = (const galleryView = getGalleryView(values);const settings = getGallerySettings(values);const searchTerm = getGallerySearchTerm(values);+ const starredOnly = getGalleryStarredOnly(values);const boards = backendBoards.length? backendBoards: [@@ -445,7 +433,8 @@ export const getGalleryStateView = (const generationSequence = getGalleryGenerationSequence(queueItems, liveTarget);// A ranked similarity result has no chronological insertion point, so// pending placeholders (which stand in for images-to-come) are hidden while- // a semantic query is active — exactly as they are for a text search.+ // a semantic query is active — exactly as they are for a text search, and+ // for the starred-only filter, which a fresh generation never matches.const semanticImageQuery = getGallerySemanticImageQuery(values);const page = getGalleryPage(values);const isAnchoredInfiniteWindow = settings.paginationMode === 'infinite' && page > 0;@@ -455,6 +444,7 @@ export const getGalleryStateView = (galleryView === 'images' &&searchTerm.trim() === '' &&semanticImageQuery === null &&+ !starredOnly &&showsIncomingItemLanding? generationSequence.liveSlot?.boardId === selectedBoardId? generationSequence.liveSlot@@ -474,7 +464,8 @@ export const getGalleryStateView = (selectedImageQuery.boardId === selectedBoardId &&selectedImageQuery.galleryView === galleryView &&selectedImageQuery.imageOrderDir === settings.imageOrderDir &&- selectedImageQuery.searchTerm === searchTerm+ selectedImageQuery.searchTerm === searchTerm &&+ selectedImageQuery.starredOnly === starredOnly? selectedImageQuery.page: null;@@ -489,7 +480,7 @@ export const getGalleryStateView = (isLoading,page,pendingPlaceholders:- settings.showPendingItems && semanticImageQuery === null && showsIncomingItemLanding+ settings.showPendingItems && semanticImageQuery === null && !starredOnly && showsIncomingItemLanding? getVisibleGalleryQueuePlaceholders(generationSequence.chronologicalSlots, {galleryView,imageOrderDir: settings.imageOrderDir,@@ -508,6 +499,7 @@ export const getGalleryStateView = (: selectedItemKeys,semanticImageQuery,settings,+ starredOnly,};};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts b/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.tsindex 656fd710ec..58cd523d6f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/useGalleryPickerScope.ts@@ -39,7 +39,7 @@ export const useGalleryPickerScope = () => {}));const deferredSearchTerm = useDeferredValue(scope.searchTerm);const settings = useMemo<GallerySettings>(- () => ({ ...getGallerySettings(galleryValues), paginationMode: 'infinite', starredFirst: true }),+ () => ({ ...getGallerySettings(galleryValues), paginationMode: 'infinite' }),[galleryValues]);const data = useGalleryData({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 107089d36a..124cfba4d7 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@@ -172,6 +172,7 @@ const adapter: GalleryUiAdapter = {setPage: noop,setPageInfo: noop,setSearchTerm: noop,+ setStarredOnly: noop,setView: noop,toggleItemSelection: noop,updateSettings: noop,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex f98527bc4a..e33ade2aa0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -205,6 +205,7 @@ export const useGalleryActions = ({selectItemRange: (items, primaryItem) => gallery.setItemMultiSelection(items.map(toGalleryItemKey), primaryItem),setCompareItem: gallery.setCompareItem,setSearchTerm: gallery.setSearchTerm,+ setStarredOnly: gallery.setStarredOnly,// The similarity reference is widget state rather than a workbench// command: it patches the gallery widget's persisted values, the same// surface the parsed query is read back from. Changing the query resetsdiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.tsindex b505ce47fe..dd01f943cf 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts@@ -27,7 +27,6 @@ const filter = {galleryView: 'images' as const,orderDir: 'DESC' as const,searchTerm: '',- starredFirst: false,};const createBackendItem = (name: string, createdAt: string): GalleryItem => ({@@ -45,7 +44,7 @@ const createBackendItem = (name: string, createdAt: string): GalleryItem => ({});describe('mergeGalleryItemWindow', () => {- it('deduplicates by qualified key and mirrors server starred/time/kind/name ordering', () => {+ it('deduplicates by qualified key and mirrors server time/kind/name ordering', () => {const image = {boardId: 'none',category: 'general',@@ -68,7 +67,7 @@ describe('mergeGalleryItemWindow', () => {const recent = asGenerated(createImage(99, {imageName: 'recent',- queuedAt: image.createdAt,+ queuedAt: '2026-07-30T12:00:01.000Z',starred: true,}));@@ -76,7 +75,7 @@ describe('mergeGalleryItemWindow', () => {expect(mergeGalleryItemWindow({backendItems: [image, video, image],- filter: { ...filter, starredFirst: true },+ filter,maxRows: 60,recentImages: [recent],}).map(({ kind, name }) => `${kind}:${name}`)@@ -124,6 +123,32 @@ describe('mergeGalleryItemWindow', () => {).toEqual(['oldest.png', 'newest.png', 'middle.png']);});+ it('overlays recents onto the unstarred listing only, and never a recent that has since been starred', () => {+ const backend = createBackendItem('backend.png', '2026-01-01T00:00:00.000Z');+ const fresh = asGenerated(createImage(1));+ const starredSince = asGenerated(createImage(2, { starred: true }));++ expect(+ mergeGalleryItemWindow({+ backendItems: [backend],+ filter: { ...filter, starred: false },+ maxRows: 60,+ recentImages: [fresh, starredSince],+ }).map((item) => item.name)+ ).toEqual([fresh.imageName, backend.name]);++ const starred = { ...createBackendItem('starred.png', '2026-01-01T00:00:00.000Z'), starred: true };++ expect(+ mergeGalleryItemWindow({+ backendItems: [starred],+ filter: { ...filter, starred: true },+ maxRows: 60,+ recentImages: [fresh],+ })+ ).toEqual([starred]);+ });+it('places an overlaid recent by its instant, not by timestamp shape, against backend items', () => {// Backend rows carry SQLite `created_at` ("2026-08-29 13:01:20.649"); the// overlay carries the queue's ISO `submittedAt`. The overlaid recent isdiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.tsindex 7d76dfaeb5..4afc199156 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts@@ -58,10 +58,15 @@ const useGalleryBoards = ({ settings }: { settings: GallerySettings }) => {};const isRecentItemVisible = (item: GalleryItem, filter: GalleryItemsFilter): boolean => {+ // A recent belongs to the unstarred listing (the grid); the starred-only+ // listing has no slot for it — exactly like a text search — and a recent+ // starred since it landed has moved to the strip.if (filter.searchTerm !== '' ||filter.createdFrom !== undefined ||filter.createdTo !== undefined ||+ filter.starred === true ||+ (filter.starred === false && item.starred) ||Boolean(filter.semanticQuery) ||isDateBoardId(filter.boardId)) {@@ -110,7 +115,7 @@ export const mergeGalleryItemWindow = ({// destroy; the backend order is the meaning of the list. (No recent items// are overlaid in that mode, so the merge is the backend window itself.)if (!filter.semanticQuery) {- mergedItems.sort((a, b) => compareGalleryItems(a, b, filter));+ mergedItems.sort((a, b) => compareGalleryItems(a, b, { orderDir: filter.orderDir }));}return mergedItems.slice(0, maxRows);@@ -148,6 +153,7 @@ export const useGalleryData = ({selectedBoardId,semanticQuery = null,settings,+ starred,}: {galleryView: GalleryView;page: number;@@ -158,6 +164,12 @@ export const useGalleryData = ({/** When set, items come from semantic search (similarity order) instead of the board listing. */semanticQuery?: GallerySemanticReference | null;settings: GallerySettings;+ /**+ * Partition to list: the grid asks for unstarred (`false`) or, under its+ * starred filter, starred (`true`); consumers like the picker omit it and+ * see everything.+ */+ starred?: boolean;}): GalleryData => {const { boards } = useGalleryBoards({ settings });const boardId = resolveGallerySelectedBoardId({ projectBoardId, selectedBoardId }, boards);@@ -172,7 +184,7 @@ export const useGalleryData = ({orderDir: settings.imageOrderDir,searchTerm: dateParse.text,...(semanticQuery ? { semanticQuery } : {}),- starredFirst: settings.starredFirst,+ ...(starred !== undefined ? { starred } : {}),}),[boardId,@@ -182,7 +194,7 @@ export const useGalleryData = ({galleryView,semanticQuery,settings.imageOrderDir,- settings.starredFirst,+ starred,]);const {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.tsindex b1bfe862d0..4fc0e990f5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridHotkeys.ts@@ -1,14 +1,15 @@-import type { GalleryItemRef } from '@features/gallery/core/items';+import type { GalleryItem, GalleryItemRef } from '@features/gallery/core/items';import { shouldStarSelection, toGalleryItemKey, toGalleryItemRef } from '@features/gallery/core/items';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';-type GalleryNavDirection = 'down' | 'left' | 'right' | 'up';-const GALLERY_HOTKEYS = [['gallery.selectAllOnPage', 'widgets.gallery.commands.selectAllOnPage', null, ['mod+a']],['gallery.clearSelection', 'widgets.gallery.commands.clearSelection', null, ['esc']],@@ -22,7 +23,8 @@ const GALLERY_HOTKEYS = [['gallery.galleryNavLeftAlt', 'widgets.gallery.commands.navigationLeft', 'left', ['alt+arrowleft']],['gallery.deleteSelection', 'widgets.gallery.commands.deleteSelection', null, ['delete', 'backspace']],['gallery.starImage', 'widgets.gallery.commands.toggleStarImage', null, ['.']],-] as const satisfies readonly (readonly [string, string, GalleryNavDirection | null, readonly string[]])[];+ ['gallery.toggleStarredOnly', 'widgets.gallery.commands.toggleStarredOnly', null, []],+] as const satisfies readonly (readonly [string, string, GalleryGridNavDirection | null, readonly string[]])[];/*** Registers the grid's commands and their default keys.@@ -34,29 +36,31 @@ const GALLERY_HOTKEYS = [export const useGalleryGridHotkeys = ({actionSelectionRefs,columnCount,+ loadedItems,+ navigation,scrollToItemIndex,}: {actionSelectionRefs: GalleryItemRef[];columnCount: number;+ /** 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;}) => {const { t } = useTranslation();const { actions, gallery, itemActions, runtime } = useGalleryWidget();const { gallery: galleryCommands } = useGalleryUi();- const navigate = useEffectEvent((direction: GalleryNavDirection) => {- const itemCount = gallery.items.length;-- if (itemCount === 0) {+ const navigate = useEffectEvent((direction: GalleryGridNavDirection) => {+ if (navigation.items.length === 0) {return;}- const selectedIndex = gallery.items.findIndex((item) => toGalleryItemKey(item) === gallery.selectedItemKey);- const fallbackIndex = selectedIndex === -1 ? 0 : selectedIndex;- const delta =- direction === 'right' ? 1 : direction === 'left' ? -1 : direction === 'down' ? columnCount : -columnCount;- const nextIndex = Math.min(itemCount - 1, Math.max(0, fallbackIndex + delta));- const nextItem = gallery.items[nextIndex];+ 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);@@ -85,7 +89,12 @@ export const useGalleryGridHotkeys = ({}if (commandId === 'gallery.starImage' && actionSelectionRefs.length > 0) {- void itemActions.setItemsStarred(actionSelectionRefs, shouldStarSelection(gallery.items, actionSelectionRefs));+ void itemActions.setItemsStarred(actionSelectionRefs, shouldStarSelection(loadedItems, actionSelectionRefs));+ return;+ }++ if (commandId === 'gallery.toggleStarredOnly' && gallery.semanticImageQuery === null) {+ actions.setStarredOnly(!gallery.starredOnly);}});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.tsindex de8f61c2fe..b06f1fbfe9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryGridSelection.ts@@ -45,7 +45,9 @@ const getGalleryItemRange = (* when the click happened.*/export const useGalleryGridSelection = () => {- const { actions, filter, gallery } = useGalleryWidget();+ // `loadedItems` includes the strip, whose starred items the listing window+ // may not hold; the context menu and ctrl-toggle must resolve those too.+ const { actions, filter, gallery, loadedItems, starredStrip } = useGalleryWidget();const queryClient = useQueryClient();const [contextMenuTarget, setContextMenuTarget] = useState<GalleryItemContextMenuTarget | null>(null);@@ -73,8 +75,8 @@ export const useGalleryGridSelection = () => {const primaryTargetItemKey = toGalleryItemKey(primaryTargetItem);- return gallery.items.some((item) => toGalleryItemKey(item) === primaryTargetItemKey) ? contextMenuTarget : null;- }, [contextMenuTarget, gallery.items]);+ return loadedItems.some((item) => toGalleryItemKey(item) === primaryTargetItemKey) ? contextMenuTarget : null;+ }, [contextMenuTarget, loadedItems]);const selectItemRange = useCallback(async (item: GalleryItem) => {@@ -123,11 +125,13 @@ export const useGalleryGridSelection = () => {}}- if (!selectFromRefs(materializedRefs)) {+ // The names list describes the listing only; a range inside the strip+ // resolves against the strip's own order.+ if (!selectFromRefs(materializedRefs) && !selectFromRefs(starredStrip.items.map(toGalleryItemRef))) {actions.selectItem(item);}},- [actions, filter, gallery.items, queryClient]+ [actions, filter, gallery.items, queryClient, starredStrip.items]);const handleThumbnailClick = useCallback(@@ -147,7 +151,7 @@ export const useGalleryGridSelection = () => {const remainingItemKeys = gallery.selectedItemKeys.filter((key) => key !== itemKey);const nextPrimaryItem =gallery.selectedItemKey === itemKey- ? (gallery.items.find(+ ? (loadedItems.find((candidate) => toGalleryItemKey(candidate) === remainingItemKeys[remainingItemKeys.length - 1]) ?? null): null;@@ -157,7 +161,7 @@ export const useGalleryGridSelection = () => {actions.selectItem(item);}},- [actions, gallery.items, gallery.selectedItemKey, gallery.selectedItemKeys, selectItemRange]+ [actions, gallery.selectedItemKey, gallery.selectedItemKeys, loadedItems, selectItemRange]);const handleThumbnailContextMenu = useCallback(@@ -167,7 +171,7 @@ export const useGalleryGridSelection = () => {if (selectedItemKeys.has(itemKey) && selectedItemKeys.size > 1) {const selectionItems = [item,- ...gallery.items.filter(+ ...loadedItems.filter((candidate) => toGalleryItemKey(candidate) !== itemKey && selectedItemKeys.has(toGalleryItemKey(candidate))),];@@ -178,7 +182,7 @@ export const useGalleryGridSelection = () => {setContextMenuTarget({ itemRefs: [toGalleryItemRef(item)], items: [item], x, y });},- [gallery.items, selectedItemKeys, selectedItemRefs]+ [loadedItems, selectedItemKeys, selectedItemRefs]);const getDragItems = useCallback(@@ -214,6 +218,7 @@ export const useGalleryGridSelection = () => {handleCloseContextMenu,handleThumbnailClick,handleThumbnailContextMenu,+ loadedItems,selectedItemKeys,syncRangeInteractionContext,};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryStarredStrip.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryStarredStrip.browser.test.tsxnew file mode 100644index 0000000000..74c0a1be3d--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryStarredStrip.browser.test.tsx@@ -0,0 +1,95 @@+import type { GalleryItem } from '@features/gallery/core/items';++import { galleryStarredStripOptions } from '@features/gallery/data/queries';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useGalleryStarredStrip } from './useGalleryStarredStrip';++vi.mock('@features/gallery/data/backend', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ // Never resolves: the cases below run entirely from the seeded cache.+ listGalleryItems: vi.fn(+ () =>+ new Promise(() => {+ /* pending */+ })+ ),+}));++const filter = { boardId: 'board-1', galleryView: 'images' as const, searchTerm: '' };+const starred: GalleryItem = {+ boardId: 'board-1',+ category: 'general',+ createdAt: '2026-07-30T00:00:00.000Z',+ fullUrl: '/full/starred.png',+ height: 64,+ isIntermediate: false,+ kind: 'image',+ name: 'starred.png',+ starred: true,+ thumbnailUrl: '/thumb/starred.png',+ width: 64,+};++const Probe = ({ enabled }: { enabled: boolean }) => {+ const strip = useGalleryStarredStrip({ enabled, filter });++ return (+ <output data-testid="strip">+ {JSON.stringify({ names: strip.items.map((item) => item.name), total: strip.total })}+ </output>+ );+};++let host: HTMLDivElement | null = null;+let root: Root | null = null;+let queryClient: QueryClient | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const renderProbe = async (enabled: boolean) => {+ await act(() =>+ root?.render(+ <QueryClientProvider client={queryClient!}>+ <Probe enabled={enabled} />+ </QueryClientProvider>+ )+ );++ return JSON.parse(host?.querySelector('[data-testid="strip"]')?.textContent ?? '{}') as {+ names: string[];+ total: number;+ };+};++beforeEach(() => {+ accountLifecycle.activate('starred-strip-hook-test');+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ // A strip page already in the cache, as after a board visit.+ queryClient.setQueryData(galleryStarredStripOptions(filter).queryKey, { items: [starred], total: 4 });+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ queryClient?.clear();+ host = null;+ root = null;+ queryClient = null;+});++describe('useGalleryStarredStrip', () => {+ it('reports the cached strip while enabled and empty the moment it is disabled', async () => {+ expect(await renderProbe(true)).toEqual({ names: ['starred.png'], total: 4 });+ // A disabled query still holds its cached data; the section must vanish+ // regardless (starred-only listing, ranked search, anchored window).+ expect(await renderProbe(false)).toEqual({ names: [], total: 0 });+ expect(await renderProbe(true)).toEqual({ names: ['starred.png'], total: 4 });+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryStarredStrip.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryStarredStrip.tsnew file mode 100644index 0000000000..8bb6d21856--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryStarredStrip.ts@@ -0,0 +1,29 @@+import type { GalleryItemsFilter } from '@features/gallery/data/queries';++import { galleryStarredStripOptions } from '@features/gallery/data/queries';+import { useQuery } from '@tanstack/react-query';+import { useMemo } from 'react';++import type { GalleryStarredStrip } from './GalleryWidgetContext';++export const EMPTY_GALLERY_STARRED_STRIP: GalleryStarredStrip = { items: [], total: 0 };++/**+ * The bounded starred strip for the listing `filter` describes. Disabled+ * strips report empty rather than their last cached page, so the section+ * leaves the grid the moment it stops applying.+ */+export const useGalleryStarredStrip = ({+ enabled,+ filter,+}: {+ enabled: boolean;+ filter: GalleryItemsFilter;+}): GalleryStarredStrip => {+ const { data } = useQuery({ ...galleryStarredStripOptions(filter), enabled });++ return useMemo(+ () => (enabled && data ? { items: data.items, total: data.total } : EMPTY_GALLERY_STARRED_STRIP),+ [data, enabled]+ );+};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 ffd48e25cf..485071ce0c 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@@ -91,6 +91,7 @@ const adapter: GalleryUiAdapter = {setPage: noop,setPageInfo: noop,setSearchTerm: noop,+ setStarredOnly: noop,setView: noop,toggleItemSelection: noop,updateSettings: noop,diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.tsindex 022855ea7b..64dd138460 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts@@ -7,8 +7,9 @@ describe('firstPartyHotkeyCatalog', () => {// 91 legacy-parity entries + `canvas.newSession` (webv2 new-canvas command,// no default keys — Task 46) + `app.openCommandPalette` (webv2-only, mod+k)// + the seven top-bar redesign commands (alt+mod+enter, mod+p, an unbound- // save, and alt+1..4) + `app.openSettings` (mod+,).- expect(firstPartyHotkeyCatalog).toHaveLength(101);+ // save, and alt+1..4) + `app.openSettings` (mod+,) + `gallery.toggleStarredOnly`+ // (webv2 starred-only listing filter, unbound).+ expect(firstPartyHotkeyCatalog).toHaveLength(102);expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invoke');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.openCommandPalette');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('canvas.mergeDown');@@ -16,6 +17,7 @@ describe('firstPartyHotkeyCatalog', () => {expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('workflows.copySelection');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.galleryNavLeft');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.remix');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.toggleStarredOnly');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('viewer.deleteImage');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invokeToOtherDestination');expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.openProjectSwitcher');diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.tsindex d03962c8bd..df65726a50 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts@@ -92,6 +92,7 @@ const implemented = new Set(['gallery.remix','gallery.selectAllOnPage','gallery.starImage',+ 'gallery.toggleStarredOnly','viewer.nextComparisonMode','viewer.deleteImage','viewer.recallAll',@@ -282,4 +283,5 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [hotkey('gallery', 'deleteSelection', ['delete', 'backspace']),hotkey('gallery', 'remix', ['r']),hotkey('gallery', 'starImage', ['.']),+ hotkey('gallery', 'toggleStarredOnly', []),];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 199793d1ce..42f4041fc4 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@@ -411,11 +411,13 @@ describe('partial image mutation outcomes', () => {starred: true,});- // Only the rejected ref flips back once the backend answers.+ // The rejected ref must reappear where it was: the cache snapshot comes+ // back and only the confirmed ref is re-applied; the store flips it back.+ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), {kind: 'star',- result: { failed: [], succeeded: [{ kind: 'image', name: 'locked.png' }] },- starred: false,+ result: { failed: [], succeeded: [{ kind: 'image', name: 'starred.png' }] },+ starred: true,});expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(2, ['image:locked.png'], { starred: false });});@@ -540,10 +542,11 @@ describe('mixed item mutation outcomes', () => {});expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(1, ['image:shared', 'video:shared'], { starred: true });+ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();expect(mocks.patchGalleryItemCaches).toHaveBeenNthCalledWith(2, expect.anything(), {kind: 'star',- result: { failed: [], succeeded: [refs[0]] },- starred: false,+ result: { failed: [], succeeded: [refs[1]] },+ starred: true,});expect(mocks.galleryPatchItems).toHaveBeenNthCalledWith(2, ['image:shared'], { starred: false });expect(mocks.galleryRemoveItems).not.toHaveBeenCalled();@@ -824,14 +827,12 @@ describe('total transport failure rollback', () => {starred: true,});- // Each item reverts to its own prior flag, not a single blanket value.+ // Each store item reverts to its own prior flag, not a single blanket+ // value; the cache restores the snapshot the optimistic patch returned.expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:was-starred.png'], { starred: true });expect(mocks.galleryPatchItems).toHaveBeenCalledWith(['image:was-unstarred.png'], { starred: false });- expect(mocks.patchGalleryItemCaches).toHaveBeenCalledWith(expect.anything(), {- kind: 'star',- result: { failed: [], succeeded: [refs[1]] },- starred: false,- });+ expect(mocks.patchGalleryItemCaches).toHaveBeenCalledOnce();+ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();expect(mocks.reportError).toHaveBeenCalledOnce();expect(mocks.notificationsAdd).not.toHaveBeenCalled();@@ -862,12 +863,13 @@ describe('total transport failure rollback', () => {await getItemActions().setItemsStarred(refs, true);});- // Neither the cache nor the store restore ran: the rollback's read of- // current state never matched what this batch painted (`true`), so it- // correctly assumed something else had already written a newer value- // and left it alone instead of forcing it back to the prior flag.+ // The store restore never ran: the rollback's read of current state+ // never matched what this batch painted (`true`), so it correctly assumed+ // something else had already written a newer value and left it alone. The+ // cache side hands the same decision to the snapshot's own CAS rollback.expect(mocks.galleryPatchItems).toHaveBeenCalledOnce();expect(mocks.patchGalleryItemCaches).toHaveBeenCalledOnce();+ expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();});});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 1d7acf195e..1dff2f8206 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -541,25 +541,6 @@ export const useImageActions = ({},});};- const patchItemsStarred = (refs: GalleryItemRef[], starred: boolean): void => {- if (refs.length === 0) {- return;- }-- patchGalleryItemCaches(queryClient, { kind: 'star', result: { failed: [], succeeded: refs }, starred });- gallery.patchItems(refs.map(toGalleryItemKey), { starred });- };- // Split cache/store writers used only by the CAS-guarded rollback below,- // where the two sides can pass or fail the "still current" check- // independently (e.g. a trailing invalidation already reconciled the- // cache but the store overlay wasn't touched).- const patchStarredCacheOnly = (refs: GalleryItemRef[], starred: boolean): void => {- if (refs.length === 0) {- return;- }-- patchGalleryItemCaches(queryClient, { kind: 'star', result: { failed: [], succeeded: refs }, starred });- };const patchStarredStoreOnly = (keys: GalleryItemKey[], starred: boolean): void => {if (keys.length === 0) {return;@@ -568,10 +549,13 @@ export const useImageActions = ({gallery.patchItems(keys, { starred });};const setItemsStarred = (items: GalleryItemRef[], starred: boolean): Promise<void> => {- // Optimistic: paint the whole selection and flip back only what the- // backend refuses. A total failure cannot lean on the trailing- // invalidation, so capture each item's actual prior flag up front — a- // blanket invert would wrongly flip items that already matched.+ // Optimistic: paint the whole selection and put back only what the+ // backend refuses. The listing and the starred strip partition on the+ // flag, so a star moves items between cache windows; the cache side is+ // therefore a snapshot/restore pair with its own CAS, like delete and+ // move. The store overlay is a value flip, so it captures each item's+ // actual prior flag up front — a blanket invert would wrongly flip+ // items that already matched.const previousStarred = new Map<GalleryItemKey, boolean>([...collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items)].map(([key, fields]) => [key,@@ -583,52 +567,66 @@ export const useImageActions = ({previousStarred.set(key, cachedStarred);}- patchItemsStarred(items, starred);+ let rollbackCaches: (() => void) | null = patchGalleryItemCaches(queryClient, {+ kind: 'star',+ result: { failed: [], succeeded: items },+ starred,+ });+ const rollbackCachesOnce = () => {+ rollbackCaches?.();+ rollbackCaches = null;+ };++ patchStarredStoreOnly(items.map(toGalleryItemKey), starred);return runItemMutation({action: starred ? 'star' : 'unstar',- applyConfirmed: (result) => patchItemsStarred(result.failed, !starred),+ // Rejected refs must reappear where they were, so restore the+ // snapshot and re-apply only the confirmed ones.+ applyConfirmed: (result) => {+ if (result.failed.length === 0) {+ return;+ }++ rollbackCachesOnce();+ patchGalleryItemCaches(queryClient, {+ kind: 'star',+ result: { failed: [], succeeded: result.succeeded },+ starred,+ });+ patchStarredStoreOnly(result.failed.map(toGalleryItemKey), !starred);+ },mutate: (signal) => galleryItemOrganization.setStarred(items, starred, signal),requested: items,- // Total failure: restore each item's actual prior flag, leaving items- // with no known prior as painted. Star's optimistic apply is a value- // flip rather than a snapshot/restore pair, so unlike delete/move the- // patch carries no CAS of its own — both the cache and store writes- // need their own "still painted" check.+ // Total failure: the cache restores its snapshot; the store restores+ // each item's actual prior flag, leaving items with no known prior as+ // painted, and only where the painted value is still what is there.rollback: () => {+ rollbackCachesOnce();+const requestedKeys = items.map(toGalleryItemKey);- const currentCacheStarred = getGalleryItemStarredFromCaches(queryClient, items);const currentStoreFields = collectGalleryStoreKnownItemFields(queries.getSnapshot().projects, items);- const safeCacheKeys = new Set(- selectItemKeysUnchangedSince(requestedKeys, starred, (key) => currentCacheStarred.get(key))- );const safeStoreKeys = new Set(selectItemKeysUnchangedSince(requestedKeys, starred, (key) => currentStoreFields.get(key)?.starred));- const restoreGroups = new Map<boolean, GalleryItemRef[]>();+ const restoreGroups = new Map<boolean, GalleryItemKey[]>();for (const item of items) {- const priorStarred = previousStarred.get(toGalleryItemKey(item));+ const key = toGalleryItemKey(item);+ const priorStarred = previousStarred.get(key);- if (priorStarred === undefined) {+ if (priorStarred === undefined || !safeStoreKeys.has(key)) {continue;}const group = restoreGroups.get(priorStarred) ?? [];- group.push(item);+ group.push(key);restoreGroups.set(priorStarred, group);}- for (const [priorStarred, refs] of restoreGroups) {- patchStarredCacheOnly(- refs.filter((ref) => safeCacheKeys.has(toGalleryItemKey(ref))),- priorStarred- );- patchStarredStoreOnly(- refs.filter((ref) => safeStoreKeys.has(toGalleryItemKey(ref))).map(toGalleryItemKey),- priorStarred- );+ for (const [priorStarred, keys] of restoreGroups) {+ patchStarredStoreOnly(keys, priorStarred);}},});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsxindex e851f50bae..502b740940 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx@@ -16,7 +16,7 @@ const mocks = vi.hoisted(() => ({selectBoard: vi.fn(),selectItem: vi.fn(),setPage: vi.fn(),- settings: { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: false } as Record<string, unknown>,+ settings: { imageOrderDir: 'DESC', paginationMode: 'paginated' } as Record<string, unknown>,setView: vi.fn(),}));@@ -138,14 +138,13 @@ const namesWithImageAt = (imageName: string, index: number) => ({kind: 'image',name: position === index ? imageName : `other-${String(position)}.png`,})),- starredCount: 0,total: index + 1,});beforeEach(() => {mocks.cachedPageCount = null;mocks.galleryValues = {};- mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: false };+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };// Empty boards read as "still loading" — the reveal gives the board the// benefit of the doubt, matching the gallery's own fallback rules.mocks.fetchBoards.mockResolvedValue([]);@@ -154,7 +153,7 @@ beforeEach(() => {return Promise.resolve();});- mocks.fetchNames.mockResolvedValue({ items: [], starredCount: 0, total: 0 });+ mocks.fetchNames.mockResolvedValue({ items: [], total: 0 });mocks.registerImageCluster.mockReturnValue('cluster-key-1');});@@ -212,7 +211,7 @@ describe('useMapSelection', () => {});it('lands the gallery on the page holding the image in paginated mode', async () => {- mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: false };+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));await mount();@@ -227,7 +226,7 @@ describe('useMapSelection', () => {});it("resolves the image's position against the listing the reveal lands on", async () => {- mocks.settings = { imageOrderDir: 'ASC', paginationMode: 'paginated', starredFirst: false };+ mocks.settings = { imageOrderDir: 'ASC', paginationMode: 'paginated' };mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'a.png', imageCategory: 'general' }]);mocks.fetchNames.mockResolvedValue(namesWithImageAt('a.png', 0));await mount();@@ -239,7 +238,7 @@ describe('useMapSelection', () => {galleryView: 'images',orderDir: 'ASC',searchTerm: '',- starredFirst: false,+ starred: false,});});@@ -247,7 +246,7 @@ describe('useMapSelection', () => {// A plain prefetch is not enough: the mounted gallery keeps the query// fresh, and a fresh cache short-circuits the fetch WITHOUT honoring// the `pages` option — the window would never grow.- mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite', starredFirst: true };+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite' };mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));await mount();@@ -261,7 +260,7 @@ describe('useMapSelection', () => {});it('skips the fetch when the window already covers the image', async () => {- mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite', starredFirst: true };+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite' };mocks.cachedPageCount = 5;mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));@@ -277,7 +276,7 @@ describe('useMapSelection', () => {// The base infinite window cannot load beyond GALLERY_MAX_ROWS, so a// deeper image is revealed by anchoring the window at its page instead// of loading toward it; the mounted gallery query fetches on its own.- mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite', starredFirst: true };+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'infinite' };mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 700));await mount();@@ -296,13 +295,13 @@ describe('useMapSelection', () => {// unrelated screen of images.const names = deferred<ReturnType<typeof namesWithImageAt>>();- mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: false };+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);mocks.fetchNames.mockReturnValue(names.promise);await mount();await flush(() => handle.click?.('deep.png'));- mocks.settings = { imageOrderDir: 'ASC', paginationMode: 'paginated', starredFirst: false };+ mocks.settings = { imageOrderDir: 'ASC', paginationMode: 'paginated' };await flush(() => names.resolve(namesWithImageAt('deep.png', 130)));expect(mocks.setPage).not.toHaveBeenCalled();@@ -314,7 +313,7 @@ describe('useMapSelection', () => {// The gallery falls back to Uncategorized for a board its boards query// does not list (archived with "show archived" off); landing on the// hidden board's page number there would jump to an unrelated page.- mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: false };+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };mocks.fetchBoards.mockResolvedValue([{ id: 'board-other' }]);mocks.resolveMany.mockResolvedValue([{ boardId: 'board-archived', image_name: 'deep.png', imageCategory: 'general' },@@ -330,7 +329,7 @@ describe('useMapSelection', () => {});it('keeps the page landing when the boards lookup fails', async () => {- mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated', starredFirst: false };+ mocks.settings = { imageOrderDir: 'DESC', paginationMode: 'paginated' };mocks.fetchBoards.mockRejectedValue(new Error('boards endpoint down'));mocks.resolveMany.mockResolvedValue([{ boardId: 'board-a', image_name: 'deep.png', imageCategory: 'general' }]);mocks.fetchNames.mockResolvedValue(namesWithImageAt('deep.png', 130));@@ -350,7 +349,28 @@ describe('useMapSelection', () => {await flush(() => handle.click?.('a.png'));- expect(mocks.patchValues).toHaveBeenCalledWith('gallery', { searchTerm: '', semanticImageQuery: null });+ expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {+ searchTerm: '',+ semanticImageQuery: null,+ starredOnly: false,+ });+ });++ it('reveals a starred image in the starred listing it belongs to', async () => {+ mocks.resolveMany.mockResolvedValue([+ { boardId: 'board-a', image_name: 'a.png', imageCategory: 'general', starred: true },+ ]);+ mocks.fetchNames.mockResolvedValue(namesWithImageAt('a.png', 0));+ await mount();++ await flush(() => handle.click?.('a.png'));++ expect(mocks.fetchNames.mock.calls[0]?.[0].filter).toMatchObject({ boardId: 'board-a', starred: true });+ expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {+ searchTerm: '',+ semanticImageQuery: null,+ starredOnly: true,+ });});it('leaves the filters alone when none are active', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.tsindex cd95840c8e..777bdfefd8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts@@ -103,12 +103,15 @@ export const useMapSelection = (): MapSelectionActions => {// The board listing the gallery will show once the reveal below has// cleared any search: identical filter shape, so the name list (and// the prefetched pages) land in the cache the gallery reads.+ // The grid partitions on the flag: a starred image is revealed in+ // the starred-only listing, an unstarred one in the plain listing.+ const wantsStarredOnly = image.starred === true;const listingFilter = {boardId: image.boardId,galleryView: targetView,orderDir: settings.imageOrderDir,searchTerm: '',- starredFirst: settings.starredFirst,+ starred: wantsStarredOnly,};// The image's position within its board's ordering, which is what// lets the gallery land on the right page rather than page 0. A@@ -154,22 +157,28 @@ export const useMapSelection = (): MapSelectionActions => {const settingsNow = getGallerySettings(values);// The listing's ordering may have changed while the name list was- // in flight (sort direction, starred-first); the computed index- // describes the old ordering, so the page landing is dropped.- if (- settingsNow.imageOrderDir !== settings.imageOrderDir ||- settingsNow.starredFirst !== settings.starredFirst- ) {+ // in flight (sort direction); the computed index describes the old+ // ordering, so the page landing is dropped.+ if (settingsNow.imageOrderDir !== settings.imageOrderDir) {boardIndex = null;}const currentView: GalleryView = values.galleryView === 'assets' ? 'assets' : 'images';const hasSearch = typeof values.searchTerm === 'string' && values.searchTerm !== '';- // Filters would hide the board listing the index was computed- // against (the image may not match them), so the reveal clears them.- if (hasSearch || (values.semanticImageQuery !== null && values.semanticImageQuery !== undefined)) {- commands.widgets.patchValues('gallery', { searchTerm: '', semanticImageQuery: null });+ // Filters would hide the listing the index was computed against+ // (the image may not match them), so the reveal clears them and sets+ // the starred filter to the image's own side of the partition.+ if (+ hasSearch ||+ (values.starredOnly === true) !== wantsStarredOnly ||+ (values.semanticImageQuery !== null && values.semanticImageQuery !== undefined)+ ) {+ commands.widgets.patchValues('gallery', {+ searchTerm: '',+ semanticImageQuery: null,+ starredOnly: wantsStarredOnly,+ });}if (currentView !== targetView) {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 a9cd27c5e2..a6574a308b 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@@ -107,6 +107,7 @@ const mocks = vi.hoisted(() => {preview: { state: { values: {} }, typeId: 'preview' },},},+ galleryItemFilters: [] as Array<{ boardId: string; starred?: boolean }>,galleryItemPageOffsets: [] as number[],galleryItemWindowOffsets: [] as number[],galleryItemPages: [] as GalleryItemsPage[],@@ -148,9 +149,10 @@ vi.mock('@features/gallery/queries', () => ({data?.pages.flatMap((page) => page.items) ?? [],galleryBoardsOptions: () => ({ queryFn: () => [], queryKey: ['test-boards'], staleTime: Infinity }),galleryItemsInfiniteOptions: (- query: { boardId: string; orderDir?: 'ASC' | 'DESC' },+ query: { boardId: string; orderDir?: 'ASC' | 'DESC'; starred?: boolean },window: { kind: 'anchor' | 'infinite' | 'page'; offset?: number } = { kind: 'infinite' }) => {+ mocks.galleryItemFilters.push(query);const pages = mocks.galleryItemPages.map((page) => {const items = page.items.filter((item) => item.boardId === query.boardId);@@ -437,6 +439,7 @@ beforeEach(() => {boardId: 'none',};mocks.project.widgetInstances.gallery.state.values.selectedImageName = 'newest';+ mocks.galleryItemFilters.length = 0;mocks.galleryItemPageOffsets.length = 0;mocks.galleryItemWindowOffsets.length = 0;mocks.imageActionOptions = null;@@ -474,6 +477,28 @@ 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 () => {+ await render();++ expect(mocks.galleryItemFilters.length).toBeGreaterThan(0);+ expect(mocks.galleryItemFilters.every((query) => query.starred === false)).toBe(true);++ // 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;+ setGalleryValues({+ recentImages: mocks.recentImages.map((image) =>+ image.imageName === 'newest' ? { ...image, starred: true } : image+ ),+ selectedImage: { ...legacyImage('newest', '2026-07-23T00: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);+ });+it('handles one arrow press as exactly one selection and stops propagation', async () => {const documentKeydown = vi.fn();document.addEventListener('keydown', documentKeydown);@@ -553,6 +578,39 @@ describe('preview keyboard navigation boundary', () => {);});+ it('walks the starred-only listing the selection was made in, and keeps recents out of it', async () => {+ // The grid under the starred filter shows starred items only; Preview's+ // arrows must step through that same list, and a fresh (unstarred)+ // generation has no place in it.+ const starredNewer = { ...createImageItem('starred-newer', '2026-07-20T00:00:02.000Z'), starred: true };+ const starredOlder = { ...createImageItem('starred-older', '2026-07-20T00:00:01.000Z'), starred: true };++ setGalleryValues({+ recentImages: [legacyImage('fresh-generation', '2026-07-23T00:00:00.000Z', 'queue-item-done')],+ selectedImage: legacyImage('starred-newer', '2026-07-20T00:00:02.000Z'),+ selectedImageName: 'starred-newer',+ selectedImageQuery: { ...deepQuery, page: 0, starredOnly: true },+ starredOnly: true,+ });+ mocks.galleryItemPages = [{ items: [starredNewer, starredOlder], total: 2 }];++ await render();++ expect(mocks.galleryItemFilters.at(-1)).toMatchObject({ boardId: 'none', starred: true });+ expect(mocks.galleryItemFilters.every((query) => query.starred === true)).toBe(true);++ await pressArrow('ArrowRight');+ await pressArrow('ArrowLeft');++ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledTimes(1);+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'starred-older' }),+ undefined,+ expect.any(Number),+ true+ );+ });+it('keeps settled recents out of an infinite window anchored at a deep reveal', async () => {// A deep reveal anchors Preview's window ~1800 rows down the board. Recents// belong at the TOP of the listing: date-sorting them into a slice fromdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.tsindex 9abaf7ff5d..d36087b8a7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.test.ts@@ -57,16 +57,8 @@ describe('mergePreviewBoardItems', () => {const middle = item('image', 'middle', '2026-07-21T00:00:02.000Z');const newest = item('image', 'newest', '2026-07-21T00:00:03.000Z');- expect(mergePreviewBoardItems([newest, oldest], [middle, newest], 'DESC', { starredFirst: true })).toEqual([- newest,- middle,- oldest,- ]);- expect(mergePreviewBoardItems([oldest, newest], [middle, oldest], 'ASC', { starredFirst: true })).toEqual([- oldest,- middle,- newest,- ]);+ expect(mergePreviewBoardItems([newest, oldest], [middle, newest], 'DESC')).toEqual([newest, middle, oldest]);+ expect(mergePreviewBoardItems([oldest, newest], [middle, oldest], 'ASC')).toEqual([oldest, middle, newest]);});it('preserves relevance order for a ranked list', () => {@@ -79,17 +71,17 @@ describe('mergePreviewBoardItems', () => {const third = item('image', 'third', '2026-07-21T00:00:02.000Z');const optimistic = item('image', 'optimistic', '2026-07-21T00:00:09.000Z');- expect(mergePreviewBoardItems([first, second, third], [], 'DESC', { isRanked: true, starredFirst: true })).toEqual([+ expect(mergePreviewBoardItems([first, second, third], [], 'DESC', { isRanked: true })).toEqual([first,second,third,]);- // Without the flag the same input is re-sorted (starred first, then- // newest) and the optimistic item is spliced in, so the ranked path really- // is what preserves the list.- expect(mergePreviewBoardItems([first, second, third], [optimistic], 'DESC', { starredFirst: true })).toEqual([- second,+ // Without the flag the same input is re-sorted newest-first and the+ // optimistic item is spliced in, so the ranked path really is what+ // preserves the list.+ expect(mergePreviewBoardItems([first, second, third], [optimistic], 'DESC')).toEqual([optimistic,+ second,third,first,]);@@ -103,40 +95,19 @@ describe('mergePreviewBoardItems', () => {const ranked = item('image', 'ranked', '2026-07-21T00:00:01.000Z');const outsider = item('image', 'outsider', '2026-07-21T00:00:09.000Z');- expect(mergePreviewBoardItems([ranked], [outsider], 'DESC', { isRanked: true, starredFirst: true })).toEqual([- outsider,- ranked,- ]);+ expect(mergePreviewBoardItems([ranked], [outsider], 'DESC', { isRanked: true })).toEqual([outsider, ranked]);// Already a member: kept once, in its ranked position.- expect(mergePreviewBoardItems([ranked], [ranked], 'DESC', { isRanked: true, starredFirst: true })).toEqual([- ranked,- ]);+ expect(mergePreviewBoardItems([ranked], [ranked], 'DESC', { isRanked: true })).toEqual([ranked]);});- it('keeps starred backend items ahead of optimistic unstarred items', () => {- const starred = item('video', 'starred', '2026-07-21T00:00:01.000Z', true);- const optimistic = item('image', 'optimistic', '2026-07-21T00:00:03.000Z');- const existing = item('video', 'existing', '2026-07-21T00:00:02.000Z');-- expect(mergePreviewBoardItems([starred, existing], [optimistic], 'DESC', { starredFirst: true })).toEqual([- starred,- optimistic,- existing,- ]);- });-- it('merges chronologically past starred items in a flat listing', () => {- // Paginated pages are flat: navigation must walk the same order the grid+ it('merges chronologically past starred items', () => {+ // The listing is flat: navigation must walk the same order the grid// shows, not lift starred items to the front.const starred = item('video', 'starred', '2026-07-21T00:00:01.000Z', true);const optimistic = item('image', 'optimistic', '2026-07-21T00:00:03.000Z');const existing = item('video', 'existing', '2026-07-21T00:00:02.000Z');- expect(mergePreviewBoardItems([starred, existing], [optimistic], 'DESC', { starredFirst: false })).toEqual([- optimistic,- existing,- starred,- ]);+ expect(mergePreviewBoardItems([starred, existing], [optimistic], 'DESC')).toEqual([optimistic, existing, starred]);});it('uses the server kind/name tie-breakers for equal timestamps in both directions', () => {@@ -146,13 +117,8 @@ describe('mergePreviewBoardItems', () => {const videoA = item('video', 'a', createdAt);const videoZ = item('video', 'z', createdAt);- expect(mergePreviewBoardItems([videoA, imageZ], [videoZ, imageA], 'ASC', { starredFirst: true })).toEqual([- imageA,- imageZ,- videoA,- videoZ,- ]);- expect(mergePreviewBoardItems([imageA, videoZ], [imageZ, videoA], 'DESC', { starredFirst: true })).toEqual([+ expect(mergePreviewBoardItems([videoA, imageZ], [videoZ, imageA], 'ASC')).toEqual([imageA, imageZ, videoA, videoZ]);+ expect(mergePreviewBoardItems([imageA, videoZ], [imageZ, videoA], 'DESC')).toEqual([videoZ,videoA,imageZ,@@ -170,7 +136,7 @@ describe('mergePreviewBoardItems', () => {backend[GALLERY_MAX_ROWS - 1] = item('image', 'shared', new Date((GALLERY_MAX_ROWS - 1) * 1_000).toISOString());optimistic[0] = item('video', 'shared', new Date((GALLERY_MAX_ROWS + 1) * 1_000).toISOString());- const merged = mergePreviewBoardItems(backend, optimistic, 'DESC', { starredFirst: true });+ const merged = mergePreviewBoardItems(backend, optimistic, 'DESC');expect(merged).toHaveLength(GALLERY_MAX_ROWS);expect(merged[0]?.name).toBe('optimistic-59');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.tsindex 754eaa135e..474d4a0226 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.test.ts@@ -37,7 +37,6 @@ const buildSequence = (overrides: Partial<Parameters<typeof getPreviewNavigationboardImages: [item('image', 'newest'), item('video', 'middle'), item('image', 'oldest')],galleryView: 'images',imageOrderDir: 'DESC',- starredFirst: true,...overrides,});@@ -55,53 +54,16 @@ describe('getPreviewNavigationSequence', () => {]);});- it('places the placeholder after the leading starred block when starred-first sorts descending', () => {- expect(- keys(- buildSequence({- boardImages: [- item('video', 'starred-a', true),- item('image', 'starred-b', true),- item('image', 'newest'),- item('video', 'oldest'),- ],- })- )- ).toEqual(['video:starred-a', 'image:starred-b', 'placeholder', 'image:newest', 'video:oldest']);- });-- it('places the placeholder first in a flat descending listing even when starred items lead it', () => {+ it('places the placeholder first in a descending listing even when starred items lead it', () => {expect(keys(buildSequence({boardImages: [item('image', 'starred-newest', true), item('image', 'older')],- starredFirst: false,}))).toEqual(['placeholder', 'image:starred-newest', 'image:older']);});- it('places the placeholder last when every item is starred', () => {- expect(- keys(- buildSequence({- boardImages: [item('image', 'starred-a', true), item('video', 'starred-b', true)],- })- )- ).toEqual(['image:starred-a', 'video:starred-b', 'placeholder']);- });-- it('keeps the placeholder last in ascending order even with starred-first', () => {- expect(- keys(- buildSequence({- boardImages: [item('video', 'starred-a', true), item('image', 'newest')],- imageOrderDir: 'ASC',- })- )- ).toEqual(['video:starred-a', 'image:newest', 'placeholder']);- });-it('excludes the placeholder when it belongs to another board or the assets view', () => {expect(keys(buildSequence({ boardId: 'board-2' }))).toEqual(['image:newest', 'video:middle', 'image:oldest']);expect(keys(buildSequence({ galleryView: 'assets' }))).toEqual(['image:newest', 'video:middle', 'image:oldest']);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.tsindex 18dfe06e97..84321ba471 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewNavigation.ts@@ -20,7 +20,6 @@ import { getGalleryPlaceholderInsertionIndex, toGalleryItemKey } from '@featuresinterface NavigableItem {kind: GalleryItemKind;name: string;- starred?: boolean;}export type PreviewNavigationItem<TItem extends NavigableItem> =@@ -33,7 +32,6 @@ export const getPreviewNavigationSequence = <TItem extends NavigableItem>({boardImages,galleryView,imageOrderDir,- starredFirst,}: {/** The live slot from getGalleryGenerationSequence, or null. */activePlaceholder: GalleryQueuePlaceholder | null;@@ -43,8 +41,6 @@ export const getPreviewNavigationSequence = <TItem extends NavigableItem>({boardImages: TItem[];galleryView: GalleryView;imageOrderDir: GalleryOrderDir;- /** Whether `boardImages` leads with the starred block — see isGalleryStarredFirst. */- starredFirst: boolean;}): PreviewNavigationItem<TItem>[] => {const items: PreviewNavigationItem<TItem>[] = boardImages.map((item) => ({ item, kind: 'item' }));const includePlaceholder =@@ -54,7 +50,7 @@ export const getPreviewNavigationSequence = <TItem extends NavigableItem>({return items;}- items.splice(getGalleryPlaceholderInsertionIndex(boardImages, imageOrderDir, starredFirst), 0, {+ items.splice(getGalleryPlaceholderInsertionIndex(boardImages.length, imageOrderDir), 0, {kind: 'placeholder',placeholder: activePlaceholder,});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex 80297355e6..d32771c565 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -9,12 +9,7 @@ import type { QueueItem } from '@features/queue/contracts';import type { InfiniteData } from '@tanstack/react-query';import type { KeyboardEvent } from 'react';-import {- compareGalleryItems,- gallerySemanticReferenceKey,- isGalleryStarredFirst,- toGalleryItemKey,-} from '@features/gallery/contracts';+import { compareGalleryItems, gallerySemanticReferenceKey, toGalleryItemKey } from '@features/gallery/contracts';import {flattenGalleryItemsData,GALLERY_MAX_ROWS,@@ -51,13 +46,12 @@ const flattenPreviewItems = (data: InfiniteData<GalleryItemsPage, number> | undeconst getOrderedPreviewItems = (items: GalleryItem[],imageOrderDir: 'ASC' | 'DESC',- starredFirst: boolean,inputOrder: 'display' | 'newest-first'): GalleryItem[] =>items.map((item, index) => ({ index, item })).sort((a, b) => {- const canonicalOrder = compareGalleryItems(a.item, b.item, { orderDir: imageOrderDir, starredFirst });+ const canonicalOrder = compareGalleryItems(a.item, b.item, { orderDir: imageOrderDir });if (canonicalOrder !== 0) {return canonicalOrder;@@ -79,18 +73,15 @@ const getOrderedLocalItems = ({galleryView,items,imageOrderDir,- starredFirst,}: {boardId: string;galleryView: GalleryView;items: GalleryItem[];imageOrderDir: 'ASC' | 'DESC';- starredFirst: boolean;}): GalleryItem[] =>getOrderedPreviewItems(items.filter((item) => item.boardId === boardId && getItemGalleryView(item) === galleryView),imageOrderDir,- starredFirst,'newest-first');@@ -98,7 +89,7 @@ export const mergePreviewBoardItems = (backendItems: GalleryItem[],localItems: GalleryItem[],imageOrderDir: 'ASC' | 'DESC',- { isRanked = false, starredFirst }: { isRanked?: boolean; starredFirst: boolean }+ { isRanked = false }: { isRanked?: boolean } = {}): GalleryItem[] => {const backendKeys = new Set(backendItems.map(toGalleryItemKey));@@ -121,7 +112,7 @@ export const mergePreviewBoardItems = (return backendItems.slice(0, GALLERY_MAX_ROWS);}- return getOrderedPreviewItems([...backendItems, ...missingLocalItems], imageOrderDir, starredFirst, 'display').slice(+ return getOrderedPreviewItems([...backendItems, ...missingLocalItems], imageOrderDir, 'display').slice(0,GALLERY_MAX_ROWS);@@ -188,10 +179,12 @@ export const usePreviewNavigation = ({shouldFollowLive && activePlaceholder ? activePlaceholder.boardId : selectedImageQuery.boardId;const navigationGalleryView = shouldFollowLive ? 'images' : selectedImageQuery.galleryView;const navigationOrderDir = shouldFollowLive ? imageOrderDir : selectedImageQuery.imageOrderDir;- // Live-follow watches the gallery's own listing, so its mode decides.- const navigationStarredFirst = isGalleryStarredFirst(- shouldFollowLive ? galleryPaginationMode : selectedImageQuery.paginationMode- );+ // The grid partitions starred items into its strip, so Preview walks the+ // list the selected item belongs to: the starred one for a starred item or+ // under the starred filter, the unstarred listing otherwise. Following live+ // means watching the board a (never starred) result lands in, so the+ // filter is dropped for that mode as the search is.+ const navigationStarredOnly = !shouldFollowLive && (selectedImageQuery.starredOnly || selectedItem?.starred === true);// Read from the gallery's CURRENT search, not from a copy stamped onto the// selection: the chip is a view mode, and Preview has to follow it the// moment it is set or cleared or it walks a list that is no longer on@@ -201,8 +194,8 @@ export const usePreviewNavigation = ({const navigationSemanticQuery = shouldFollowLive ? null : semanticQuery;const navigationSemanticKey = gallerySemanticReferenceKey(navigationSemanticQuery);const hasNavigationContext = shouldFollowLive || hasSelectedItem;- const navigationContextKey = `${shouldFollowLive}:${selectedItemKey ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${selectedImageQuery.searchTerm}:${navigationSemanticKey}`;- const navigationQueryKey = `${shouldFollowLive}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.searchTerm}:${navigationSemanticKey}`;+ const navigationContextKey = `${shouldFollowLive}:${selectedItemKey ?? ''}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.page}:${selectedImageQuery.searchTerm}:${navigationStarredOnly}:${navigationSemanticKey}`;+ const navigationQueryKey = `${shouldFollowLive}:${navigationBoardId}:${navigationGalleryView}:${navigationOrderDir}:${selectedImageQuery.paginationMode}:${selectedImageQuery.searchTerm}:${navigationStarredOnly}:${navigationSemanticKey}`;// Lets a boundary fetch that resolves after the user has moved on compare the// context it started in against the one now on screen, and drop its stale@@ -301,7 +294,9 @@ export const usePreviewNavigation = ({orderDir: navigationOrderDir,searchTerm: shouldFollowLive ? '' : selectedImageSearch.text,...(navigationSemanticQuery ? { semanticQuery: navigationSemanticQuery } : {}),- starredFirst: navigationStarredFirst,+ // The grid partitions: the listing is unstarred-only unless the+ // selection was made under the starred filter.+ starred: navigationStarredOnly,},navigationWindow),@@ -373,14 +368,15 @@ export const usePreviewNavigation = ({// row"; dropping a completed batch during that window made arrow keys skip// the images just generated. So local items stay unconditionally, except// where the backend window is a *subset* of the board and dedupe cannot- // help: an active search (backend-filtered, local items are not), and any- // window anchored mid-board — paginated, or the infinite window a deep+ // help: an active search or starred filter (backend-filtered, local items+ // are not), and any window anchored mid-board — paginated, or the infinite window a deep// reveal anchors — where settled recents would splice in permanently.// Recents belong at the TOP of the listing, so a window nowhere near the// top is not theirs to join; the grid draws the same line for its own// window. There, only in-flight work and the selection merge.const hasActiveSearch =- !shouldFollowLive && (selectedImageSearch.text.trim() !== '' || selectedImageSearch.range !== undefined);+ navigationStarredOnly ||+ (!shouldFollowLive && (selectedImageSearch.text.trim() !== '' || selectedImageSearch.range !== undefined));if (!hasActiveSearch && !isPaginatedWindow && deepAnchorOffset === 0) {return localItems;@@ -401,6 +397,7 @@ export const usePreviewNavigation = ({isFetchingBoardItems,isPaginatedWindow,localItems,+ navigationStarredOnly,optimisticQueueItemIds,selectedImageSearch,selectedItem,@@ -413,9 +410,8 @@ export const usePreviewNavigation = ({galleryView: navigationGalleryView,items: navigationLocalItems,imageOrderDir: navigationOrderDir,- starredFirst: navigationStarredFirst,}),- [navigationBoardId, navigationGalleryView, navigationLocalItems, navigationOrderDir, navigationStarredFirst]+ [navigationBoardId, navigationGalleryView, navigationLocalItems, navigationOrderDir]);const previewLocalBoardItems = useMemo(() => {if (@@ -442,16 +438,8 @@ export const usePreviewNavigation = ({? EMPTY_PREVIEW_ITEMS: mergePreviewBoardItems(backendBoardItems, previewMergeItems, navigationOrderDir, {isRanked: navigationSemanticQuery !== null,- starredFirst: navigationStarredFirst,}),- [- backendBoardItems,- hasNavigationContext,- navigationOrderDir,- navigationSemanticQuery,- navigationStarredFirst,- previewMergeItems,- ]+ [backendBoardItems, hasNavigationContext, navigationOrderDir, navigationSemanticQuery, previewMergeItems]);const isLoadingBoard = hasNavigationContext && isFetchingBoardItems;const navigationSequence = useMemo(@@ -465,7 +453,6 @@ export const usePreviewNavigation = ({boardImages: boardItems,galleryView: navigationGalleryView,imageOrderDir: navigationOrderDir,- starredFirst: navigationStarredFirst,}),[activePlaceholder,@@ -474,7 +461,6 @@ export const usePreviewNavigation = ({navigationGalleryView,navigationOrderDir,navigationSemanticQuery,- navigationStarredFirst,]);const navigationCursor = getPreviewNavigationCursor(navigationSequence, {@@ -528,7 +514,6 @@ export const usePreviewNavigation = ({const nextBackendBoardItems = flattenPreviewItems(result.data);const nextBoardItems = mergePreviewBoardItems(nextBackendBoardItems, previewMergeItems, navigationOrderDir, {isRanked: navigationSemanticQuery !== null,- starredFirst: navigationStarredFirst,});const nextNavigationSequence = getPreviewNavigationSequence({// Same exclusion as the render path: a ranked list has no@@ -539,7 +524,6 @@ export const usePreviewNavigation = ({boardImages: nextBoardItems,galleryView: navigationGalleryView,imageOrderDir: navigationOrderDir,- starredFirst: navigationStarredFirst,});const nextNavigationCursor = getPreviewNavigationCursor(nextNavigationSequence, {isFollowingLive: shouldFollowLive,@@ -575,7 +559,6 @@ export const usePreviewNavigation = ({navigationOrderDir,navigationSemanticQuery,navigationSequence,- navigationStarredFirst,previewMergeItems,selectedItemKey,selectPreviewItem,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 4f6d1489f9..dd302143a6 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -3971,6 +3971,57 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);});+ it('resets the page and stamps the selection query when the starred-only filter changes', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { page: 4, type: 'setGalleryPage' });+ state = workbenchReducer(state, { starredOnly: true, type: 'setGalleryStarredOnly' });++ let values = getProjectWidgetValues(getActiveProject(state), 'gallery');+ expect(values.starredOnly).toBe(true);+ expect(values.galleryPage).toBe(0);++ state = workbenchReducer(state, { item: createGalleryImageItem('starred.png'), type: 'selectGalleryItem' });+ values = getProjectWidgetValues(getActiveProject(state), 'gallery');+ expect(values.selectedImageQuery).toMatchObject({ starredOnly: true });++ // Releasing the filter is a listing change too: the page resets, and a+ // later selection is stamped against the unfiltered listing.+ state = workbenchReducer(state, { page: 2, type: 'setGalleryPage' });+ state = workbenchReducer(state, { starredOnly: false, type: 'setGalleryStarredOnly' });+ state = workbenchReducer(state, {+ itemKeys: ['image:a.png', 'image:b.png'],+ primaryItem: createGalleryImageItem('b.png'),+ type: 'setGalleryMultiSelection',+ });+ values = getProjectWidgetValues(getActiveProject(state), 'gallery');+ expect(values.galleryPage).toBe(0);+ expect(values.selectedImageQuery).toMatchObject({ starredOnly: false });+ });++ it('stamps a landing generation against the unfiltered listing', () => {+ // A fresh result is never starred, so following it means leaving the+ // starred-only listing — the stamp says so, exactly as it clears the search.+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { starredOnly: true, type: 'setGalleryStarredOnly' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];+ state = workbenchReducer(state, {+ images: [createImage('completed.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageQuery).toMatchObject({+ searchTerm: '',+ starredOnly: false,+ });+ });+it('stores selected backend board id for gallery submissions', () => {let state = createInitialWorkbenchState();diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex dbc190d0e9..494b52b8f0 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -362,7 +362,8 @@ type WorkbenchReducerAction =| { type: 'clearGallerySelection'; projectId?: string }| { type: 'setGalleryView'; galleryView: 'images' | 'assets'; projectId?: string }| { type: 'setGallerySearchTerm'; searchTerm: string; projectId?: string }- | { type: 'updateGallerySettings'; settings: Partial<Omit<GallerySettings, 'starredFirst'>>; projectId?: string }+ | { type: 'setGalleryStarredOnly'; starredOnly: boolean; projectId?: string }+ | { type: 'updateGallerySettings'; settings: Partial<GallerySettings>; projectId?: string }| { type: 'setGalleryPage'; page: number; projectId?: string }| { type: 'setGalleryPageInfo'; totalImages: number; projectId?: string }| {@@ -2923,6 +2924,7 @@ const updateGalleryWithResultImages = (project: Project, images: GeneratedImageCpage: 0,paginationMode: gallerySettings.paginationMode,searchTerm: '',+ starredOnly: false,},}: {}),@@ -4348,6 +4350,7 @@ export const __workbenchReducerInternal = (page: selectedImagePage,paginationMode: settings.paginationMode,searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',+ starredOnly: values.starredOnly === true,};const itemKey = toGalleryItemKey(action.item);@@ -4392,6 +4395,7 @@ export const __workbenchReducerInternal = (page: selectedImagePage,paginationMode: settings.paginationMode,searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',+ starredOnly: values.starredOnly === true,},};}@@ -4469,6 +4473,7 @@ export const __workbenchReducerInternal = (page: selectedImagePage,paginationMode: settings.paginationMode,searchTerm: typeof values.searchTerm === 'string' ? values.searchTerm : '',+ starredOnly: values.starredOnly === true,},};},@@ -4524,6 +4529,17 @@ export const __workbenchReducerInternal = (action.projectId);}+ case 'setGalleryStarredOnly': {+ return updateGalleryValues(+ state,+ (values) => ({+ ...values,+ galleryPage: 0,+ starredOnly: action.starredOnly,+ }),+ action.projectId+ );+ }case 'updateGallerySettings': {const resetsQuery = action.settings.imageOrderDir !== undefined || action.settings.paginationMode !== undefined;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 779f3fff3a..d2ac4aac76 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -192,6 +192,10 @@ const createCommands = (projectId,searchTerm,})),+ setStarredOnly: command('setGalleryStarredOnly', (starredOnly: boolean, projectId?: string) => ({+ projectId,+ starredOnly,+ })),setView: command('setGalleryView',(galleryView: ActionPayload<'setGalleryView'>['galleryView'], projectId?: string) => ({