Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(gallery): keep older recents out of the sparse leading rows
Josh Corbett57263f4a522d
diff --git a/invokeai/frontend/webv2/src/features/gallery/README.md b/invokeai/frontend/webv2/src/features/gallery/README.mdindex 645dda294c..f4e8c7b6e8 100644--- a/invokeai/frontend/webv2/src/features/gallery/README.md+++ b/invokeai/frontend/webv2/src/features/gallery/README.md@@ -2,7 +2,7 @@Paths are relative to the webv2 `src/` directory.-Gallery ordinary listings are Query-owned sparse pages shared by grid, picker, Preview, and deep-reveal flows. The Gallery widget's media kind (both, images, or videos) is part of the canonical listing filter, present only when restricted; the picker always lists both kinds. Page key = account lifetime + canonical listing filters + aligned absolute offset; each result keeps its authoritative total and absolute item positions so hydrated gaps never compact. Consumers own separate visible ranges and scroll anchors. Cold numbered page after page zero first requests count-only metadata, then reads only its clamped 60-item page; virtual scrolling discovers count from its first item page. Recent local completions use a temporary overlay, with listing-scoped membership evidence bounded by recent-item limit so an authoritative item does not reappear in overlay when its page is evicted. Query layer retains at most ten inactive idle pages per listing while protecting observed pages, and schedules at most four distinct page reads per QueryClient. Deep reveal resolves an item's filtered listing rank, reads its containing page, verifies item at returned absolute position, and retries that rank/page check at most once if offsets shifted. Persisted Preview selection keeps listing identity, media kind included, from when item was selected (a stamp without a media kind lists both); changing active Gallery filters does not rewrite that cursor. While a search is active, the Gallery's `searchScope` setting can widen the listing from the selected board to `ALL_READABLE_BOARDS_ID` (`all`): the caller's own unboarded items plus every non-archived board they may read, as the backend's `board_id=all` defines it. Only the listing's board id changes (`getGalleryListingBoardId`); the selected board, the auto-add board and upload destinations stay put, uploads are refused while it applies, and a selection made in it is stamped `all`, so Preview steps through the search's results. Clearing the search returns the scope to `board`. Preview re-resolves a stale item page after listing mutations; its async navigation is fenced by captured account epoch so a late page cannot stamp selection into a newer account lifetime.+Gallery ordinary listings are Query-owned sparse pages shared by grid, picker, Preview, and deep-reveal flows. The Gallery widget's media kind (both, images, or videos) is part of the canonical listing filter, present only when restricted; the picker always lists both kinds. Page key = account lifetime + canonical listing filters + aligned absolute offset; each result keeps its authoritative total and absolute item positions so hydrated gaps never compact. Consumers own separate visible ranges and scroll anchors. Cold numbered page after page zero first requests count-only metadata, then reads only its clamped 60-item page; virtual scrolling discovers count from its first item page. Recent local completions use a temporary overlay, with listing-scoped membership evidence bounded by recent-item limit so an authoritative item does not reappear in overlay when its page is evicted. Sparse viewports render that overlay as rows apart from backend slots and cannot interleave it, so they overlay only recents created after the newest loaded backend item. An older recent (such as an existing image a workflow echoed) belongs inside the backend listing range, not ahead of it; the listing places it, or the post-run gallery refresh does once its board attach lands. Query layer retains at most ten inactive idle pages per listing while protecting observed pages, and schedules at most four distinct page reads per QueryClient. Deep reveal resolves an item's filtered listing rank, reads its containing page, verifies item at returned absolute position, and retries that rank/page check at most once if offsets shifted. Persisted Preview selection keeps listing identity, media kind included, from when item was selected (a stamp without a media kind lists both); changing active Gallery filters does not rewrite that cursor. While a search is active, the Gallery's `searchScope` setting can widen the listing from the selected board to `ALL_READABLE_BOARDS_ID` (`all`): the caller's own unboarded items plus every non-archived board they may read, as the backend's `board_id=all` defines it. Only the listing's board id changes (`getGalleryListingBoardId`); the selected board, the auto-add board and upload destinations stay put, uploads are refused while it applies, and a selection made in it is stamped `all`, so Preview steps through the search's results. Clearing the search returns the scope to `board`. Preview re-resolves a stale item page after listing mutations; its async navigation is fenced by captured account epoch so a late page cannot stamp selection into a newer account lifetime.## Realtime refresh and external revealdiff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.tsindex a050b603db..353f754640 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/items.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.ts@@ -96,7 +96,7 @@ const compareSqliteBinaryText = (a: string, b: string): number => (a === b ? 0 :* Normalize SQLite and ISO timestamps before comparing; their space/T separators otherwise misorder same-day* items.*/-const compareCreatedAt = (a: string, b: string): number =>+export const compareCreatedAt = (a: string, b: string): number =>compareSqliteBinaryText(normalizeServerTimestamp(a), normalizeServerTimestamp(b));/** Mirrors the backend's time/kind/name order for mixed gallery items. */diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsxindex 230650d7cc..ab9137f711 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.browser.test.tsx@@ -809,6 +809,24 @@ describe('useGalleryData sparse page subscriptions', () => {expect(latestData?.total).toBe(TOTAL);});+ it('overlays only recents newer than the loaded backend items, keeping items and rows in agreement', async () => {+ const [olderThanBackend] = recentImages;+ const newerThanBackend: GalleryImage = {+ ...olderThanBackend!,+ createdAt: '2027-01-01T00:00:00.000Z',+ imageName: 'fresh.png',+ queuedAt: '2027-01-01T00:00:00.000Z',+ };++ await renderProbe({ recentImages: [newerThanBackend, olderThanBackend!] });+ await vi.waitFor(() => expect(latestData?.sparseListing?.itemSlots.size).toBe(60));++ expect(latestData?.sparseListing?.recentItems.map((item) => item.name)).toEqual(['fresh.png']);+ expect(latestData?.items?.some((item) => item.name === 'recent.png')).toBe(false);+ expect(latestData?.items?.filter((item) => item.name === 'fresh.png')).toHaveLength(1);+ expect(latestData?.items).toHaveLength(61);+ });+it('uses an indexed distant range while the initial page is still pending', async () => {let releaseCountDiscovery: (() => void) | undefined;mocks.listGalleryItems.mockImplementation(({ offset, limit }: { offset: number; limit: number }) => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.tsindex 248fb9d062..c3b1dde55a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts@@ -104,6 +104,37 @@ describe('getGalleryRecentItems', () => {).toEqual([]);});+ it('omits persisted recents no newer than the newest loaded backend item, in either order direction', () => {+ // Backend timestamps in SQLite form; recents in ISO form, so the cut compares instants rather than strings.+ const backendItems = [+ createBackendItem('backend-middle.png', '2026-08-29 12:00:00.000'),+ createBackendItem('backend-newest.png', '2026-08-29 13:01:20.649'),+ ];+ const recentImages = [+ asGenerated(createImage(1, { createdAt: '2026-08-29T02:28:40.566Z', imageName: 'echoed-old.png' })),+ asGenerated(createImage(2, { createdAt: '2026-08-29T13:01:20.649Z', imageName: 'same-instant.png' })),+ asGenerated(createImage(3, { createdAt: '2026-08-29T13:01:20.650Z', imageName: 'fresh.png' })),+ ];+ const namesFor = (orderDir: 'ASC' | 'DESC', items: readonly GalleryItem[]) =>+ getGalleryRecentItems({+ backendItems: items,+ filter: { ...filter, orderDir },+ omitPersisted: true,+ recentImages,+ }).map((item) => item.name);++ expect(namesFor('DESC', backendItems)).toEqual(['fresh.png']);+ expect(namesFor('ASC', backendItems)).toEqual(['fresh.png']);+ // Nothing loaded yet proves nothing persisted, so every recent stays overlaid.+ expect(namesFor('DESC', [])).toEqual(['fresh.png', 'same-instant.png', 'echoed-old.png']);+ // The dense window keeps interleaving old recents by their instant.+ expect(getGalleryRecentItems({ backendItems, filter, recentImages }).map((item) => item.name)).toEqual([+ 'fresh.png',+ 'same-instant.png',+ 'echoed-old.png',+ ]);+ });+it('hides local outputs whose media kind the listing excludes', () => {const recent = asGenerated(createImage(1, { imageName: 'recent-1.png' }));const namesFor = (mediaKind: 'image' | 'video') =>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.tsindex 66e60b66d5..eb22312668 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts@@ -3,7 +3,12 @@ import type { GallerySemanticReference } from '@features/gallery/core/semanticImimport type { GallerySearchScope, GallerySettings } from '@features/gallery/core/settings';import type { GalleryBoard, GalleryView, GeneratedImageContract } from '@features/gallery/core/types';-import { compareGalleryItems, legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery/core/items';+import {+ compareCreatedAt,+ compareGalleryItems,+ legacyGeneratedImageToGalleryItem,+ toGalleryItemKey,+} from '@features/gallery/core/items';import { GALLERY_RECENT_IMAGE_LIMIT } from '@features/gallery/core/recentImages';import { ALL_READABLE_BOARDS_ID, isDateBoardId } from '@features/gallery/data/backend';import {@@ -83,7 +88,10 @@ export interface GallerySparsePageState {export interface GallerySparseListing {itemSlots: ReadonlyMap<number, GalleryItem>;pageStates: ReadonlyMap<number, GallerySparsePageState>;- /** Project-local outputs stay in separate virtual rows and never change backend item indexes. */+ /**+ * Project-local outputs created after the newest loaded backend item. They stay in separate virtual rows and never+ * change backend item indexes.+ */recentItems: GalleryItem[];total: number | null;}@@ -172,23 +180,21 @@ const isRecentItemVisible = (item: GalleryItem, filter: GalleryItemsFilter): booreturn hasMatchingBoard && hasMatchingCategory;};-export const mergeGalleryItemWindow = ({+/** Merges an already resolved recent overlay into the backend window in listing order. */+const mergeRecentItemsIntoWindow = ({backendItems,filter,- knownBackendItemKeys,maxRows,- recentImages,+ recentItems,}: {backendItems: readonly GalleryItem[];filter: GalleryItemsFilter;- knownBackendItemKeys?: ReadonlySet<ReturnType<typeof toGalleryItemKey>>;maxRows: number;- recentImages: readonly GeneratedImageContract[];+ recentItems: readonly GalleryItem[];}): GalleryItem[] => {- const missingRecentItems = getGalleryRecentItems({ backendItems, filter, knownBackendItemKeys, recentImages });const seenItemKeys = new Set<string>();- const mergedItems = [...missingRecentItems, ...backendItems].filter((item) => {+ const mergedItems = [...recentItems, ...backendItems].filter((item) => {const key = toGalleryItemKey(item);if (seenItemKeys.has(key)) {@@ -209,19 +215,53 @@ export const mergeGalleryItemWindow = ({return mergedItems.slice(0, maxRows);};+/** Interleaves the recent overlay with the loaded backend window by listing order. */+export const mergeGalleryItemWindow = ({+ backendItems,+ filter,+ maxRows,+ recentImages,+}: {+ backendItems: readonly GalleryItem[];+ filter: GalleryItemsFilter;+ maxRows: number;+ recentImages: readonly GeneratedImageContract[];+}): GalleryItem[] =>+ mergeRecentItemsIntoWindow({+ backendItems,+ filter,+ maxRows,+ recentItems: getGalleryRecentItems({ backendItems, filter, recentImages }),+ });++const getNewestCreatedAt = (items: readonly GalleryItem[]): string | undefined =>+ items.reduce<string | undefined>(+ (newest, { createdAt }) => (newest === undefined || compareCreatedAt(createdAt, newest) > 0 ? createdAt : newest),+ undefined+ );+/** Returns the bounded local recent overlay without assigning it a backend position. */export const getGalleryRecentItems = ({backendItems,knownBackendItemKeys,filter,+ omitPersisted = false,recentImages,}: {backendItems: readonly GalleryItem[];knownBackendItemKeys?: ReadonlySet<ReturnType<typeof toGalleryItemKey>>;filter: GalleryItemsFilter;+ /**+ * Also drop recents created no later than the newest loaded backend item. Sparse viewports render recents as rows+ * apart from the backend slots and cannot interleave them, so such a recent belongs inside the backend listing range,+ * not ahead of it: the listing places it, or the post-run gallery refresh does once its board attach lands. The dense+ * window interleaves instead.+ */+ omitPersisted?: boolean;recentImages: readonly GeneratedImageContract[];}): GalleryItem[] => {const backendItemKeys = new Set(backendItems.map(toGalleryItemKey));+ const persistedThrough = omitPersisted ? getNewestCreatedAt(backendItems) : undefined;const recentItems = recentImages.slice(0, GALLERY_RECENT_IMAGE_LIMIT).map(legacyGeneratedImageToGalleryItem)@@ -229,6 +269,7 @@ export const getGalleryRecentItems = ({(item) =>!backendItemKeys.has(toGalleryItemKey(item)) &&!knownBackendItemKeys?.has(toGalleryItemKey(item)) &&+ (persistedThrough === undefined || compareCreatedAt(item.createdAt, persistedThrough) > 0) &&isRecentItemVisible(item, filter));@@ -677,44 +718,24 @@ export const useGalleryData = ({backendItems,filter,knownBackendItemKeys: reconciledBackendRecentKeys,+ omitPersisted: true,recentImages,}): [],[backendItems, filter, recentImages, reconciledBackendRecentKeys, shouldOverlayRecentItems, sparseViewport]);+ // The sparse rows render `recentItems`, so selection and navigation merge exactly that overlay.const sparseItems = useMemo(() =>- sparseViewport- ? pageResults.some((result) => result.data) || recentItems.length > 0 || knownTotal === 0- ? mergeGalleryItemWindow({- backendItems,- filter,- knownBackendItemKeys: reconciledBackendRecentKeys,- maxRows: Math.max(GALLERY_MAX_ROWS, backendItems.length + GALLERY_RECENT_IMAGE_LIMIT),- recentImages: shouldOverlayRecentItems ? recentImages : [],- })- : null- : queryData || (shouldOverlayRecentItems && recentImages.length > 0)- ? mergeGalleryItemWindow({- backendItems,- filter,- maxRows,- recentImages: shouldOverlayRecentItems ? recentImages : [],- })- : null,- [- backendItems,- filter,- knownTotal,- maxRows,- pageResults,- queryData,- recentItems.length,- recentImages,- reconciledBackendRecentKeys,- shouldOverlayRecentItems,- sparseViewport,- ]+ sparseViewport && (pageResults.some((result) => result.data) || recentItems.length > 0 || knownTotal === 0)+ ? mergeRecentItemsIntoWindow({+ backendItems,+ filter,+ maxRows: Math.max(GALLERY_MAX_ROWS, backendItems.length + GALLERY_RECENT_IMAGE_LIMIT),+ recentItems,+ })+ : null,+ [backendItems, filter, knownTotal, pageResults, recentItems, sparseViewport]);const scopedItems = useMemo(() =>