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): server-paginated workflow library browse store with lazy enrichment

joshistoast7e8fd8e61eb4
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.test.ts
new file mode 100644
index 0000000000..cd24190c61
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseWorkflowTags, sortTagCounts } from './libraryTags';
+
+describe('parseWorkflowTags', () => {
+ it('splits the comma-separated string, trimming each tag and dropping empties', () => {
+ expect(parseWorkflowTags(' lora ,upscaling,, ,sdxl ')).toEqual(['lora', 'upscaling', 'sdxl']);
+ });
+
+ it('returns an empty list for absent or blank tag strings', () => {
+ expect(parseWorkflowTags(null)).toEqual([]);
+ expect(parseWorkflowTags(undefined)).toEqual([]);
+ expect(parseWorkflowTags('')).toEqual([]);
+ expect(parseWorkflowTags(' , ')).toEqual([]);
+ });
+});
+
+describe('sortTagCounts', () => {
+ it('orders by count descending, then by tag name', () => {
+ expect(
+ sortTagCounts([
+ { count: 2, tag: 'upscaling' },
+ { count: 9, tag: 'sdxl' },
+ { count: 2, tag: 'lora' },
+ ])
+ ).toEqual([
+ { count: 9, tag: 'sdxl' },
+ { count: 2, tag: 'lora' },
+ { count: 2, tag: 'upscaling' },
+ ]);
+ });
+
+ it('drops tags with no matching workflows and leaves the input untouched', () => {
+ const counts = [
+ { count: 0, tag: 'empty' },
+ { count: 1, tag: 'lora' },
+ ] as const;
+
+ expect(sortTagCounts(counts)).toEqual([{ count: 1, tag: 'lora' }]);
+ expect(counts).toEqual([
+ { count: 0, tag: 'empty' },
+ { count: 1, tag: 'lora' },
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.ts b/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.ts
new file mode 100644
index 0000000000..cce8ca0c44
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/core/libraryTags.ts
@@ -0,0 +1,30 @@
+/**
+ * Workflow library tag helpers. The backend stores a record's tags as one
+ * comma-separated string and reports per-tag counts as a plain map, so both
+ * shapes need the same normalization everywhere they are rendered: split and
+ * trim exactly like the record service does, and drop tags no workflow in the
+ * current category carries.
+ */
+
+export interface WorkflowTagCount {
+ tag: string;
+ count: number;
+}
+
+/** Splits a record's `tags` column into trimmed, non-empty tags. */
+export const parseWorkflowTags = (tags: string | null | undefined): string[] => {
+ if (!tags) {
+ return [];
+ }
+
+ return tags
+ .split(',')
+ .map((tag) => tag.trim())
+ .filter((tag) => tag.length > 0);
+};
+
+/** Orders tag chips by how many workflows carry them, then alphabetically; empty tags are omitted. */
+export const sortTagCounts = (counts: readonly WorkflowTagCount[]): WorkflowTagCount[] =>
+ counts
+ .filter((entry) => entry.count > 0)
+ .sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag));
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts
new file mode 100644
index 0000000000..df0cd2b143
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts
@@ -0,0 +1,530 @@
+import type { InvocationTemplate } from '@features/workflow/core/types';
+import type * as accountLifecycleModule from '@platform/state/accountLifecycle';
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { WorkflowLibraryListItem, WorkflowLibraryPage } from './api';
+import type * as libraryBrowseStoreModule from './libraryBrowseStore';
+
+const api = vi.hoisted(() => ({
+ getAllWorkflowTags: vi.fn(),
+ getWorkflowTagCounts: vi.fn(),
+ listLibraryWorkflows: vi.fn(),
+}));
+
+const libraryCache = vi.hoisted(() => ({
+ getLibraryWorkflowCached: vi.fn(),
+ onWorkflowLibraryCacheInvalidated: vi.fn(),
+}));
+
+const templates = vi.hoisted(() => ({
+ getInvocationTemplatesSnapshot: vi.fn(),
+ refreshInvocationTemplates: vi.fn(),
+}));
+
+vi.mock('./api', () => api);
+vi.mock('./libraryCache', () => libraryCache);
+vi.mock('./templates', () => templates);
+
+const MODEL_LOADER_TEMPLATE: InvocationTemplate = {
+ category: 'model',
+ classification: 'stable',
+ description: '',
+ inputs: {
+ model: {
+ default: undefined,
+ description: '',
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ input: 'any',
+ maximum: null,
+ minimum: null,
+ multipleOf: null,
+ name: 'model',
+ options: null,
+ required: true,
+ title: 'Model',
+ type: { batch: false, cardinality: 'SINGLE', name: 'ModelIdentifierField' },
+ uiChoiceLabels: null,
+ uiComponent: null,
+ uiHidden: false,
+ uiModelBase: ['sdxl'],
+ uiModelFormat: null,
+ uiModelType: ['main'],
+ uiOrder: null,
+ },
+ },
+ nodePack: 'invokeai',
+ outputs: {},
+ outputType: 'model_loader_output',
+ tags: [],
+ title: 'Main Model',
+ type: 'main_model_loader',
+ useCache: true,
+ version: '1.0.0',
+};
+
+const buildItem = (workflowId: string, overrides: Partial<WorkflowLibraryListItem> = {}): WorkflowLibraryListItem => ({
+ category: 'user',
+ description: '',
+ name: `Workflow ${workflowId}`,
+ tags: 'lora, upscaling',
+ updated_at: '2026-08-18T00:00:00Z',
+ workflow_id: workflowId,
+ ...overrides,
+});
+
+const buildPage = (
+ items: WorkflowLibraryListItem[],
+ overrides: Partial<Omit<WorkflowLibraryPage, 'items'>> = {}
+): WorkflowLibraryPage => ({ items, page: 0, pages: 1, total: items.length, ...overrides });
+
+/** Minimal WorkflowV3 payload: `count` model-loader nodes, each holding a distinct model. */
+const buildRawWorkflow = (count: number): Record<string, unknown> => ({
+ edges: [],
+ name: 'Raw workflow',
+ nodes: Array.from({ length: count }, (_unused, index) => ({
+ data: {
+ inputs: {
+ model: {
+ label: '',
+ name: 'model',
+ value: { base: 'sdxl', key: `model-${index}`, name: `Model ${index}`, type: 'main' },
+ },
+ },
+ type: 'main_model_loader',
+ },
+ id: `node-${index}`,
+ position: { x: 0, y: 0 },
+ type: 'invocation',
+ })),
+});
+
+interface Deferred<T> {
+ promise: Promise<T>;
+ reject: (error: unknown) => void;
+ resolve: (value: T) => void;
+}
+
+const createDeferred = <T>(): Deferred<T> => {
+ let reject!: (error: unknown) => void;
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ reject = rejectPromise;
+ resolve = resolvePromise;
+ });
+
+ return { promise, reject, resolve };
+};
+
+/** Lets every queued microtask (and the coalesced refresh) run before asserting. */
+const flushAsyncWork = (): Promise<void> =>
+ new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+let account: typeof accountLifecycleModule;
+let browse: typeof libraryBrowseStoreModule;
+let invalidate: () => void;
+
+beforeEach(async () => {
+ vi.resetModules();
+ api.getAllWorkflowTags.mockReset().mockResolvedValue([]);
+ api.getWorkflowTagCounts.mockReset().mockResolvedValue({});
+ api.listLibraryWorkflows.mockReset().mockResolvedValue(buildPage([]));
+ libraryCache.getLibraryWorkflowCached.mockReset().mockResolvedValue(buildRawWorkflow(1));
+ libraryCache.onWorkflowLibraryCacheInvalidated.mockReset().mockImplementation((listener: () => void) => {
+ invalidate = listener;
+ return () => undefined;
+ });
+ templates.getInvocationTemplatesSnapshot
+ .mockReset()
+ .mockReturnValue({ error: null, status: 'loaded', templates: { main_model_loader: MODEL_LOADER_TEMPLATE } });
+ templates.refreshInvocationTemplates.mockReset().mockResolvedValue(undefined);
+
+ account = await import('@platform/state/accountLifecycle');
+ browse = await import('./libraryBrowseStore');
+ account.accountLifecycle.activate('user-a');
+});
+
+describe('workflow library page fetching', () => {
+ it('sends the active category, tag, and search filter to the list endpoint', async () => {
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+
+ expect(api.listLibraryWorkflows).toHaveBeenCalledWith(
+ expect.objectContaining({ category: 'user', page: 0, perPage: 20, query: undefined, tags: undefined })
+ );
+
+ api.listLibraryWorkflows.mockClear();
+ browse.setWorkflowLibraryBrowseFilter({ category: 'default', search: 'upscale', tag: 'lora' });
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');
+ });
+
+ expect(api.listLibraryWorkflows).toHaveBeenCalledWith(
+ expect.objectContaining({ category: 'default', page: 0, perPage: 20, query: 'upscale', tags: ['lora'] })
+ );
+ });
+
+ it('ignores a repeated filter patch that changes nothing', async () => {
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ api.listLibraryWorkflows.mockClear();
+
+ browse.setWorkflowLibraryBrowseFilter({ category: 'user', search: '' });
+
+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();
+ });
+
+ it('appends the next page and stops once the last page is loaded', async () => {
+ api.listLibraryWorkflows.mockImplementation(({ page }: { page: number }) =>
+ Promise.resolve(
+ buildPage([buildItem(`page-${page}-a`), buildItem(`page-${page}-b`)], { page, pages: 2, total: 4 })
+ )
+ );
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(2);
+
+ browse.loadNextWorkflowLibraryPage();
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');
+ });
+
+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();
+ expect(snapshot.entries.map((entry) => entry.item.workflow_id)).toEqual([
+ 'page-0-a',
+ 'page-0-b',
+ 'page-1-a',
+ 'page-1-b',
+ ]);
+ expect(snapshot.page).toBe(1);
+
+ api.listLibraryWorkflows.mockClear();
+ browse.loadNextWorkflowLibraryPage();
+
+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();
+ });
+
+ it('clears the accumulated pages as soon as the filter changes', async () => {
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a'), buildItem('b')], { pages: 3, total: 6 }));
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ browse.setWorkflowLibraryBrowseFilter({ tag: 'lora' });
+
+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();
+ expect(snapshot.entries).toEqual([]);
+ expect(snapshot).toMatchObject({ page: 0, pages: 0, status: 'loading', total: 0 });
+ });
+
+ it('drops a stale in-flight page when the filter changes mid-flight', async () => {
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+
+ const stale = createDeferred<WorkflowLibraryPage>();
+ api.listLibraryWorkflows.mockReturnValueOnce(stale.promise);
+ browse.setWorkflowLibraryBrowseFilter({ search: 'stale' });
+
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('fresh')]));
+ browse.setWorkflowLibraryBrowseFilter({ search: 'fresh' });
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');
+ });
+
+ stale.resolve(buildPage([buildItem('stale')]));
+ await flushAsyncWork();
+
+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();
+ expect(snapshot.entries.map((entry) => entry.item.workflow_id)).toEqual(['fresh']);
+ expect(snapshot.filter.search).toBe('fresh');
+ expect(snapshot.status).toBe('loaded');
+ });
+
+ it('records the error message when a page request fails', async () => {
+ api.listLibraryWorkflows.mockRejectedValue(new Error('backend down'));
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+
+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();
+ expect(snapshot.status).toBe('error');
+ expect(snapshot.error).toContain('backend down');
+ });
+
+ it('parses each item tag string once into the entry', async () => {
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a', { tags: ' lora , , sdxl ' })]));
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.tags).toEqual(['lora', 'sdxl']);
+ });
+});
+
+describe('workflow library tag counts', () => {
+ it('stores sorted, non-zero counts for the active category', async () => {
+ api.getAllWorkflowTags.mockResolvedValue(['lora', 'sdxl', 'unused']);
+ api.getWorkflowTagCounts.mockResolvedValue({ lora: 2, sdxl: 5, unused: 0 });
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+
+ expect(api.getAllWorkflowTags).toHaveBeenCalledWith(expect.objectContaining({ categories: ['user'] }));
+ expect(api.getWorkflowTagCounts).toHaveBeenCalledWith(
+ expect.objectContaining({ categories: ['user'], tags: ['lora', 'sdxl', 'unused'] })
+ );
+ expect(browse.getWorkflowLibraryBrowseSnapshot().tagCounts).toEqual([
+ { count: 5, tag: 'sdxl' },
+ { count: 2, tag: 'lora' },
+ ]);
+ });
+
+ it('refetches counts for the new category and not for a search-only change', async () => {
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ api.getAllWorkflowTags.mockClear();
+
+ browse.setWorkflowLibraryBrowseFilter({ search: 'cat' });
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().filter.search).toBe('cat');
+ });
+ expect(api.getAllWorkflowTags).not.toHaveBeenCalled();
+
+ browse.setWorkflowLibraryBrowseFilter({ category: 'default' });
+ await vi.waitFor(() => {
+ expect(api.getAllWorkflowTags).toHaveBeenCalledWith(expect.objectContaining({ categories: ['default'] }));
+ });
+ });
+});
+
+describe('workflow library entry enrichment', () => {
+ it('fills node count and model requirements for loaded entries', async () => {
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));
+ libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(2));
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');
+ });
+
+ const enrichment = browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment;
+ expect(enrichment).toMatchObject({ nodeCount: 2, status: 'ready' });
+ expect(enrichment?.status === 'ready' && enrichment.requirements.primaryBase).toBe('sdxl');
+ expect(enrichment?.status === 'ready' && enrichment.requirements.requirements).toHaveLength(2);
+ expect(enrichment?.status === 'ready' && enrichment.document.nodes).toHaveLength(2);
+ });
+
+ it('marks a single failed entry as an error without stalling the rest of the pool', async () => {
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('bad'), buildItem('good')]));
+ libraryCache.getLibraryWorkflowCached.mockImplementation((workflowId: string) =>
+ workflowId === 'bad' ? Promise.reject(new Error('payload gone')) : Promise.resolve(buildRawWorkflow(1))
+ );
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[1]?.enrichment.status).toBe('ready');
+ });
+
+ const failed = browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment;
+ expect(failed?.status).toBe('error');
+ expect(failed?.status === 'error' && failed.message).toContain('payload gone');
+ });
+
+ it('marks unparseable workflow payloads as errors', async () => {
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));
+ libraryCache.getLibraryWorkflowCached.mockResolvedValue('not a workflow');
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('error');
+ });
+ });
+
+ it('enriches at most four entries concurrently', async () => {
+ const deferrals = new Map<string, Deferred<Record<string, unknown>>>();
+ api.listLibraryWorkflows.mockResolvedValue(
+ buildPage(Array.from({ length: 6 }, (_unused, index) => buildItem(`item-${index}`)))
+ );
+ libraryCache.getLibraryWorkflowCached.mockImplementation((workflowId: string) => {
+ const deferred = createDeferred<Record<string, unknown>>();
+
+ deferrals.set(workflowId, deferred);
+
+ return deferred.promise;
+ });
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ await vi.waitFor(() => {
+ expect(deferrals.size).toBe(4);
+ });
+
+ // The pool must stay saturated at four, never fanning out to all six.
+ await flushAsyncWork();
+ expect(deferrals.size).toBe(4);
+
+ // Resolutions continue in a microtask, so the map is not mutated mid-loop.
+ for (const deferred of deferrals.values()) {
+ deferred.resolve(buildRawWorkflow(1));
+ }
+
+ await vi.waitFor(() => {
+ expect(deferrals.size).toBe(6);
+ });
+ });
+
+ it('drops enrichment results for entries that left the snapshot', async () => {
+ const stalled = createDeferred<Record<string, unknown>>();
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('gone')]));
+ libraryCache.getLibraryWorkflowCached.mockReturnValueOnce(stalled.promise);
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('kept')]));
+ libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(3));
+ browse.setWorkflowLibraryBrowseFilter({ search: 'kept' });
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');
+ });
+
+ stalled.resolve(buildRawWorkflow(9));
+ await flushAsyncWork();
+
+ const entries = browse.getWorkflowLibraryBrowseSnapshot().entries;
+ expect(entries).toHaveLength(1);
+ expect(entries[0]?.item.workflow_id).toBe('kept');
+ expect(entries[0]?.enrichment).toMatchObject({ nodeCount: 3 });
+ });
+
+ it('keeps untouched entry identities stable while enrichment lands', async () => {
+ const slow = createDeferred<Record<string, unknown>>();
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('fast'), buildItem('slow')]));
+ libraryCache.getLibraryWorkflowCached.mockImplementation((workflowId: string) =>
+ workflowId === 'slow' ? slow.promise : Promise.resolve(buildRawWorkflow(1))
+ );
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');
+ });
+
+ const enrichedFirst = browse.getWorkflowLibraryBrowseSnapshot().entries[0];
+
+ slow.resolve(buildRawWorkflow(1));
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[1]?.enrichment.status).toBe('ready');
+ });
+
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]).toBe(enrichedFirst);
+ });
+});
+
+describe('workflow library browse refresh', () => {
+ it('coalesces a burst of cache invalidations into one refresh', async () => {
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ api.listLibraryWorkflows.mockClear();
+
+ invalidate();
+ invalidate();
+ invalidate();
+
+ await vi.waitFor(() => {
+ expect(api.listLibraryWorkflows).toHaveBeenCalledTimes(1);
+ });
+ await flushAsyncWork();
+ expect(api.listLibraryWorkflows).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not refresh while the store is idle', async () => {
+ invalidate();
+
+ await flushAsyncWork();
+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();
+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('idle');
+ });
+
+ 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 }))
+ );
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ browse.loadNextWorkflowLibraryPage();
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(2);
+ });
+
+ const before = browse.getWorkflowLibraryBrowseSnapshot().entries;
+ api.listLibraryWorkflows.mockClear();
+
+ await browse.refreshWorkflowLibraryBrowse();
+
+ expect(api.listLibraryWorkflows.mock.calls.map(([params]) => params.page)).toEqual([0, 1]);
+
+ const after = browse.getWorkflowLibraryBrowseSnapshot().entries;
+ expect(after.map((entry) => entry.item.workflow_id)).toEqual(['page-0', 'page-1']);
+ expect(after[0]).toBe(before[0]);
+ expect(after[1]).toBe(before[1]);
+ });
+
+ it('re-enriches a row whose server record changed', async () => {
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));
+ libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(1));
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment).toMatchObject({ nodeCount: 1 });
+ });
+
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a', { updated_at: '2026-08-19T00:00:00Z' })]));
+ libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(5));
+
+ await browse.refreshWorkflowLibraryBrowse();
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment).toMatchObject({ nodeCount: 5 });
+ });
+ });
+});
+
+describe('workflow library browse account ownership', () => {
+ it('resets to the initial snapshot when the account switches', async () => {
+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')], { total: 3 }));
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ browse.setWorkflowLibraryBrowseFilter({ category: 'default', search: 'cat', tag: 'lora' });
+ await vi.waitFor(() => {
+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(1);
+ });
+
+ account.accountLifecycle.activate('user-b');
+
+ expect(browse.getWorkflowLibraryBrowseSnapshot()).toEqual({
+ entries: [],
+ error: null,
+ filter: { category: 'user', search: '', tag: null },
+ page: 0,
+ pages: 0,
+ status: 'idle',
+ tagCounts: [],
+ total: 0,
+ userTotal: null,
+ });
+ });
+});
+
+describe('workflow library user total probe', () => {
+ it('probes the user category with a one-row request', async () => {
+ api.listLibraryWorkflows.mockImplementation(({ perPage }: { perPage: number }) =>
+ Promise.resolve(perPage === 1 ? buildPage([buildItem('a')], { total: 7 }) : buildPage([]))
+ );
+
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+
+ expect(api.listLibraryWorkflows).toHaveBeenCalledWith(
+ expect.objectContaining({ category: 'user', page: 0, perPage: 1 })
+ );
+ expect(browse.getWorkflowLibraryBrowseSnapshot().userTotal).toBe(7);
+ });
+
+ it('probes only once across repeated ensure calls', async () => {
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+ await browse.ensureWorkflowLibraryBrowseLoaded();
+
+ expect(api.listLibraryWorkflows.mock.calls.filter(([params]) => params.perPage === 1)).toHaveLength(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts
new file mode 100644
index 0000000000..adf61ffea9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts
@@ -0,0 +1,505 @@
+import type { WorkflowTagCount } from '@features/workflow/core/libraryTags';
+import type { WorkflowModelRequirementSet } from '@features/workflow/core/modelRequirements';
+import type { InvocationTemplates, ProjectGraphState } from '@features/workflow/core/types';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+
+import { parseWorkflowTags, sortTagCounts } from '@features/workflow/core/libraryTags';
+import { extractWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';
+import { parseWorkflowJson } from '@features/workflow/core/workflowJson';
+import {
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+import { shallowEqual } from '@platform/state/selectorCore';
+import { createTrailingSingleFlight } from '@platform/state/singleFlight';
+import { getApiErrorMessage } from '@platform/transport/http';
+
+import type { WorkflowLibraryCategory, WorkflowLibraryListItem, WorkflowLibraryPage } from './api';
+
+import { getAllWorkflowTags, getWorkflowTagCounts, listLibraryWorkflows } from './api';
+import { getLibraryWorkflowCached, onWorkflowLibraryCacheInvalidated } from './libraryCache';
+import { getInvocationTemplatesSnapshot, refreshInvocationTemplates } from './templates';
+
+/**
+ * Browse state for the workflow library dialog. The library is backend-owned
+ * and can hold thousands of records, so filtering and pagination are server
+ * side: every filter change is one page-0 request, infinite scroll appends the
+ * next page, and nothing is filtered locally. What the list endpoint cannot
+ * answer — node count and model requirements — is enriched in the background
+ * from the cached workflow payloads, per entry, so cards fill in as they load
+ * without blocking the grid.
+ */
+
+export type { WorkflowTagCount } from '@features/workflow/core/libraryTags';
+
+export interface WorkflowLibraryBrowseFilter {
+ category: WorkflowLibraryCategory;
+ tag: string | null;
+ search: string;
+}
+
+export type WorkflowLibraryEntryEnrichment =
+ | { status: 'pending' }
+ | { status: 'error'; message: string }
+ | { status: 'ready'; document: ProjectGraphState; nodeCount: number; requirements: WorkflowModelRequirementSet };
+
+export interface WorkflowLibraryEntry {
+ item: WorkflowLibraryListItem;
+ /** Parsed once from `item.tags` so cards never re-split the raw string. */
+ tags: readonly string[];
+ enrichment: WorkflowLibraryEntryEnrichment;
+}
+
+export interface WorkflowLibraryBrowseSnapshot {
+ filter: WorkflowLibraryBrowseFilter;
+ status: 'idle' | 'loading' | 'loadingMore' | 'loaded' | 'error';
+ /** Accumulated pages for the current filter, in server order. */
+ entries: readonly WorkflowLibraryEntry[];
+ /** Last loaded page (0-based, mirroring the API). */
+ page: number;
+ pages: number;
+ total: number;
+ /** Chip counts for the current category. */
+ tagCounts: readonly WorkflowTagCount[];
+ /** Total user-category workflows, for the one-time Browse/Yours auto-switch. */
+ userTotal: number | null;
+ error: string | null;
+}
+
+const PER_PAGE = 20;
+const ENRICHMENT_CONCURRENCY = 4;
+
+const PENDING_ENRICHMENT: WorkflowLibraryEntryEnrichment = { status: 'pending' };
+const EMPTY_ENTRIES: readonly WorkflowLibraryEntry[] = [];
+const EMPTY_TAG_COUNTS: readonly WorkflowTagCount[] = [];
+const INITIAL_FILTER: WorkflowLibraryBrowseFilter = { category: 'user', search: '', tag: null };
+
+const INITIAL_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {
+ entries: EMPTY_ENTRIES,
+ error: null,
+ filter: INITIAL_FILTER,
+ page: 0,
+ pages: 0,
+ status: 'idle',
+ tagCounts: EMPTY_TAG_COUNTS,
+ total: 0,
+ userTotal: null,
+};
+
+const store = createExternalStore<WorkflowLibraryBrowseSnapshot>(INITIAL_SNAPSHOT);
+
+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.
+ */
+let fetchToken = 0;
+
+const nextFetchToken = (): number => {
+ fetchToken += 1;
+
+ return fetchToken;
+};
+
+const isFetchCurrent = (token: number, owner: AccountScope): boolean =>
+ token === fetchToken && isAccountScopeCurrent(owner);
+
+// #region Entries
+
+const toEntry = (item: WorkflowLibraryListItem): WorkflowLibraryEntry => ({
+ enrichment: PENDING_ENRICHMENT,
+ item,
+ tags: parseWorkflowTags(item.tags),
+});
+
+/**
+ * Rebuilds the entry list from a server response while keeping the identity —
+ * and the completed enrichment — of every row the server reports unchanged.
+ * Selectors and memoized cards depend on those identities holding across
+ * refreshes.
+ */
+const mergeEntries = (
+ previous: readonly WorkflowLibraryEntry[],
+ items: readonly WorkflowLibraryListItem[]
+): WorkflowLibraryEntry[] => {
+ const previousById = new Map(previous.map((entry) => [entry.item.workflow_id, entry]));
+
+ return items.map((item) => {
+ const existing = previousById.get(item.workflow_id);
+
+ return existing && shallowEqual(existing.item, item) ? existing : toEntry(item);
+ });
+};
+
+const publishPage = (result: WorkflowLibraryPage, mode: 'append' | 'replace'): void => {
+ const previous = store.getSnapshot().entries;
+ const merged = mergeEntries(previous, result.items);
+
+ store.patchSnapshot({
+ entries: mode === 'append' ? [...previous, ...merged] : merged,
+ error: null,
+ page: result.page,
+ pages: result.pages,
+ status: 'loaded',
+ total: result.total,
+ });
+
+ pumpEnrichment();
+};
+
+// #endregion
+
+// #region Enrichment
+
+/**
+ * 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.
+ */
+let templatesFlight: Promise<void> | null = null;
+
+const loadTemplates = async (): Promise<InvocationTemplates> => {
+ const snapshot = getInvocationTemplatesSnapshot();
+
+ if (snapshot.status === 'loaded') {
+ return snapshot.templates;
+ }
+
+ templatesFlight ??= refreshInvocationTemplates().finally(() => {
+ templatesFlight = null;
+ });
+ await templatesFlight;
+
+ return getInvocationTemplatesSnapshot().templates;
+};
+
+const enrichmentQueue: string[] = [];
+const queuedWorkflowIds = new Set<string>();
+let activeEnrichmentWorkers = 0;
+
+const findEntryIndex = (workflowId: string): number =>
+ store.getSnapshot().entries.findIndex((entry) => entry.item.workflow_id === workflowId);
+
+/** Publishes one entry's enrichment, reusing every other entry object as-is. */
+const applyEnrichment = (workflowId: string, enrichment: WorkflowLibraryEntryEnrichment, owner: AccountScope): void => {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ const { entries } = store.getSnapshot();
+ const index = entries.findIndex((entry) => entry.item.workflow_id === workflowId);
+ const existing = entries[index];
+
+ // The row was filtered or paged away while its payload was in flight.
+ if (!existing) {
+ return;
+ }
+
+ const next = entries.slice();
+
+ next[index] = { ...existing, enrichment };
+ store.patchSnapshot({ entries: next });
+};
+
+const enrichEntry = async (workflowId: string, owner: AccountScope): Promise<void> => {
+ try {
+ const templates = await loadTemplates();
+ const raw = await getLibraryWorkflowCached(workflowId, owner.signal);
+ const { document } = parseWorkflowJson(raw);
+
+ applyEnrichment(
+ workflowId,
+ {
+ document,
+ nodeCount: document.nodes.length,
+ requirements: extractWorkflowModelRequirements(document, templates),
+ status: 'ready',
+ },
+ owner
+ );
+ } catch (error) {
+ // One unreadable workflow marks its own card and never fails the pool.
+ applyEnrichment(
+ workflowId,
+ { message: getApiErrorMessage(error, 'Failed to read this workflow.'), status: 'error' },
+ owner
+ );
+ }
+};
+
+const runEnrichmentWorker = async (): Promise<void> => {
+ try {
+ for (let workflowId = enrichmentQueue.shift(); workflowId !== undefined; workflowId = enrichmentQueue.shift()) {
+ queuedWorkflowIds.delete(workflowId);
+
+ // Each item captures the scope it starts under, so a worker that outlives
+ // an account switch drops its result instead of writing it.
+ if (findEntryIndex(workflowId) !== -1) {
+ await enrichEntry(workflowId, captureAccountScope());
+ }
+ }
+ } finally {
+ activeEnrichmentWorkers -= 1;
+ }
+};
+
+/** Queues every still-pending entry and tops the worker pool back up. */
+const pumpEnrichment = (): void => {
+ for (const entry of store.getSnapshot().entries) {
+ const workflowId = entry.item.workflow_id;
+
+ if (entry.enrichment.status === 'pending' && !queuedWorkflowIds.has(workflowId)) {
+ queuedWorkflowIds.add(workflowId);
+ enrichmentQueue.push(workflowId);
+ }
+ }
+
+ while (activeEnrichmentWorkers < ENRICHMENT_CONCURRENCY && enrichmentQueue.length > 0) {
+ activeEnrichmentWorkers += 1;
+ void runEnrichmentWorker();
+ }
+};
+
+// #endregion
+
+// #region Fetching
+
+const fetchPage = (
+ filter: WorkflowLibraryBrowseFilter,
+ page: number,
+ owner: AccountScope
+): Promise<WorkflowLibraryPage> =>
+ listLibraryWorkflows({
+ category: filter.category,
+ page,
+ perPage: PER_PAGE,
+ query: filter.search || undefined,
+ signal: owner.signal,
+ tags: filter.tag ? [filter.tag] : undefined,
+ });
+
+const loadFirstPage = async (filter: WorkflowLibraryBrowseFilter, owner: AccountScope): Promise<void> => {
+ const token = nextFetchToken();
+
+ try {
+ const result = await fetchPage(filter, 0, owner);
+
+ if (isFetchCurrent(token, owner)) {
+ publishPage(result, 'replace');
+ }
+ } catch (error) {
+ if (isFetchCurrent(token, 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();
+
+ try {
+ const result = await fetchPage(filter, page, owner);
+
+ if (isFetchCurrent(token, owner)) {
+ publishPage(result, 'append');
+ }
+ } catch (error) {
+ if (isFetchCurrent(token, owner)) {
+ store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to load more workflows.'), status: 'error' });
+ }
+ }
+};
+
+/** Tag chips are best-effort: a failed count leaves the previous chips in place. */
+const loadTagCounts = async (category: WorkflowLibraryCategory, owner: AccountScope): Promise<void> => {
+ try {
+ const tags = await getAllWorkflowTags({ categories: [category], signal: owner.signal });
+ const counts =
+ tags.length > 0 ? await getWorkflowTagCounts({ categories: [category], signal: owner.signal, tags }) : {};
+
+ // A category switch mid-flight owns the chips now.
+ if (!isAccountScopeCurrent(owner) || store.getSnapshot().filter.category !== category) {
+ return;
+ }
+
+ const tagCounts = sortTagCounts(Object.entries(counts).map(([tag, count]) => ({ count, tag })));
+
+ store.patchSnapshot({ tagCounts: tagCounts.length > 0 ? tagCounts : EMPTY_TAG_COUNTS });
+ } catch {
+ // Chips are decoration around the grid; the list request owns the error state.
+ }
+};
+
+/**
+ * One-row probe of the user category. Task 6 auto-switches to the bundled
+ * defaults on a fresh install, and this answers "does this account have any
+ * workflows?" without loading the user list.
+ */
+const probeUserTotal = async (owner: AccountScope): Promise<void> => {
+ if (store.getSnapshot().userTotal !== null) {
+ return;
+ }
+
+ try {
+ const result = await listLibraryWorkflows({ category: 'user', page: 0, perPage: 1, signal: owner.signal });
+
+ if (isAccountScopeCurrent(owner)) {
+ store.patchSnapshot({ userTotal: result.total });
+ }
+ } catch {
+ // Leaves `userTotal` null: the dialog simply keeps the category it opened on.
+ }
+};
+
+// #endregion
+
+// #region Public API
+
+/** Applies a filter patch, resets the accumulated pages, and refetches page 0. */
+export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrowseFilter>): void => {
+ const snapshot = store.getSnapshot();
+ const filter = { ...snapshot.filter, ...patch };
+
+ if (shallowEqual(filter, snapshot.filter)) {
+ return;
+ }
+
+ const owner = captureAccountScope();
+ const isCategoryChanged = filter.category !== snapshot.filter.category;
+
+ store.patchSnapshot({
+ entries: EMPTY_ENTRIES,
+ error: null,
+ filter,
+ page: 0,
+ pages: 0,
+ status: 'loading',
+ tagCounts: isCategoryChanged ? EMPTY_TAG_COUNTS : snapshot.tagCounts,
+ total: 0,
+ });
+
+ void loadFirstPage(filter, owner);
+
+ if (isCategoryChanged) {
+ void loadTagCounts(filter.category, owner);
+ }
+};
+
+/** Appends the next page; a no-op while a page is in flight or on the last page. */
+export const loadNextWorkflowLibraryPage = (): void => {
+ const { filter, page, pages, status } = store.getSnapshot();
+
+ if (status !== 'loaded' || page + 1 >= pages) {
+ return;
+ }
+
+ store.patchSnapshot({ status: 'loadingMore' });
+ void loadMorePages(filter, page + 1, captureAccountScope());
+};
+
+/** First open: page 0, the category's tag counts, and the user-total probe. */
+export const ensureWorkflowLibraryBrowseLoaded = (): Promise<void> => {
+ const { status } = store.getSnapshot();
+
+ if (status !== 'idle' && status !== 'error') {
+ return initialLoadFlight.inflight() ?? Promise.resolve();
+ }
+
+ return initialLoadFlight.run(async () => {
+ const owner = captureAccountScope();
+ const { filter } = store.getSnapshot();
+
+ store.patchSnapshot({ error: null, status: 'loading' });
+
+ await Promise.all([loadFirstPage(filter, owner), loadTagCounts(filter.category, owner), probeUserTotal(owner)]);
+ });
+};
+
+/** Revalidates every page the user has scrolled through, plus the tag counts. */
+export const refreshWorkflowLibraryBrowse = (): Promise<void> =>
+ refreshFlight.run(async () => {
+ const { filter, page, status } = store.getSnapshot();
+
+ if (status === 'idle') {
+ return;
+ }
+
+ const owner = captureAccountScope();
+ const token = nextFetchToken();
+
+ try {
+ const results = await Promise.all(
+ Array.from({ length: page + 1 }, (_unused, index) => fetchPage(filter, index, owner))
+ );
+ const last = results[results.length - 1];
+
+ if (last && isFetchCurrent(token, owner)) {
+ const items = results.flatMap((result) => result.items);
+
+ store.patchSnapshot({
+ entries: mergeEntries(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)),
+ pages: last.pages,
+ status: 'loaded',
+ total: last.total,
+ });
+ pumpEnrichment();
+ }
+ } catch (error) {
+ if (isFetchCurrent(token, owner)) {
+ store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to refresh workflows.'), status: 'error' });
+ }
+ }
+
+ await loadTagCounts(filter.category, owner);
+ });
+
+export const getWorkflowLibraryBrowseSnapshot = (): WorkflowLibraryBrowseSnapshot => store.getSnapshot();
+
+export const useWorkflowLibraryBrowseSelector = store.useSelector;
+
+// #endregion
+
+/**
+ * Any local mutation (save, delete, thumbnail) invalidates the library cache
+ * and shifts ordering, so the visible pages are refetched. A burst of
+ * invalidations from one action collapses into a single refresh.
+ */
+let isRefreshScheduled = false;
+
+onWorkflowLibraryCacheInvalidated(() => {
+ if (isRefreshScheduled || store.getSnapshot().status === 'idle') {
+ return;
+ }
+
+ isRefreshScheduled = true;
+ queueMicrotask(() => {
+ isRefreshScheduled = false;
+
+ // The account may have reset between the invalidation and this microtask.
+ if (store.getSnapshot().status !== 'idle') {
+ void refreshWorkflowLibraryBrowse();
+ }
+ });
+});
+
+registerAccountOwnedResource({
+ clear: () => {
+ enrichmentQueue.length = 0;
+ queuedWorkflowIds.clear();
+ templatesFlight = null;
+ isRefreshScheduled = false;
+ initialLoadFlight.reset();
+ refreshFlight.reset();
+ store.setSnapshot(INITIAL_SNAPSHOT);
+ },
+ name: 'workflow-library-browse',
+});