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(webv2): harden browse store refresh race and template-error enrichment
joshistoasta674fd3a7681
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.tsindex df0cd2b143..5ec379464c 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts@@ -366,6 +366,53 @@ describe('workflow library entry enrichment', () => {});});+ it('refetches node definitions at most once for a page when the template load fails', async () => {+ templates.getInvocationTemplatesSnapshot.mockReturnValue({+ error: 'Node definitions unavailable.',+ status: 'error',+ templates: {},+ });+ api.listLibraryWorkflows.mockResolvedValue(+ buildPage(Array.from({ length: 6 }, (_unused, index) => buildItem(`item-${index}`)))+ );++ await browse.ensureWorkflowLibraryBrowseLoaded();+ await vi.waitFor(() => {+ expect(+ browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry) => entry.enrichment.status === 'error')+ ).toBe(true);+ });++ // One attempt for the whole batch — never one OpenAPI reparse per worker.+ expect(templates.refreshInvocationTemplates).toHaveBeenCalledTimes(1);+ expect(libraryCache.getLibraryWorkflowCached).not.toHaveBeenCalled();+ });++ it('retries entries that failed to enrich on the next refresh', async () => {+ templates.getInvocationTemplatesSnapshot.mockReturnValue({+ error: 'Node definitions unavailable.',+ status: 'error',+ templates: {},+ });+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));++ await browse.ensureWorkflowLibraryBrowseLoaded();+ await vi.waitFor(() => {+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('error');+ });++ templates.getInvocationTemplatesSnapshot.mockReturnValue({+ error: null,+ status: 'loaded',+ templates: { main_model_loader: MODEL_LOADER_TEMPLATE },+ });++ await browse.refreshWorkflowLibraryBrowse();+ await vi.waitFor(() => {+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');+ });+ });+it('drops enrichment results for entries that left the snapshot', async () => {const stalled = createDeferred<Record<string, unknown>>();api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('gone')]));@@ -438,6 +485,44 @@ describe('workflow library browse refresh', () => {expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('idle');});+ it('publishes the refreshed list when an infinite-scroll append races the refresh', async () => {+ const refreshedFirstPage = createDeferred<WorkflowLibraryPage>();+ let firstPageCalls = 0;++ api.listLibraryWorkflows.mockImplementation(({ page, perPage }: { page: number; perPage: number }) => {+ if (perPage === 1) {+ return Promise.resolve(buildPage([], { total: 0 }));+ }++ if (page > 0) {+ return Promise.resolve(buildPage([buildItem('scrolled')], { page, pages: 3, total: 4 }));+ }++ firstPageCalls += 1;++ return firstPageCalls === 1+ ? Promise.resolve(buildPage([buildItem('kept'), buildItem('deleted')], { pages: 3, total: 5 }))+ : refreshedFirstPage.promise;+ });++ await browse.ensureWorkflowLibraryBrowseLoaded();++ // A delete invalidated the cache; the user scrolls while the refresh is in flight.+ const refreshing = browse.refreshWorkflowLibraryBrowse();++ browse.loadNextWorkflowLibraryPage();+ await vi.waitFor(() => {+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(3);+ });++ refreshedFirstPage.resolve(buildPage([buildItem('kept')], { pages: 2, total: 3 }));+ await refreshing;++ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();+ expect(snapshot.entries.map((entry) => entry.item.workflow_id)).toEqual(['kept']);+ expect(snapshot.status).toBe('loaded');+ });+it('refetches every loaded page and keeps unchanged entry identities', async () => {api.listLibraryWorkflows.mockImplementation(({ page }: { page: number }) =>Promise.resolve(buildPage([buildItem(`page-${page}`)], { page, pages: 2, total: 2 }))diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.tsindex adf61ffea9..7742a207fa 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts@@ -94,20 +94,17 @@ const initialLoadFlight = createTrailingSingleFlight();const refreshFlight = createTrailingSingleFlight();/**- * Bumped by every list request. A response whose token is no longer the latest- * belongs to a filter the user has already moved on from, so it is discarded- * instead of overwriting the current page.+ * Bumped only when the filter (or the account) changes. A response tagged with+ * an older generation was requested for a view the user has moved on from, so+ * it is discarded. Two requests for the *same* filter — a cache-invalidation+ * refresh racing an infinite-scroll append — are both current, and both+ * publish: keying staleness to the request order instead would let the append+ * silently swallow the refresh that removed a deleted row.*/-let fetchToken = 0;+let filterGeneration = 0;-const nextFetchToken = (): number => {- fetchToken += 1;-- return fetchToken;-};--const isFetchCurrent = (token: number, owner: AccountScope): boolean =>- token === fetchToken && isAccountScopeCurrent(owner);+const isFilterCurrent = (generation: number, owner: AccountScope): boolean =>+ generation === filterGeneration && isAccountScopeCurrent(owner);// #region Entries@@ -136,6 +133,14 @@ const mergeEntries = (});};+/** Re-arms rows whose enrichment failed so an explicit revalidation retries them. */+const retryFailedEnrichment = (entries: readonly WorkflowLibraryEntry[]): readonly WorkflowLibraryEntry[] =>+ entries.some((entry) => entry.enrichment.status === 'error')+ ? entries.map((entry) =>+ entry.enrichment.status === 'error' ? { ...entry, enrichment: PENDING_ENRICHMENT } : entry+ )+ : entries;+const publishPage = (result: WorkflowLibraryPage, mode: 'append' | 'replace'): void => {const previous = store.getSnapshot().entries;const merged = mergeEntries(previous, result.items);@@ -158,11 +163,15 @@ const publishPage = (result: WorkflowLibraryPage, mode: 'append' | 'replace'): v/*** Templates are needed to know which inputs are model fields. They are a- * session-lived, shared load, so enrichment waits for the existing snapshot- * rather than parsing the schema per entry. A failed template load leaves the- * requirement set empty; the editor surfaces that failure on its own.+ * session-lived, shared load, so enrichment waits for one shared attempt+ * instead of parsing the schema per entry. A failed attempt is remembered:+ * `refreshInvocationTemplates` refetches and reparses the whole OpenAPI+ * document, so retrying it per entry would turn one outage into a fetch storm.+ * The memo is re-armed by an explicit refresh, a filter change, or an account+ * switch.*/let templatesFlight: Promise<void> | null = null;+let hasTemplateLoadFailed = false;const loadTemplates = async (): Promise<InvocationTemplates> => {const snapshot = getInvocationTemplatesSnapshot();@@ -171,12 +180,24 @@ const loadTemplates = async (): Promise<InvocationTemplates> => {return snapshot.templates;}+ if (hasTemplateLoadFailed) {+ throw new Error('Node definitions are unavailable.');+ }+templatesFlight ??= refreshInvocationTemplates().finally(() => {templatesFlight = null;});await templatesFlight;- return getInvocationTemplatesSnapshot().templates;+ const settled = getInvocationTemplatesSnapshot();++ if (settled.status !== 'loaded') {+ hasTemplateLoadFailed = true;++ throw new Error(settled.error ?? 'Node definitions are unavailable.');+ }++ return settled.templates;};const enrichmentQueue: string[] = [];@@ -285,32 +306,32 @@ const fetchPage = (});const loadFirstPage = async (filter: WorkflowLibraryBrowseFilter, owner: AccountScope): Promise<void> => {- const token = nextFetchToken();+ const generation = filterGeneration;try {const result = await fetchPage(filter, 0, owner);- if (isFetchCurrent(token, owner)) {+ if (isFilterCurrent(generation, owner)) {publishPage(result, 'replace');}} catch (error) {- if (isFetchCurrent(token, owner)) {+ if (isFilterCurrent(generation, owner)) {store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to load workflows.'), status: 'error' });}}};const loadMorePages = async (filter: WorkflowLibraryBrowseFilter, page: number, owner: AccountScope): Promise<void> => {- const token = nextFetchToken();+ const generation = filterGeneration;try {const result = await fetchPage(filter, page, owner);- if (isFetchCurrent(token, owner)) {+ if (isFilterCurrent(generation, owner)) {publishPage(result, 'append');}} catch (error) {- if (isFetchCurrent(token, owner)) {+ if (isFilterCurrent(generation, owner)) {store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to load more workflows.'), status: 'error' });}}@@ -373,6 +394,10 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBroconst owner = captureAccountScope();const isCategoryChanged = filter.category !== snapshot.filter.category;+ // Everything already in flight was requested for the previous filter.+ filterGeneration += 1;+ hasTemplateLoadFailed = false;+store.patchSnapshot({entries: EMPTY_ENTRIES,error: null,@@ -415,6 +440,7 @@ export const ensureWorkflowLibraryBrowseLoaded = (): Promise<void> => {const owner = captureAccountScope();const { filter } = store.getSnapshot();+ hasTemplateLoadFailed = false;store.patchSnapshot({ error: null, status: 'loading' });await Promise.all([loadFirstPage(filter, owner), loadTagCounts(filter.category, owner), probeUserTotal(owner)]);@@ -431,7 +457,10 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>}const owner = captureAccountScope();- const token = nextFetchToken();+ const generation = filterGeneration;++ // An explicit revalidation is also the retry path for a failed enrichment.+ hasTemplateLoadFailed = false;try {const results = await Promise.all(@@ -439,11 +468,11 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>);const last = results[results.length - 1];- if (last && isFetchCurrent(token, owner)) {+ if (last && isFilterCurrent(generation, owner)) {const items = results.flatMap((result) => result.items);store.patchSnapshot({- entries: mergeEntries(store.getSnapshot().entries, items),+ entries: mergeEntries(retryFailedEnrichment(store.getSnapshot().entries), items),error: null,// Deletions can shrink the library below the page the user was on.page: Math.min(page, Math.max(0, last.pages - 1)),@@ -454,7 +483,7 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>pumpEnrichment();}} catch (error) {- if (isFetchCurrent(token, owner)) {+ if (isFilterCurrent(generation, owner)) {store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to refresh workflows.'), status: 'error' });}}@@ -493,9 +522,11 @@ onWorkflowLibraryCacheInvalidated(() => {registerAccountOwnedResource({clear: () => {+ filterGeneration += 1;enrichmentQueue.length = 0;queuedWorkflowIds.clear();templatesFlight = null;+ hasTemplateLoadFailed = false;isRefreshScheduled = false;initialLoadFlight.reset();refreshFlight.reset();