Skip to content

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.

feat(webv2): keep workflow library tabs cached between visits

Josh Corbettef696290fb0e
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts
index 5ba6dd8441..15b016401b 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts
@@ -615,3 +615,95 @@ describe('workflow library user total probe', () => {
expect(api.listLibraryWorkflows.mock.calls.filter(([params]) => params.perPage === 1)).toHaveLength(1);
});
});
+
+describe('workflow library view cache', () => {
+ const userItems = [buildItem('a'), buildItem('b')];
+ const listByCategory = (items: Record<string, WorkflowLibraryListItem[]>) =>
+ api.listLibraryWorkflows.mockImplementation(({ category }: { category: string }) =>
+ Promise.resolve(buildPage(items[category] ?? []))
+ );
+ const allEnriched = () =>
+ browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry) => entry.enrichment.status === 'ready');
+
+ const browseYoursThenBrowse = async () => {
+ listByCategory({ default: [buildItem('x', { category: 'default' })], user: userItems });
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ await vi.waitFor(() => expect(allEnriched()).toBe(true));
+ const yours = browse.getWorkflowLibraryBrowseSnapshot().entries;
+
+ browse.setWorkflowLibraryBrowseFilter({ category: 'default', tag: null });
+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));
+ api.listLibraryWorkflows.mockClear();
+ libraryCache.getLibraryWorkflowCached.mockClear();
+
+ return yours;
+ };
+
+ it('returns to a view browsed moments ago at once, without refetching or re-reading its rows', async () => {
+ const yours = await browseYoursThenBrowse();
+
+ browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });
+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();
+
+ expect(snapshot.status).toBe('loaded');
+ expect(snapshot.entries).toBe(yours);
+ await flushAsyncWork();
+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();
+ expect(libraryCache.getLibraryWorkflowCached).not.toHaveBeenCalled();
+ });
+
+ it('keeps a stale view on screen while it revalidates, then merges without re-reading unchanged rows', async () => {
+ const yours = await browseYoursThenBrowse();
+ const later = Date.now() + 60_000;
+ const now = vi.spyOn(Date, 'now').mockReturnValue(later);
+ const refreshed = createDeferred<WorkflowLibraryPage>();
+ api.listLibraryWorkflows.mockReturnValueOnce(refreshed.promise);
+
+ browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });
+
+ // The cached rows stay up while the refresh is in flight.
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toBe(yours);
+ await vi.waitFor(() => expect(api.listLibraryWorkflows).toHaveBeenCalled());
+
+ refreshed.resolve(buildPage([...userItems, buildItem('c')]));
+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(3));
+
+ const entries = browse.getWorkflowLibraryBrowseSnapshot().entries;
+ expect(entries[0]).toBe(yours[0]);
+ expect(entries[1]).toBe(yours[1]);
+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(1));
+ expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledWith('c', expect.anything());
+ now.mockRestore();
+ });
+
+ it('fetches a view afresh after a library change, which can alter any view', async () => {
+ await browseYoursThenBrowse();
+
+ invalidate();
+ await flushAsyncWork();
+ api.listLibraryWorkflows.mockClear();
+
+ browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });
+
+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loading');
+ await vi.waitFor(() => expect(api.listLibraryWorkflows).toHaveBeenCalled());
+ });
+
+ it('does not keep a view that a library change outdated when it is left before its refresh lands', async () => {
+ await browseYoursThenBrowse();
+ browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });
+
+ // The change's refresh is scheduled but has not run when the user moves on.
+ invalidate();
+ browse.setWorkflowLibraryBrowseFilter({ category: 'default', tag: null });
+ await flushAsyncWork();
+ api.listLibraryWorkflows.mockClear();
+
+ browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });
+
+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loading');
+ await vi.waitFor(() =>
+ expect(api.listLibraryWorkflows).toHaveBeenCalledWith(expect.objectContaining({ category: 'user' }))
+ );
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts
index 93e89a5ee2..334fc73f5f 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts
@@ -88,6 +88,57 @@ const INITIAL_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {
const store = createExternalStore<WorkflowLibraryBrowseSnapshot>(INITIAL_SNAPSHOT);
+// #region View cache
+
+/**
+ * Views already browsed (Browse, Yours, a tag or search), kept so switching back shows them at once with their
+ * enrichment instead of refetching and re-reading every row. A view older than `VIEW_FRESH_MS` is revalidated in the
+ * background and merged in place; library mutations drop the other views.
+ */
+interface CachedBrowseView {
+ entries: readonly WorkflowLibraryEntry[];
+ fetchedAt: number;
+ page: number;
+ pages: number;
+ tagCounts: readonly WorkflowTagCount[];
+ total: number;
+}
+
+const VIEW_CACHE_LIMIT = 8;
+const VIEW_FRESH_MS = 30_000;
+const viewCache = new Map<string, CachedBrowseView>();
+/** When the current view's pages last arrived from the server. */
+let currentViewFetchedAt = 0;
+
+const getFilterKey = ({ category, search, tag }: WorkflowLibraryBrowseFilter): string =>
+ JSON.stringify([category, search, tag]);
+
+const rememberCurrentView = (): void => {
+ const { entries, filter, page, pages, status, tagCounts, total } = store.getSnapshot();
+
+ // An unfetched view is one a library change has outdated; leaving before its refresh lands must not keep it.
+ if (status !== 'loaded' || currentViewFetchedAt === 0) {
+ return;
+ }
+
+ const key = getFilterKey(filter);
+
+ viewCache.delete(key);
+ viewCache.set(key, { entries, fetchedAt: currentViewFetchedAt, page, pages, tagCounts, total });
+
+ // Maps iterate in insertion order, so the first key is the least recently left view.
+ while (viewCache.size > VIEW_CACHE_LIMIT) {
+ const oldest = viewCache.keys().next().value;
+
+ if (oldest === undefined) {
+ break;
+ }
+ viewCache.delete(oldest);
+ }
+};
+
+// #endregion
+
const initialLoadFlight = createTrailingSingleFlight();
const refreshFlight = createTrailingSingleFlight();
@@ -131,6 +182,10 @@ const publishPage = (result: WorkflowLibraryPage, mode: 'append' | 'replace'): v
const previous = store.getSnapshot().entries;
const merged = mergeEntries(previous, result.items);
+ if (mode === 'replace') {
+ currentViewFetchedAt = Date.now();
+ }
+
store.patchSnapshot({
entries: mode === 'append' ? [...previous, ...merged] : merged,
error: null,
@@ -363,7 +418,10 @@ const probeUserTotal = async (owner: AccountScope): Promise<void> => {
}
};
-/** Applies a filter patch, resets the accumulated pages, and refetches page 0. */
+/**
+ * Applies a filter patch. A view browsed before comes back from the cache at once (revalidated in the background once
+ * stale); a new one resets the accumulated pages and fetches page 0.
+ */
export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrowseFilter>): void => {
const snapshot = store.getSnapshot();
const filter = { ...snapshot.filter, ...patch };
@@ -375,10 +433,34 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBro
const owner = captureAccountScope();
const isCategoryChanged = filter.category !== snapshot.filter.category;
+ rememberCurrentView();
+
// Everything already in flight was requested for the previous filter.
filterGeneration += 1;
hasTemplateLoadFailed = false;
+ const cached = viewCache.get(getFilterKey(filter));
+
+ if (cached) {
+ currentViewFetchedAt = cached.fetchedAt;
+ store.patchSnapshot({
+ entries: cached.entries,
+ error: null,
+ filter,
+ page: cached.page,
+ pages: cached.pages,
+ status: 'loaded',
+ tagCounts: cached.tagCounts,
+ total: cached.total,
+ });
+ pumpEnrichment();
+
+ if (Date.now() - cached.fetchedAt > VIEW_FRESH_MS) {
+ void refreshWorkflowLibraryBrowse();
+ }
+ return;
+ }
+
store.patchSnapshot({
entries: EMPTY_ENTRIES,
error: null,
@@ -452,6 +534,7 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>
if (last && isFilterCurrent(generation, owner)) {
const items = results.flatMap((result) => result.items);
+ currentViewFetchedAt = Date.now();
store.patchSnapshot({
entries: mergeEntries(retryFailedEnrichment(store.getSnapshot().entries), items),
error: null,
@@ -487,6 +570,10 @@ export const useWorkflowLibraryBrowseSelector = store.useSelector;
let isRefreshScheduled = false;
onWorkflowLibraryCacheInvalidated(() => {
+ // A mutation can change any view; the current one refreshes below, the others fetch afresh when revisited.
+ viewCache.clear();
+ currentViewFetchedAt = 0;
+
if (isRefreshScheduled || store.getSnapshot().status === 'idle') {
return;
}
@@ -510,6 +597,8 @@ registerAccountOwnedResource({
templatesFlight = null;
hasTemplateLoadFailed = false;
isRefreshScheduled = false;
+ viewCache.clear();
+ currentViewFetchedAt = 0;
initialLoadFlight.reset();
refreshFlight.reset();
store.setSnapshot(INITIAL_SNAPSHOT);