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
perf(workflows): bound library rendering and enrichment (#10167)
Josh Corbett2acb3f0398f2
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex 459ee21e16..14e98ac14d 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -63,6 +63,7 @@ Behavior specs live beside their owning code. Read the owner's document before c| Settings contributions and the settings dialog | [workbench/settings/README.md](src/workbench/settings/README.md) || Widget manifests and extension discovery | [workbench/extensions/README.md](src/workbench/extensions/README.md) || Canvas engine | [workbench/canvas-engine/ARCHITECTURE.md](src/workbench/canvas-engine/ARCHITECTURE.md) |+| Workflow library retention and demand | [features/workflow/data/README.md](src/features/workflow/data/README.md) || Performance gates and byte budgets | [performance/README.md](performance/README.md) |## Contract ownershipdiff --git a/invokeai/frontend/webv2/performance/README.md b/invokeai/frontend/webv2/performance/README.mdindex 1d125f5f05..62cd8d9c31 100644--- a/invokeai/frontend/webv2/performance/README.md+++ b/invokeai/frontend/webv2/performance/README.md@@ -76,3 +76,9 @@ Failures name an owner and a remediation ticket: structural work that would reti| `seal-canvas-engine-seam` | Importers of `@workbench/canvas-engine/contracts` || `finish-queue-ownership` | Importers of `@features/queue` || `define-gallery-feature` | Importers of `./GalleryWidgetView` |++## Workflow-library scaling fixture++The mock backend accepts `POST /__workflow-library` with JSON `{"scenario":"large"}`. This opt-in workload replaces library records with 1,000 user workflows, each containing 40 integer nodes; normal route fixtures and resource budgets are unchanged. Scenarios `empty`, `failed-page`, `slow-detail`, and `changed-revision` respectively empty the library, fail page 2 once (retry succeeds), delay detail reads by 300 ms, and advance each record's revision on its first detail read. `POST /__reset` restores ordinary fixtures. `GET /__workflow-requests` records list/detail requests since seeding.++For a comparison, seed the same scenario on base and candidate with identical viewport, zoom, browser and hardware. Open Yours, select a detail, traverse the library in both directions, switch search/tag views repeatedly, and return. Count `[data-workflow-card]` elements and workflow detail/list GETs at each position. Record long tasks and force-GC retained heap with the same browser profiling procedure on both builds; heap and wall time are observations, not deterministic counts. Run the normal timing profile only against its corresponding fresh performance build, with exclusive use of the machine. Owner resource observations and unit-fixture reads are not substitutes for this browser comparison.diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjsindex 1684eb65d9..542163bb4f 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs@@ -1080,6 +1080,23 @@ const createWorkflows = (count) =>};});+/** Opt-in library workload; ordinary route fixtures and their budgets stay unchanged. */+export const createLargeWorkflowLibraryFixture = () =>+ createWorkflows(1000).map((record, index) => ({+ ...record,+ category: 'user',+ workflow_id: `large-workflow-${String(index).padStart(4, '0')}`,+ workflow: {+ ...record.workflow,+ nodes: range(40, (node) => ({+ id: `node-${node}`,+ type: 'invocation',+ position: { x: node * 100, y: 0 },+ data: { type: 'integer', inputs: { value: { name: 'value', value: node, label: '' } } },+ })),+ },+ }));+/** Per-project intermediates rows for the Settings manager; ids match the projects fixture so entry points preselect. */const createIntermediates = () => [{diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex e352bef331..d5b9e8174b 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -2404,3 +2404,33 @@ test('wildcards are stateful: create, rename, delete one, and delete a batch ofawait backend.close();}});++test('opt-in large library has pageable metadata, representative documents, retry and revision scenarios', async () => {+ const backend = await startMockBackend(0, { profile: 'representative' });+ try {+ const seed = (scenario) =>+ getJson(backend, '/__workflow-library', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ scenario }),+ });+ assert.equal((await seed('large')).count, 1000);+ const first = await getJson(backend, '/api/v1/workflows/?page=0&per_page=20');+ assert.equal(first.total, 1000);+ assert.equal(first.pages, 50);+ assert.equal(first.items.length, 20);+ assert.equal('workflow' in first.items[0], false);+ const id = first.items[0].workflow_id;+ assert.equal((await getJson(backend, `/api/v1/workflows/i/${id}`)).workflow.nodes.length, 40);+ await seed('failed-page');+ const failedPath = '/api/v1/workflows/?page=2&per_page=20';+ assert.equal((await fetch(`${backend.origin}${failedPath}`)).status, 503);+ assert.equal((await getJson(backend, failedPath)).page, 2);+ await seed('changed-revision');+ assert.equal((await getJson(backend, `/api/v1/workflows/i/${id}`)).revision, 2);+ await seed('empty');+ assert.equal((await getJson(backend, '/api/v1/workflows/')).total, 0);+ } finally {+ await backend.close();+ }+});diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 09102abbc9..d10f5d4322 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -9,6 +9,7 @@ import {CATALOG_MANAGED_EXTERNAL_SOURCE,collectCanvasLeaves,createMockBackendFixture,+ createLargeWorkflowLibraryFixture,getFixtureProjectWorkflowDocument,getMockBackendFixtureCounts,MOCK_BACKEND_FIXED_EPOCH,@@ -506,6 +507,8 @@ const createState = (profile, clock) => {nextWorkflowThumbnailVersion: 1,/** Every workflow-library request since the last reset, so journeys can prove which writes happened. */workflowRequests: [],+ libraryScenario: null,+ hasLibraryPageFailed: false,};};@@ -3183,6 +3186,19 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt: json(404, { detail: 'Video not found' });}+ if (method === 'POST' && path === '/__workflow-library') {+ const { scenario = 'large' } = await readJsonBody(request);+ if (!['large', 'empty', 'failed-page', 'slow-detail', 'changed-revision'].includes(scenario)) {+ return json(400, { detail: 'Unknown workflow library scenario' });+ }+ const workflows = scenario === 'empty' ? [] : createLargeWorkflowLibraryFixture();+ state.workflows = new Map(workflows.map((workflow) => [workflow.workflow_id, workflow]));+ state.libraryScenario = scenario;+ state.hasLibraryPageFailed = false;+ state.workflowRequests = [];+ return json(200, { count: workflows.length, nodesPerDocument: 40, scenario });+ }+if (path.startsWith('/api/v1/workflows')) {state.workflowRequests.push({ method, path });}@@ -3334,6 +3350,14 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt}if (method === 'GET') {+ if (state.libraryScenario === 'slow-detail') {+ await new Promise((resolve) => {+ setTimeout(resolve, 300);+ });+ }+ if (state.libraryScenario === 'changed-revision' && workflow.revision === 1) {+ workflow.revision = 2;+ }return json(200, workflowRecord(workflow));}@@ -3430,6 +3454,10 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt// The API pages from 0; the client asks for page 0 first.const page = Math.max(0, Number(url.searchParams.get('page') ?? 0) || 0);const perPage = Math.max(1, Number(url.searchParams.get('per_page') ?? 20) || 20);+ if (state.libraryScenario === 'failed-page' && page === 2 && !state.hasLibraryPageFailed) {+ state.hasLibraryPageFailed = true;+ return json(503, { detail: 'Synthetic page failure; retry succeeds' });+ }const orderBy = url.searchParams.get('order_by') ?? 'updated_at';const sign = url.searchParams.get('direction') === 'ASC' ? 1 : -1;// As the server orders: names ignoring ASCII case (SQLite's NOCASE), NULLs lowest, the id breaking ties.diff --git a/invokeai/frontend/webv2/src/features/workflow/data/README.md b/invokeai/frontend/webv2/src/features/workflow/data/README.mdnew file mode 100644index 0000000000..4104d13fae--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/data/README.md@@ -0,0 +1,13 @@+# Workflow library browsing++Paths are relative to the webv2 package.++`src/features/workflow/data/libraryBrowseStore.ts` owns account-scoped server listings, navigation positions, and demand-driven enrichment. Search, category/visibility, tags, order, totals and tag counts are server-authoritative. A result position is a server offset, not an index in a locally filtered subset.++The active view retains at most 60 consecutive metadata entries. Requests usually align to three server pages of 20; a tall viewport spanning four pages retains partial edge pages within the same 60-entry bound. Its `startIndex` locates that window in the full server result. `loadWorkflowLibraryRange` fetches missing pages, reusing only complete resident page positions from the current list generation while the window is no more than 30 seconds old. Partial reads preserve that conservative window age; only a read of every retained position renews it, including rereads after a changed total. Stale cached views remain ineligible for position reuse until a fresh list read completes, including when revalidation queues behind another filter. Partial edge pages must be read again before extension. Forced Retry and list revalidation read resident positions again. Known mutations immediately disable reuse and fence existing first-page, range and refresh publications before notifying subscribers, even when revalidation queues behind another filter. A changed total detected by a missing-page read also rereads reused offsets. The server supplies no list snapshot version, so concurrent external reorderings still converge through revalidation; newer range requests abort and fence older requests. List revalidation reads the pages intersecting the resident window and retains only its bounded positions; selected metadata is revalidated independently. `selectWorkflowLibraryEntry` selects the freshest matching resident or selected revision from a supplied snapshot, preferring selected state (including errors) at equal revisions. Both enrichment scheduling and the dialog use this policy so detail and preview cannot fall behind selected validation. Invalidation drops enrichment while preserving the selected identity, and only a confirmed removal or access loss clears that pin. Transient failures retain its metadata with a retryable detail error. If deletions move that window beyond the end, it reads the last remaining page. The eight least-recently-used view records retain metadata, totals and one logical scroll anchor per view, with no parsed documents: at most 540 metadata entries across current and cached views, plus one selected entry. Returning to an evicted view starts a fresh server listing.++The grid supplies visible workflow identities before overscan so the 48-identity enrichment bound reaches every visible card even in tall viewports. During restoration, its target rows take that priority until the measured viewport reaches them. Selected detail supplies a separate identity and has priority over visible work. Four workers perform revision-aware raw reads, parsing and requirement extraction. There is no accumulated enrichment queue. Leaving demand aborts work and drops parsed documents immediately; an aborted, obsolete-generation, old-revision or old-account completion cannot publish. Selected detail can retain one document outside the metadata window. Preview owns at most one additional document through its explicit preview request, released after exit or library close. Operations consume documents through their existing operation lifetimes. The raw record cache in `libraryCache.ts` separately retains at most 50 records, validated against list revision and cleared on invalidation/account change.++`src/features/workflow/ui/library/WorkflowLibraryGrid.tsx` virtualizes rows with one to three columns (at least 180 px per card where space permits) against the actual `Scrollable` viewport, measures mounted rows and observes viewport width. The account's view records retain only a server item position and the fraction of its row above the viewport, not row measurement caches. The dialog does not subscribe to anchor changes: each keyed grid reads its filter-owned anchor once at mount, so fractional scrolling does not render the shell or detail rail. A returning grid waits for its actual width before demanding the anchor's range, navigates to that row through the virtualizer, and translates the saved fraction using the resident row's measured geometry. Preliminary top/incorrect-column ranges cannot evict that window. Restoration moves only the grid viewport, never focus; keyboard, pointer or wheel intent cancels it, and filter/account changes or unmount discard it. Narrow dialogs stack the detail rail below the grid, preserving both scroll areas at increased zoom. The viewport is capped at 15 estimated rows even on unusually tall displays, keeping visible rows plus two overscan rows on either side within the metadata bound; one focused/menu row may also remain mounted. Focus pinning retains metadata only; a confirmed local deletion clears the matching pin without discarding a valid off-window focused or menu card. Tab navigation scrolls and refetches the next position before focusing its card/menu control. Matching range requests share transport while their metadata reuse remains fresh; an expired partial flight is replaced by a full read. Each caller checks its own requested positions after settlement; superseded, failed or removed targets do not claim readiness. Focus intent waits for resident metadata and mounted controls, and ends on another keyboard/pointer/focus intent, filter/account change, or unmount. A sticky viewport notice exposes range failures, and explicit Retry revalidates even resident positions. A pinned card's action refetches its metadata position before acting. The project view uses the same virtual rows over its project-owned collection without making library reads. Library selection survives metadata eviction; filters and accounts reset its demand through keyed mount leases. An explicit selection remains preferred when present in the returned view. Otherwise detail selects the first resident entry near the restored viewport, avoiding a page-zero read that would evict its anchor window; per-view selections are not cached.++The owner tests exercise 1,000 workflows with 40 nodes each, repeated view changes, return positions, selected pins and obsolete completions. `getWorkflowLibraryBrowseRetention` exposes deterministic resource counts for that fixture. It does not measure browser heap or production latency.diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.tsindex c2f0db3f4f..52942c7821 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts@@ -26,6 +26,7 @@ const api = vi.hoisted(() => {const libraryCache = vi.hoisted(() => ({getLibraryWorkflowCached: vi.fn(),+ getLibraryWorkflowRecordCached: vi.fn(),onWorkflowLibraryCacheInvalidated: vi.fn(),WorkflowLibraryChangedDuringReadError: class extends Error {},}));@@ -141,6 +142,10 @@ const flushAsyncWork = (): Promise<void> =>let account: typeof accountLifecycleModule;let browse: typeof libraryBrowseStoreModule;let invalidate: () => void;+const demandEntries = () =>+ browse.setWorkflowLibraryVisibleDemand(+ browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item.workflow_id)+ );beforeEach(async () => {vi.resetModules();@@ -148,6 +153,9 @@ beforeEach(async () => {api.getAllWorkflowTags.mockReset().mockResolvedValue([]);api.getWorkflowTagCounts.mockReset().mockResolvedValue({});api.listLibraryWorkflows.mockReset().mockResolvedValue(buildPage([]));+ libraryCache.getLibraryWorkflowRecordCached+ .mockReset()+ .mockImplementation((id: string) => Promise.resolve({ workflow_id: id, name: id, revision: 1, workflow: {} }));libraryCache.getLibraryWorkflowCached.mockReset().mockResolvedValue(buildRawWorkflow(1));libraryCache.onWorkflowLibraryCacheInvalidated.mockReset().mockImplementation((listener: () => void) => {invalidate = listener;@@ -166,6 +174,7 @@ beforeEach(async () => {describe('workflow library page fetching', () => {it('sends the active category, tag, and search filter to the list endpoint', async () => {await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();expect(api.listLibraryWorkflows).toHaveBeenCalledWith(expect.objectContaining({ category: 'user', page: 0, perPage: 20, query: undefined, tags: undefined })@@ -174,6 +183,7 @@ describe('workflow library page fetching', () => {api.listLibraryWorkflows.mockClear();browse.setWorkflowLibraryBrowseFilter({ category: 'default', search: 'upscale', tag: 'lora' });await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');});@@ -186,9 +196,15 @@ describe('workflow library page fetching', () => {api.getAllWorkflowTags.mockResolvedValue(['shared-tag']);api.getWorkflowTagCounts.mockResolvedValue({ 'shared-tag': 2 });api.listLibraryWorkflows.mockImplementation(({ isPublic, page }: { isPublic?: boolean; page: number }) =>- Promise.resolve(buildPage([buildItem(isPublic ? `shared-${page}` : 'yours')], { page, pages: 2, total: 2 }))+ Promise.resolve(+ buildPage(+ Array.from({ length: 20 }, (_, i) => buildItem(`${isPublic ? 'shared' : 'yours'}-${page * 20 + i}`)),+ { page, pages: 2, total: 40 }+ )+ ));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();expect(api.listLibraryWorkflows.mock.calls[0]?.[0]).toMatchObject({ category: 'user', page: 0, perPage: 20 });expect(api.listLibraryWorkflows.mock.calls[0]?.[0]).not.toHaveProperty('isPublic');@@ -199,6 +215,7 @@ describe('workflow library page fetching', () => {browse.setWorkflowLibraryBrowseFilter({ category: 'user', isPublic: true, tag: null });await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');expect(api.getWorkflowTagCounts).toHaveBeenCalled();});@@ -214,8 +231,7 @@ describe('workflow library page fetching', () => {expect.objectContaining({ categories: ['user'], isPublic: true, tags: ['shared-tag'] }));- browse.loadNextWorkflowLibraryPage();- await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().page).toBe(1));+ await browse.loadWorkflowLibraryRange(20, 20);expect(api.listLibraryWorkflows).toHaveBeenCalledWith(expect.objectContaining({ category: 'user', isPublic: true, page: 1, perPage: 20 }));@@ -241,6 +257,7 @@ describe('workflow library page fetching', () => {it('ignores a repeated filter patch that changes nothing', async () => {await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();api.listLibraryWorkflows.mockClear();browse.setWorkflowLibraryBrowseFilter({ category: 'user', search: '' });@@ -248,40 +265,11 @@ describe('workflow library page fetching', () => {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('updated');- 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('updated');+ demandEntries();browse.setWorkflowLibraryBrowseFilter({ tag: 'lora' });const snapshot = browse.getWorkflowLibraryBrowseSnapshot();@@ -291,6 +279,7 @@ describe('workflow library page fetching', () => {it('drops a stale in-flight page when the filter changes mid-flight', async () => {await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();const stale = createDeferred<WorkflowLibraryPage>();api.listLibraryWorkflows.mockReturnValueOnce(stale.promise);@@ -299,6 +288,7 @@ describe('workflow library page fetching', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('fresh')]));browse.setWorkflowLibraryBrowseFilter({ search: 'fresh' });await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');});@@ -315,6 +305,7 @@ describe('workflow library page fetching', () => {api.listLibraryWorkflows.mockRejectedValue(new Error('backend down'));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();const snapshot = browse.getWorkflowLibraryBrowseSnapshot();expect(snapshot.status).toBe('error');@@ -325,6 +316,7 @@ describe('workflow library page fetching', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a', { tags: ' lora , , sdxl ' })]));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.tags).toEqual(['lora', 'sdxl']);});@@ -343,6 +335,7 @@ describe('workflow library sort', () => {it('refetches page 0 in a new sort, and returns to an earlier sort from the cache', async () => {await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();api.listLibraryWorkflows.mockClear();browse.setWorkflowLibraryBrowseFilter({ sort: 'name' });@@ -402,10 +395,12 @@ describe('workflow library sort', () => {it('keeps views in other orders when a workflow is opened', async () => {await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();api.listLibraryWorkflows.mockClear();api.notifyOpened();await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await flushAsyncWork();expect(api.listLibraryWorkflows).not.toHaveBeenCalled();@@ -433,6 +428,7 @@ describe('workflow library tag counts', () => {api.getWorkflowTagCounts.mockResolvedValue({ lora: 2, sdxl: 5, unused: 0 });await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();expect(api.getAllWorkflowTags).toHaveBeenCalledWith(expect.objectContaining({ categories: ['user'] }));expect(api.getWorkflowTagCounts).toHaveBeenCalledWith(@@ -446,16 +442,19 @@ describe('workflow library tag counts', () => {it('refetches counts for the new category and not for a search-only change', async () => {await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();api.getAllWorkflowTags.mockClear();browse.setWorkflowLibraryBrowseFilter({ search: 'cat' });await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().filter.search).toBe('cat');});expect(api.getAllWorkflowTags).not.toHaveBeenCalled();browse.setWorkflowLibraryBrowseFilter({ category: 'default' });await vi.waitFor(() => {+ demandEntries();expect(api.getAllWorkflowTags).toHaveBeenCalledWith(expect.objectContaining({ categories: ['default'] }));});});@@ -467,7 +466,9 @@ describe('workflow library entry enrichment', () => {libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(2));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');});@@ -485,7 +486,9 @@ describe('workflow library entry enrichment', () => {);await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[1]?.enrichment.status).toBe('ready');});@@ -499,7 +502,9 @@ describe('workflow library entry enrichment', () => {libraryCache.getLibraryWorkflowCached.mockResolvedValue('not a workflow');await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('error');});});@@ -518,7 +523,9 @@ describe('workflow library entry enrichment', () => {});await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => {+ demandEntries();expect(deferrals.size).toBe(4);});@@ -532,6 +539,7 @@ describe('workflow library entry enrichment', () => {}await vi.waitFor(() => {+ demandEntries();expect(deferrals.size).toBe(6);});});@@ -547,7 +555,9 @@ describe('workflow library entry enrichment', () => {);await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry) => entry.enrichment.status === 'error')).toBe(true);@@ -567,7 +577,9 @@ describe('workflow library entry enrichment', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('error');});@@ -579,6 +591,7 @@ describe('workflow library entry enrichment', () => {await browse.refreshWorkflowLibraryBrowse();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');});});@@ -589,11 +602,14 @@ describe('workflow library entry enrichment', () => {libraryCache.getLibraryWorkflowCached.mockReturnValueOnce(stalled.promise);await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(1));api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('kept')]));libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(3));browse.setWorkflowLibraryBrowseFilter({ search: 'kept' });await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');});@@ -614,7 +630,9 @@ describe('workflow library entry enrichment', () => {);await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');});@@ -622,6 +640,7 @@ describe('workflow library entry enrichment', () => {slow.resolve(buildRawWorkflow(1));await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[1]?.enrichment.status).toBe('ready');});@@ -634,6 +653,7 @@ describe('workflow library browse refresh', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();api.listLibraryWorkflows.mockClear();invalidate();@@ -641,6 +661,7 @@ describe('workflow library browse refresh', () => {invalidate();await vi.waitFor(() => {+ demandEntries();expect(api.listLibraryWorkflows).toHaveBeenCalledTimes(1);});await flushAsyncWork();@@ -654,8 +675,10 @@ describe('workflow library browse refresh', () => {);await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();browse.setWorkflowLibraryBrowseFilter({ category: 'user', isPublic: true, tag: null });await vi.waitFor(() => {+ demandEntries();const snapshot = browse.getWorkflowLibraryBrowseSnapshot();expect(snapshot.status).toBe('loaded');expect(snapshot.entries.map((entry) => entry.item.workflow_id)).toEqual(['shared']);@@ -665,6 +688,7 @@ describe('workflow library browse refresh', () => {invalidate();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot()).toMatchObject({entries: [],filter: { category: 'user', isPublic: true },@@ -684,121 +708,54 @@ describe('workflow library browse refresh', () => {expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('idle');});- describe('racing infinite scroll', () => {- // Deleting `b` elsewhere shifts every later row up one place.- const BEFORE_DELETE = [- ['a', 'b'],- ['c', 'd'],- ['e', 'f'],- ];- const AFTER_DELETE = [['a', 'c'], ['d', 'e'], ['f']];- const listPage = (library: string[][], page: number) =>+ it.each(['range first', 'refresh first'])('fences overlapping range and refresh publications: %s', async (order) => {+ const page = (index: number, revision = 1) =>buildPage(- (library[page] ?? []).map((id) => buildItem(id)),- {- page,- pages: library.length,- total: library.flat().length,- }+ Array.from({ length: 20 }, (_, i) => buildItem(`wf-${index * 20 + i}`, { revision })),+ { page: index, pages: 10, total: 200 });- const entryIds = () => browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item.workflow_id);-- /** Holds every page request open so each test chooses the completion order. */- const holdPageRequests = async () => {- const held: { page: number; response: Deferred<WorkflowLibraryPage> }[] = [];-- api.listLibraryWorkflows.mockImplementation(({ page, perPage }: { page: number; perPage: number }) => {- if (perPage === 1) {- return Promise.resolve(buildPage([], { total: 0 }));- }-- const response = createDeferred<WorkflowLibraryPage>();-- held.push({ page, response });-- return response.promise;- });-- const loading = browse.ensureWorkflowLibraryBrowseLoaded('updated');-- held[0]?.response.resolve(listPage(BEFORE_DELETE, 0));- await loading;-- return held;- };-- it.each(['the scrolled page', 'the revalidation'])(- 'rereads a page requested before a revalidation and drops its stale response when %s lands first',- async (first) => {- const held = await holdPageRequests();-- browse.loadNextWorkflowLibraryPage();- // The delete's revalidation starts while the scrolled page is in flight.- const refreshing = browse.refreshWorkflowLibraryBrowse();- const [, scrolled, ...reads] = held;- const answerScroll = () => scrolled?.response.resolve(listPage(BEFORE_DELETE, 1));- const answerReads = () => reads.forEach(({ page, response }) => response.resolve(listPage(AFTER_DELETE, page)));-- if (first === 'the scrolled page') {- answerScroll();- await flushAsyncWork();- answerReads();- } else {- answerReads();- await flushAsyncWork();- answerScroll();- }- await refreshing;- await flushAsyncWork();-- expect(entryIds()).toEqual(['a', 'c', 'd', 'e']);- expect(browse.getWorkflowLibraryBrowseSnapshot()).toMatchObject({ page: 1, status: 'loaded', total: 5 });- }- );-- it('holds a scroll during a revalidation, then loads the next page of the revalidated list', async () => {- const held = await holdPageRequests();- const refreshing = browse.refreshWorkflowLibraryBrowse();-- browse.loadNextWorkflowLibraryPage();- expect(held.map(({ page }) => page)).toEqual([0, 0]);- expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loadingMore');-- held[1]?.response.resolve(listPage(AFTER_DELETE, 0));- await vi.waitFor(() => expect(held).toHaveLength(3));- expect(held[2]?.page).toBe(1);-- held[2]?.response.resolve(listPage(AFTER_DELETE, 1));- await refreshing;- await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));-- expect(entryIds()).toEqual(['a', 'c', 'd', 'e']);- expect(browse.getWorkflowLibraryBrowseSnapshot().page).toBe(1);+ api.listLibraryWorkflows.mockImplementation(({ page: index }: { page: number }) => Promise.resolve(page(index)));+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ const held: { index: number; response: Deferred<WorkflowLibraryPage> }[] = [];+ api.listLibraryWorkflows.mockImplementation(({ page: index }: { page: number }) => {+ const response = createDeferred<WorkflowLibraryPage>();+ held.push({ index, response });+ return response.promise;});+ const first =+ order === 'range first' ? browse.loadWorkflowLibraryRange(100, 110) : browse.refreshWorkflowLibraryBrowse();+ const old = [...held];+ const second =+ order === 'range first' ? browse.refreshWorkflowLibraryBrowse() : browse.loadWorkflowLibraryRange(100, 110);+ const current = held.slice(old.length);+ current.forEach(({ index, response }) => response.resolve(page(index, 2)));+ await second;+ old.forEach(({ index, response }) => response.resolve(page(index)));+ await first;+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();+ expect(snapshot.startIndex).toBe(order === 'range first' ? 0 : 100);+ expect(snapshot.entries.every((entry) => entry.item.revision === 2)).toBe(true);+ expect(snapshot.entries).toHaveLength(order === 'range first' ? 20 : 60);});- it('refetches every loaded page and keeps unchanged entry identities', async () => {+ it('revalidates resident pages and preserves unchanged entry identities', async () => {api.listLibraryWorkflows.mockImplementation(({ page }: { page: number }) =>- Promise.resolve(buildPage([buildItem(`page-${page}`)], { page, pages: 2, total: 2 }))+ Promise.resolve(+ buildPage(+ Array.from({ length: 20 }, (_, index) => buildItem(`wf-${page * 20 + index}`)),+ { page, pages: 5, total: 100 }+ )+ ));-await browse.ensureWorkflowLibraryBrowseLoaded('updated');- browse.loadNextWorkflowLibraryPage();- await vi.waitFor(() => {- expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(2);- });-+ await browse.loadWorkflowLibraryRange(20, 25);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]);+ expect(api.listLibraryWorkflows.mock.calls.map(([params]) => params.page)).toEqual([1, 2, 3]);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry, index) => entry === before[index])).toBe(+ true+ );});it('re-enriches a row whose server record changed', async () => {@@ -806,7 +763,9 @@ describe('workflow library browse refresh', () => {libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(1));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment).toMatchObject({ nodeCount: 1 });});@@ -815,6 +774,7 @@ describe('workflow library browse refresh', () => {await browse.refreshWorkflowLibraryBrowse();await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment).toMatchObject({ nodeCount: 5 });});});@@ -825,8 +785,10 @@ describe('workflow library browse account ownership', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')], { total: 3 }));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();browse.setWorkflowLibraryBrowseFilter({ category: 'default', search: 'cat', tag: 'lora' });await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(1);});@@ -847,6 +809,7 @@ describe('workflow library browse account ownership', () => {it('drops an in-flight shared page when the account switches', async () => {await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();const stale = createDeferred<WorkflowLibraryPage>();api.listLibraryWorkflows.mockReturnValueOnce(stale.promise);@@ -871,6 +834,7 @@ describe('workflow library user total probe', () => {);await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();expect(api.listLibraryWorkflows).toHaveBeenCalledWith(expect.objectContaining({ category: 'user', page: 0, perPage: 1 })@@ -880,7 +844,9 @@ describe('workflow library user total probe', () => {it('probes only once across repeated ensure calls', async () => {await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();expect(api.listLibraryWorkflows.mock.calls.filter(([params]) => params.perPage === 1)).toHaveLength(1);});@@ -892,12 +858,15 @@ describe('workflow library view cache', () => {api.listLibraryWorkflows.mockImplementation(({ category }: { category: string }) =>Promise.resolve(buildPage(items[category] ?? [])));- const allEnriched = () =>- browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry) => entry.enrichment.status === 'ready');+ const allEnriched = () => {+ demandEntries();+ return browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry) => entry.enrichment.status === 'ready');+ };const browseYoursThenBrowse = async () => {listByCategory({ default: [buildItem('x', { category: 'default' })], user: userItems });await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() => expect(allEnriched()).toBe(true));const yours = browse.getWorkflowLibraryBrowseSnapshot().entries;@@ -916,7 +885,7 @@ describe('workflow library view cache', () => {const snapshot = browse.getWorkflowLibraryBrowseSnapshot();expect(snapshot.status).toBe('loaded');- expect(snapshot.entries).toBe(yours);+ expect(snapshot.entries.map((entry) => entry.item)).toEqual(yours.map((entry) => entry.item));await flushAsyncWork();expect(api.listLibraryWorkflows).not.toHaveBeenCalled();expect(libraryCache.getLibraryWorkflowCached).not.toHaveBeenCalled();@@ -934,6 +903,7 @@ describe('workflow library view cache', () => {);await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ demandEntries();await vi.waitFor(() =>expect(browse.getWorkflowLibraryBrowseSnapshot().tagCounts).toEqual([{ count: 1, tag: 'yours-tag' }]));@@ -941,6 +911,7 @@ describe('workflow library view cache', () => {browse.setWorkflowLibraryBrowseFilter({ isPublic: true });await vi.waitFor(() => {+ demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.workflow_id).toBe('shared');expect(browse.getWorkflowLibraryBrowseSnapshot().tagCounts).toEqual([{ count: 2, tag: 'shared-tag' }]);});@@ -948,17 +919,21 @@ describe('workflow library view cache', () => {api.listLibraryWorkflows.mockClear();browse.setWorkflowLibraryBrowseFilter({ isPublic: undefined });- expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toBe(yours);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item)).toEqual(+ yours.map((entry) => entry.item)+ );expect(browse.getWorkflowLibraryBrowseSnapshot().tagCounts).toEqual([{ count: 1, tag: 'yours-tag' }]);browse.setWorkflowLibraryBrowseFilter({ isPublic: true });- expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toBe(shared);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item)).toEqual(+ shared.map((entry) => entry.item)+ );expect(browse.getWorkflowLibraryBrowseSnapshot().tagCounts).toEqual([{ count: 2, tag: 'shared-tag' }]);await flushAsyncWork();expect(api.listLibraryWorkflows).not.toHaveBeenCalled();});- it('keeps a stale view on screen while it revalidates, then merges without re-reading unchanged rows', async () => {+ it('keeps stale metadata on screen while it revalidates and waits for renewed detail demand', async () => {const yours = await browseYoursThenBrowse();const later = Date.now() + 60_000;const now = vi.spyOn(Date, 'now').mockReturnValue(later);@@ -968,16 +943,20 @@ describe('workflow library view cache', () => {browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });// The cached rows stay up while the refresh is in flight.- expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toBe(yours);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item)).toEqual(+ yours.map((entry) => entry.item)+ );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(entries[0]?.item).toEqual(yours[0]?.item);+ expect(entries[1]?.item).toEqual(yours[1]?.item);+ expect(libraryCache.getLibraryWorkflowCached).not.toHaveBeenCalled();+ demandEntries();+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(3));expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledWith('c', expect.anything());now.mockRestore();});@@ -1013,3 +992,1066 @@ describe('workflow library view cache', () => {);});});++describe('stale cached view revalidation', () => {+ type HeldPage = { query: string; page: number; response: Deferred<WorkflowLibraryPage> };+ const page = (query: string, index: number, perPage: number, fresh: boolean) => {+ const ids = Array.from({ length: 125 }, (_, position) => position);+ if (fresh && query === '') {+ ids.reverse();+ }+ const items = ids.map((id, position) =>+ buildItem(`${query || 'all'}-${id}`, {+ name: `${fresh ? 'Renamed' : 'Original'} ${String(position).padStart(3, '0')}`,+ revision: fresh ? 2 : 1,+ })+ );+ return buildPage(items.slice(index * perPage, (index + 1) * perPage), {+ page: index,+ pages: Math.ceil(items.length / perPage),+ total: items.length,+ });+ };+ const seed = async (sort: libraryBrowseStoreModule.WorkflowLibrarySort = 'name') => {+ api.listLibraryWorkflows.mockImplementation(+ ({ query = '', page: index, perPage }: { query?: string; page: number; perPage: number }) =>+ Promise.resolve(page(query, index, perPage, false))+ );+ await browse.ensureWorkflowLibraryBrowseLoaded(sort);+ await browse.loadWorkflowLibraryRange(0, 59);+ browse.setWorkflowLibraryBrowseFilter({ search: 'other' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ const held: HeldPage[] = [];+ api.listLibraryWorkflows+ .mockClear()+ .mockImplementation(({ query = '', page: index }: { query?: string; page: number }) => {+ const read = { query, page: index, response: createDeferred<WorkflowLibraryPage>() };+ held.push(read);+ return read.response.promise;+ });+ return held;+ };+ const answer = (reads: readonly HeldPage[]) => {+ for (const read of reads) {+ read.response.resolve(page(read.query, read.page, 20, true));+ }+ };+ const expectFreshWindow = () => {+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();+ expect(snapshot.startIndex).toBe(20);+ expect(snapshot.entries.map(({ item }) => [item.workflow_id, item.name, item.revision])).toEqual(+ Array.from({ length: 60 }, (_, index) => [+ `all-${104 - index}`,+ `Renamed ${String(20 + index).padStart(3, '0')}`,+ 2,+ ])+ );+ };+ const leaveForThird = async (held: HeldPage[]) => {+ browse.setWorkflowLibraryBrowseFilter({ search: 'third' });+ answer(held.filter((read) => read.query === 'third'));+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ };++ it.each(['refresh first', 'range first'])(+ 'rereads overlapping restored positions when %s completes',+ async (order) => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ const held = await seed();+ now.mockReturnValue(160_001);+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[20]?.item.revision).toBe(1);+ const refreshing = held.slice();+ const range = browse.loadWorkflowLibraryRange(20, 79);+ const overlapping = held.slice(refreshing.length);+ expect(held.map((read) => [read.query, read.page])).toEqual([+ ['', 0],+ ['', 1],+ ['', 2],+ ['', 1],+ ['', 2],+ ['', 3],+ ]);+ if (order === 'refresh first') {+ answer(refreshing);+ await flushAsyncWork();+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(0);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[20]?.item.revision).toBe(1);+ }+ answer(overlapping);+ expect(await range).toBe(true);+ if (order === 'range first') {+ answer(refreshing);+ }+ await flushAsyncWork();+ expectFreshWindow();+ await leaveForThird(held);+ const beforeReturn = held.length;+ now.mockReturnValue(160_002);+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ await flushAsyncWork();+ expect(held).toHaveLength(beforeReturn);+ expectFreshWindow();+ } finally {+ now.mockRestore();+ }+ }+ );++ it('does not cache stale overlap as fresh when its revalidation queues behind another filter', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ const held = await seed();+ now.mockReturnValue(160_001);+ const previousFilterRefresh = browse.refreshWorkflowLibraryBrowse();+ expect(held.map((read) => [read.query, read.page])).toEqual([['other', 0]]);+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ const range = browse.loadWorkflowLibraryRange(20, 79);+ answer(held.filter((read) => read.query === ''));+ expect(await range).toBe(true);+ await leaveForThird(held);+ answer(held.filter((read) => read.query === 'other'));+ await previousFilterRefresh;+ await vi.waitFor(() => expect(held.filter((read) => read.query === 'third')).toHaveLength(2));+ answer(held.filter((read) => read.query === 'third'));+ await flushAsyncWork();+ const beforeReturn = held.length;+ now.mockReturnValue(160_002);+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ await flushAsyncWork();+ expect(held).toHaveLength(beforeReturn);+ expectFreshWindow();+ expect(held.map((read) => [read.query, read.page])).toEqual([+ ['other', 0],+ ['', 1],+ ['', 2],+ ['', 3],+ ['third', 0],+ ['third', 0],+ ]);+ } finally {+ now.mockRestore();+ }+ });+ it.each(['cache invalidation', 'opened notification'] as const)(+ 'fences an existing partial range before a queued refresh after %s',+ async (change) => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ const held = await seed(change === 'opened notification' ? 'opened' : 'name');+ now.mockReturnValue(110_000);+ const previousFilterRefresh = browse.refreshWorkflowLibraryBrowse();+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ const range = browse.loadWorkflowLibraryRange(20, 79);+ const partialSignal = api.listLibraryWorkflows.mock.calls[1]?.[0].signal;+ expect(held.map((read) => [read.query, read.page])).toEqual([+ ['other', 0],+ ['', 3],+ ]);+ if (change === 'cache invalidation') {+ invalidate();+ } else {+ api.notifyOpened();+ }+ await flushAsyncWork();+ answer(held.filter((read) => read.query === ''));+ expect(await range).toBe(false);+ expect(partialSignal.aborted).toBe(true);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.name).toBe('Original 000');+ await leaveForThird(held);+ answer(held.filter((read) => read.query === 'other'));+ await previousFilterRefresh;+ await vi.waitFor(() => expect(held.filter((read) => read.query === 'third')).toHaveLength(2));+ answer(held.filter((read) => read.query === 'third'));+ await flushAsyncWork();+ now.mockReturnValue(110_001);+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ const returned = held.filter((read) => read.query === '').slice(1);+ expect(returned.map((read) => read.page)).toEqual([0]);+ answer(returned);+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ expect(+ browse+ .getWorkflowLibraryBrowseSnapshot()+ .entries.map(({ item }) => [item.workflow_id, item.name, item.revision])+ ).toEqual(+ Array.from({ length: 20 }, (_, index) => [+ `all-${124 - index}`,+ `Renamed ${String(index).padStart(3, '0')}`,+ 2,+ ])+ );+ expect(held.map((read) => [read.query, read.page])).toEqual([+ ['other', 0],+ ['', 3],+ ['third', 0],+ ['third', 0],+ ['', 0],+ ]);+ } finally {+ now.mockRestore();+ }+ }+ );+ it('fences pre-mutation refresh rows while its next refresh is still queued', async () => {+ const held = await seed();+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ const tags = createDeferred<Record<string, number>>();+ api.getAllWorkflowTags.mockResolvedValue(['hold-refresh']);+ api.getWorkflowTagCounts.mockReturnValue(tags.promise);+ const refreshing = browse.refreshWorkflowLibraryBrowse();+ expect(held.map((read) => [read.query, read.page])).toEqual([+ ['', 0],+ ['', 1],+ ['', 2],+ ]);+ invalidate();+ await flushAsyncWork();+ answer(held);+ await flushAsyncWork();+ expect(api.getWorkflowTagCounts).toHaveBeenCalled();+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.map(({ item }) => item.name)).toEqual(+ Array.from({ length: 60 }, (_, index) => `Original ${String(index).padStart(3, '0')}`)+ );+ tags.resolve({});+ await refreshing;+ await vi.waitFor(() => expect(held).toHaveLength(6));+ answer(held.slice(3));+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.name).toBe('Renamed 000'));+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.revision).toBe(2);+ });+ it.each(['success', 'error'] as const)(+ 'fences an uncached first-page %s when its post-mutation refresh queues',+ async (completion) => {+ const held = await seed();+ const previousFilterRefresh = browse.refreshWorkflowLibraryBrowse();+ browse.setWorkflowLibraryBrowseFilter({ search: 'third' });+ expect(held.map((read) => [read.query, read.page])).toEqual([+ ['other', 0],+ ['third', 0],+ ]);+ invalidate();+ await flushAsyncWork();+ const oldFirstPage = held.find((read) => read.query === 'third')!;+ if (completion === 'success') {+ oldFirstPage.response.resolve(page('third', 0, 20, false));+ } else {+ oldFirstPage.response.reject(new Error('obsolete first-page failure'));+ }+ await flushAsyncWork();+ expect(browse.getWorkflowLibraryBrowseSnapshot()).toMatchObject({ status: 'loading', error: null, entries: [] });+ answer(held.filter((read) => read.query === 'other'));+ await previousFilterRefresh;+ await vi.waitFor(() => expect(held.filter((read) => read.query === 'third')).toHaveLength(2));+ answer(held.filter((read) => read.query === 'third').slice(1));+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ expect(+ browse+ .getWorkflowLibraryBrowseSnapshot()+ .entries.map(({ item }) => [item.workflow_id, item.name, item.revision])+ ).toEqual(+ Array.from({ length: 20 }, (_, index) => [`third-${index}`, `Renamed ${String(index).padStart(3, '0')}`, 2])+ );+ expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull();+ expect(held.map((read) => [read.query, read.page])).toEqual([+ ['other', 0],+ ['third', 0],+ ['third', 0],+ ]);+ }+ );+});++describe('large library retention fixture', () => {+ const seedLargeLibrary = () => {+ api.listLibraryWorkflows.mockImplementation(({ page, perPage }: { page: number; perPage: number }) =>+ Promise.resolve(+ buildPage(+ Array.from({ length: perPage }, (_, index) => buildItem(`large-${page * perPage + index}`)),+ { page, pages: Math.ceil(1000 / perPage), total: 1000 }+ )+ )+ );+ libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(40));+ };++ it('bounds retention and reads only demanded workflows across 1,000 results', async () => {+ seedLargeLibrary();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ expect(libraryCache.getLibraryWorkflowCached).not.toHaveBeenCalled();+ browse.setWorkflowLibrarySelectedDemand('large-0');+ for (let page = 0; page < 50; page += 1) {+ await browse.loadWorkflowLibraryRange(page * 20, page * 20 + 5);+ const ids = Array.from({ length: 6 }, (_, index) => `large-${page * 20 + index}`);+ browse.setWorkflowLibraryVisibleDemand(ids);+ await vi.waitFor(() =>+ expect(+ ids.every(+ (id) =>+ browse.getWorkflowLibraryBrowseSnapshot().entries.find((entry) => entry.item.workflow_id === id)+ ?.enrichment.status === 'ready'+ )+ ).toBe(true)+ );+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.length).toBeLessThanOrEqual(60);+ expect(+ browse.getWorkflowLibraryBrowseSnapshot().entries.filter((entry) => entry.enrichment.status === 'ready').length+ ).toBeLessThanOrEqual(7);+ }+ expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(300);+ expect(api.listLibraryWorkflows).toHaveBeenCalledTimes(51);+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.item.workflow_id).toBe('large-0');+ await browse.loadWorkflowLibraryRange(0, 5);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.workflow_id).toBe('large-0');+ expect(browse.getWorkflowLibraryBrowseSnapshot().total).toBe(1000);+ browse.setWorkflowLibraryVisibleDemand([]);+ browse.setWorkflowLibrarySelectedDemand(null);+ expect(+ browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry) => entry.enrichment.status === 'pending')+ ).toBe(true);+ });++ it('reaches a stable bound across repeated cached views and restores return-scroll', async () => {+ seedLargeLibrary();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ for (let view = 0; view < 20; view += 1) {+ browse.setWorkflowLibraryBrowseFilter({ search: `view-${view}` });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ await browse.loadWorkflowLibraryRange(400, 405);+ browse.rememberWorkflowLibraryScroll(browse.getWorkflowLibraryBrowseSnapshot().filter, {+ index: 400,+ fraction: view / 20,+ });+ browse.setWorkflowLibraryVisibleDemand(['large-400']);+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready')+ );+ const retained = browse.getWorkflowLibraryBrowseRetention();+ expect(retained.cachedViews).toBeLessThanOrEqual(8);+ expect(retained.metadataEntries).toBeLessThanOrEqual(540);+ expect(retained.parsedDocuments).toBe(1);+ }+ browse.setWorkflowLibraryBrowseFilter({ search: 'view-18' });+ expect(browse.getWorkflowLibraryBrowseSnapshot()).toMatchObject({+ startIndex: 400,+ scrollAnchor: { index: 400, fraction: 0.9 },+ total: 1000,+ });+ expect(browse.getWorkflowLibraryBrowseRetention().parsedDocuments).toBe(0);+ });++ it('rejects scroll measurements from a leaving view', async () => {+ seedLargeLibrary();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ const leavingFilter = browse.getWorkflowLibraryBrowseSnapshot().filter;+ browse.rememberWorkflowLibraryScroll(leavingFilter, { index: 400, fraction: 0.75 });+ browse.setWorkflowLibraryBrowseFilter({ search: 'another view' });+ browse.rememberWorkflowLibraryScroll(leavingFilter, { index: 0, fraction: 0 });+ expect(browse.getWorkflowLibraryBrowseSnapshot().scrollAnchor).toBeNull();+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ expect(browse.getWorkflowLibraryBrowseSnapshot().scrollAnchor).toEqual({ index: 400, fraction: 0.75 });+ });++ it('gives selected detail priority over waiting visible work', async () => {+ seedLargeLibrary();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibrarySelectedDemand('large-19');+ browse.setWorkflowLibraryVisibleDemand(['large-0', 'large-1', 'large-2', 'large-3', 'large-4']);+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalled());+ expect(libraryCache.getLibraryWorkflowCached.mock.calls[0]?.[0]).toBe('large-19');+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseRetention().activeReads).toBe(0));+ expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(6);+ });++ it('aborts obsolete demand and fences late reads of the same revision', async () => {+ seedLargeLibrary();+ const slow = createDeferred<Record<string, unknown>>();+ libraryCache.getLibraryWorkflowCached.mockReturnValue(slow.promise);+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibraryVisibleDemand(['large-0']);+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(1));+ const signal = libraryCache.getLibraryWorkflowCached.mock.calls[0]?.[1].signal as AbortSignal;+ browse.setWorkflowLibraryVisibleDemand([]);+ expect(signal.aborted).toBe(true);+ slow.resolve(buildRawWorkflow(40));+ await flushAsyncWork();+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('pending');+ });+});++describe('review regressions', () => {+ const seed = async () => {+ api.listLibraryWorkflows.mockImplementation(({ page, perPage }: { page: number; perPage: number }) =>+ Promise.resolve(+ buildPage(+ Array.from({ length: perPage }, (_, i) => buildItem(`wf-${page * perPage + i}`)),+ { page, pages: 50, total: 1000 }+ )+ )+ );+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibrarySelectedDemand('wf-0');+ await browse.loadWorkflowLibraryRange(400, 410);+ };+ it('keeps and independently updates an off-window selection on unrelated invalidation, without retaining raw payload in metadata', async () => {+ await seed();+ libraryCache.getLibraryWorkflowRecordCached.mockResolvedValue({+ workflow_id: 'wf-0',+ name: 'Updated selection',+ revision: 2,+ workflow: { description: 'new', nodes: Array(40).fill({}) },+ });+ invalidate();+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.item.workflow_id).toBe('wf-0');+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.item.name).toBe('Updated selection')+ );+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.item).not.toHaveProperty('workflow');+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(400);+ });+ it('keeps fresh resident metadata and its document when an older selected read finishes last', async () => {+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0')]));+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibrarySelectedDemand('wf-0');+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment.status).toBe('ready')+ );+ const selectedRead = createDeferred<{+ workflow_id: string;+ name: string;+ revision: number;+ workflow: Record<string, unknown>;+ }>();+ const residentRead = createDeferred<WorkflowLibraryPage>();+ libraryCache.getLibraryWorkflowRecordCached.mockReturnValueOnce(selectedRead.promise);+ libraryCache.getLibraryWorkflowCached.mockImplementation((_id, { expectedRevision }) =>+ Promise.resolve({ ...buildRawWorkflow(expectedRevision), name: `Document revision ${expectedRevision}` })+ );+ api.listLibraryWorkflows.mockReturnValueOnce(residentRead.promise);+ const refresh = browse.refreshWorkflowLibraryBrowse();+ residentRead.resolve(buildPage([buildItem('wf-0', { revision: 2, name: 'Fresh listing' })]));+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.revision).toBe(2));+ selectedRead.resolve({+ workflow_id: 'wf-0',+ revision: 1,+ name: 'Old selected read',+ workflow: buildRawWorkflow(1),+ });+ await refresh;+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment.status).toBe('ready')+ );+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();+ expect(snapshot.selectedEntry?.item).toMatchObject({ revision: 2, name: 'Fresh listing' });+ expect(snapshot.selectedEntry?.item).not.toHaveProperty('workflow');+ for (const entry of [snapshot.selectedEntry, snapshot.entries[0]]) {+ expect(entry?.enrichment).toMatchObject({+ status: 'ready',+ nodeCount: 2,+ document: { name: 'Document revision 2' },+ });+ }+ });++ it('keeps fresh resident metadata when the concurrent selected read fails transiently', async () => {+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0')]));+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibrarySelectedDemand('wf-0');+ const selectedRead = createDeferred<never>();+ libraryCache.getLibraryWorkflowRecordCached.mockReturnValueOnce(selectedRead.promise);+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0', { revision: 2, name: 'Fresh listing' })]));+ const refresh = browse.refreshWorkflowLibraryBrowse();+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.revision).toBe(2));+ selectedRead.reject(new Error('temporarily offline'));+ await refresh;+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry).toMatchObject({+ item: { revision: 2, name: 'Fresh listing' },+ enrichment: { status: 'error', message: 'temporarily offline' },+ });+ });++ it('retains a newer selected revision when an older resident listing arrives later', async () => {+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0')]));+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibrarySelectedDemand('wf-0');+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment.status).toBe('ready')+ );+ const residentRead = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockReturnValueOnce(residentRead.promise);+ libraryCache.getLibraryWorkflowRecordCached.mockResolvedValueOnce({+ workflow_id: 'wf-0',+ revision: 2,+ name: 'Fresh selection',+ workflow: buildRawWorkflow(2),+ });+ libraryCache.getLibraryWorkflowCached.mockImplementation((_id, { expectedRevision }) =>+ Promise.resolve({ ...buildRawWorkflow(expectedRevision), name: `Document revision ${expectedRevision}` })+ );+ const refresh = browse.refreshWorkflowLibraryBrowse();+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.item.revision).toBe(2));+ residentRead.resolve(buildPage([buildItem('wf-0')]));+ await refresh;+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment.status).toBe('ready')+ );+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry).toMatchObject({+ item: { revision: 2, name: 'Fresh selection' },+ enrichment: { status: 'ready', nodeCount: 2, document: { name: 'Document revision 2' } },+ });+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]).toMatchObject({+ item: { revision: 1 },+ enrichment: { status: 'ready', nodeCount: 1, document: { name: 'Raw workflow' } },+ });+ });++ it('discards old selected enrichment when resident metadata advances during the read', async () => {+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0')]));+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ const oldDocument = createDeferred<Record<string, unknown>>();+ libraryCache.getLibraryWorkflowCached.mockReturnValueOnce(oldDocument.promise).mockResolvedValue({+ ...buildRawWorkflow(2),+ name: 'Fresh document',+ });+ browse.setWorkflowLibrarySelectedDemand('wf-0');+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(1));+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0', { revision: 2, name: 'Fresh listing' })]));+ await browse.loadWorkflowLibraryRange(0, 0, true);+ oldDocument.resolve({ ...buildRawWorkflow(1), name: 'Obsolete document' });+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment.status).toBe('ready')+ );+ for (const entry of [+ browse.getWorkflowLibraryBrowseSnapshot().selectedEntry,+ browse.getWorkflowLibraryBrowseSnapshot().entries[0],+ ]) {+ expect(entry).toMatchObject({+ item: { revision: 2, name: 'Fresh listing' },+ enrichment: { status: 'ready', nodeCount: 2, document: { name: 'Fresh document' } },+ });+ }+ });++ it.each([403, 404, 500])('clears a selected pin only for confirmed access loss/removal (%s)', async (status) => {+ await seed();+ const { ApiError } = await import('@platform/transport/http');+ libraryCache.getLibraryWorkflowRecordCached.mockRejectedValue(new ApiError('unavailable', status));+ invalidate();+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowRecordCached).toHaveBeenCalled());+ await flushAsyncWork();+ const selected = browse.getWorkflowLibraryBrowseSnapshot().selectedEntry;+ if (status === 500) {+ expect(selected?.item.workflow_id).toBe('wf-0');+ expect(selected?.enrichment.status).toBe('error');+ } else {+ expect(selected).toBeNull();+ }+ });+ it('keeps independent selected revalidation inside the detail concurrency bound', async () => {+ await seed();+ let release!: (value: unknown) => void;+ libraryCache.getLibraryWorkflowRecordCached.mockImplementation(+ () =>+ new Promise((resolve) => {+ release = resolve;+ })+ );+ libraryCache.getLibraryWorkflowCached.mockImplementation(() => new Promise(() => {}));+ invalidate();+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowRecordCached).toHaveBeenCalled());+ browse.setWorkflowLibraryVisibleDemand(['wf-400', 'wf-401', 'wf-402', 'wf-403', 'wf-404']);+ expect(browse.getWorkflowLibraryBrowseRetention().activeReads).toBe(4);+ release({ workflow_id: 'wf-0', name: 'selected', revision: 2, workflow: {} });+ await flushAsyncWork();+ expect(browse.getWorkflowLibraryBrowseRetention().activeReads).toBeLessThanOrEqual(4);+ });+ it.each(['filter', 'account'])('fences independent selection reads after a %s change', async (change) => {+ await seed();+ let release!: (value: unknown) => void;+ libraryCache.getLibraryWorkflowRecordCached.mockImplementation(+ () =>+ new Promise((resolve) => {+ release = resolve;+ })+ );+ invalidate();+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowRecordCached).toHaveBeenCalled());+ if (change === 'filter') {+ browse.setWorkflowLibraryBrowseFilter({ search: 'other' });+ } else {+ account.accountLifecycle.invalidate();+ }+ expect(libraryCache.getLibraryWorkflowRecordCached.mock.calls.at(-1)?.[1].signal.aborted).toBe(true);+ release({ workflow_id: 'wf-0', name: 'obsolete', revision: 99, workflow: {} });+ await flushAsyncWork();+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry).toBeNull();+ });+ it('coalesces range waiters and distinguishes supersession from readiness', async () => {+ await seed();+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const list = api.listLibraryWorkflows.getMockImplementation()!;+ api.listLibraryWorkflows.mockImplementation(async (params) => {+ await gate;+ return list(params);+ });+ const before = api.listLibraryWorkflows.mock.calls.length;+ const first = browse.loadWorkflowLibraryRange(100, 105);+ const joined = browse.loadWorkflowLibraryRange(100, 105);+ expect(api.listLibraryWorkflows.mock.calls.length - before).toBe(3);+ const newer = browse.loadWorkflowLibraryRange(200, 205);+ release();+ expect(await first).toBe(false);+ expect(await joined).toBe(false);+ expect(await newer).toBe(true);+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(200);+ });+ it('explicit retry revalidates resident entries after failed refresh', async () => {+ await seed();+ api.listLibraryWorkflows.mockRejectedValueOnce(new Error('offline'));+ await browse.refreshWorkflowLibraryBrowse();+ expect(browse.getWorkflowLibraryBrowseSnapshot().error).not.toBeNull();+ const before = api.listLibraryWorkflows.mock.calls.length;+ expect(await browse.loadWorkflowLibraryRange(400, 410, true)).toBe(true);+ expect(api.listLibraryWorkflows.mock.calls.length).toBe(before + 3);+ expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull();+ });+});++describe('overlapping metadata windows', () => {+ const seed = async () => {+ api.listLibraryWorkflows.mockImplementation(({ page, perPage }: { page: number; perPage: number }) =>+ Promise.resolve(+ buildPage(+ Array.from({ length: Math.min(perPage, 125 - page * perPage) }, (_, index) =>+ buildItem(`wf-${page * perPage + index}`)+ ),+ { page, pages: Math.ceil(125 / perPage), total: 125 }+ )+ )+ );+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ api.listLibraryWorkflows.mockClear();+ };+ const requests = () => api.listLibraryWorkflows.mock.calls.map(([params]) => params.page);+ const ids = () => browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item.workflow_id);+ const serveRevision = (revision: number) => {+ api.listLibraryWorkflows.mockImplementation(({ page, perPage }: { page: number; perPage: number }) =>+ Promise.resolve(+ buildPage(+ Array.from({ length: Math.min(perPage, 125 - page * perPage) }, (_, index) => {+ const position = page * perPage + index;+ return buildItem(`wf-${position}`, { name: `Renamed ${revision}: ${position}`, revision });+ }),+ { page, pages: Math.ceil(125 / perPage), total: 125 }+ )+ )+ );+ };+ const expectRevisionWindow = (start: number, revision: number) => {+ expect(+ browse.getWorkflowLibraryBrowseSnapshot().entries.map(({ item }) => [item.workflow_id, item.name, item.revision])+ ).toEqual(+ Array.from({ length: 60 }, (_, index) => [+ `wf-${start + index}`,+ `Renamed ${revision}: ${start + index}`,+ revision,+ ])+ );+ };+ it.each([+ { start: 0, end: 59, pages: [0, 1, 2] },+ { start: 20, end: 79, pages: [1, 2, 3] },+ ])('rereads expired metadata for positions $start..$end', async ({ start, end, pages }) => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ api.listLibraryWorkflows.mockClear();+ serveRevision(2);+ now.mockReturnValue(130_001);+ expect(await browse.loadWorkflowLibraryRange(start, end)).toBe(true);+ expectRevisionWindow(start, 2);+ expect(requests()).toEqual(pages);+ browse.setWorkflowLibraryBrowseFilter({ search: 'other' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ api.listLibraryWorkflows.mockClear();+ now.mockReturnValue(130_002);+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ await flushAsyncWork();+ expectRevisionWindow(start, 2);+ expect(requests()).toEqual([]);+ } finally {+ now.mockRestore();+ }+ });+ it('does not extend the freshness of reused rows through successive partial scrolls', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ api.listLibraryWorkflows.mockClear();+ serveRevision(2);+ now.mockReturnValue(110_000);+ expect(await browse.loadWorkflowLibraryRange(20, 79)).toBe(true);+ expect(requests()).toEqual([3]);+ now.mockReturnValue(120_000);+ expect(await browse.loadWorkflowLibraryRange(40, 99)).toBe(true);+ expect(requests()).toEqual([3, 4]);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item).toEqual(buildItem('wf-40'));+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.at(-1)?.item.name).toBe('Renamed 2: 99');+ now.mockReturnValue(130_000);+ expect(await browse.loadWorkflowLibraryRange(40, 99)).toBe(true);+ expect(requests()).toEqual([3, 4]);+ api.listLibraryWorkflows.mockClear();+ serveRevision(3);+ now.mockReturnValue(130_001);+ expect(await browse.loadWorkflowLibraryRange(60, 119)).toBe(true);+ expectRevisionWindow(60, 3);+ expect(requests()).toEqual([3, 4, 5]);+ } finally {+ now.mockRestore();+ }+ });+ it('preserves the reused cohort age when a partial read finishes after expiry', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ const pending = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockClear().mockReturnValueOnce(pending.promise);+ now.mockReturnValue(129_999);+ const loading = browse.loadWorkflowLibraryRange(20, 79);+ expect(requests()).toEqual([3]);+ now.mockReturnValue(130_001);+ pending.resolve(+ buildPage(+ Array.from({ length: 20 }, (_, index) => buildItem(`wf-${60 + index}`, { revision: 2 })),+ { page: 3, pages: 7, total: 125 }+ )+ );+ expect(await loading).toBe(true);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item).toEqual(buildItem('wf-20'));+ api.listLibraryWorkflows.mockClear();+ serveRevision(3);+ expect(await browse.loadWorkflowLibraryRange(20, 79)).toBe(true);+ expectRevisionWindow(20, 3);+ expect(requests()).toEqual([1, 2, 3]);+ } finally {+ now.mockRestore();+ }+ });+ it('supersedes a partial flight when a same-window caller arrives after expiry', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ const pending = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockClear().mockReturnValueOnce(pending.promise);+ now.mockReturnValue(129_999);+ const partial = browse.loadWorkflowLibraryRange(20, 79);+ now.mockReturnValue(130_001);+ serveRevision(2);+ const expired = browse.loadWorkflowLibraryRange(20, 79);+ pending.resolve(+ buildPage(+ Array.from({ length: 20 }, (_, index) => buildItem(`wf-${60 + index}`)),+ { page: 3, pages: 7, total: 125 }+ )+ );+ const ready = await Promise.all([partial, expired]);+ expectRevisionWindow(20, 2);+ expect(ready).toEqual([false, true]);+ expect(requests()).toEqual([3, 1, 2, 3]);+ } finally {+ now.mockRestore();+ }+ });+ it('keeps sharing an all-server flight when its caller arrives after the old window expires', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ serveRevision(2);+ const serve = api.listLibraryWorkflows.getMockImplementation()!;+ const pending = createDeferred<void>();+ api.listLibraryWorkflows.mockClear().mockImplementation(async (params) => {+ await pending.promise;+ return serve(params);+ });+ now.mockReturnValue(129_999);+ const first = browse.loadWorkflowLibraryRange(80, 85);+ now.mockReturnValue(130_001);+ const joined = browse.loadWorkflowLibraryRange(90, 95);+ pending.resolve();+ expect(await Promise.all([first, joined])).toEqual([true, true]);+ expect(requests()).toEqual([4, 5, 6]);+ expect(+ browse+ .getWorkflowLibraryBrowseSnapshot()+ .entries.map(({ item }) => [item.workflow_id, item.name, item.revision])+ ).toEqual(Array.from({ length: 45 }, (_, index) => [`wf-${80 + index}`, `Renamed 2: ${80 + index}`, 2]));+ } finally {+ now.mockRestore();+ }+ });+ it('revalidates an expired window on return after a failed range read', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ api.listLibraryWorkflows.mockClear();+ serveRevision(2);+ api.listLibraryWorkflows.mockRejectedValueOnce(new Error('expired range offline'));+ now.mockReturnValue(130_001);+ expect(await browse.loadWorkflowLibraryRange(20, 79)).toBe(false);+ expect(requests()).toEqual([1, 2, 3]);+ expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBe('expired range offline');+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item).toEqual(buildItem('wf-0'));+ browse.setWorkflowLibraryBrowseFilter({ search: 'other' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ api.listLibraryWorkflows.mockClear();+ now.mockReturnValue(130_002);+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.revision).toBe(2));+ expectRevisionWindow(0, 2);+ expect(requests()).toEqual([0, 1, 2]);+ expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull();+ } finally {+ now.mockRestore();+ }+ });+ it('fetches only missing complete pages when moving forward and back', async () => {+ await seed();+ expect(await browse.loadWorkflowLibraryRange(0, 59)).toBe(true);+ expect(requests()).toEqual([1, 2]);+ api.listLibraryWorkflows.mockClear();+ expect(await browse.loadWorkflowLibraryRange(20, 79)).toBe(true);+ expect(requests()).toEqual([3]);+ expect(ids()).toEqual(Array.from({ length: 60 }, (_, i) => `wf-${20 + i}`));+ api.listLibraryWorkflows.mockClear();+ expect(await browse.loadWorkflowLibraryRange(0, 59)).toBe(true);+ expect(requests()).toEqual([0]);+ expect(ids()).toEqual(Array.from({ length: 60 }, (_, i) => `wf-${i}`));+ api.listLibraryWorkflows.mockClear();+ await browse.loadWorkflowLibraryRange(0, 59, true);+ expect(requests()).toEqual([0, 1, 2]);+ });+ it('loads a four-page span without retaining partial pages as complete positions', async () => {+ await seed();+ expect(await browse.loadWorkflowLibraryRange(19, 61)).toBe(true);+ expect(requests()).toEqual([1, 2, 3]);+ expect(ids()).toEqual(Array.from({ length: 60 }, (_, i) => `wf-${19 + i}`));+ api.listLibraryWorkflows.mockClear();+ expect(await browse.loadWorkflowLibraryRange(0, 59)).toBe(true);+ expect(requests()).toEqual([0]);+ api.listLibraryWorkflows.mockClear();+ await browse.loadWorkflowLibraryRange(19, 61);+ api.listLibraryWorkflows.mockClear();+ await browse.refreshWorkflowLibraryBrowse();+ expect(requests()).toEqual([0, 1, 2, 3]);+ expect(ids()).toEqual(Array.from({ length: 60 }, (_, i) => `wf-${19 + i}`));+ });+ it('rereads reused offsets when a missing page reveals a deletion and changed total', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);+ try {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ now.mockReturnValue(130_000);+ api.listLibraryWorkflows.mockClear().mockImplementation(({ page }: { page: number }) =>+ Promise.resolve(+ buildPage(+ Array.from({ length: Math.min(20, 124 - page * 20) }, (_, index) =>+ buildItem(`wf-${page * 20 + index + 1}`, { revision: 2 })+ ),+ { page, pages: 7, total: 124 }+ )+ )+ );+ expect(await browse.loadWorkflowLibraryRange(20, 79)).toBe(true);+ expect(requests()).toEqual([3, 1, 2]);+ expect(ids()).toEqual(Array.from({ length: 60 }, (_, i) => `wf-${21 + i}`));+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry) => entry.item.revision === 2)).toBe(true);+ api.listLibraryWorkflows.mockClear();+ now.mockReturnValue(130_001);+ expect(await browse.loadWorkflowLibraryRange(20, 79)).toBe(true);+ expect(requests()).toEqual([]);+ } finally {+ now.mockRestore();+ }+ });+ it('does not join a forced retry to an ordinary flight that reused resident pages', async () => {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ const deferred = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockClear().mockReturnValueOnce(deferred.promise);+ const ordinary = browse.loadWorkflowLibraryRange(20, 79);+ const forced = browse.loadWorkflowLibraryRange(20, 79, true);+ expect(api.listLibraryWorkflows.mock.calls[0]?.[0].signal.aborted).toBe(true);+ expect(requests()).toEqual([3, 1, 2, 3]);+ deferred.resolve(buildPage([], { page: 3, pages: 7, total: 125 }));+ expect(await ordinary).toBe(false);+ expect(await forced).toBe(true);+ });+ it('supersedes a distant flight when the latest demand returns to resident positions', async () => {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ const resident = browse.getWorkflowLibraryBrowseSnapshot().entries;+ const deferred = createDeferred<void>();+ const list = api.listLibraryWorkflows.getMockImplementation()!;+ api.listLibraryWorkflows.mockClear().mockImplementation(async (params) => {+ await deferred.promise;+ return list(params);+ });+ const distant = browse.loadWorkflowLibraryRange(80, 85);+ expect(requests()).toEqual([4, 5, 6]);+ expect(await browse.loadWorkflowLibraryRange(0, 10)).toBe(true);+ expect(api.listLibraryWorkflows.mock.calls.every(([params]) => params.signal.aborted)).toBe(true);+ deferred.resolve();+ expect(await distant).toBe(false);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toBe(resident);+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(0);+ expect(requests()).toEqual([4, 5, 6]);+ });+ it.each(['resident', 'failed refresh'])('preserves a covering forced retry during %s demand', async (state) => {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ if (state === 'failed refresh') {+ api.listLibraryWorkflows.mockRejectedValueOnce(new Error('refresh offline'));+ await browse.refreshWorkflowLibraryBrowse();+ }+ const deferred = createDeferred<void>();+ const list = api.listLibraryWorkflows.getMockImplementation()!;+ api.listLibraryWorkflows.mockClear().mockImplementation(async (params) => {+ await deferred.promise;+ return list(params);+ });+ const retry = browse.loadWorkflowLibraryRange(0, 59, true);+ const current = browse.loadWorkflowLibraryRange(20, 25);+ expect(requests()).toEqual([0, 1, 2]);+ expect(api.listLibraryWorkflows.mock.calls.every(([params]) => !params.signal.aborted)).toBe(true);+ deferred.resolve();+ expect(await retry).toBe(true);+ expect(await current).toBe(true);+ expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull();+ });+ it('does not report the position after the last resident entry as ready', async () => {+ await seed();+ await browse.loadWorkflowLibraryRange(119, 124);+ expect(await browse.loadWorkflowLibraryRange(125, 125)).toBe(false);+ });+ it.each([0, 5])('does not report readiness when a shrink to %i removes the requested position', async (total) => {+ await seed();+ const deferred = createDeferred<void>();+ api.listLibraryWorkflows.mockImplementation(async ({ page }: { page: number }) => {+ await deferred.promise;+ return buildPage(page === 0 ? Array.from({ length: total }, (_, index) => buildItem(`remaining-${index}`)) : [], {+ page,+ pages: total ? 1 : 0,+ total,+ });+ });+ const loading = browse.loadWorkflowLibraryRange(80, 85);+ deferred.resolve();+ expect(await loading).toBe(false);+ expect(browse.getWorkflowLibraryBrowseSnapshot().total).toBe(total);+ expect(ids()).toEqual(Array.from({ length: total }, (_, index) => `remaining-${index}`));+ });+ it.each([+ { force: true, total: 5, start: 0, end: 59, missing: 20, valid: 1 },+ { force: true, total: 10, start: 0, end: 59, missing: 20, valid: 1 },+ { force: false, total: 100, start: 80, end: 85, missing: 100, valid: 90 },+ ])(+ 'checks each joined caller after a shrink to $total (forced: $force)',+ async ({ force, total, start, end, missing, valid }) => {+ await seed();+ const gate = createDeferred<void>();+ api.listLibraryWorkflows.mockClear().mockImplementation(async ({ page }: { page: number }) => {+ await gate.promise;+ return buildPage(+ Array.from({ length: Math.max(0, Math.min(20, total - page * 20)) }, (_, index) =>+ buildItem(`wf-${page * 20 + index}`)+ ),+ { page, pages: Math.ceil(total / 20), total }+ );+ });+ const initiating = browse.loadWorkflowLibraryRange(start, end, force);+ const removed = browse.loadWorkflowLibraryRange(missing, missing + 2);+ const surviving = browse.loadWorkflowLibraryRange(valid, valid + 2);+ expect(requests()).toEqual(force ? [0, 1, 2] : [4, 5, 6]);+ gate.resolve();+ expect(await initiating).toBe(true);+ expect(await removed).toBe(false);+ expect(await surviving).toBe(true);+ expect(requests()).toEqual(force ? [0, 1, 2] : [4, 5, 6]);+ }+ );+ it.each([false, true])('reports shared transport failure to every caller (forced: %s)', async (force) => {+ await seed();+ const gate = createDeferred<void>();+ api.listLibraryWorkflows.mockClear().mockImplementation(async () => {+ await gate.promise;+ throw new Error('shared range offline');+ });+ const first = browse.loadWorkflowLibraryRange(80, 85, force);+ const joined = browse.loadWorkflowLibraryRange(100, 105);+ const other = browse.loadWorkflowLibraryRange(90, 95);+ expect(requests()).toEqual([4, 5, 6]);+ gate.resolve();+ expect(await Promise.all([first, joined, other])).toEqual([false, false, false]);+ expect(requests()).toEqual([4, 5, 6]);+ });+ it('never reports readiness for demand exceeding its resident capacity', async () => {+ await seed();+ expect(await browse.loadWorkflowLibraryRange(19, 100)).toBe(false);+ expect(ids()).toHaveLength(60);+ expect(ids()[0]).toBe('wf-19');+ expect(ids().at(-1)).toBe('wf-78');+ });+ it('does not reuse positions after an invalidation, including before its refresh microtask', async () => {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ api.listLibraryWorkflows.mockClear();+ invalidate();+ const range = browse.loadWorkflowLibraryRange(20, 79);+ expect(requests()).toEqual([1, 2, 3]);+ await range;+ await flushAsyncWork();+ expect(requests().slice(3)).toEqual([0, 1, 2]);+ });+ it('keeps failed overlaps retryable and bounds the partial last page', async () => {+ await seed();+ await browse.loadWorkflowLibraryRange(0, 59);+ api.listLibraryWorkflows.mockRejectedValueOnce(new Error('range offline'));+ expect(await browse.loadWorkflowLibraryRange(20, 79)).toBe(false);+ expect(ids()[0]).toBe('wf-0');+ expect(await browse.loadWorkflowLibraryRange(20, 79)).toBe(true);+ expect(await browse.loadWorkflowLibraryRange(119, 124)).toBe(true);+ expect(ids()).toEqual(Array.from({ length: 45 }, (_, i) => `wf-${80 + i}`));+ api.listLibraryWorkflows.mockClear();+ expect(await browse.loadWorkflowLibraryRange(120, 124)).toBe(true);+ expect(requests()).toEqual([]);+ expect(browse.getWorkflowLibraryBrowseRetention().metadataEntries).toBeLessThanOrEqual(60);+ });+});++it('selects matching snapshot entries by revision with selected errors authoritative on ties', () => {+ const resident: libraryBrowseStoreModule.WorkflowLibraryEntry = {+ item: buildItem('wf-0'),+ tags: [],+ enrichment: { status: 'pending' },+ };+ const selected: libraryBrowseStoreModule.WorkflowLibraryEntry = {+ ...resident,+ enrichment: { status: 'error', message: 'record offline' },+ };+ expect(browse.selectWorkflowLibraryEntry({ entries: [resident], selectedEntry: selected }, 'wf-0')).toBe(selected);+ const newer = { ...resident, item: buildItem('wf-0', { revision: 2 }) };+ expect(browse.selectWorkflowLibraryEntry({ entries: [newer], selectedEntry: selected }, 'wf-0')).toBe(newer);+ expect(browse.selectWorkflowLibraryEntry({ entries: [resident], selectedEntry: selected }, 'other')).toBeUndefined();+ expect(browse.selectWorkflowLibraryEntry({ entries: [resident], selectedEntry: selected }, null)).toBeUndefined();+});diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.tsindex a32c734ac4..253d35f7da 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts@@ -15,13 +15,14 @@ import {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 { ApiError, getApiErrorMessage } from '@platform/transport/http';import type { WorkflowLibraryCategory, WorkflowLibraryListItem, WorkflowLibraryPage } from './api';import { getAllWorkflowTags, getWorkflowTagCounts, listLibraryWorkflows, onLibraryWorkflowOpened } from './api';import {getLibraryWorkflowCached,+ getLibraryWorkflowRecordCached,onWorkflowLibraryCacheInvalidated,WorkflowLibraryChangedDuringReadError,} from './libraryCache';@@ -61,10 +62,19 @@ export interface WorkflowLibraryEntry {enrichment: WorkflowLibraryEntryEnrichment;}+/** A server item position and the fraction of its row above the grid viewport. */+export interface WorkflowLibraryScrollAnchor {+ index: number;+ fraction: number;+}+export interface WorkflowLibraryBrowseSnapshot {filter: WorkflowLibraryBrowseFilter;- status: 'idle' | 'loading' | 'loadingMore' | 'loaded' | 'error';- /** Accumulated pages for the current filter, in server order. */+ status: 'idle' | 'loading' | 'loaded' | 'error';+ /** Resident metadata window, in server order. */+ startIndex?: number;+ scrollAnchor?: WorkflowLibraryScrollAnchor | null;+ selectedEntry?: WorkflowLibraryEntry | null;entries: readonly WorkflowLibraryEntry[];/** Last loaded page (0-based, mirroring the API). */page: number;@@ -78,6 +88,8 @@ export interface WorkflowLibraryBrowseSnapshot {}const PER_PAGE = 20;+const MAX_RESIDENT_ENTRIES = PER_PAGE * 3;+const MAX_DEMAND = 48;const ENRICHMENT_CONCURRENCY = 4;const PENDING_ENRICHMENT: WorkflowLibraryEntryEnrichment = { status: 'pending' };@@ -122,12 +134,13 @@ const store = createExternalStore<WorkflowLibraryBrowseSnapshot>(INITIAL_SNAPSHO// #region View cache/**- * Views already browsed (Browse, Yours, Shared, 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+ * Views already browsed (Browse, Yours, Shared, a tag or search), kept so switching back shows their metadata at once instead of refetching 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[];+ startIndex: number;+ scrollAnchor: WorkflowLibraryScrollAnchor | null;fetchedAt: number;orderBy: ReturnType<typeof getListOrder>['orderBy'];page: number;@@ -139,7 +152,7 @@ interface CachedBrowseView {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. */+/** Conservative freshness timestamp for the current metadata window. */let currentViewFetchedAt = 0;const getFilterKey = (filter: WorkflowLibraryBrowseFilter): string =>@@ -164,7 +177,11 @@ const rememberCurrentView = (): void => {viewCache.delete(key);viewCache.set(key, {- entries,+ entries: entries.map((entry) =>+ entry.enrichment.status === 'pending' ? entry : { ...entry, enrichment: PENDING_ENRICHMENT }+ ),+ startIndex: store.getSnapshot().startIndex ?? 0,+ scrollAnchor: store.getSnapshot().scrollAnchor ?? null,fetchedAt: currentViewFetchedAt,orderBy: getListOrder(filter).orderBy,page,@@ -194,8 +211,8 @@ const refreshFlight = createTrailingSingleFlight();* the current view starts a new generation, so a page requested before it cannot publish over what it read.*/let listGeneration = 0;-/** The generation of the revalidation reading the current view's pages; infinite scroll waits for it. */-let revalidatingGeneration: number | null = null;+/** Only metadata published in this list generation can satisfy overlapping range reads. */+let metadataGeneration = -1;const isListCurrent = (generation: number, owner: AccountScope): boolean =>generation === listGeneration && isAccountScopeCurrent(owner);@@ -230,23 +247,18 @@ const retryFailedEnrichment = (entries: readonly WorkflowLibraryEntry[]): readon): entries;-const publishPage = (result: WorkflowLibraryPage, mode: 'append' | 'replace'): void => {- const previous = store.getSnapshot().entries;- const merged = mergeEntries(previous, result.items);-- if (mode === 'replace') {- currentViewFetchedAt = Date.now();- }-+const publishPage = (result: WorkflowLibraryPage): void => {+ currentViewFetchedAt = Date.now();+ metadataGeneration = listGeneration;store.patchSnapshot({- entries: mode === 'append' ? [...previous, ...merged] : merged,+ entries: mergeEntries(store.getSnapshot().entries, result.items),+ startIndex: result.page * PER_PAGE,error: null,page: result.page,pages: result.pages,status: 'loaded',total: result.total,});-pumpEnrichment();};@@ -258,6 +270,7 @@ let templatesFlight: Promise<void> | null = null;let hasTemplateLoadFailed = false;const loadTemplates = async (): Promise<InvocationTemplates> => {+ const owner = captureAccountScope();const snapshot = getInvocationTemplatesSnapshot();if (snapshot.status === 'loaded') {@@ -268,10 +281,16 @@ const loadTemplates = async (): Promise<InvocationTemplates> => {throw new Error('Node definitions are unavailable.');}- templatesFlight ??= refreshInvocationTemplates().finally(() => {- templatesFlight = null;- });+ if (!templatesFlight) {+ const flight = refreshInvocationTemplates().finally(() => {+ if (templatesFlight === flight) {+ templatesFlight = null;+ }+ });+ templatesFlight = flight;+ }await templatesFlight;+ owner.signal.throwIfAborted();const settled = getInvocationTemplatesSnapshot();@@ -284,117 +303,325 @@ const loadTemplates = async (): Promise<InvocationTemplates> => {return settled.templates;};-const enrichmentQueue: string[] = [];-const queuedWorkflowIds = new Set<string>();-let activeEnrichmentWorkers = 0;+// Demand belongs to mounted UI leases; selected detail is independent of the metadata window.+let visibleDemand: readonly string[] = [];+let selectedDemand: string | null = null;+let selectedValidation: number | null = null;+let selectedController: AbortController | null = null;+const activeReads = new Map<string, AbortController>();++export const selectWorkflowLibraryEntry = (+ snapshot: Pick<WorkflowLibraryBrowseSnapshot, 'entries' | 'selectedEntry'>,+ workflowId: string | null+): WorkflowLibraryEntry | undefined => {+ const selected = snapshot.selectedEntry?.item.workflow_id === workflowId ? snapshot.selectedEntry : undefined;+ const resident = snapshot.entries.find((entry) => entry.item.workflow_id === workflowId);+ // Independent list and selected reads can complete in either order; neither may lower the revision floor.+ return selected && (!resident || selected.item.revision >= resident.item.revision) ? selected : resident;+};const findEntry = (workflowId: string): WorkflowLibraryEntry | undefined =>- store.getSnapshot().entries.find((entry) => entry.item.workflow_id === workflowId);+ selectWorkflowLibraryEntry(store.getSnapshot(), 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 demandedIds = (): Set<string> =>+ new Set([...(selectedDemand ? [selectedDemand] : []), ...visibleDemand.slice(0, MAX_DEMAND)]);- 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 trimDocuments = (): void => {+ const demand = demandedIds();+ const snapshot = store.getSnapshot();+ const selectedEntry = selectedDemand ? (findEntry(selectedDemand) ?? null) : null;+ const entries = snapshot.entries.map((entry) =>+ !demand.has(entry.item.workflow_id) && entry.enrichment.status !== 'pending'+ ? { ...entry, enrichment: PENDING_ENRICHMENT }+ : entry+ );+ if (selectedEntry !== snapshot.selectedEntry || entries.some((entry, index) => entry !== snapshot.entries[index])) {+ store.patchSnapshot({ entries, selectedEntry });+ }+ for (const [id, controller] of activeReads) {+ if (!demand.has(id)) {+ controller.abort();+ }}-- const next = entries.slice();-- next[index] = { ...existing, enrichment };- store.patchSnapshot({ entries: next });};-const enrichEntry = async (- { revision, workflow_id: workflowId }: WorkflowLibraryListItem,- owner: AccountScope-): Promise<void> => {- try {- const templates = await loadTemplates();- const raw = await getLibraryWorkflowCached(workflowId, { expectedRevision: revision, signal: owner.signal });- const { document } = parseWorkflowJson(raw);-- applyEnrichment(- workflowId,- {- document,- nodeCount: document.nodes.length,- requirements: extractWorkflowModelRequirements(document, templates),- status: 'ready',- },- owner- );- } catch (error) {- // The library, not this row, kept changing mid-read: the row stays pending and is read again. This recurs only- // while invalidations keep landing.- if (error instanceof WorkflowLibraryChangedDuringReadError) {- if (isAccountScopeCurrent(owner)) {+const pumpEnrichment = (): void => {+ trimDocuments();+ if (+ selectedDemand &&+ findEntry(selectedDemand)?.enrichment.status === 'pending' &&+ !activeReads.has(selectedDemand) &&+ activeReads.size >= ENRICHMENT_CONCURRENCY+ ) {+ const obsolete = [...activeReads].reverse().find(([id]) => id !== selectedDemand);+ obsolete?.[1].abort();+ }+ for (const workflowId of demandedIds()) {+ if (activeReads.size + (selectedValidation !== null ? 1 : 0) >= ENRICHMENT_CONCURRENCY) {+ break;+ }+ const entry = findEntry(workflowId);+ if (+ !entry ||+ (workflowId === selectedDemand && selectedValidation !== null) ||+ entry.enrichment.status !== 'pending' ||+ activeReads.has(workflowId)+ ) {+ continue;+ }+ const controller = new AbortController();+ const owner = captureAccountScope();+ const generation = listGeneration;+ activeReads.set(workflowId, controller);+ const signal = AbortSignal.any([owner.signal, controller.signal]);+ const publish = (enrichment: WorkflowLibraryEntryEnrichment) => {+ if (+ signal.aborted ||+ !isListCurrent(generation, owner) ||+ !demandedIds().has(workflowId) ||+ findEntry(workflowId)?.item.revision !== entry.item.revision+ ) {+ return;+ }+ const snapshot = store.getSnapshot();+ store.patchSnapshot({+ entries: snapshot.entries.map((candidate) =>+ candidate.item.workflow_id === workflowId && candidate.item.revision === entry.item.revision+ ? { ...candidate, enrichment }+ : candidate+ ),+ selectedEntry: selectedDemand === workflowId ? { ...entry, enrichment } : snapshot.selectedEntry,+ });+ };+ void (async () => {+ try {+ const templates = await loadTemplates();+ signal.throwIfAborted();+ const raw = await getLibraryWorkflowCached(workflowId, { expectedRevision: entry.item.revision, signal });+ signal.throwIfAborted();+ const { document } = parseWorkflowJson(raw);+ publish({+ document,+ nodeCount: document.nodes.length,+ requirements: extractWorkflowModelRequirements(document, templates),+ status: 'ready',+ });+ } catch (error) {+ if (!signal.aborted && !(error instanceof WorkflowLibraryChangedDuringReadError)) {+ publish({ message: getApiErrorMessage(error, 'Failed to read this workflow.'), status: 'error' });+ }+ } finally {+ if (activeReads.get(workflowId) === controller) {+ activeReads.delete(workflowId);+ }pumpEnrichment();}- return;- }-- // One unreadable workflow marks its own card and never fails the pool.- libraryLogger.warn({- context: { workflowId },- error,- message: 'Failed to read a library workflow',- name: 'workflows.library-read-failed',- });- 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);+export const setWorkflowLibraryVisibleDemand = (ids: readonly string[]): void => {+ visibleDemand = ids.slice(0, MAX_DEMAND);+ pumpEnrichment();+};- const entry = findEntry(workflowId);+export const setWorkflowLibrarySelectedDemand = (id: string | null): void => {+ if (selectedDemand !== id) {+ selectedValidation = null;+ selectedController?.abort();+ selectedController = null;+ }+ selectedDemand = id;+ pumpEnrichment();+};- // Each item captures the scope it starts under, so a worker that outlives- // an account switch drops its result instead of writing it.- if (entry) {- await enrichEntry(entry.item, captureAccountScope());- }- }- } finally {- activeEnrichmentWorkers -= 1;+export const rememberWorkflowLibraryScroll = (+ filter: WorkflowLibraryBrowseFilter,+ scrollAnchor: WorkflowLibraryScrollAnchor+): void => {+ const snapshot = store.getSnapshot();+ // A leaving grid may still report measurements during the new view's commit.+ if (+ snapshot.filter === filter &&+ (snapshot.scrollAnchor?.index !== scrollAnchor.index || snapshot.scrollAnchor.fraction !== scrollAnchor.fraction)+ ) {+ store.patchSnapshot({ scrollAnchor });}};-/** 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;+let windowRequest = 0;+let rangeController: AbortController | null = null;+/** Share bounded metadata reads, but resolve readiness for each caller's requested positions. */+export const loadWorkflowLibraryRange = async (start: number, end: number, force = false): Promise<boolean> => {+ const generation = listGeneration;+ const owner = captureAccountScope();+ const loading = loadWorkflowLibraryWindow(start, end, force);+ const request = windowRequest;+ const loaded = await loading;+ const snapshot = store.getSnapshot();+ const residentStart = snapshot.startIndex ?? 0;+ const residentEnd = residentStart + snapshot.entries.length;+ return (+ loaded &&+ isListCurrent(generation, owner) &&+ request === windowRequest &&+ start >= residentStart &&+ start < residentEnd &&+ Math.min(end, snapshot.total - 1) < residentEnd+ );+};- if (entry.enrichment.status === 'pending' && !queuedWorkflowIds.has(workflowId)) {- queuedWorkflowIds.add(workflowId);- enrichmentQueue.push(workflowId);+/** Retain at most 60 consecutive positions. Partial edge pages are transient fetch buffers only. */+const loadWorkflowLibraryWindow = (start: number, end: number, force: boolean): Promise<boolean> => {+ const snapshot = store.getSnapshot();+ if (snapshot.status === 'idle' || snapshot.status === 'loading' || snapshot.pages === 0) {+ return Promise.resolve(false);+ }+ const residentStart = snapshot.startIndex ?? 0;+ const requestedEnd = Math.min(end, snapshot.total - 1);+ const flightCoversDemand =+ rangeFlightWindow !== null &&+ start >= rangeFlightWindow.start &&+ start < rangeFlightWindow.end &&+ requestedEnd < rangeFlightWindow.end;+ // A viewport update inside Retry's window must not replace its forced revalidation with reused pages.+ if (!force && rangeFlightWindow?.force && flightCoversDemand) {+ return rangeFlight!;+ }+ const fetchedAt = currentViewFetchedAt;+ const canReuse =+ !force && metadataGeneration === listGeneration && fetchedAt !== 0 && Date.now() - fetchedAt <= VIEW_FRESH_MS;+ if (+ canReuse &&+ start >= residentStart &&+ start < residentStart + snapshot.entries.length &&+ requestedEnd < residentStart + snapshot.entries.length+ ) {+ if (rangeFlightWindow && !flightCoversDemand) {+ rangeController?.abort();+ windowRequest += 1;+ rangeFlightWindow = null;+ rangeFlight = null;}+ return Promise.resolve(true);}-- while (activeEnrichmentWorkers < ENRICHMENT_CONCURRENCY && enrichmentQueue.length > 0) {- activeEnrichmentWorkers += 1;- void runEnrichmentWorker();+ // Most viewports fit aligned pages. A tall viewport can cross four pages while still needing only 60 positions.+ const alignedStart = Math.max(0, Math.min(Math.floor(start / PER_PAGE), snapshot.pages - 3)) * PER_PAGE;+ const windowStart = end < alignedStart + MAX_RESIDENT_ENTRIES ? alignedStart : Math.max(0, start);+ const windowEnd = Math.min(snapshot.total, windowStart + MAX_RESIDENT_ENTRIES);+ const first = Math.floor(windowStart / PER_PAGE);+ const last = Math.max(first, Math.ceil(windowEnd / PER_PAGE) - 1);+ const key = `${listGeneration}:${windowStart}:${windowEnd}:${force}`;+ if (rangeFlightWindow?.key === key && (canReuse || !rangeFlightWindow.reusesMetadata)) {+ return rangeFlight!;}+ const flightWindow = { key, start: windowStart, end: windowEnd, force, reusesMetadata: false };+ rangeFlightWindow = flightWindow;+ rangeController?.abort();+ const controller = new AbortController();+ rangeController = controller;+ const request = ++windowRequest;+ const generation = listGeneration;+ const owner = captureAccountScope();+ const flight = (async (): Promise<boolean> => {+ try {+ const reusedPages = new Set<number>();+ let results = await Promise.all(+ Array.from({ length: last - first + 1 }, (_, index) => {+ const page = first + index;+ const offset = page * PER_PAGE - residentStart;+ const size = Math.min(PER_PAGE, snapshot.total - page * PER_PAGE);+ // Reuse complete positions only: a clipped edge page must be read again before extending it.+ if (canReuse && offset >= 0 && offset + size <= snapshot.entries.length) {+ reusedPages.add(page);+ flightWindow.reusesMetadata = true;+ return Promise.resolve({+ page,+ pages: snapshot.pages,+ total: snapshot.total,+ items: snapshot.entries.slice(offset, offset + size).map((entry) => entry.item),+ });+ }+ return fetchPage(snapshot.filter, page, owner, controller.signal);+ })+ );+ if (!isListCurrent(generation, owner) || request !== windowRequest || controller.signal.aborted) {+ return false;+ }+ // A changed total is evidence that offsets shifted; reread reused positions before combining them.+ if (reusedPages.size && results.some((page) => page.total !== snapshot.total || page.pages !== snapshot.pages)) {+ flightWindow.reusesMetadata = false;+ results = await Promise.all(+ results.map((page) =>+ reusedPages.has(page.page) ? fetchPage(snapshot.filter, page.page, owner, controller.signal) : page+ )+ );+ reusedPages.clear();+ }+ let publishedStart = windowStart;+ if (results[0] && windowStart >= results[0].total) {+ results = [await fetchPage(snapshot.filter, Math.max(0, results[0].pages - 1), owner, controller.signal)];+ publishedStart = (results[0]?.page ?? 0) * PER_PAGE;+ }+ if (!isListCurrent(generation, owner) || request !== windowRequest || controller.signal.aborted) {+ return false;+ }+ // A fetched page owns totals; reused pages describe the previous response, not a later server mutation.+ const result =+ results.find((page) => page.total !== snapshot.total || page.pages !== snapshot.pages) ?? results[0];+ if (!result) {+ return false;+ }+ const items = results.flatMap((page) => page.items).slice(publishedStart - (results[0]?.page ?? 0) * PER_PAGE);+ metadataGeneration = generation;+ // A partial read cannot renew the age of positions it did not read, even if the flight crossed expiry.+ currentViewFetchedAt = reusedPages.size ? fetchedAt : Date.now();+ store.patchSnapshot({+ entries: mergeEntries(+ store.getSnapshot().entries,+ items.slice(0, Math.min(MAX_RESIDENT_ENTRIES, Math.max(0, result.total - publishedStart)))+ ),+ startIndex: publishedStart,+ page: Math.min(last, Math.max(0, result.pages - 1)),+ pages: result.pages,+ total: result.total,+ error: null,+ status: 'loaded',+ });+ if (!isListCurrent(generation, owner) || request !== windowRequest || controller.signal.aborted) {+ return false;+ }+ pumpEnrichment();+ return true;+ } catch (error) {+ if (!controller.signal.aborted && isListCurrent(generation, owner) && request === windowRequest) {+ store.patchSnapshot({ error: getApiErrorMessage(error, 'Failed to load workflows.') });+ }+ return false;+ } finally {+ if (request === windowRequest) {+ rangeFlightWindow = null;+ rangeFlight = null;+ }+ }+ })();+ rangeFlight = flight;+ return flight;};+let rangeFlight: Promise<boolean> | null = null;+let rangeFlightWindow: {+ key: string;+ start: number;+ end: number;+ force: boolean;+ reusesMetadata: boolean;+} | null = null;const fetchPage = (filter: WorkflowLibraryBrowseFilter,page: number,- owner: AccountScope+ owner: AccountScope,+ signal?: AbortSignal): Promise<WorkflowLibraryPage> =>listLibraryWorkflows({...getListOrder(filter),@@ -403,21 +630,22 @@ const fetchPage = (page,perPage: PER_PAGE,query: filter.search || undefined,- signal: owner.signal,+ signal: signal ? AbortSignal.any([signal, owner.signal]) : owner.signal,tags: filter.tag ? [filter.tag] : undefined,});const loadFirstPage = async (filter: WorkflowLibraryBrowseFilter, owner: AccountScope): Promise<void> => {const generation = listGeneration;+ const request = windowRequest;try {const result = await fetchPage(filter, 0, owner);- if (isListCurrent(generation, owner)) {- publishPage(result, 'replace');+ if (isListCurrent(generation, owner) && request === windowRequest) {+ publishPage(result);}} catch (error) {- if (isListCurrent(generation, owner)) {+ if (isListCurrent(generation, owner) && request === windowRequest) {libraryLogger.warn({error,message: 'Failed to load workflows',@@ -428,27 +656,6 @@ const loadFirstPage = async (filter: WorkflowLibraryBrowseFilter, owner: Account}};-const loadMorePages = async (filter: WorkflowLibraryBrowseFilter, page: number, owner: AccountScope): Promise<void> => {- const generation = listGeneration;-- try {- const result = await fetchPage(filter, page, owner);-- if (isListCurrent(generation, owner)) {- publishPage(result, 'append');- }- } catch (error) {- if (isListCurrent(generation, owner)) {- libraryLogger.warn({- error,- message: 'Failed to load more workflows',- name: 'workflows.library-load-failed',- });- 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,@@ -496,7 +703,7 @@ const probeUserTotal = async (owner: AccountScope): Promise<void> => {/*** 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.+ * stale); a new one starts from page 0.*/export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrowseFilter>): void => {const snapshot = store.getSnapshot();@@ -511,17 +718,34 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBroconst isTagScopeChanged = isCategoryChanged || filter.isPublic !== snapshot.filter.isPublic;rememberCurrentView();+ rangeController?.abort();+ rangeFlightWindow = null;+ windowRequest += 1;// Everything already in flight was requested for the previous filter.listGeneration += 1;+ visibleDemand = [];+ selectedDemand = null;+ selectedValidation = null;+ selectedController?.abort();+ selectedController = null;+ for (const controller of activeReads.values()) {+ controller.abort();+ }hasTemplateLoadFailed = false;const cached = viewCache.get(getFilterKey(filter));if (cached) {+ const isStale = Date.now() - cached.fetchedAt > VIEW_FRESH_MS;currentViewFetchedAt = cached.fetchedAt;+ // Revalidation may queue behind another filter; stale positions cannot satisfy overlapping demand.+ metadataGeneration = isStale ? -1 : listGeneration;store.patchSnapshot({entries: cached.entries,+ startIndex: cached.startIndex,+ scrollAnchor: cached.scrollAnchor,+ selectedEntry: null,error: null,filter,page: cached.page,@@ -532,7 +756,7 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBro});pumpEnrichment();- if (Date.now() - cached.fetchedAt > VIEW_FRESH_MS) {+ if (isStale) {void refreshWorkflowLibraryBrowse();}return;@@ -540,6 +764,9 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrostore.patchSnapshot({entries: EMPTY_ENTRIES,+ startIndex: 0,+ scrollAnchor: null,+ selectedEntry: null,error: null,filter,page: 0,@@ -556,24 +783,6 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBro}};-/**- * Appends the next page; a no-op while a page is in flight or on the last page. During a revalidation the request- * waits for it and then reads the next page of the revalidated list, because offsets may have shifted.- */-export const loadNextWorkflowLibraryPage = (): void => {- const { filter, page, pages, status } = store.getSnapshot();-- if (status !== 'loaded' || page + 1 >= pages) {- return;- }-- store.patchSnapshot({ status: 'loadingMore' });-- if (revalidatingGeneration !== listGeneration) {- void loadMorePages(filter, page + 1, captureAccountScope());- }-};-/*** First open: page 0, the category's tag counts, and the user-total probe, in the account's stored sort so the first* request already comes back in order. A later open with another sort switches to it as a filter change.@@ -604,13 +813,71 @@ export const ensureWorkflowLibraryBrowseLoaded = (sort: WorkflowLibrarySort): Pr});};+/** Revalidate the selected pin independently of the resident list window. */+const revalidateSelected = async (generation: number, owner: AccountScope): Promise<void> => {+ const entry = store.getSnapshot().selectedEntry;+ if (!entry || entry.item.workflow_id !== selectedDemand) {+ return;+ }+ const id = entry.item.workflow_id;+ selectedController?.abort();+ const controller = new AbortController();+ selectedController = controller;+ selectedValidation = generation;+ const current = () => !controller.signal.aborted && isListCurrent(generation, owner) && selectedDemand === id;+ try {+ const record = await getLibraryWorkflowRecordCached(id, { signal: controller.signal });+ if (!current() || record.revision < (findEntry(id)?.item.revision ?? entry.item.revision)) {+ return;+ }+ const item: WorkflowLibraryListItem = {+ ...entry.item,+ workflow_id: record.workflow_id,+ name: record.name,+ revision: record.revision,+ user_id: record.user_id,+ is_public: record.is_public,+ created_at: record.created_at,+ updated_at: record.updated_at,+ opened_at: record.opened_at,+ last_run_at: record.last_run_at,+ thumbnail_url: record.thumbnail_url,+ call_saved_workflow_compatibility: record.call_saved_workflow_compatibility,+ description: typeof record.workflow.description === 'string' ? record.workflow.description : '',+ tags: typeof record.workflow.tags === 'string' ? record.workflow.tags : '',+ };+ store.patchSnapshot({ selectedEntry: toEntry(item) });+ } catch (error) {+ if (!current()) {+ return;+ }+ if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {+ selectedDemand = null;+ store.patchSnapshot({ selectedEntry: null });+ } else {+ store.patchSnapshot({+ selectedEntry: {+ ...(findEntry(id) ?? entry),+ enrichment: { status: 'error', message: getApiErrorMessage(error, 'Failed to read this workflow.') },+ },+ });+ }+ } finally {+ if (selectedController === controller) {+ selectedController = null;+ }+ if (selectedValidation === generation) {+ selectedValidation = null;+ }+ }+};+/**- * Revalidates every page the user has scrolled through, plus the tag counts. It supersedes a page still in flight and- * reads that page itself; a scroll during it waits and then appends from the revalidated list.+ * Revalidate resident positions and tag counts. A later range owns the window and fences this list publication.*/export const refreshWorkflowLibraryBrowse = (): Promise<void> =>refreshFlight.run(async () => {- const { filter, page, status } = store.getSnapshot();+ const { filter, status } = store.getSnapshot();if (status === 'idle') {return;@@ -619,30 +886,52 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>const owner = captureAccountScope();listGeneration += 1;+ for (const controller of activeReads.values()) {+ controller.abort();+ }+ activeReads.clear();+ rangeController?.abort();+ rangeFlightWindow = null;+ const request = ++windowRequest;const generation = listGeneration;- const lastPage = status === 'loadingMore' ? page + 1 : page;-- revalidatingGeneration = generation;+ const firstPage = Math.floor((store.getSnapshot().startIndex ?? 0) / PER_PAGE);+ const residentStart = store.getSnapshot().startIndex ?? 0;+ const residentEnd = residentStart + store.getSnapshot().entries.length;+ const lastPage = Math.max(firstPage, Math.ceil(residentEnd / PER_PAGE) - 1);// An explicit revalidation is also the retry path for a failed enrichment.hasTemplateLoadFailed = false;+ const selectedRead = revalidateSelected(generation, owner);try {- const results = await Promise.all(- Array.from({ length: lastPage + 1 }, (_unused, index) => fetchPage(filter, index, owner))+ let results = await Promise.all(+ Array.from({ length: lastPage - firstPage + 1 }, (_unused, index) =>+ fetchPage(filter, firstPage + index, owner)+ ));+ let publishedStart = residentStart;+ if (results[0] && residentStart >= results[0].total) {+ results = [await fetchPage(filter, Math.max(0, results[0].pages - 1), owner)];+ publishedStart = (results[0]?.page ?? 0) * PER_PAGE;+ }const last = results[results.length - 1];- if (last && isListCurrent(generation, owner)) {+ if (last && isListCurrent(generation, owner) && request === windowRequest) {const items = results.flatMap((result) => result.items);- // A scroll that arrived during this read; one already in flight when it began is part of `lastPage`.- const isScrollWaiting = status !== 'loadingMore' && store.getSnapshot().status === 'loadingMore';-currentViewFetchedAt = Date.now();- revalidatingGeneration = null;+ metadataGeneration = generation;store.patchSnapshot({- entries: mergeEntries(retryFailedEnrichment(store.getSnapshot().entries), items),+ startIndex: publishedStart,+ entries: mergeEntries(+ retryFailedEnrichment(store.getSnapshot().entries),+ items.slice(+ publishedStart - (results[0]?.page ?? 0) * PER_PAGE,+ publishedStart -+ (results[0]?.page ?? 0) * PER_PAGE ++ Math.min(MAX_RESIDENT_ENTRIES, Math.max(0, last.total - publishedStart))+ )+ ),error: null,// Deletions can shrink the library below the page the user was on.page: Math.min(lastPage, Math.max(0, last.pages - 1)),@@ -650,15 +939,11 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>status: 'loaded',total: last.total,});+ await selectedRead;pumpEnrichment();-- if (isScrollWaiting) {- loadNextWorkflowLibraryPage();- }}} catch (error) {- if (isListCurrent(generation, owner)) {- revalidatingGeneration = null;+ if (isListCurrent(generation, owner) && request === windowRequest) {libraryLogger.warn({error,message: 'Failed to refresh workflows',@@ -668,11 +953,31 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>}}+ await selectedRead;+ pumpEnrichment();await loadTagCounts(filter.category, filter.isPublic, owner);});export const getWorkflowLibraryBrowseSnapshot = (): WorkflowLibraryBrowseSnapshot => store.getSnapshot();+/** Owner-level resource observations for the large-library fixture, independent of browser heap noise. */+export const getWorkflowLibraryBrowseRetention = () => {+ const snapshot = store.getSnapshot();+ const entries = [+ ...snapshot.entries,+ ...[...viewCache.values()].flatMap((view) => view.entries),+ ...(snapshot.selectedEntry ? [snapshot.selectedEntry] : []),+ ];+ return {+ activeReads: activeReads.size + (selectedValidation !== null ? 1 : 0),+ cachedViews: viewCache.size,+ metadataEntries: entries.length,+ parsedDocuments: new Set(+ entries.filter((entry) => entry.enrichment.status === 'ready').map((entry) => entry.enrichment)+ ).size,+ };+};+export const useWorkflowLibraryBrowseSelector = store.useSelector;// #endregion@@ -683,6 +988,13 @@ let isRefreshScheduled = false;/** Marks the current view outdated, so leaving it before the refresh lands does not cache it, and refreshes it. */const scheduleCurrentViewRefresh = (): void => {currentViewFetchedAt = 0;+ // Fence existing list publications now, even when another filter holds the refresh flight.+ const controller = rangeController;+ rangeController = null;+ rangeFlightWindow = null;+ rangeFlight = null;+ windowRequest += 1;+ controller?.abort();if (isRefreshScheduled || store.getSnapshot().status === 'idle') {return;@@ -700,9 +1012,23 @@ const scheduleCurrentViewRefresh = (): void => {};onWorkflowLibraryCacheInvalidated(() => {+ metadataGeneration = -1;+ currentViewFetchedAt = 0;// A mutation can change any view; the current one refreshes, the others fetch afresh when revisited.viewCache.clear();+ for (const controller of activeReads.values()) {+ controller.abort();+ }+ activeReads.clear();+ selectedController?.abort();+ selectedValidation = store.getSnapshot().selectedEntry ? listGeneration + 1 : null;scheduleCurrentViewRefresh();+ store.patchSnapshot({+ entries: store.getSnapshot().entries.map((entry) => ({ ...entry, enrichment: PENDING_ENRICHMENT })),+ selectedEntry: store.getSnapshot().selectedEntry+ ? { ...store.getSnapshot().selectedEntry!, enrichment: PENDING_ENRICHMENT }+ : null,+ });});// Opening a workflow moves it to the top of every view ordered by last opened. The server may record the open after@@ -722,9 +1048,19 @@ onLibraryWorkflowOpened(() => {registerAccountOwnedResource({clear: () => {listGeneration += 1;- revalidatingGeneration = null;- enrichmentQueue.length = 0;- queuedWorkflowIds.clear();+ metadataGeneration = -1;+ visibleDemand = [];+ selectedDemand = null;+ selectedValidation = null;+ selectedController?.abort();+ selectedController = null;+ for (const controller of activeReads.values()) {+ controller.abort();+ }+ rangeFlightWindow = null;+ rangeController?.abort();+ rangeController = null;+ windowRequest += 1;templatesFlight = null;hasTemplateLoadFailed = false;isRefreshScheduled = false;diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.tsindex 4b576b6deb..84a9a57c05 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts@@ -113,6 +113,7 @@ describe('workflow library record freshness', () => {api.getLibraryWorkflowRecord.mockResolvedValue(buildRecord('a', 1));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibraryVisibleDemand(['a']);await vi.waitFor(() => expect(enrichedNodeCount()).toBe(1));// Opening what the list shows reuses the record enrichment read.@@ -151,6 +152,7 @@ describe('workflow library record freshness', () => {api.getLibraryWorkflowRecord.mockResolvedValue(buildRecord('a', 2));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibraryVisibleDemand(['a']);await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.revision).toBe(2));await vi.waitFor(() => expect(enrichedNodeCount()).toBe(2));// A caller still holding the old row is served the newer record without another report.@@ -291,6 +293,7 @@ describe('workflow library invalidation fencing', () => {.mockResolvedValue(buildRecord('a', 1));await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ browse.setWorkflowLibraryVisibleDemand(['a']);await vi.waitFor(() => expect(api.getLibraryWorkflowRecord).toHaveBeenCalledTimes(1));// The refreshes these invalidations start never land, so nothing but the row's own read can enrich it.api.listLibraryWorkflows.mockReturnValue(createDeferred<WorkflowLibraryPage>().promise);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsxindex d3a45e40da..406a215eb6 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx@@ -24,7 +24,7 @@ import {Trash2Icon,WorkflowIcon,} from 'lucide-react';-import { useCallback, useMemo, useState } from 'react';+import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import {@@ -55,6 +55,26 @@ import { WORKFLOW_THUMBNAIL_ASPECT_RATIO, WorkflowThumbnailImage } from './workf*/const DETAIL_RAIL_WIDTH = '18rem';+const COLUMNS_CSS = {+ '@container workflow-library-content (width < 42rem) and ((height >= 32rem) or (width < 32rem))': {+ flexDirection: 'column',+ },+ '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {+ flex: '0 0 auto',+ },+} as const;+const DETAIL_RAIL_CSS = {+ '@container workflow-library-content (width < 42rem) and ((height >= 32rem) or (width < 32rem))': {+ width: '100%',+ },+ '@container workflow-library-content (width < 42rem) and (height >= 32rem)': {+ flexBasis: '45%',+ },+ '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {+ flex: '0 0 auto',+ height: '20rem',+ },+} as const;export interface ProjectWorkflowsViewProps {contextMenuPoint: WorkflowCardMenuAnchor | null;@@ -155,7 +175,7 @@ export const ProjectWorkflowsView = ({</Button></HStack></HStack>- <HStack align="stretch" flex="1" gap="3" minH="0" minW="0">+ <HStack css={COLUMNS_CSS} align="stretch" flex="1" gap="3" minH="0" minW="0"><WorkflowLibraryGridactiveWorkflowId={activeWorkflowId}entries={entries}@@ -235,6 +255,14 @@ const ProjectWorkflowDetailPanel = ({onRemove,onRename,}: ProjectWorkflowDetailPanelProps) => {+ const panelRef = useRef<HTMLDivElement>(null);+ // Portaled action menus belong to this dialog's visible bounds, rather than the whole viewport.+ const menuPositioning = useMemo(+ () => ({+ boundary: () => panelRef.current?.closest<HTMLElement>('[data-scope="dialog"][data-part="content"]') ?? [],+ }),+ []+ );const { t } = useTranslation();const session = useAuthSession();const deps = useModelRequirementDeps();@@ -264,11 +292,12 @@ const ProjectWorkflowDetailPanel = ({() =>contextMenuPoint?.kind === 'point'? {+ ...menuPositioning,getAnchorRect: () => ({ height: 1, width: 1, x: contextMenuPoint.x, y: contextMenuPoint.y }),placement: 'bottom-start' as const,}- : { placement: 'bottom-end' as const },- [contextMenuPoint]+ : { ...menuPositioning, placement: 'bottom-end' as const },+ [contextMenuPoint, menuPositioning]);const handleContextMenuOpenChange = useCallback((event: { open: boolean }) => {@@ -315,7 +344,15 @@ const ProjectWorkflowDetailPanel = ({if (!entry || !libraryEntry) {return (- <Box borderColor="border.subtle" borderWidth="1px" flexShrink={0} minH="0" rounded="md" w={DETAIL_RAIL_WIDTH} />+ <Box+ css={DETAIL_RAIL_CSS}+ borderColor="border.subtle"+ borderWidth="1px"+ flexShrink={0}+ minH="0"+ rounded="md"+ w={DETAIL_RAIL_WIDTH}+ />);}@@ -381,6 +418,8 @@ const ProjectWorkflowDetailPanel = ({<StackborderColor="border.subtle"borderWidth="1px"+ css={DETAIL_RAIL_CSS}+ ref={panelRef}data-project-workflow-detail={workflowId}flexShrink={0}gap="0"@@ -422,7 +461,7 @@ const ProjectWorkflowDetailPanel = ({</HStack>{entry.document.description ? (- <Text color="fg.muted" fontSize="xs" lineClamp={4}>+ <Text color="fg.muted" fontSize="xs" overflowWrap="anywhere">{entry.document.description}</Text>) : null}@@ -456,7 +495,7 @@ const ProjectWorkflowDetailPanel = ({<Button disabled={isActive} flex="1" minW="0" size="lg" onClick={handleOpen}>{isActive ? t('workflowLibrary.activeWorkflow') : t('workflowLibrary.open')}</Button>- <Menu.Root ids={moreActionsIds}>+ <Menu.Root ids={moreActionsIds} positioning={menuPositioning}>{/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, themenu never takes focus and the first pointer move onto it closes it. */}<Menu.Trigger asChild>@@ -468,7 +507,9 @@ const ProjectWorkflowDetailPanel = ({</Menu.Trigger><Portal><Menu.Positioner>- <MenuContent minW="16rem">{actionItems}</MenuContent>+ <MenuContent minW="min(16rem, var(--available-width))" maxW="var(--available-width)">+ {actionItems}+ </MenuContent></Menu.Positioner></Portal></Menu.Root>@@ -499,7 +540,11 @@ const ProjectWorkflowDetailPanel = ({><Portal><Menu.Positioner>- <MenuContent data-workflow-context-menu minW="16rem">+ <MenuContent+ data-workflow-context-menu+ minW="min(16rem, var(--available-width))"+ maxW="var(--available-width)"+ >{actionItems}</MenuContent></Menu.Positioner>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsxnew file mode 100644index 0000000000..98c02f1dd2--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsx@@ -0,0 +1,735 @@+import type { ListWorkflowsParams, WorkflowLibraryListItem, WorkflowLibraryPage } from '@features/workflow/data/api';+import type { WorkflowUiAdapter, WorkflowPreferences } from '@features/workflow/ui/WorkflowUiContext';+import type * as DialogModule from '@platform/ui/Dialog';++import { ChakraProvider } from '@chakra-ui/react';+import { GalleryHostProvider } from '@features/gallery/picker';+import * as browse from '@features/workflow/data/libraryBrowseStore';+import { invalidateWorkflowLibraryCache } from '@features/workflow/data/libraryCache';+import { WorkflowUiProvider, WorkflowGraphPreviewProvider } from '@features/workflow/ui/WorkflowUiContext';+import { setWorkflowLibraryTab } from '@features/workflow/ui/workflowUiStore';+import { createProjectGraph } from '@features/workflow/utility';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';+import { system } from '@theme/system';+import { act, StrictMode, Profiler, type ComponentProps } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import type * as DetailModule from './WorkflowLibraryDetailPanel';++import { WorkflowLibraryDialog } from './WorkflowLibraryDialog';++const transport = vi.hoisted(() => ({+ list: vi.fn<(params: ListWorkflowsParams) => Promise<WorkflowLibraryPage>>(),+ record: vi.fn(),+ delete: vi.fn(),+}));+vi.mock('@features/workflow/data/api', async (original) => ({+ ...(await original<Record<string, unknown>>()),+ listLibraryWorkflows: (params: ListWorkflowsParams) => transport.list(params),+ getLibraryWorkflowRecord: (id: string) => transport.record(id),+ deleteLibraryWorkflow: (id: string) => transport.delete(id),+ getWorkflowTagCounts: () => Promise.resolve({ fixture1000: 1000 }),+ getAllWorkflowTags: () => Promise.resolve(['fixture1000']),+}));+const commits = vi.hoisted(() => ({ shell: 0, toolbar: 0, detail: 0 }));+const recordToolbarCommit = () => {+ commits.toolbar += 1;+};+const recordDetailCommit = () => {+ commits.detail += 1;+};+vi.mock('@features/workflow/data/libraryBrowseStore', async (original) => {+ const actual = await original<typeof browse>();+ return {+ ...actual,+ useWorkflowLibraryBrowseSelector: (...args: Parameters<typeof actual.useWorkflowLibraryBrowseSelector>) => {+ commits.shell += 1;+ return actual.useWorkflowLibraryBrowseSelector(...args);+ },+ };+});+vi.mock('@platform/ui/Dialog', async (original) => {+ const actual = await original<typeof DialogModule>();+ return {+ ...actual,+ Dialog: {+ ...actual.Dialog,+ Header: (props: ComponentProps<typeof actual.Dialog.Header>) => (+ <Profiler id="toolbar" onRender={recordToolbarCommit}>+ <actual.Dialog.Header {...props} />+ </Profiler>+ ),+ },+ };+});+vi.mock('./WorkflowLibraryDetailPanel', async (original) => {+ const actual = await original<typeof DetailModule>();+ return {+ ...actual,+ WorkflowLibraryDetailPanel: (props: ComponentProps<typeof actual.WorkflowLibraryDetailPanel>) => (+ <Profiler id="detail" onRender={recordDetailCommit}>+ <actual.WorkflowLibraryDetailPanel {...props} />+ </Profiler>+ ),+ };+});+const templatesSnapshot = {+ status: 'loaded',+ error: null,+ templates: {+ integer: {+ category: 'test',+ classification: 'stable',+ description: '',+ inputs: {},+ outputs: {},+ nodePack: 'invokeai',+ outputType: 'integer_output',+ tags: [],+ title: 'integer',+ type: 'integer',+ useCache: true,+ version: '1.0.0',+ },+ },+};+vi.mock('@features/workflow/data/templates', async (original) => ({+ ...(await original<Record<string, unknown>>()),+ getInvocationTemplatesSnapshot: () => templatesSnapshot,+ useInvocationTemplatesSnapshot: () => templatesSnapshot,+}));+vi.mock('@features/identity', async (original) => ({+ ...(await original<Record<string, unknown>>()),+ useAuthSession: () => ({ multiuserEnabled: false, phase: 'ready', user: null }),+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: { count?: number; source?: string }) =>+ key === 'workflowLibrary.nodeCount'+ ? `${values?.count} nodes`+ : key === 'graphPreview.compiledFrom'+ ? `Compiled from ${values?.source}`+ : key,+ }),+}));++const graph = createProjectGraph('project-workflow');+const project = {+ id: 'project',+ activeWorkflow: { document: graph },+ activeWorkflowId: graph.id,+ projectGraph: graph,+ workflows: [{ document: graph }],+ galleryValues: {},+ workflowValues: {},+ isWorkflowRunning: false,+};+const port = <T,>(snapshot: T) => ({ getSnapshot: () => snapshot, subscribe: () => () => {} });+const adapter = {+ project: port(project),+ preferences: port({+ themeId: 'classic',+ workflowLibrarySort: 'updated',+ workflowLibraryThumbnailFit: 'cover',+ } as WorkflowPreferences),+ commands: {},+ getProjectGraph: () => graph,+ setLibraryPreferences: vi.fn(),+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ openAddModels: vi.fn(),+} as unknown as WorkflowUiAdapter;+const galleryHost = { galleryValues: {}, notifications: { add: vi.fn(), reportError: vi.fn() }, projectName: '' };+const previewAdapter = {+ openDocumentInNewProject: vi.fn(),+ getRoute: () => null,+ invoke: () => Promise.resolve(false),+ focusSource: vi.fn(),+ openWorkflowEditor: vi.fn(),+};+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root;+let host: HTMLDivElement;+let count = 1000;+const item = (index: number): WorkflowLibraryListItem => ({+ workflow_id: `wf-${index}`,+ name: `Workflow ${index}`,+ revision: 1,+ category: 'user',+ description: '',+ tags: '',+});+const list = ({ page, perPage = 20 }: ListWorkflowsParams) =>+ Promise.resolve({+ page,+ pages: Math.ceil(count / perPage),+ total: count,+ items: Array.from({ length: Math.min(perPage, Math.max(0, count - page * perPage)) }, (_, i) =>+ item(page * perPage + i)+ ),+ });+const card = (index: number) => document.querySelector<HTMLElement>(`[data-workflow-card="wf-${index}"]`);+const viewport = () =>+ card(0)?.closest<HTMLElement>('[data-scope="scroll-area"][data-part="viewport"]') ??+ document.querySelector<HTMLElement>('[data-part="viewport"][aria-label="workflowLibrary.title"]');+const waitFor = (assert: () => void) =>+ act(async () => {+ await vi.waitFor(assert, { timeout: 5000 });+ });+const open = async () => {+ setWorkflowLibraryTab('user');+ await act(async () => {+ await Promise.resolve();+ root.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <GalleryHostProvider host={galleryHost}>+ <WorkflowGraphPreviewProvider adapter={previewAdapter}>+ <WorkflowLibraryDialog isOpen onOpenChange={vi.fn()} />+ </WorkflowGraphPreviewProvider>+ </GalleryHostProvider>+ </WorkflowUiProvider>+ </ChakraProvider>+ </StrictMode>+ );+ });+ await waitFor(() => expect(card(0)).not.toBeNull());+};+beforeEach(async () => {+ accountLifecycle.invalidate();+ count = 1000;+ transport.list.mockReset().mockImplementation(list);+ transport.delete.mockReset().mockResolvedValue(undefined);+ transport.record.mockReset().mockImplementation((id: string) =>+ Promise.resolve({+ ...item(Number(id.slice(3))),+ created_at: '',+ updated_at: '',+ user_id: '',+ is_public: false,+ workflow: { id, name: id, nodes: [], edges: [], meta: { version: '3.0.0', category: 'user' } },+ })+ );+ await page.viewport(1280, 800);+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});+afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ accountLifecycle.invalidate();+});++it('shows middle-range failure and successful Retry inside the viewport with bounded cards', async () => {+ await open();+ transport.list.mockImplementation((params: ListWorkflowsParams) => {+ if (params.page >= 20) {+ return Promise.reject(new Error('middle offline'));+ }+ return list(params);+ });+ const scroll = viewport()!;+ await act(() => {+ scroll.scrollTop = scroll.scrollHeight / 2;+ scroll.dispatchEvent(new Event('scroll'));+ });+ await waitFor(() => expect(document.querySelector('[role="alert"]')?.textContent).toContain('middle offline'));+ const retry = document.querySelector<HTMLElement>('[role="alert"] button')!;+ const rect = retry.getBoundingClientRect();+ const box = scroll.getBoundingClientRect();+ expect(rect.top).toBeGreaterThanOrEqual(box.top);+ expect(rect.bottom).toBeLessThanOrEqual(box.bottom);+ transport.list.mockImplementation(list);+ await act(() => userEvent.click(retry));+ await waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull());+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBeGreaterThan(300);+ expect(document.querySelectorAll('[data-workflow-card]').length).toBeLessThan(48);+});+it('Retry rereads a failed resident refresh while keeping existing cards', async () => {+ count = 5;+ await open();+ transport.list.mockRejectedValueOnce(new Error('refresh offline'));+ await act(() => browse.refreshWorkflowLibraryBrowse());+ expect(card(0)).not.toBeNull();+ const calls = transport.list.mock.calls.length;+ const retry = document.querySelector<HTMLElement>('[role="alert"] button')!;+ await act(() => userEvent.click(retry));+ await waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull());+ expect(transport.list.mock.calls.length).toBeGreaterThan(calls);+ expect(browse.getWorkflowLibraryBrowseSnapshot().total).toBe(5);+});+it.each(['coalesced', 'superseded', 'canceled intent', 'wheel intent'])(+ 'finishes delayed real dialog boundary navigation: %s',+ async (scenario) => {+ await open();+ await act(() => browse.loadWorkflowLibraryRange(0, 59));+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ transport.list.mockImplementation(async (params: ListWorkflowsParams) => {+ await gate;+ return list(params);+ });+ // Scroll to the last resident row, then focus its last menu control.+ const scroll = viewport()!;+ await act(() => {+ scroll.scrollTop = 19 * 200;+ scroll.dispatchEvent(new Event('scroll'));+ });+ await waitFor(() => expect(document.querySelector('[data-workflow-card-menu="wf-59"]')).not.toBeNull());+ const source = document.querySelector<HTMLElement>('[data-workflow-card-menu="wf-59"]')!;+ await act(() => source.focus());+ const demand = browse.loadWorkflowLibraryRange(60, 65);+ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement).toBe(source);+ const superseding = scenario === 'superseded' ? browse.loadWorkflowLibraryRange(40, 65) : null;+ if (scenario === 'canceled intent') {+ await act(() => userEvent.keyboard('{Shift>}{Tab}{/Shift}'));+ expect(document.activeElement).toBe(card(59));+ }+ if (scenario === 'wheel intent') {+ await act(() => {+ scroll.dispatchEvent(new WheelEvent('wheel', { bubbles: true, deltaY: -400 }));+ scroll.scrollTop -= 400;+ scroll.dispatchEvent(new Event('scroll'));+ });+ await act(() => {+ scroll.scrollTop += 400;+ scroll.dispatchEvent(new Event('scroll'));+ });+ }+ await act(async () => {+ release();+ await demand;+ await superseding;+ });+ await waitFor(() => expect(card(60)).not.toBeNull());+ await waitFor(() => {+ if (scenario === 'wheel intent') {+ expect(document.activeElement).toBe(source);+ } else {+ expect(document.activeElement).toBe(card(scenario === 'canceled intent' ? 59 : 60));+ }+ });+ }+);++const detail = () => document.querySelector<HTMLElement>('[data-workflow-detail="wf-0"]')!;+const previewButton = () =>+ Array.from(detail().querySelectorAll('button')).find(+ (button) => button.textContent === 'workflowLibrary.previewGraph'+ )!;++it('uses the newer selected metadata and document when the resident list arrives later', async () => {+ count = 1;+ await open();+ await waitFor(() => expect(previewButton().disabled).toBe(false));+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ transport.list.mockImplementation(async (params: ListWorkflowsParams) => {+ await gate;+ const result = await list(params);+ return { ...result, items: result.items.map((entry) => ({ ...entry, name: 'Older resident refresh' })) };+ });+ transport.record.mockResolvedValue({+ ...item(0),+ name: 'Fresh selection',+ description: 'Fresh description',+ revision: 2,+ workflow: {+ name: 'Fresh document',+ description: 'Fresh description',+ edges: [],+ nodes: [0, 1].map((index) => ({+ id: `fresh-node-${index}`,+ type: 'invocation',+ position: { x: index * 200, y: 0 },+ data: { type: 'integer', inputs: {} },+ })),+ },+ });+ await act(() => invalidateWorkflowLibraryCache('wf-0'));+ await waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.item.revision).toBe(2));+ await act(() => release());+ await waitFor(() => {+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');+ expect(card(0)?.textContent).toContain('Older resident refresh');+ expect(detail().textContent).toContain('Fresh selection');+ expect(detail().textContent).toContain('Fresh description');+ expect(previewButton().disabled).toBe(false);+ });+ await act(() => userEvent.click(previewButton()));+ await waitFor(() => expect(document.body.textContent).toContain('Compiled from Fresh selection'));+ await waitFor(() => expect(document.querySelectorAll('.react-flow__node')).toHaveLength(2));+ await act(() => userEvent.click(page.getByRole('tab', { name: 'common.json', exact: true })));+ await waitFor(() => {+ expect(document.body.textContent).toContain('fresh-node-0');+ expect(document.body.textContent).toContain('fresh-node-1');+ });+});++it('shows the selected transient error over equal-revision resident pending state and recovers', async () => {+ count = 1;+ await open();+ await waitFor(() => expect(previewButton().disabled).toBe(false));+ transport.list.mockImplementation(async (params: ListWorkflowsParams) => {+ const result = await list(params);+ return { ...result, items: result.items.map((entry) => ({ ...entry, name: 'Refreshed resident' })) };+ });+ transport.record.mockRejectedValue(new Error('selected record offline'));+ await act(() => invalidateWorkflowLibraryCache('wf-0'));+ await waitFor(() => {+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');+ expect(card(0)?.textContent).toContain('Refreshed resident');+ expect(detail().textContent).toContain('selected record offline');+ expect(detail().textContent).toContain('Workflow 0');+ expect(previewButton().disabled).toBe(true);+ });+ transport.record.mockResolvedValue({+ ...item(0),+ workflow: {+ name: 'Recovered document',+ nodes: [],+ edges: [],+ },+ });+ await act(() => browse.refreshWorkflowLibraryBrowse());+ await waitFor(() => {+ expect(detail().textContent).not.toContain('selected record offline');+ expect(detail().textContent).toContain('Workflow 0');+ expect(previewButton().disabled).toBe(false);+ });+});++const firstVisibleRow = (scroll: HTMLElement) => {+ const top = scroll.getBoundingClientRect().top;+ const rows = Array.from(scroll.querySelectorAll<HTMLElement>('[data-index]'));+ const row = rows.find((element) => element.getBoundingClientRect().bottom > top)!;+ const rect = row.getBoundingClientRect();+ return {+ id: row.querySelector<HTMLElement>('[data-workflow-card]')?.dataset.workflowCard,+ offset: top - rect.top,+ fraction: (top - rect.top) / rect.height,+ columns: row.querySelectorAll('[data-workflow-card]').length,+ };+};+const settle = () =>+ act(+ () =>+ new Promise((resolve) => {+ setTimeout(resolve, 250);+ })+ );+const scrollTo = async (scroll: HTMLElement, top: number) => {+ await act(() => {+ scroll.scrollTop = top;+ scroll.dispatchEvent(new Event('scroll'));+ });+ await act(+ () =>+ new Promise((resolve) => {+ setTimeout(resolve, 120);+ })+ );+};+it.each([+ [1280, 800, 3],+ [512, 800, 2],+ [320, 400, 1],+])(+ 'returns to the measured deep row at %ix%i (%i columns) through the real browse owner',+ async (width, height, columns) => {+ // This case measures fresh cached restoration; real scrolling and layout timing remain independent.+ const freshAt = Date.now();+ const clock = vi.spyOn(Date, 'now').mockReturnValue(freshAt);+ onTestFinished(() => clock.mockRestore());+ await open();+ const scroll = viewport()!;+ for (let top = 0; top <= 39600; top += 1200) {+ await scrollTo(scroll, top);+ expect(document.querySelectorAll('[data-workflow-card]').length).toBeLessThan(48);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.length).toBeLessThanOrEqual(60);+ }+ await settle();+ const before = firstVisibleRow(scroll);+ expect(Number(before.id?.slice(3))).toBeGreaterThan(400);+ expect(before.offset).toBeGreaterThan(10);+ const requests = transport.list.mock.calls.length;+ await act(() => userEvent.click(page.getByRole('button', { name: 'fixture1000', exact: false })));+ await settle();+ await page.viewport(width!, height!);+ await settle();+ const all = page.getByRole('button', { name: 'workflowLibrary.allTag', exact: false });+ const modal = document.querySelector<HTMLElement>('[role=dialog]')!;+ const outerOffset = modal.scrollTop;+ await act(() => userEvent.click(all));+ await settle();+ const restored = viewport()!;+ const expectedIndex = Math.floor(Number(before.id?.slice(3)) / columns!) * columns!;+ await waitFor(() => expect(firstVisibleRow(restored).id).toBe(`wf-${expectedIndex}`));+ expect(firstVisibleRow(restored).columns).toBe(columns);+ expect(Math.abs(firstVisibleRow(restored).fraction - before.fraction)).toBeLessThan(0.01);+ if (width === 1280) {+ expect(Math.abs(firstVisibleRow(restored).offset - before.offset)).toBeLessThan(3);+ }+ expect(document.activeElement).toBe(all.element());+ expect(modal.scrollTop).toBe(outerOffset);+ expect(document.querySelectorAll('[data-workflow-card]').length).toBeLessThan(48);+ expect(browse.getWorkflowLibraryBrowseRetention().metadataEntries).toBeLessThanOrEqual(540);+ // Only the new tag view needs a listing; returning must not replace its cached deep window with page zero.+ expect(transport.list.mock.calls.length - requests).toBe(1);+ await scrollTo(restored, 0);+ await waitFor(() => expect(card(0)).not.toBeNull());+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(0);+ },+ 30000+);++it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return', 'account', 'unmount'])(+ 'handles a delayed missing-window return: %s',+ async (scenario) => {+ await open();+ const scroll = viewport()!;+ await scrollTo(scroll, 39600);+ await settle();+ const before = firstVisibleRow(scroll);+ const anchorIndex = Number(before.id?.slice(3));+ // A real position read may finish just as a user leaves. Retained metadata and the last visible anchor+ // are independent; returning must wait for the anchor's window instead of restoring placeholder geometry.+ await act(async () => {+ await browse.loadWorkflowLibraryRange(700, 705);+ browse.setWorkflowLibraryBrowseFilter({ tag: 'fixture1000' });+ });+ await waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let failReturn = scenario === 'retry';+ transport.list.mockImplementation(async (params: ListWorkflowsParams) => {+ if (!params.tags?.length && params.page > 0) {+ await gate;+ if (failReturn) {+ throw new Error('return window offline');+ }+ }+ return list(params);+ });+ transport.list.mockClear();+ await act(() => browse.setWorkflowLibraryBrowseFilter({ tag: null }));+ await waitFor(() => expect(transport.list.mock.calls.length).toBe(3));+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(700);+ const returned = viewport()!;+ expect(returned.scrollTop).toBe(0);+ expect(firstVisibleRow(returned).id).toBeUndefined();+ const focus = document.activeElement;+ let canceledOffset = 0;+ if (['wheel', 'pointer', 'key'].includes(scenario)) {+ await act(() => {+ returned.dispatchEvent(+ scenario === 'wheel'+ ? new WheelEvent('wheel', { bubbles: true, deltaY: -1200 })+ : scenario === 'pointer'+ ? new PointerEvent('pointerdown', { bubbles: true })+ : new KeyboardEvent('keydown', { bubbles: true, key: 'PageUp' })+ );+ });+ await scrollTo(returned, 0);+ canceledOffset = returned.scrollTop;+ } else if (scenario === 'filter' || scenario === 'rapid return') {+ await act(() => browse.setWorkflowLibraryBrowseFilter({ tag: 'fixture1000' }));+ if (scenario === 'rapid return') {+ await act(() => browse.setWorkflowLibraryBrowseFilter({ tag: null }));+ await waitFor(() => expect(transport.list.mock.calls.length).toBe(6));+ }+ } else if (scenario === 'account') {+ await act(() => accountLifecycle.invalidate());+ } else if (scenario === 'unmount') {+ await act(() => root.render(null));+ }+ await act(async () => {+ release();+ await gate;+ });+ await settle();+ if (scenario === 'retry') {+ await waitFor(() =>+ expect(document.querySelector('[role=alert]')?.textContent).toContain('return window offline')+ );+ expect(transport.list.mock.calls).toHaveLength(3);+ failReturn = false;+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[role=alert] button')!));+ await settle();+ }+ if (scenario === 'finish' || scenario === 'rapid return') {+ const active = viewport()!;+ await waitFor(() => expect(firstVisibleRow(active).id).toBe(before.id));+ expect(Math.abs(firstVisibleRow(active).offset - before.offset)).toBeLessThan(3);+ expect(document.activeElement).toBe(focus);+ const pages = transport.list.mock.calls.map(([params]) => params.page);+ expect(scenario === 'rapid return' ? pages.slice(3) : pages).toEqual([+ Math.floor((anchorIndex - 6) / 20),+ Math.floor((anchorIndex - 6) / 20) + 1,+ Math.floor((anchorIndex - 6) / 20) + 2,+ ]);+ } else if (scenario === 'retry') {+ expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull();+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.length).toBeGreaterThan(0);+ expect(returned.scrollTop).toBe(0);+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(0);+ expect(firstVisibleRow(returned).id).toBe('wf-0');+ } else if (['wheel', 'pointer', 'key'].includes(scenario)) {+ expect(returned.scrollTop).toBe(canceledOffset);+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(0);+ expect(firstVisibleRow(returned).id).toBe('wf-0');+ } else if (scenario === 'filter') {+ expect(browse.getWorkflowLibraryBrowseSnapshot().filter.tag).toBe('fixture1000');+ expect(firstVisibleRow(viewport()!).id).toBe('wf-0');+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(0);+ } else if (scenario === 'account') {+ expect(browse.getWorkflowLibraryBrowseSnapshot().scrollAnchor).toBeUndefined();+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(0);+ } else {+ expect(returned.isConnected).toBe(false);+ }+ const canceled = !['finish', 'unmount'].includes(scenario);+ expect(transport.list.mock.calls.slice(0, 3).every(([params]) => params.signal?.aborted)).toBe(canceled);+ expect(transport.list.mock.calls).toHaveLength(+ ['wheel', 'pointer', 'key', 'rapid return', 'retry'].includes(scenario) ? 6 : 3+ );+ if (scenario === 'account' || scenario === 'unmount') {+ expect(browse.getWorkflowLibraryBrowseRetention().parsedDocuments).toBe(0);+ }+ expect(browse.getWorkflowLibraryBrowseRetention().metadataEntries).toBeLessThanOrEqual(540);+ expect(document.querySelectorAll('[data-workflow-card]').length).toBeLessThan(48);+ },+ 15000+);++it('records fractional scroll without rendering the shell or committing toolbar and detail', async () => {+ await open();+ await settle();+ const scroll = viewport()!;+ await scrollTo(scroll, 20);+ await settle();+ const before = browse.getWorkflowLibraryBrowseSnapshot();+ const first = firstVisibleRow(scroll).id;+ expect(commits.shell).toBeGreaterThan(0);+ expect(commits.toolbar).toBeGreaterThan(0);+ expect(commits.detail).toBeGreaterThan(0);+ commits.shell = commits.toolbar = commits.detail = 0;+ await scrollTo(scroll, 25);+ await settle();+ const after = browse.getWorkflowLibraryBrowseSnapshot();+ expect(firstVisibleRow(scroll).id).toBe(first);+ expect(after.entries).toBe(before.entries);+ expect(after.startIndex).toBe(before.startIndex);+ expect(after.scrollAnchor?.fraction).toBeGreaterThan(before.scrollAnchor?.fraction ?? 0);+ expect(commits.shell).toBe(0);+ expect(commits.toolbar).toBe(0);+ expect(commits.detail).toBe(0);+});++it('fills a tall viewport crossing four server pages and settles without refetch loops', async () => {+ await page.viewport(1280, 4800);+ await open();+ await settle();+ const scroll = viewport()!;+ const rows = Array.from(scroll.querySelectorAll<HTMLElement>('[data-index]'));+ const rowHeight = rows[0]!.getBoundingClientRect().height;+ await scrollTo(scroll, rowHeight * 6.95);+ await settle();+ const bounds = scroll.getBoundingClientRect();+ const renderedRows = Array.from(scroll.querySelectorAll<HTMLElement>('[data-index]')).filter((row) => {+ const rect = row.getBoundingClientRect();+ return rect.bottom > bounds.top && rect.top < bounds.bottom;+ });+ const indexes = renderedRows.map((row) => Number(row.dataset.index));+ expect((Math.max(...indexes) - Math.min(...indexes) + 1) * 3).toBeGreaterThan(41);+ for (const row of renderedRows) {+ expect(row.querySelectorAll('[data-workflow-card]')).toHaveLength(3);+ expect(row.querySelector('[aria-busy=true]')).toBeNull();+ }+ await waitFor(() => expect(browse.getWorkflowLibraryBrowseRetention().activeReads).toBe(0));+ const visibleCards = renderedRows.flatMap((row) =>+ Array.from(row.querySelectorAll<HTMLElement>('[data-workflow-card]'))+ );+ expect(firstVisibleRow(scroll).fraction).toBeGreaterThan(0.9);+ expect(visibleCards.length).toBeLessThanOrEqual(48);+ for (const card of visibleCards) {+ expect(card.textContent).toContain('0 nodes');+ expect(card.querySelector('[data-enrichment-placeholder]')).toBeNull();+ }+ expect(document.querySelectorAll('[data-workflow-card]').length).toBeLessThanOrEqual(60);+ expect(+ browse.getWorkflowLibraryBrowseSnapshot().entries.filter((entry) => entry.enrichment.status === 'ready').length+ ).toBeLessThanOrEqual(48);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(60);+ expect((browse.getWorkflowLibraryBrowseSnapshot().startIndex ?? 0) % 20).toBeGreaterThan(0);+ const requests = transport.list.mock.calls.length;+ await settle();+ expect(transport.list.mock.calls).toHaveLength(requests);+});++it('releases a confirmed deleted focused card while preserving valid focus outside the resident window', async () => {+ await open();+ await settle();+ await act(() => card(0)!.focus());+ const scroll = viewport()!;+ await scrollTo(scroll, 39600);+ await settle();+ expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBeGreaterThan(400);+ expect(card(0)).not.toBeNull();+ expect(document.activeElement).toBe(card(0));+ let deleted = false;+ const record = transport.record.getMockImplementation()!;+ transport.record.mockImplementation((id: string) =>+ deleted && id === 'wf-0' ? Promise.reject(new ApiError('deleted', 404)) : record(id)+ );+ transport.delete.mockImplementation(() => {+ deleted = true;+ return Promise.resolve();+ });+ transport.list.mockImplementation(async (params: ListWorkflowsParams) => {+ const result = await list(params);+ return deleted+ ? {+ ...result,+ total: count - 1,+ items: result.items.map((entry) => item(Number(entry.workflow_id.slice(3)) + 1)),+ }+ : result;+ });+ await act(() => userEvent.click(detail().querySelector<HTMLElement>('[aria-label="workflowLibrary.moreActions"]')!));+ await act(() => userEvent.click(page.getByRole('menuitem', { name: 'workflowLibrary.delete', exact: false })));+ await act(() => userEvent.click(page.getByRole('button', { name: 'workflowLibrary.delete', exact: true })));+ await waitFor(() => expect(transport.delete).toHaveBeenCalledWith('wf-0'));+ await settle();+ expect(card(0)).toBeNull();+ expect(document.querySelector('[data-workflow-detail="wf-0"]')).toBeNull();+});++it('returns detail selection to the first resident entry when the previous choice is absent', async () => {+ await open();+ const scroll = viewport()!;+ await scrollTo(scroll, 39600);+ await settle();+ const resident = browse.getWorkflowLibraryBrowseSnapshot().entries[0]!.item.workflow_id;+ const before = firstVisibleRow(scroll);+ await act(() => userEvent.click(page.getByRole('button', { name: 'fixture1000', exact: false })));+ await settle();+ const requests = transport.list.mock.calls.length;+ await act(() => userEvent.click(page.getByRole('button', { name: 'workflowLibrary.allTag', exact: false })));+ await settle();+ expect(document.querySelector(`[data-workflow-detail="${resident}"]`)).not.toBeNull();+ expect(firstVisibleRow(viewport()!).id).toBe(before.id);+ expect(transport.list.mock.calls).toHaveLength(requests);+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsxindex f43d1bc1ce..289893cf04 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx@@ -61,6 +61,18 @@ import {/** Install missing models before offering Open; keep the detail rail mounted across selections to prevent flashing. */const DETAIL_RAIL_WIDTH = '18rem';+const DETAIL_RAIL_CSS = {+ '@container workflow-library-content (width < 42rem) and ((height >= 32rem) or (width < 32rem))': {+ width: '100%',+ },+ '@container workflow-library-content (width < 42rem) and (height >= 32rem)': {+ flexBasis: '45%',+ },+ '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {+ flex: '0 0 auto',+ height: '20rem',+ },+} as const;const INSTALL_HOVER = { opacity: 0.85 } as const;type VisibilityState =@@ -112,6 +124,14 @@ export const WorkflowLibraryDetailPanel = ({onPreview,projectWorkflows,}: WorkflowLibraryDetailPanelProps) => {+ const panelRef = useRef<HTMLDivElement>(null);+ // Portaled action menus belong to this dialog's visible bounds, rather than the whole viewport.+ const menuPositioning = useMemo(+ () => ({+ boundary: () => panelRef.current?.closest<HTMLElement>('[data-scope="dialog"][data-part="content"]') ?? [],+ }),+ []+ );const { t } = useTranslation();const deps = useModelRequirementDeps();const notify = useWorkflowNotifications();@@ -355,11 +375,12 @@ export const WorkflowLibraryDetailPanel = ({() =>contextMenuPoint?.kind === 'point'? {+ ...menuPositioning,getAnchorRect: () => ({ height: 1, width: 1, x: contextMenuPoint.x, y: contextMenuPoint.y }),placement: 'bottom-start' as const,}- : { placement: 'bottom-end' as const },- [contextMenuPoint]+ : { ...menuPositioning, placement: 'bottom-end' as const },+ [contextMenuPoint, menuPositioning]);const handleContextMenuOpenChange = useCallback((event: { open: boolean }) => {@@ -628,6 +649,8 @@ export const WorkflowLibraryDetailPanel = ({<StackborderColor="border.subtle"borderWidth="1px"+ css={DETAIL_RAIL_CSS}+ ref={panelRef}data-workflow-detail={item.workflow_id}flexShrink={0}gap="0"@@ -712,7 +735,7 @@ export const WorkflowLibraryDetailPanel = ({) : null}{item.description ? (- <Text color="fg.muted" fontSize="xs" lineClamp={4}>+ <Text color="fg.muted" fontSize="xs" overflowWrap="anywhere">{item.description}</Text>) : null}@@ -754,7 +777,7 @@ export const WorkflowLibraryDetailPanel = ({{openLabel}</Button>)}- <Menu.Root ids={moreActionsIds}>+ <Menu.Root ids={moreActionsIds} positioning={menuPositioning}>{/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, themenu never takes focus and the first pointer move onto it closes it. */}<Menu.Trigger asChild>@@ -766,7 +789,9 @@ export const WorkflowLibraryDetailPanel = ({</Menu.Trigger><Portal><Menu.Positioner>- <MenuContent minW="16rem">{actionItems}</MenuContent>+ <MenuContent minW="min(16rem, var(--available-width))" maxW="var(--available-width)">+ {actionItems}+ </MenuContent></Menu.Positioner></Portal></Menu.Root>@@ -794,7 +819,11 @@ export const WorkflowLibraryDetailPanel = ({><Portal><Menu.Positioner>- <MenuContent data-workflow-context-menu minW="16rem">+ <MenuContent+ data-workflow-context-menu+ minW="min(16rem, var(--available-width))"+ maxW="var(--available-width)"+ >{actionItems}</MenuContent></Menu.Positioner>@@ -812,7 +841,15 @@ export const WorkflowLibraryDetailPanel = ({/></Stack>) : (- <Box borderColor="border.subtle" borderWidth="1px" flexShrink={0} minH="0" rounded="md" w={DETAIL_RAIL_WIDTH} />+ <Box+ css={DETAIL_RAIL_CSS}+ borderColor="border.subtle"+ borderWidth="1px"+ flexShrink={0}+ minH="0"+ rounded="md"+ w={DETAIL_RAIL_WIDTH}+ />)}{/* Outside the rail: a delete empties or retargets it while this dialog animates out. */}<ConfirmDialogdiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsxindex 454160472b..40a7c9af1c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx@@ -6,6 +6,7 @@ import type {ProjectGraphState,ProjectWorkflowEntry,} from '@features/workflow/core/types';+import type * as libraryBrowseStoreModule from '@features/workflow/data/libraryBrowseStore';import type {WorkflowLibraryBrowseSnapshot,WorkflowLibraryEntry,@@ -28,6 +29,7 @@ import {workflowUiStore,} from '@features/workflow/ui/workflowUiStore';import { buildInvocationNode, createProjectGraph, projectGraphReducer } from '@features/workflow/utility';+import { settleAnimations } from '@platform/browser/settleAnimations.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';import { system } from '@theme/system';import { act, StrictMode } from 'react';@@ -128,12 +130,13 @@ const browse = vi.hoisted(() => ({ensureWorkflowLibraryBrowseLoaded: vi.fn(() => Promise.resolve()),// Assigned by the module factory below, which owns the store instance.getSnapshot: null as null | (() => WorkflowLibraryBrowseSnapshot),- loadNextWorkflowLibraryPage: vi.fn(),+ loadWorkflowLibraryRange: vi.fn((_start: number, _end: number) => Promise.resolve(true)),setSnapshot: null as null | ((snapshot: WorkflowLibraryBrowseSnapshot) => void),setWorkflowLibraryBrowseFilter: vi.fn(),}));-vi.mock('@features/workflow/data/libraryBrowseStore', async () => {+vi.mock('@features/workflow/data/libraryBrowseStore', async (original) => {+ const { selectWorkflowLibraryEntry } = await original<typeof libraryBrowseStoreModule>();const { createExternalStore } = await import('@platform/state/externalStore');const store = createExternalStore<WorkflowLibraryBrowseSnapshot>({entries: [],@@ -151,9 +154,13 @@ vi.mock('@features/workflow/data/libraryBrowseStore', async () => {browse.setSnapshot = store.setSnapshot;return {+ selectWorkflowLibraryEntry,ensureWorkflowLibraryBrowseLoaded: browse.ensureWorkflowLibraryBrowseLoaded,getWorkflowLibraryBrowseSnapshot: store.getSnapshot,- loadNextWorkflowLibraryPage: browse.loadNextWorkflowLibraryPage,+ loadWorkflowLibraryRange: browse.loadWorkflowLibraryRange,+ rememberWorkflowLibraryScroll: vi.fn(),+ setWorkflowLibraryVisibleDemand: vi.fn(),+ setWorkflowLibrarySelectedDemand: vi.fn(),setWorkflowLibraryBrowseFilter: browse.setWorkflowLibraryBrowseFilter,useWorkflowLibraryBrowseSelector: store.useSelector,};@@ -194,6 +201,18 @@ vi.mock('@features/models', async (importOriginal) => ({// Provide English/plural strings without booting the HTTP-backed i18n client.const TRANSLATIONS: Record<string, string> = {+ 'workflowLibrary.openProjectWorkflowHint': 'Makes it the active workflow',+ 'workflowLibrary.renameProjectWorkflowHint': 'Changes its name in this project; a linked template keeps its own',+ 'workflowLibrary.duplicateProjectWorkflowHint': 'A copy beside it in this project',+ 'workflowLibrary.saveToLibraryHint': 'Creates a new template from this workflow',+ 'workflowLibrary.updateTemplateHint': 'Writes this workflow over its library template',+ 'workflowLibrary.removeHint': 'Removes it from this project only',+ 'workflowLibrary.renameTemplateHint': "Changes the template's name in the library",+ 'workflowLibrary.duplicateHint': 'Saves a copy under Yours, original untouched',+ 'workflowLibrary.downloadJsonHint': 'For bug reports and sharing',+ 'workflowLibrary.forkIntoProjectHint': 'Copies it into a new project',+ 'workflowLibrary.deleteHint': 'Removes it from your library',+'common.close': 'Close','workflowLibrary.activeWorkflow': 'Active','workflowLibrary.addAnotherCopy': 'Add another copy',@@ -212,7 +231,6 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.installModels_one': 'Install 1 model','workflowLibrary.installModels_other': 'Install {{count}} models','workflowLibrary.loading': 'Loading workflows…',- 'workflowLibrary.loadingMore': 'Loading more…','workflowLibrary.moreActions': 'More actions','workflowLibrary.newWorkflow': 'New workflow','workflowLibrary.nodeCount_one': '{{count}} node',@@ -556,38 +574,41 @@ describe('WorkflowLibraryDialog', () => {const gridViewport = () => document.querySelector<HTMLElement>('[role="region"][aria-label="Workflows"]');- /**- * Real layout in a `Dialog` portal gives no deterministic scroll geometry,- * so the viewport's metrics are defined directly — the assertion is about- * the dialog's near-bottom threshold, not the browser's layout engine.- */- const scrollTo = async (scrollTop: number) => {- const viewport = gridViewport();- expect(viewport).not.toBeNull();-- for (const [property, value] of [- ['clientHeight', 400],- ['scrollHeight', 4000],- ['scrollTop', scrollTop],- ] as const) {- Object.defineProperty(viewport, property, { configurable: true, value, writable: true });- }+ const expectContained = (element: HTMLElement | Range, container: HTMLElement) => {+ const box = element.getBoundingClientRect();+ const bounds = container.getBoundingClientRect();+ expect(box.left).toBeGreaterThanOrEqual(bounds.left - 1);+ expect(box.right).toBeLessThanOrEqual(bounds.right + 1);+ expect(box.top).toBeGreaterThanOrEqual(bounds.top - 1);+ expect(+ box.bottom,+ element instanceof HTMLElement ? element.outerHTML.slice(0, 180) : 'metadata ending'+ ).toBeLessThanOrEqual(bounds.bottom + 1);+ };- await act(async () => {- viewport?.dispatchEvent(new Event('scroll'));- // Settle deferred ScrollArea reactions within the same act scope.- await settleFrame();+ const expectWrappedRenameHint = async (menu: HTMLElement, dialog: HTMLElement) => {+ await act(() => userEvent.keyboard('{Home}{ArrowDown}'));+ const rename = menu.querySelector<HTMLElement>('[data-menu-item="rename"]')!;+ await vi.waitFor(() => {+ expect(menu.getAttribute('aria-activedescendant')).toBe(rename.id);+ const hint = rename.querySelector('p')!;+ expect(hint.textContent).toBe(TRANSLATIONS['workflowLibrary.renameProjectWorkflowHint']);+ const text = document.createRange();+ text.selectNodeContents(hint);+ expect(text.getClientRects().length).toBeGreaterThan(1);+ expectContained(text, menu);+ expectContained(text, dialog);});};- beforeEach(() => {+ beforeEach(async () => {+ await resizeViewport(1280, 800);host = document.createElement('div');document.body.append(host);root = createRoot(host);onOpenChange = vi.fn((_isOpen: boolean) => {});identity.session = { multiuserEnabled: false, phase: 'ready', user: null };browse.ensureWorkflowLibraryBrowseLoaded.mockClear();- browse.loadNextWorkflowLibraryPage.mockClear();browse.setWorkflowLibraryBrowseFilter.mockClear();loader.open.mockClear();loader.resume.mockClear();@@ -931,16 +952,384 @@ describe('WorkflowLibraryDialog', () => {expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ search: 'photo' });});- it('requests the next page only once the grid is scrolled near the bottom', async () => {- await openWith(LOADED_SNAPSHOT);+ it('bounds mounted cards and requests server positions while scrolling 1,000 workflows', async () => {+ await resizeViewport(1280, 800);+ const entries = Array.from({ length: 1000 }, (_, index) => ({+ ...LOADED_SNAPSHOT.entries[0]!,+ item: { ...LOADED_SNAPSHOT.entries[0]!.item, workflow_id: `large-${index}`, name: `Large ${index}` },+ }));+ await openWith({ ...LOADED_SNAPSHOT, entries, total: 1000, pages: 50 });+ expect(cards().length).toBeGreaterThan(0);+ expect(cards().length).toBeLessThan(40);+ const viewport = gridViewport()!;+ await act(async () => {+ viewport.scrollTop = 3200;+ viewport.dispatchEvent(new Event('scroll'));+ await settleFrame();+ });+ expect(cards().length).toBeLessThan(40);+ expect(browse.loadWorkflowLibraryRange.mock.calls.some(([start]) => Number(start) > 0)).toBe(true);+ await act(async () => {+ viewport.scrollTop = 0;+ viewport.dispatchEvent(new Event('scroll'));+ await settleFrame();+ });+ expect(card('large-0')).not.toBeNull();+ });- await scrollTo(100);+ it('keeps measured rows separated after viewport resize, zoom and text reflow', async () => {+ const entries = Array.from({ length: 90 }, (_, index) => ({+ ...PORTRAIT,+ item: { ...PORTRAIT.item, workflow_id: `reflow-${index}`, name: LONG_NAME },+ }));+ await openWith({ ...LOADED_SNAPSHOT, entries, total: 90, pages: 5 });+ const rootStyle = document.documentElement.style;+ const previousZoom = rootStyle.zoom;+ const previousFontSize = rootStyle.fontSize;+ onTestFinished(() => {+ rootStyle.zoom = previousZoom;+ rootStyle.fontSize = previousFontSize;+ });- expect(browse.loadNextWorkflowLibraryPage).not.toHaveBeenCalled();+ const expectRowGaps = async (zoom = 1, gap = 12) => {+ await vi.waitFor(() => {+ const rows = [...new Set(cards().map((element) => element.closest<HTMLElement>('[data-index]')!))].sort(+ (a, b) => Number(a.dataset.index) - Number(b.dataset.index)+ );+ expect(rows.length).toBeGreaterThanOrEqual(3);+ expect(cards().length).toBeLessThan(40);+ for (let index = 1; index < rows.length; index += 1) {+ const previous = rows[index - 1]!;+ const current = rows[index]!;+ const previousRect = previous.getBoundingClientRect();+ const currentRect = current.getBoundingClientRect();+ // Row padding owns the 12px gap; the row boxes themselves must meet without overlap.+ expect(Math.abs((currentRect.top - previousRect.bottom) / zoom)).toBeLessThanOrEqual(1);+ const cardBottom = Math.max(+ ...[...previous.querySelectorAll<HTMLElement>('[data-workflow-card]')].map(+ (element) => element.getBoundingClientRect().bottom+ )+ );+ expect(Math.abs((currentRect.top - cardBottom) / zoom - gap)).toBeLessThanOrEqual(1);+ }+ });+ };- await scrollTo(3200);+ await expectRowGaps();+ await page.viewport(700, 800);+ await expectRowGaps();+ await page.viewport(1280, 800);+ await expectRowGaps();+ await act(() => {+ rootStyle.zoom = '2';+ });+ await expectRowGaps(2);+ await act(() => {+ rootStyle.zoom = previousZoom;+ rootStyle.fontSize = '20px';+ });+ // Text scaling also scales the rem-based gap.+ await expectRowGaps(1, 15);+ await act(() => {+ const viewport = gridViewport()!;+ viewport.scrollTop = 1000;+ viewport.dispatchEvent(new Event('scroll'));+ });+ await page.viewport(900, 800);+ await expectRowGaps(1, 15);+ });- expect(browse.loadNextWorkflowLibraryPage).toHaveBeenCalled();+ it.each(+ (['library', 'project'] as const).flatMap((view) =>+ [+ [640, 400],+ [512, 384],+ [320, 400],+ [1280, 320],+ [700, 320],+ [640, 320],+ [512, 320],+ [320, 320],+ ].map(([width, height]) => ({ view, width: width!, height: height! }))+ )+ )(+ 'keeps the $view grid, selected metadata and actions usable at $width×$height layout viewport',+ async ({ view, width: targetWidth, height: targetHeight }) => {+ const description = `${'Required workflow metadata. '.repeat(200)}End of required metadata.`;+ const entries = [+ { ...PREVIEW_FIXTURE, item: { ...PREVIEW_FIXTURE.item, description } },+ ...Array.from({ length: 1000 }, (_, index) => ({+ ...PORTRAIT,+ item: { ...PORTRAIT.item, workflow_id: `layout-${index}` },+ })),+ ];+ project.setSnapshot(+ projectSnapshot([+ ...PROJECT_WORKFLOWS.map((entry) =>+ entry === USER_COPY ? { ...entry, document: { ...entry.document, description } } : entry+ ),+ ...Array.from({ length: 1000 }, (_, index) => ({+ ...USER_COPY,+ document: { ...USER_COPY.document, id: `project-layout-${index}` },+ })),+ ])+ );+ await openWith(withSnapshot({ entries, total: entries.length, pages: 51 }));+ if (view === 'project') {+ await clickSegment('project');+ await vi.waitFor(() => expect(card('wf-user')).not.toBeNull());+ await act(() => card('wf-user')!.click());+ expect(document.querySelector('[data-project-workflow-detail="wf-user"]')).not.toBeNull();+ }++ const dialog = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;+ const detail = dialog.querySelector<HTMLElement>('[data-workflow-detail], [data-project-workflow-detail]')!;+ const metadata = detail.querySelector<HTMLElement>('[role="region"]')!;+ const grid = gridViewport()!;+ const close = dialog.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!;+ const open = [...detail.querySelectorAll<HTMLButtonElement>('button')].find(+ (button) => button.textContent === 'Open'+ )!;+ const preview = [...detail.querySelectorAll<HTMLButtonElement>('button')].find(+ (button) => button.textContent === 'Preview graph'+ )!;+ const menu = detail.querySelector<HTMLButtonElement>('button[aria-label="More actions"]')!;++ for (const [width, height] of [+ [1280, 800],+ [700, 800],+ [targetWidth, targetHeight],+ ] as const) {+ // Real layout-viewport reduction, as at 200% browser zoom on a 1280×800 display. CSS zoom misses this.+ await page.viewport(width, height);+ expect(window.innerWidth).toBe(width);+ expect(window.innerHeight).toBe(height);+ await vi.waitFor(() => {+ // Enough for readable metadata and a substantial part of a card, rather than merely nonzero boxes.+ expect(metadata.clientHeight, 'selected metadata scroll viewport').toBeGreaterThanOrEqual(80);+ expect(grid.clientHeight, 'workflow grid scroll viewport').toBeGreaterThanOrEqual(120);+ expect(grid.clientHeight, 'finite virtual grid viewport').toBeLessThanOrEqual(640);+ expect(detail.clientHeight, 'finite detail pane').toBeLessThanOrEqual(640);+ if (width <= 512 || height === 320) {+ expect(grid.clientHeight, 'flow grid has a finite viewport').toBe(256);+ expect(detail.getBoundingClientRect().height, 'flow detail does not grow with metadata').toBe(320);+ }+ expect(dialog.scrollWidth).toBeLessThanOrEqual(dialog.clientWidth + 1);+ expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(width);+ expect(dialog.getBoundingClientRect().top).toBeGreaterThanOrEqual(0);+ expect(dialog.getBoundingClientRect().bottom).toBeLessThanOrEqual(height);+ if ((width >= 640 && height >= 400) || height >= 640) {+ for (const action of [open, preview, menu, close]) {+ expectContained(action, dialog);+ }+ }+ for (const control of dialog.querySelectorAll<HTMLElement>(+ 'input[type="search"], [role="combobox"], [role="tab"], [aria-label="Thumbnail display"]'+ )) {+ expectContained(control, dialog);+ }+ if ((width === 700 && height >= 640) || width <= 512) {+ expect(grid.getBoundingClientRect().bottom).toBeLessThanOrEqual(detail.getBoundingClientRect().top);+ } else {+ expect(grid.getBoundingClientRect().right).toBeLessThanOrEqual(detail.getBoundingClientRect().left);+ }+ expect(grid.scrollWidth).toBeLessThanOrEqual(grid.clientWidth + 1);+ expect(cards().length).toBeGreaterThan(0);+ expect(cards().length).toBeLessThan(40);+ for (const element of cards()) {+ const box = element.getBoundingClientRect();+ const bounds = grid.getBoundingClientRect();+ expect(box.left).toBeGreaterThanOrEqual(bounds.left);+ expect(box.right).toBeLessThanOrEqual(bounds.right + 1);+ expect(box.width).toBeGreaterThanOrEqual(180);+ const row = element.closest<HTMLElement>('[data-index]')!;+ expectContained(element, row);+ const nextRow = row.nextElementSibling;+ if (nextRow) {+ expect(box.bottom).toBeLessThanOrEqual(nextRow.getBoundingClientRect().top);+ }+ }+ });+ }++ const expectUnclipped = (element: HTMLElement) => {+ expectContained(element, dialog);+ for (let parent = element.parentElement; parent && parent !== dialog; parent = parent.parentElement) {+ const style = getComputedStyle(parent);+ if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {+ expectContained(element, parent);+ }+ }+ };+ await act(() => cards()[0]!.focus());+ const focusedCard = cards()[0]!.getBoundingClientRect();+ const gridBounds = grid.getBoundingClientRect();+ const modalBounds = dialog.getBoundingClientRect();+ expect(+ Math.min(focusedCard.bottom, gridBounds.bottom, modalBounds.bottom) -+ Math.max(focusedCard.top, gridBounds.top, modalBounds.top)+ ).toBeGreaterThanOrEqual(120);+ await act(() => grid.focus());+ await act(() => userEvent.keyboard('{PageDown}'));+ await vi.waitFor(() => {+ expect(grid.scrollTop).toBeGreaterThan(0);+ expect(cards().length).toBeLessThan(40);+ expect(grid.clientHeight).toBeLessThanOrEqual(640);+ });+ await act(() => metadata.focus());+ expect(document.activeElement).toBe(metadata);+ expectUnclipped(metadata);+ await act(() => userEvent.keyboard('{End}'));+ await vi.waitFor(() => {+ expect(metadata.scrollTop).toBeGreaterThan(0);+ const lastMetadata =+ metadata.querySelector<HTMLElement>('[data-workflow-source]') ?? [...metadata.querySelectorAll('p')].at(-1)!;+ const ending = document.createRange();+ ending.selectNodeContents(lastMetadata);+ const text = lastMetadata.firstChild!;+ ending.setStart(text, Math.max(0, text.textContent!.length - 24));+ expectContained(ending, metadata);+ expectContained(ending, dialog);+ });++ // Native focus scrolling must bring each action into the modal's clipped viewport, including flow layouts.+ const reached = new Set<Element>();+ for (let index = 0; index < 40 && reached.size < 4; index += 1) {+ await act(() => userEvent.keyboard('{Tab}'));+ if ([open, preview, menu, close].includes(document.activeElement as HTMLButtonElement)) {+ expectUnclipped(document.activeElement as HTMLElement);+ reached.add(document.activeElement!);+ }+ }+ expect(reached.size).toBe(4);+ const toolbarTargets = [+ dialog.querySelector<HTMLElement>('input[type="search"]'),+ dialog.querySelector<HTMLElement>('[role="combobox"]'),+ dialog.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'),+ [...dialog.querySelectorAll<HTMLButtonElement>('button')].find(+ (button) => button.textContent === 'New workflow'+ ),+ ].filter((element): element is HTMLElement => Boolean(element));+ const toolbarReached = new Set<Element>();+ for (const key of ['{Shift>}{Tab}{/Shift}', '{Tab}']) {+ await act(() => close.focus());+ for (let index = 0; index < 30; index += 1) {+ await act(() => userEvent.keyboard(key));+ const focused = document.activeElement as HTMLElement;+ if (focused.hasAttribute('data-workflow-card')) {+ break;+ }+ if (toolbarTargets.includes(focused)) {+ expectUnclipped(focused);+ toolbarReached.add(focused);+ }+ }+ }+ expect(toolbarReached.size).toBe(toolbarTargets.length);+ if (dialog.scrollHeight > dialog.clientHeight + 1) {+ await act(() => close.focus());+ await act(() => userEvent.keyboard('{End}'));+ await vi.waitFor(() => {+ expect(dialog.scrollTop).toBeGreaterThan(0);+ expectUnclipped(preview);+ });+ }+ // Focus first, as a keyboard user would, so offscreen controls scroll into view before activation.+ await act(() => menu.focus());+ expectUnclipped(menu);+ await act(() => userEvent.keyboard('{Enter}'));+ await vi.waitFor(() => expect(menu.getAttribute('aria-expanded')).toBe('true'));+ const menuContent = document.querySelector<HTMLElement>('[role="menu"]')!;+ // Open state precedes the entry slide's final geometry.+ await act(() => settleAnimations(menuContent));+ expectContained(menuContent, dialog);+ if (view === 'project' && targetWidth === 320) {+ await expectWrappedRenameHint(menuContent, dialog);+ }+ await act(() => userEvent.keyboard('{End}'));+ const lastAction = [...menuContent.querySelectorAll<HTMLElement>('[role="menuitem"]')].at(-1)!;+ await vi.waitFor(() => {+ expect(menuContent.getAttribute('aria-activedescendant')).toBe(lastAction.id);+ expectContained(lastAction, menuContent);+ expectContained(lastAction, dialog);+ });+ await act(() => userEvent.keyboard('{Escape}'));+ await act(() => preview.focus());+ expectUnclipped(preview);+ await act(() => userEvent.keyboard('{Enter}'));+ await waitForPreviewDialog();+ expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();+ // The preview renderer is stubbed; close it through its existing harness controls before using the rail.+ await clickText('Close preview');+ await clickText('Finish preview exit');+ await act(() => open.focus());+ expectUnclipped(open);+ await act(() => userEvent.keyboard('{Enter}'));+ expect(view === 'project' ? COMMANDS.selectWorkflow : loader.open).toHaveBeenCalled();+ await act(() => close.focus());+ expectUnclipped(close);+ await act(() => userEvent.keyboard('{Enter}'));+ expect(onOpenChange).toHaveBeenCalledWith(false);+ }+ );++ it('keeps keyboard focus mounted across virtual row boundaries', async () => {+ await resizeViewport(1280, 800);+ const entries = Array.from({ length: 90 }, (_, index) => ({+ ...PORTRAIT,+ item: { ...PORTRAIT.item, workflow_id: `key-${index}` },+ }));+ await openWith({ ...LOADED_SNAPSHOT, entries, total: 90, pages: 5 });+ await act(() => document.querySelector<HTMLElement>('[data-workflow-card-menu="key-0"]')?.focus());+ for (let index = 1; index <= 18; index += 1) {+ await act(async () => {+ await userEvent.keyboard('{Tab}');+ await settleFrame();+ await settleFrame();+ });+ await vi.waitFor(() => expect(document.activeElement?.getAttribute('data-workflow-card')).toBe(`key-${index}`));+ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement?.getAttribute('data-workflow-card-menu')).toBe(`key-${index}`);+ }+ expect(cards().length).toBeLessThan(40);+ });++ it.each(['library', 'project'] as const)('keeps the %s card menu inside its dialog while resizing', async (view) => {+ await resizeViewport(320, 320);+ await openWith(LOADED_SNAPSHOT);+ if (view === 'project') {+ await clickSegment('project');+ }+ await vi.waitFor(() => expect(card(view === 'project' ? 'wf-alpha' : 'wf-landscape')).not.toBeNull());+ const source = card(view === 'project' ? 'wf-alpha' : 'wf-landscape')!;+ await act(() => source.focus());+ // Keyboard context-menu events have no pointer coordinates.+ await act(() => source.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })));+ await vi.waitFor(() =>+ expect(document.querySelector('[data-workflow-context-menu][data-state="open"]')).not.toBeNull()+ );+ const menu = document.querySelector<HTMLElement>('[data-workflow-context-menu][data-state="open"]')!;+ const dialog = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;+ await act(() => settleAnimations(menu));+ expectContained(menu, dialog);+ if (view === 'project') {+ await expectWrappedRenameHint(menu, dialog);+ }+ await act(() => userEvent.keyboard('{End}'));+ const lastAction = [...menu.querySelectorAll<HTMLElement>('[role="menuitem"]')].at(-1)!;+ await vi.waitFor(() => {+ expect(menu.getAttribute('aria-activedescendant')).toBe(lastAction.id);+ expectContained(lastAction, menu);+ expectContained(lastAction, dialog);+ });+ await resizeViewport(700, 320);+ await vi.waitFor(() => {+ expect(menu.getAttribute('data-state')).toBe('open');+ expectContained(menu, dialog);+ });+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.activeElement).toBe(source));+ expect(document.querySelector('[data-workflow-context-menu][data-state="open"]')).toBeNull();});it('auto-selects the first entry and moves the selection when it disappears', async () => {@@ -1341,6 +1730,7 @@ describe('WorkflowLibraryDialog', () => {const content = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;const contentBox = content.getBoundingClientRect();+ expect(content.scrollWidth).toBeLessThanOrEqual(content.clientWidth + 1);const title = content.querySelector<HTMLElement>('[data-part="title"]')!;const close = content.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!;const tabs = [...content.querySelectorAll<HTMLElement>('[role="tab"]')];diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex 6a9ebd854c..f78a4ea759 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -23,7 +23,9 @@ import { useAuthSession } from '@features/identity';import {ensureWorkflowLibraryBrowseLoaded,getWorkflowLibraryBrowseSnapshot,+ selectWorkflowLibraryEntry,setWorkflowLibraryBrowseFilter,+ setWorkflowLibrarySelectedDemand,useWorkflowLibraryBrowseSelector,} from '@features/workflow/data/libraryBrowseStore';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';@@ -63,6 +65,27 @@ import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';import { WorkflowThumbnailFitContext } from './workflowThumbnail';const SEARCH_DEBOUNCE_MS = 300;+// Short windows need the panes' full shared height; reclaim modal margins before compressing the toolbar.+const CONTENT_CSS: SystemStyleObject = {+ containerName: 'workflow-library-content',+ containerType: 'size',+ overflowY: 'auto',+ '@media (height < 40rem)': {+ h: 'calc(100dvh - 2rem)',+ maxH: 'calc(100dvh - 2rem)',+ maxW: 'min(72rem, calc(100vw - 1rem))',+ },+};+// A 180px card, 18rem rail, gap and body padding need 32rem; below that, keep the stacked layout.+const BODY_CSS: SystemStyleObject = {+ '@container workflow-library-content (width < 42rem) and ((height >= 32rem) or (width < 32rem))': {+ flexDirection: 'column',+ },+ // Finite panes enter modal scroll flow when they cannot share the remaining height.+ '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {+ flex: '0 0 auto',+ },+};const TAB_ITEMS: ReadonlyArray<{ labelKey: string; value: WorkflowLibraryTab }> = [{ labelKey: 'workflowLibrary.thisProject', value: 'project' },@@ -112,8 +135,13 @@ const SORT_SELECT_CSS: SystemStyleObject = { [NARROW_HEADER]: { flex: '1', minW:/** Flat and shallow-comparable, so unrelated store patches do not re-render the shell. */const selectBrowseView = (snapshot: WorkflowLibraryBrowseSnapshot) => ({+ viewKey: JSON.stringify(snapshot.filter),category: snapshot.filter.category,entries: snapshot.entries,+ startIndex: snapshot.startIndex ?? 0,+ filter: snapshot.filter,+ total: snapshot.total,+ selectedEntry: snapshot.selectedEntry,error: snapshot.error,isPublic: snapshot.filter.isPublic,status: snapshot.status,@@ -158,8 +186,20 @@ export const WorkflowLibraryDialog = ({onOpenChange: (isOpen: boolean) => void;}) => {const { t } = useTranslation();- const { category, entries, error, isPublic, status, tag, tagCounts } =- useWorkflowLibraryBrowseSelector(selectBrowseView);+ const {+ category,+ entries,+ error,+ isPublic,+ status,+ tag,+ tagCounts,+ startIndex,+ filter,+ total,+ selectedEntry,+ viewKey,+ } = useWorkflowLibraryBrowseSelector(selectBrowseView);const { selection, tab } = workflowUiStore.useSelector(selectLibraryNavigation);const authSession = useAuthSession();const projectId = useWorkflowProjectSelector((project) => project.id);@@ -170,6 +210,7 @@ export const WorkflowLibraryDialog = ({const thumbnailFit = useWorkflowPreferencesSelector((preferences) => preferences.workflowLibraryThumbnailFit);const [searchInput, setSearchInput] = useState('');const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(null);+ const [removedWorkflowId, setRemovedWorkflowId] = useState<string | null>(null);// Clear pending preview entries on every library-close path because the persistent shell otherwise resurrects// them on reopen.const [previewRequest, setPreviewRequest] = useState<PreviewRequest | null>(null);@@ -193,10 +234,13 @@ export const WorkflowLibraryDialog = ({const missingCounts = useWorkflowLibraryMissingCounts(entries);// Derive a fallback selection when filtering/deletion removes the selected row.- const activeWorkflowId = entries.some((entry) => entry.item.workflow_id === selectedWorkflowId)- ? selectedWorkflowId- : (entries[0]?.item.workflow_id ?? null);- const activeEntry = entries.find((entry) => entry.item.workflow_id === activeWorkflowId) ?? null;+ const desiredWorkflowId = selectedWorkflowId ?? selectedEntry?.item.workflow_id ?? null;+ const activeWorkflowId =+ selectedEntry?.item.workflow_id === desiredWorkflowId ||+ entries.some((entry) => entry.item.workflow_id === desiredWorkflowId)+ ? desiredWorkflowId+ : (entries[0]?.item.workflow_id ?? null);+ const activeEntry = selectWorkflowLibraryEntry({ entries, selectedEntry }, activeWorkflowId) ?? null;const isCurrentLibraryOwner =authSession.phase === 'ready' &&(authSession.multiuserEnabled@@ -361,9 +405,10 @@ export const WorkflowLibraryDialog = ({);const handleDeleted = useCallback(() => {+ setRemovedWorkflowId(activeWorkflowId);setSelectedWorkflowId(null);setContextMenuPoint(null);- }, []);+ }, [activeWorkflowId]);const handleCardContextMenu = useCallback((workflowId: string, point: WorkflowCardMenuAnchor) => {if (tab === 'project') {@@ -401,6 +446,7 @@ export const WorkflowLibraryDialog = ({[projectId]);+ const browseWindow = useMemo(() => ({ startIndex, total, filter }), [startIndex, total, filter]);const isProjectTab = tab === 'project';const tabsIdBase = useId();const activeTab: WorkflowLibraryTab = tab;@@ -421,6 +467,7 @@ export const WorkflowLibraryDialog = ({<Dialog.Positioner><Dialog.Contentref={preloadGraphPreview}+ css={CONTENT_CSS}aria-busy={isLoadPending}h="80vh"maxH="80vh"@@ -517,6 +564,7 @@ export const WorkflowLibraryDialog = ({</Stack></Dialog.Header><Dialog.Body+ css={BODY_CSS}aria-labelledby={segmentTabsTabId(tabsIdBase, activeTab)}data-library-tab={tab}data-pending-preview={previewGraphId || undefined}@@ -541,7 +589,16 @@ export const WorkflowLibraryDialog = ({/>) : (<>+ {isOpen ? (+ <SelectedDemand+ key={`${authSession.user?.user_id}:${viewKey}:${activeWorkflowId}`}+ id={activeWorkflowId}+ />+ ) : null}<WorkflowLibraryGrid+ key={`${authSession.user?.user_id}:${viewKey}`}+ window={browseWindow}+ removedWorkflowId={removedWorkflowId}entries={entries}error={error}missingCounts={missingCounts}@@ -592,3 +649,19 @@ export const WorkflowLibraryDialog = ({</>);};++let selectedLease = 0;+const SelectedDemand = ({ id }: { id: string | null }) => {+ useMountEffect(() => {+ const lease = ++selectedLease;+ setWorkflowLibrarySelectedDemand(id);+ return () => {+ queueMicrotask(() => {+ if (lease === selectedLease) {+ setWorkflowLibrarySelectedDemand(null);+ }+ });+ };+ });+ return null;+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsxindex 4fe6bee9ea..f1c4e0f5d6 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx@@ -1,23 +1,50 @@import type { WorkflowLibraryBrowseSnapshot, WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';-import { Box, HStack, Spinner, Text } from '@chakra-ui/react';-import { loadNextWorkflowLibraryPage } from '@features/workflow/data/libraryBrowseStore';+import { Box, Text } from '@chakra-ui/react';+import {+ getWorkflowLibraryBrowseSnapshot,+ loadWorkflowLibraryRange,+ rememberWorkflowLibraryScroll,+ setWorkflowLibraryVisibleDemand,+} from '@features/workflow/data/libraryBrowseStore';import { useMountEffect } from '@platform/react/useMountEffect';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { Scrollable } from '@platform/ui';-import { useMemo, useRef } from 'react';+import { Button } from '@platform/ui/Button';+import { type ComponentProps, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { defaultRangeExtractor, useVirtualizer } from 'react-hook-tanstack-virtual';import { useTranslation } from 'react-i18next';-import { WorkflowLibraryCard, type WorkflowCardMenuAnchor, type WorkflowLibraryCardProps } from './WorkflowLibraryCard';+import {+ WorkflowLibraryCard,+ getWorkflowLibraryCardId,+ getWorkflowLibraryCardMenuId,+ type WorkflowCardMenuAnchor,+ type WorkflowLibraryCardProps,+} from './WorkflowLibraryCard';-/** How close to the bottom (in viewports) counts as "fetch the next page". */-const NEAR_BOTTOM_VIEWPORTS = 1.5;-const GRID_TEMPLATE_COLUMNS = 'repeat(3, minmax(0, 1fr))';+/** Two rows before and after the viewport, plus one focused/menu row. */+const OVERSCAN_ROWS = 2;+// A partial row and four overscan rows still fit 60 metadata positions at three columns.+const MAX_VISIBLE_ROWS = 15;const NO_MISSING_COUNTS: ReadonlyMap<string, number> = new Map();+// A flow layout still needs a finite virtual viewport, independent of the collection's total row height.+const GRID_CSS = {+ '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {+ flex: '1 1 16rem',+ height: '16rem',+ },+} as const;export interface WorkflowLibraryGridProps {/** The project's active workflow, marked on its card in the This-project view. */activeWorkflowId?: string | null;entries: readonly WorkflowLibraryEntry[];+ window?: {+ startIndex: number;+ total: number;+ filter: WorkflowLibraryBrowseSnapshot['filter'];+ };error: string | null;/** What has the actions menu open, so that tile's control can name it. */openMenuAnchor?: WorkflowCardMenuAnchor | null;@@ -26,17 +53,14 @@ export interface WorkflowLibraryGridProps {/** Missing-model counts by workflow id; absent ids render no badge. */missingCounts?: ReadonlyMap<string, number>;selectedWorkflowId: string | null;+ removedWorkflowId?: string | null;status: WorkflowLibraryBrowseSnapshot['status'];onContextMenu: WorkflowLibraryCardProps['onContextMenu'];onOpen: (workflowId: string) => void;onSelect: (workflowId: string) => void;}-/**- * A refresh landing while an append is in flight can publish the same row- * twice for one frame. Duplicate React keys would corrupt the reconciliation,- * so the grid keeps the first occurrence and drops the rest.- */+/** Keep duplicate server identities from corrupting card reconciliation. */const dedupeByWorkflowId = (entries: readonly WorkflowLibraryEntry[]): WorkflowLibraryEntry[] => {const seen = new Set<string>();const unique: WorkflowLibraryEntry[] = [];@@ -54,6 +78,7 @@ const dedupeByWorkflowId = (entries: readonly WorkflowLibraryEntry[]): WorkflowLexport const WorkflowLibraryGrid = ({activeWorkflowId = null,entries,+ window: browseWindow,error,missingCounts = NO_MISSING_COUNTS,openMenuAnchor = null,@@ -62,69 +87,448 @@ export const WorkflowLibraryGrid = ({onOpen,onSelect,selectedWorkflowId,+ removedWorkflowId = null,status,}: WorkflowLibraryGridProps) => {const { t } = useTranslation();const viewportRef = useRef<HTMLDivElement | null>(null);- // Infinite scroll reads geometry off the scrolling element itself, which is- // inside `Scrollable`, so the listener is registered directly rather than- // through a React `onScroll` prop (scroll events do not bubble).+ const pendingFocus = useRef<{+ index: number;+ menu: boolean;+ source: HTMLElement;+ filter: WorkflowLibraryBrowseSnapshot['filter'];+ owner: ReturnType<typeof captureAccountScope>;+ } | null>(null);+ const attemptFocus = useCallback(() => {+ const intent = pendingFocus.current;+ if (!intent) {+ return;+ }+ const snapshot = getWorkflowLibraryBrowseSnapshot();+ if (+ !isAccountScopeCurrent(intent.owner) ||+ snapshot.filter !== intent.filter ||+ document.activeElement !== intent.source+ ) {+ pendingFocus.current = null;+ return;+ }+ const entry = snapshot.entries[intent.index - (snapshot.startIndex ?? 0)];+ if (!entry) {+ return;+ }+ const element = document.getElementById(+ intent.menu+ ? getWorkflowLibraryCardMenuId(entry.item.workflow_id)+ : getWorkflowLibraryCardId(entry.item.workflow_id)+ );+ if (element) {+ pendingFocus.current = null;+ element.focus();+ element.scrollIntoView({ block: 'nearest' });+ }+ }, []);+ const [width, setWidth] = useState(0);+ const [owner] = useState(captureAccountScope);+ const [restoreAnchor, setRestoreAnchor] = useState(() => {+ const snapshot = getWorkflowLibraryBrowseSnapshot();+ return browseWindow?.filter === snapshot.filter ? (snapshot.scrollAnchor ?? null) : null;+ });+ const restorePending = useRef(restoreAnchor !== null);+ const mounted = useRef(false);+ const positionedAt = useRef<{ row: number; width: number } | null>(null);+ const [focusCard, setFocusCard] = useState<{ entry: WorkflowLibraryEntry; index: number } | null>(null);+ if (focusCard?.entry.item.workflow_id === removedWorkflowId && focusCard !== null) {+ setFocusCard(null);+ }+ const visibleEntries = useMemo(() => dedupeByWorkflowId(entries), [entries]);+ const startIndex = browseWindow?.startIndex ?? 0;+ const total = browseWindow?.total ?? visibleEntries.length;+ const columns = Math.max(1, Math.min(3, Math.floor(width / 180)));+ const rowHeight = (Math.max(1, (width - 12 * columns) / columns) * 9) / 16 + 82;+ const getScrollElement = useCallback(() => viewportRef.current, []);+ const rangeExtractor = useCallback(+ (range: Parameters<typeof defaultRangeExtractor>[0]) => {+ const indexes = defaultRangeExtractor(range);+ for (const id of [focusCard?.entry.item.workflow_id, openMenuAnchor?.workflowId]) {+ const index = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);+ if (index >= 0) {+ indexes.push(Math.floor((startIndex + index) / columns));+ } else if (+ focusCard &&+ focusCard.entry.item.workflow_id === id &&+ focusCard.index < total &&+ (focusCard.index < startIndex || focusCard.index >= startIndex + visibleEntries.length)+ ) {+ indexes.push(Math.floor(focusCard.index / columns));+ }+ }+ return [...new Set(indexes)].sort((a, b) => a - b);+ },+ [focusCard, openMenuAnchor, startIndex, visibleEntries, columns, total]+ );+ const virtualizer = useVirtualizer({+ count: Math.ceil(total / columns),+ estimateSize: () => rowHeight,+ getScrollElement,+ enabled: width > 0,+ onChange: (instance) => {+ if (!mounted.current || !browseWindow || !width || restorePending.current || !isAccountScopeCurrent(owner)) {+ return;+ }+ const offset = instance.scrollOffset ?? 0;+ const row = instance.getVirtualItems().find((item) => item.end > offset);+ if (row && row.size > 0) {+ rememberWorkflowLibraryScroll(browseWindow.filter, {+ index: row.index * columns,+ fraction: Math.max(0, Math.min(1, (offset - row.start) / row.size)),+ });+ }+ },+ overscan: OVERSCAN_ROWS,+ rangeExtractor,+ useFlushSync: false,+ });+ const { measure, measureElement, elementsCache, isScrolling, virtualItems, totalSize, cancelScroll } = virtualizer;useMountEffect(() => {const viewport = viewportRef.current;-if (!viewport) {return;}-- const handleScroll = () => {- // A grid that doesn't overflow cannot have been scrolled near its- // bottom by anyone; a scroll event there is measurement noise.- if (viewport.scrollHeight <= viewport.clientHeight) {- return;- }-- const remaining = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;-- if (remaining <= viewport.clientHeight * NEAR_BOTTOM_VIEWPORTS) {- loadNextWorkflowLibraryPage();+ mounted.current = true;+ const observer = new MutationObserver(attemptFocus);+ observer.observe(viewport, { childList: true, subtree: true });+ const cancel = () => {+ pendingFocus.current = null;+ if (restorePending.current) {+ restorePending.current = false;+ cancelScroll();+ setRestoreAnchor(null);}};-- viewport.addEventListener('scroll', handleScroll, { passive: true });-- return () => viewport.removeEventListener('scroll', handleScroll);+ owner.signal.addEventListener('abort', cancel, { once: true });+ document.addEventListener('keydown', cancel, true);+ document.addEventListener('pointerdown', cancel, true);+ document.addEventListener('wheel', cancel, { capture: true, passive: true });+ document.addEventListener('focusin', attemptFocus);+ return () => {+ pendingFocus.current = null;+ // Mount replay keeps uncanceled intent, but must restart the canceled native command.+ mounted.current = false;+ positionedAt.current = null;+ cancelScroll();+ observer.disconnect();+ owner.signal.removeEventListener('abort', cancel);+ document.removeEventListener('keydown', cancel, true);+ document.removeEventListener('pointerdown', cancel, true);+ document.removeEventListener('wheel', cancel, true);+ document.removeEventListener('focusin', attemptFocus);+ };});-- const visibleEntries = useMemo(() => dedupeByWorkflowId(entries), [entries]);+ useLayoutEffect(() => {+ measure();+ }, [measure, rowHeight]);+ useLayoutEffect(() => {+ // Clearing sizes does not retrigger ResizeObserver for unchanged mounted rows.+ // measureElement defers reads during scrolling, so retry once scrolling settles.+ if (isScrolling) {+ return;+ }+ for (const element of elementsCache.values()) {+ measureElement(element);+ }+ }, [measureElement, elementsCache, rowHeight, isScrolling]);+ useMountEffect(() => {+ const viewport = viewportRef.current;+ if (!viewport) {+ return;+ }+ const observer = new ResizeObserver(() => setWidth(viewport.clientWidth));+ observer.observe(viewport);+ return () => observer.disconnect();+ });+ const restoreRow = restoreAnchor ? Math.floor(Math.min(restoreAnchor.index, Math.max(0, total - 1)) / columns) : null;+ useLayoutEffect(() => {+ const viewport = viewportRef.current;+ if (!mounted.current || !restorePending.current || restoreRow === null || !restoreAnchor || !width || !viewport) {+ return;+ }+ if (!isAccountScopeCurrent(owner)) {+ restorePending.current = false;+ cancelScroll();+ return;+ }+ const firstItem = restoreRow * columns;+ if (+ totalSize === 0 ||+ firstItem < startIndex ||+ Math.min(total, firstItem + columns) > startIndex + visibleEntries.length+ ) {+ return;+ }+ // Wait for resident metadata and the committed sizer before starting an index command.+ // A command against an empty sizer can otherwise outlive cancellation through its pending clamp retry.+ if (positionedAt.current?.row !== restoreRow || positionedAt.current.width !== width) {+ positionedAt.current = { row: restoreRow, width };+ virtualizer.scrollToIndex(restoreRow, { align: 'start' });+ return;+ }+ const row = virtualItems.find((item) => item.index === restoreRow);+ const element = row ? elementsCache.get(row.key) : undefined;+ if (!element) {+ return;+ }+ // Translate the logical anchor using the rendered row, including its actual responsive height and gap.+ const rect = element.getBoundingClientRect();+ if (rect.height === 0) {+ return;+ }+ const delta = rect.top - viewport.getBoundingClientRect().top + restoreAnchor.fraction * rect.height;+ const target = Math.max(0, Math.min(viewport.scrollTop + delta, viewport.scrollHeight - viewport.clientHeight));+ if (Math.abs(target - viewport.scrollTop) > 1) {+ virtualizer.scrollToOffset(target);+ return;+ }+ restorePending.current = false;+ setRestoreAnchor(null);+ const visible = virtualItems.find((item) => item.end > viewport.scrollTop);+ if (browseWindow && visible && visible.size > 0) {+ rememberWorkflowLibraryScroll(browseWindow.filter, {+ index: visible.index * columns,+ fraction: Math.max(0, Math.min(1, (viewport.scrollTop - visible.start) / visible.size)),+ });+ }+ }, [+ browseWindow,+ restoreRow,+ restoreAnchor,+ width,+ owner,+ cancelScroll,+ columns,+ virtualizer,+ virtualItems,+ elementsCache,+ startIndex,+ total,+ totalSize,+ visibleEntries,+ ]);+ // Do not let the mount's unknown width/top range replace the cached window needed for restoration.+ const firstVisibleRow = restoreRow ?? virtualizer.range?.startIndex ?? 0;+ const lastVisibleRow =+ restoreRow === null+ ? (virtualizer.range?.endIndex ?? 0)+ : restoreRow + Math.ceil((virtualizer.scrollRect?.height ?? 0) / rowHeight);+ const visibleFirst = firstVisibleRow * columns;+ const visibleLast = Math.min(total - 1, (lastVisibleRow + 1) * columns - 1);+ const first = Math.max(0, firstVisibleRow - OVERSCAN_ROWS) * columns;+ const last = Math.min(total - 1, (lastVisibleRow + OVERSCAN_ROWS + 1) * columns - 1);+ const ids = useMemo(() => {+ const visible: string[] = [];+ const overscan: string[] = [];+ for (const [index, entry] of visibleEntries.entries()) {+ const position = startIndex + index;+ if (position >= first && position <= last) {+ // The owner's bounded enrichment slots must reach every visible card before either overscan edge.+ const demand = position >= visibleFirst && position <= visibleLast ? visible : overscan;+ demand.push(entry.item.workflow_id);+ }+ }+ return visible.concat(overscan);+ }, [visibleEntries, startIndex, first, last, visibleFirst, visibleLast]);const hasEntries = visibleEntries.length > 0;// Idle precedes the first open-time load; render loading rather than an empty result.const isPending = status === 'idle' || status === 'loading';+ const viewportProps = useMemo<ComponentProps<typeof Scrollable>['viewportProps']>(+ () => ({+ onKeyDown: (event) => {+ if (event.key !== 'Tab' || event.altKey || event.ctrlKey || event.metaKey) {+ return;+ }+ const target = event.target as HTMLElement;+ const isCard = target.hasAttribute('data-workflow-card');+ const isMenu = target.hasAttribute('data-workflow-card-menu');+ if ((!isCard || !event.shiftKey) && (!isMenu || event.shiftKey)) {+ return;+ }+ const id = target.dataset.workflowCard ?? target.dataset.workflowCardMenu;+ const residentIndex = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);+ const index = residentIndex >= 0 ? startIndex + residentIndex : (focusCard?.index ?? -1);+ const next = index + (event.shiftKey ? -1 : 1);+ if (index < 0 || next < 0 || next >= total) {+ return;+ }+ event.preventDefault();+ virtualizer.scrollToIndex(Math.floor(next / columns), { align: 'auto' });+ if (browseWindow) {+ pendingFocus.current = {+ index: next,+ menu: event.shiftKey,+ source: target,+ filter: getWorkflowLibraryBrowseSnapshot().filter,+ owner: captureAccountScope(),+ };+ void loadWorkflowLibraryRange(next, next).then((ready) => {+ if (ready) {+ requestAnimationFrame(attemptFocus);+ }+ });+ } else {+ requestAnimationFrame(() => {+ const entry = visibleEntries[next];+ if (!entry || document.activeElement !== target) {+ return;+ }+ document+ .getElementById(+ event.shiftKey+ ? getWorkflowLibraryCardMenuId(entry.item.workflow_id)+ : getWorkflowLibraryCardId(entry.item.workflow_id)+ )+ ?.focus();+ });+ }+ },+ onFocusCapture: (event) => {+ const card = (event.target as HTMLElement).closest<HTMLElement>(+ '[data-workflow-card],[data-workflow-card-menu]'+ );+ const id = card?.dataset.workflowCard ?? card?.dataset.workflowCardMenu;+ const index = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);+ const entry = visibleEntries[index];+ if (entry) {+ setFocusCard({ entry: { ...entry, enrichment: { status: 'pending' } }, index: startIndex + index });+ }+ },+ }),+ [browseWindow, virtualizer, visibleEntries, startIndex, focusCard, total, columns, attemptFocus]+ );+ const handleRetry = useCallback(() => {+ void loadWorkflowLibraryRange(first, last, true);+ }, [first, last]);+ const ensureCardPosition = useCallback(+ (id: string, action: () => void) => {+ const resident = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);+ const index = resident >= 0 ? startIndex + resident : focusCard?.index;+ if (browseWindow && index !== undefined && resident < 0) {+ void loadWorkflowLibraryRange(index, index).then((ready) => {+ if (ready) {+ action();+ }+ });+ } else {+ action();+ }+ },+ [browseWindow, visibleEntries, startIndex, focusCard]+ );+ const handleSelect = useCallback(+ (id: string) => ensureCardPosition(id, () => onSelect(id)),+ [ensureCardPosition, onSelect]+ );+ const handleOpen = useCallback(+ (id: string) => ensureCardPosition(id, () => onOpen(id)),+ [ensureCardPosition, onOpen]+ );+ const handleContextMenu = useCallback(+ (id: string, anchor: WorkflowCardMenuAnchor) => {+ const index = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);+ const entry = visibleEntries[index];+ if (entry) {+ setFocusCard({ entry: { ...entry, enrichment: { status: 'pending' } }, index: startIndex + index });+ }+ ensureCardPosition(id, () => onContextMenu(id, anchor));+ },+ [visibleEntries, startIndex, ensureCardPosition, onContextMenu]+ );return (- <Scrollable flex="1" label={t('workflowLibrary.title')} minH="0" minW="0" viewportRef={viewportRef}>+ <Scrollable+ css={GRID_CSS}+ flex="1"+ label={t('workflowLibrary.title')}+ minH="0"+ maxH={browseWindow ? `${rowHeight * MAX_VISIBLE_ROWS}px` : undefined}+ minW="0"+ viewportRef={viewportRef}+ viewportProps={viewportProps}+ >+ {browseWindow && width > 0 ? (+ <GridDemand key={`${first}:${last}:${ids.join(',')}`} ids={ids} start={first} end={last} />+ ) : null}<Box display="flex" flexDirection="column" gap="3" minW="0" pr="2" w="full">+ {hasEntries && error ? (+ // Keep recovery within the viewport even for a failed distant range.+ <Text+ role="alert"+ position="sticky"+ top="0"+ zIndex="1"+ bg="bg.panel"+ color="fg.subtle"+ fontSize="xs"+ py="2"+ textAlign="center"+ >+ {error}+ {browseWindow ? (+ <Button size="sm" variant="ghost" onClick={handleRetry}>+ {t('common.retry')}+ </Button>+ ) : null}+ </Text>+ ) : null}{hasEntries ? (- <Box display="grid" gap="3" gridTemplateColumns={GRID_TEMPLATE_COLUMNS} minW="0" w="full">- {visibleEntries.map((entry) => (- <WorkflowLibraryCard- key={entry.item.workflow_id}- entry={entry}- isActive={entry.item.workflow_id === activeWorkflowId}- isSelected={entry.item.workflow_id === selectedWorkflowId}- menuOpenedBy={- openMenuAnchor?.workflowId === entry.item.workflow_id- ? openMenuAnchor.kind === 'trigger'- ? 'button'- : 'card'- : null- }- missingCount={missingCounts.get(entry.item.workflow_id) ?? 0}- showVisibilityStatus={showVisibilityStatus}- onContextMenu={onContextMenu}- onOpen={onOpen}- onSelect={onSelect}- />+ <Box h={`${totalSize}px`} position="relative" minW="0" w="full">+ {virtualItems.map((row) => (+ <Box+ key={row.key}+ data-index={row.index}+ ref={virtualizer.measureElement}+ display="grid"+ gap="3"+ gridTemplateColumns={`repeat(${columns}, minmax(0, 1fr))`}+ position="absolute"+ top="0"+ left="0"+ w="full"+ pb="3"+ transform={`translateY(${row.start}px)`}+ >+ {Array.from({ length: columns }, (_, column) => {+ const index = row.index * columns + column;+ if (index >= total) {+ return null;+ }+ const entry =+ visibleEntries[index - startIndex] ?? (focusCard?.index === index ? focusCard.entry : undefined);+ if (!entry) {+ return <Box key={index} h={`${rowHeight - 12}px`} aria-busy="true" bg="bg.subtle" rounded="lg" />;+ }+ return (+ <WorkflowLibraryCard+ key={entry.item.workflow_id}+ entry={entry}+ isActive={entry.item.workflow_id === activeWorkflowId}+ isSelected={entry.item.workflow_id === selectedWorkflowId}+ menuOpenedBy={+ openMenuAnchor?.workflowId === entry.item.workflow_id+ ? openMenuAnchor.kind === 'trigger'+ ? 'button'+ : 'card'+ : null+ }+ missingCount={missingCounts.get(entry.item.workflow_id) ?? 0}+ showVisibilityStatus={showVisibilityStatus}+ onContextMenu={handleContextMenu}+ onOpen={handleOpen}+ onSelect={handleSelect}+ />+ );+ })}+ </Box>))}</Box>) : null}@@ -138,19 +542,25 @@ export const WorkflowLibraryGrid = ({{error ?? t('workflowLibrary.empty')}</Text>) : null}- {hasEntries && status === 'loadingMore' ? (- <HStack color="fg.subtle" gap="2" justify="center" py="2">- <Spinner />- <Text fontSize="xs">{t('workflowLibrary.loadingMore')}</Text>- </HStack>- ) : null}- {hasEntries && error ? (- // A failed page append never blanks the pages already loaded.- <Text color="fg.subtle" fontSize="xs" py="2" textAlign="center">- {error}- </Text>- ) : null}</Box></Scrollable>);};++// Mount leases keep external-store writes out of render and release detail demand when the viewport leaves.+let demandLease = 0;+const GridDemand = ({ ids, start, end }: { ids: readonly string[]; start: number; end: number }) => {+ useMountEffect(() => {+ const lease = ++demandLease;+ setWorkflowLibraryVisibleDemand(ids);+ void loadWorkflowLibraryRange(start, end);+ return () => {+ queueMicrotask(() => {+ if (lease === demandLease) {+ setWorkflowLibraryVisibleDemand([]);+ }+ });+ };+ });+ return null;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPanel.browser.test.tsxindex 2393fcbfcb..2322ad7ac2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPanel.browser.test.tsx@@ -373,11 +373,8 @@ describe('PreviewDetailsPanel', () => {await render(imageItem);// Availability, the lazily loaded cache, and the label request resolve in turn; wait rather than time them.- const tags = await vi.waitFor(() => {- const element = document.querySelector<HTMLElement>('[data-preview-image-tags]');- expect(element).not.toBeNull();- return element;- });+ await expect.element(page.getByText('Image tags:', { exact: true })).toBeInTheDocument();+ const tags = document.querySelector<HTMLElement>('[data-preview-image-tags]')!;const dimensions = page.getByText('512 × 768').element();expect(mocks.getImageLabels).toHaveBeenCalledWith({ kind: 'image', name: 'still.png' });expect(tags?.textContent).toBe(