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
feat(webv2): rewrite workflow library dialog as filterable card grid
joshistoast33587b2b6b18
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex d6dfed3e3b..0e4dbf1ebb 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2971,5 +2971,42 @@"description": "Invoke V7 shell version 7.0.","label": "Version"}+ },+ "workflowLibrary": {+ "allTag": "All",+ "applying": "Applying workflow…",+ "browse": "Browse",+ "delete": "Delete",+ "deleteConfirmBody": "Delete \"{{name}}\" from the workflow library? This cannot be undone.",+ "deleteConfirmTitle": "Delete workflow",+ "downloadJson": "Download JSON",+ "duplicate": "Duplicate",+ "duplicateName": "{{name}} copy",+ "empty": "No workflows match these filters.",+ "fetching": "Fetching workflow…",+ "forkIntoProject": "Fork into new project",+ "installModels_one": "Install 1 model",+ "installModels_other": "Install {{count}} models",+ "installQueued": "Model installs queued",+ "lastRun": "Your last run · {{when}}",+ "loadFailed": "Failed to load workflow",+ "loadFailedBody": "Could not load \"{{name}}\".",+ "loadWarning": "Workflow load warning",+ "loadedLabel": "Loaded \"{{name}}\" from library",+ "loading": "Loading workflows…",+ "loadingMore": "Loading more…",+ "moreActions": "More actions",+ "nodeCount_one": "{{count}} node",+ "nodeCount_other": "{{count}} nodes",+ "notRunYet": "Not run yet",+ "open": "Open",+ "previewGraph": "Preview graph",+ "requires": "Requires",+ "sampleOutput": "Sample output",+ "searchPlaceholder": "Search names, tags, or descriptions",+ "tagsLabel": "Filter by tag",+ "title": "Workflows",+ "untitled": "Untitled Workflow",+ "yours": "Yours"}}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsxnew file mode 100644index 0000000000..fb7d7b8d4b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx@@ -0,0 +1,124 @@+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';++import { Badge, Box, Flex, HStack, Icon, Image, Skeleton, Stack, Text } from '@chakra-ui/react';+import { getModelBaseLabel } from '@features/models';+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { ImageOffIcon } from 'lucide-react';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * One workflow in the library grid: a sample-output thumbnail over a footer+ * strip of the facts that decide whether this is the workflow you want — its+ * base architecture, its size, and how many models you'd have to install to+ * run it.+ *+ * A single click selects (the right rail follows the selection); a double+ * click opens. Enrichment fills the footer in asynchronously per entry, so+ * the strip reserves its height from the first paint and never reflows the+ * grid as counts arrive.+ */++const CARD_HOVER = { bg: 'bg.muted', borderColor: 'border.emphasized' } as const;+const CARD_FOCUS_VISIBLE = { outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' } as const;+const CARD_TRANSITION =+ 'border-color var(--wb-motion-duration-medium) ease, background var(--wb-motion-duration-medium) ease';+const THUMBNAIL_ASPECT_RATIO = 3 / 2;++export interface WorkflowLibraryCardProps {+ entry: WorkflowLibraryEntry;+ isSelected: boolean;+ /** Models this workflow needs that are not installed; 0 hides the badge. */+ missingCount: number;+ onOpen: (workflowId: string) => void;+ onSelect: (workflowId: string) => void;+}++export const WorkflowLibraryCard = ({+ entry,+ isSelected,+ missingCount,+ onOpen,+ onSelect,+}: WorkflowLibraryCardProps) => {+ const { t } = useTranslation();+ const [hasThumbnailFailed, setHasThumbnailFailed] = useState(false);+ const { enrichment, item } = entry;+ const workflowId = item.workflow_id;++ const handleSelect = useCallback(() => onSelect(workflowId), [onSelect, workflowId]);+ const handleOpen = useCallback(() => onOpen(workflowId), [onOpen, workflowId]);+ const handleThumbnailError = useCallback(() => setHasThumbnailFailed(true), []);++ // A broken <img> reads worse than the glyph, so a load failure falls back to+ // the same placeholder a workflow that has never run gets.+ const showThumbnail = Boolean(item.thumbnail_url) && !hasThumbnailFailed;+ const primaryBase = enrichment.status === 'ready' ? enrichment.requirements.primaryBase : null;++ return (+ <Box+ as="button"+ aria-pressed={isSelected}+ bg={isSelected ? 'bg.emphasized' : 'bg.subtle'}+ borderColor={isSelected ? 'accent.solid' : 'border.subtle'}+ borderWidth="1px"+ cursor="pointer"+ data-workflow-card={workflowId}+ minW="0"+ overflow="hidden"+ rounded="lg"+ textAlign="start"+ transition={CARD_TRANSITION}+ w="full"+ _focusVisible={CARD_FOCUS_VISIBLE}+ _hover={CARD_HOVER}+ onClick={handleSelect}+ onDoubleClick={handleOpen}+ >+ <Box aspectRatio={THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" w="full">+ {showThumbnail ? (+ <Image+ alt=""+ h="full"+ objectFit="cover"+ src={item.thumbnail_url ?? undefined}+ w="full"+ onError={handleThumbnailError}+ />+ ) : (+ <Flex align="center" direction="column" gap="1" h="full" justify="center" w="full">+ <Icon aria-hidden as={ImageOffIcon} boxSize="5" color="fg.subtle" opacity={0.6} />+ <Text color="fg.subtle" fontSize="2xs">+ {t('workflowLibrary.notRunYet')}+ </Text>+ </Flex>+ )}+ </Box>+ <Stack gap="1" minW="0" p="2.5" w="full">+ <MiddleTruncate fontSize="xs" fontWeight="600" minW="0" text={item.name || t('workflowLibrary.untitled')} />+ <HStack gap="1.5" h="4" minW="0">+ {enrichment.status === 'pending' ? (+ // Enrichment in flight. An unreadable workflow ('error') gets no+ // placeholder and no error styling — the facts simply stay absent.+ <Skeleton data-enrichment-placeholder h="3" rounded="sm" variant="pulse" w="14" />+ ) : null}+ {primaryBase ? (+ <Badge flexShrink={0} size="xs" variant="subtle">+ {getModelBaseLabel(primaryBase)}+ </Badge>+ ) : null}+ {enrichment.status === 'ready' ? (+ <Text color="fg.muted" fontSize="2xs" truncate>+ {t('workflowLibrary.nodeCount', { count: enrichment.nodeCount })}+ </Text>+ ) : null}+ {missingCount > 0 ? (+ <Badge colorPalette="orange" flexShrink={0} size="xs" variant="subtle">+ {t('workflowLibrary.installModels', { count: missingCount })}+ </Badge>+ ) : null}+ </HStack>+ </Stack>+ </Box>+ );+};diff --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.tsxnew file mode 100644index 0000000000..578f40e5ec--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx@@ -0,0 +1,436 @@+import type {+ WorkflowLibraryBrowseSnapshot,+ WorkflowLibraryEntry,+ WorkflowLibraryEntryEnrichment,+} from '@features/workflow/data/libraryBrowseStore';++import { ChakraProvider } from '@chakra-ui/react';+import { createProjectGraph } from '@features/workflow/utility';+import { system } from '@theme/system';+import { act, StrictMode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { WorkflowLibraryDialog } from './WorkflowLibraryDialog';++// The browse store is Task 5's; this suite owns the *dialog*, so the store is+// replaced by a real external store the test drives directly plus spies for+// its four commands. Using a real store (not a stub hook) keeps the dialog's+// subscription, selector equality, and re-render path under test.+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(),+ setSnapshot: null as null | ((snapshot: WorkflowLibraryBrowseSnapshot) => void),+ setWorkflowLibraryBrowseFilter: vi.fn(),+}));++vi.mock('@features/workflow/data/libraryBrowseStore', async () => {+ const { createExternalStore } = await import('@platform/state/externalStore');+ const store = createExternalStore<WorkflowLibraryBrowseSnapshot>({+ entries: [],+ error: null,+ filter: { category: 'user', search: '', tag: null },+ page: 0,+ pages: 0,+ status: 'idle',+ tagCounts: [],+ total: 0,+ userTotal: null,+ });++ browse.getSnapshot = store.getSnapshot;+ browse.setSnapshot = store.setSnapshot;++ return {+ ensureWorkflowLibraryBrowseLoaded: browse.ensureWorkflowLibraryBrowseLoaded,+ getWorkflowLibraryBrowseSnapshot: store.getSnapshot,+ loadNextWorkflowLibraryPage: browse.loadNextWorkflowLibraryPage,+ setWorkflowLibraryBrowseFilter: browse.setWorkflowLibraryBrowseFilter,+ useWorkflowLibraryBrowseSelector: store.useSelector,+ };+});++// The load sequence (fetch → parse → replace → toasts) has its own behavior+// contract; this suite only asserts the dialog *invokes* it and reflects its+// phase in the busy overlay.+const loader = vi.hoisted(() => ({+ load: vi.fn(() => Promise.resolve()),+ phase: { current: 'idle' as 'applying' | 'fetching' | 'idle' },+}));++vi.mock('./useLoadLibraryWorkflow', () => ({+ useLoadLibraryWorkflow: () => ({ load: loader.load, loadPhase: loader.phase.current }),+}));++// The real i18n client fetches en.json over HTTP, which this browser test+// never boots. Stub `t` with the English strings this dialog renders (plus+// the `_one`/`_other` plural forms) so assertions check real copy.+const TRANSLATIONS: Record<string, string> = {+ 'common.close': 'Close',+ 'workflowLibrary.allTag': 'All',+ 'workflowLibrary.applying': 'Applying workflow…',+ 'workflowLibrary.browse': 'Browse',+ 'workflowLibrary.empty': 'No workflows match these filters.',+ 'workflowLibrary.fetching': 'Fetching workflow…',+ 'workflowLibrary.loading': 'Loading workflows…',+ 'workflowLibrary.loadingMore': 'Loading more…',+ 'workflowLibrary.nodeCount_one': '{{count}} node',+ 'workflowLibrary.nodeCount_other': '{{count}} nodes',+ 'workflowLibrary.notRunYet': 'Not run yet',+ 'workflowLibrary.searchPlaceholder': 'Search names, tags, or descriptions',+ 'workflowLibrary.title': 'Workflows',+ 'workflowLibrary.yours': 'Yours',+};++const interpolate = (template: string, options?: Record<string, unknown>): string =>+ options ? template.replaceAll(/\{\{(\w+)\}\}/g, (_match, key: string) => String(options[key] ?? '')) : template;++const translate = (key: string, options?: Record<string, unknown>): string => {+ const count = options?.count;+ const plural = typeof count === 'number' ? TRANSLATIONS[`${key}_${count === 1 ? 'one' : 'other'}`] : undefined;++ return interpolate(plural ?? TRANSLATIONS[key] ?? key, options);+};++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const EMPTY_DOCUMENT = createProjectGraph('library-fixture');++const readyEnrichment = (nodeCount: number, primaryBase: string | null): WorkflowLibraryEntryEnrichment => ({+ document: EMPTY_DOCUMENT,+ nodeCount,+ requirements: { primaryBase, requirements: [] },+ status: 'ready',+});++const entry = (+ workflowId: string,+ name: string,+ enrichment: WorkflowLibraryEntryEnrichment,+ extras: { tags?: readonly string[]; thumbnailUrl?: string } = {}+): WorkflowLibraryEntry => ({+ enrichment,+ item: {+ category: 'user',+ description: `${name} description`,+ name,+ thumbnail_url: extras.thumbnailUrl ?? null,+ workflow_id: workflowId,+ },+ tags: extras.tags ?? [],+});++const PORTRAIT = entry('wf-portrait', 'Portrait Studio', readyEnrichment(12, 'sdxl'), {+ tags: ['portrait'],+ thumbnailUrl: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',+});+const LANDSCAPE = entry('wf-landscape', 'Landscape Pass', readyEnrichment(7, 'flux'), { tags: ['landscape'] });+const SKETCH = entry('wf-sketch', 'Sketch To Render', { status: 'pending' });+const UPSCALE = entry(+ 'wf-upscale',+ 'Upscale Chain',+ { message: 'unreadable', status: 'error' },+ {+ tags: ['upscale'],+ }+);++const LOADED_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {+ entries: [PORTRAIT, LANDSCAPE, SKETCH, UPSCALE],+ error: null,+ filter: { category: 'user', search: '', tag: null },+ page: 0,+ pages: 2,+ status: 'loaded',+ tagCounts: [+ { count: 2, tag: 'portrait' },+ { count: 1, tag: 'upscale' },+ ],+ total: 24,+ userTotal: 4,+};++const withSnapshot = (patch: Partial<WorkflowLibraryBrowseSnapshot>): WorkflowLibraryBrowseSnapshot => ({+ ...LOADED_SNAPSHOT,+ ...patch,+});++describe('WorkflowLibraryDialog', () => {+ let host: HTMLDivElement;+ let root: Root;+ let onOpenChange: (isOpen: boolean) => void;++ const renderDialog = async (isOpen = true) => {+ await act(() => {+ root.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <WorkflowLibraryDialog isOpen={isOpen} onOpenChange={onOpenChange} />+ </ChakraProvider>+ </StrictMode>+ );+ });+ };++ const openWith = async (snapshot: WorkflowLibraryBrowseSnapshot) => {+ await act(() => browse.setSnapshot?.(snapshot));+ await renderDialog();+ };++ /** Drains the microtask + timer queue the store probe and debounce settle on. */+ const wait = (ms: number) =>+ act(async () => {+ await new Promise<void>((resolve) => {+ setTimeout(resolve, ms);+ });+ });++ const cards = () => [...document.querySelectorAll<HTMLElement>('[data-workflow-card]')];+ const card = (workflowId: string) => document.querySelector<HTMLElement>(`[data-workflow-card="${workflowId}"]`);+ const buttonWithText = (text: string) =>+ [...document.querySelectorAll('button')].find((candidate) => (candidate.textContent ?? '') === text);++ const clickText = async (text: string) => {+ const button = buttonWithText(text);+ expect(button).not.toBeUndefined();++ await act(() => button?.click());+ };++ const clickSegment = async (value: string) => {+ const label = document.querySelector<HTMLInputElement>(`input[value="${value}"]`)?.closest('label');+ expect(label).not.toBeNull();++ await act(() => label?.click());+ };++ 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 });+ }++ await act(() => {+ viewport?.dispatchEvent(new Event('scroll'));+ });+ };++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ onOpenChange = vi.fn((_isOpen: boolean) => {});+ browse.ensureWorkflowLibraryBrowseLoaded.mockClear();+ browse.loadNextWorkflowLibraryPage.mockClear();+ browse.setWorkflowLibraryBrowseFilter.mockClear();+ loader.load.mockClear();+ loader.phase.current = 'idle';+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('renders one card per entry with its name and enriched node count', async () => {+ await openWith(LOADED_SNAPSHOT);++ expect(cards()).toHaveLength(4);++ const text = document.body.textContent ?? '';++ expect(text).toContain('Portrait Studio');+ expect(text).toContain('12 nodes');+ expect(text).toContain('SDXL');+ expect(text).toContain('Landscape Pass');+ expect(text).toContain('7 nodes');+ expect(text).toContain('FLUX');+ });++ it('shows a quiet placeholder while enrichment is pending and omits the badges when it failed', async () => {+ await openWith(LOADED_SNAPSHOT);++ const pending = card('wf-sketch');+ expect(pending?.textContent).toContain('Sketch To Render');+ expect(pending?.textContent).not.toContain('nodes');+ expect(pending?.querySelector('[data-enrichment-placeholder]')).not.toBeNull();++ // A failed enrichment is a quiet omission, never an error-styled card.+ const failed = card('wf-upscale');+ expect(failed?.textContent).toContain('Upscale Chain');+ expect(failed?.textContent).not.toContain('nodes');+ expect(failed?.querySelector('[data-enrichment-placeholder]')).toBeNull();+ });++ it('renders the thumbnail when present and the not-run-yet placeholder when absent', async () => {+ await openWith(LOADED_SNAPSHOT);++ expect(card('wf-portrait')?.querySelector('img')).not.toBeNull();+ expect(card('wf-landscape')?.querySelector('img')).toBeNull();+ expect(card('wf-landscape')?.textContent).toContain('Not run yet');+ });++ it('kicks the first load when it opens and leaves the store alone while closed', async () => {+ await act(() => browse.setSnapshot?.(LOADED_SNAPSHOT));+ await renderDialog(false);++ expect(browse.ensureWorkflowLibraryBrowseLoaded).not.toHaveBeenCalled();++ await renderDialog(true);++ // Times are not asserted: StrictMode double-invokes mount effects, and the+ // store's own single-flight is what makes that a no-op.+ expect(browse.ensureWorkflowLibraryBrowseLoaded).toHaveBeenCalled();+ });++ it('switches to the bundled defaults once when the account has no workflows of its own', async () => {+ await openWith(withSnapshot({ userTotal: 0 }));+ await wait(0);++ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ category: 'default', tag: null });+ });++ it('leaves the category alone when the account already has workflows', async () => {+ await openWith(LOADED_SNAPSHOT);+ await wait(0);++ expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalled();+ });++ it('resets the tag when the category segment changes', async () => {+ await openWith(withSnapshot({ filter: { category: 'user', search: '', tag: 'portrait' } }));++ await clickSegment('default');++ // The store applies filter patches literally, so clearing the tag on a+ // category switch is the dialog's job.+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ category: 'default', tag: null });+ });++ it('selects and clears a tag from the chip row', async () => {+ await openWith(LOADED_SNAPSHOT);++ await clickText('portrait2');++ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ tag: 'portrait' });++ await clickText('All');++ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ tag: null });+ });++ it('pushes the search term to the store once, after the debounce', async () => {+ await openWith(LOADED_SNAPSHOT);++ const input = document.querySelector<HTMLInputElement>('input[type="search"]');+ expect(input).not.toBeNull();++ // React tracks the input's value through its own setter, so assigning+ // `.value` directly would be swallowed as a no-op change.+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;++ for (const value of ['p', 'ph', 'pho', 'phot', 'photo']) {+ await act(async () => {+ setValue?.call(input, value);+ input?.dispatchEvent(new Event('input', { bubbles: true }));+ await Promise.resolve();+ });+ }++ expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalled();++ await wait(400);++ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledTimes(1);+ 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);++ await scrollTo(100);++ expect(browse.loadNextWorkflowLibraryPage).not.toHaveBeenCalled();++ await scrollTo(3200);++ expect(browse.loadNextWorkflowLibraryPage).toHaveBeenCalled();+ });++ it('auto-selects the first entry and moves the selection when it disappears', async () => {+ await openWith(LOADED_SNAPSHOT);++ expect(card('wf-portrait')?.getAttribute('aria-pressed')).toBe('true');+ expect(card('wf-landscape')?.getAttribute('aria-pressed')).toBe('false');++ await act(() => card('wf-landscape')?.click());++ expect(card('wf-landscape')?.getAttribute('aria-pressed')).toBe('true');++ // A filter change drops the selected row; selection falls back to the head+ // of the new list rather than pointing at nothing.+ await act(() => browse.setSnapshot?.(withSnapshot({ entries: [SKETCH, UPSCALE] })));++ expect(card('wf-sketch')?.getAttribute('aria-pressed')).toBe('true');+ });++ it('opens a workflow on double click', async () => {+ await openWith(LOADED_SNAPSHOT);++ await act(() => {+ card('wf-landscape')?.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));+ });++ expect(loader.load).toHaveBeenCalledTimes(1);+ expect(loader.load).toHaveBeenCalledWith(LANDSCAPE.item);+ });++ it('dedupes entries that share a workflow id', async () => {+ await openWith(withSnapshot({ entries: [PORTRAIT, LANDSCAPE, { ...PORTRAIT }] }));++ expect(cards()).toHaveLength(2);+ expect(document.querySelectorAll('[data-workflow-card="wf-portrait"]')).toHaveLength(1);+ });++ it('keeps the loaded grid and reports a failed load-more inline', async () => {+ await openWith(withSnapshot({ error: 'Failed to load more workflows.', status: 'error' }));++ expect(cards()).toHaveLength(4);+ expect(document.body.textContent ?? '').toContain('Failed to load more workflows.');+ expect(document.body.textContent ?? '').not.toContain('No workflows match these filters.');+ });++ it('shows the empty state only when nothing loaded', async () => {+ await openWith(withSnapshot({ entries: [], status: 'loaded', total: 0 }));++ expect(cards()).toHaveLength(0);+ expect(document.body.textContent ?? '').toContain('No workflows match these filters.');+ });++ it('shows the busy overlay while a workflow is being applied', async () => {+ loader.phase.current = 'applying';++ await openWith(LOADED_SNAPSHOT);++ const status = document.querySelector('[role="status"]');+ expect(status?.textContent).toContain('Applying workflow…');+ expect(document.querySelector('[aria-busy="true"]')).not.toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex 2aff40dc8c..c76d9bdde4 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -1,108 +1,66 @@-/* eslint-disable react/react-compiler, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */-import type { ProjectGraphState } from '@features/workflow/contracts';+import type { WorkflowLibraryBrowseSnapshot } from '@features/workflow/data/libraryBrowseStore';+import type { ChangeEvent } from 'react';-import { Box, Dialog, HStack, Input, Portal, SegmentGroup, Spinner, Stack, Tabs, Text } from '@chakra-ui/react';+import { Box, Dialog, HStack, Input, Portal, SegmentGroup, Spinner, Stack, Text } from '@chakra-ui/react';import {- deleteLibraryWorkflow,- getCachedWorkflowPage,- getLibraryWorkflowCached,- invalidateWorkflowLibraryCache,- listLibraryWorkflowsCached,- touchLibraryWorkflowOpenedAt,- type WorkflowLibraryCategory,- type WorkflowLibraryListItem,-} from '@features/workflow/queries';-import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';-import { useWorkflowNotifications, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';-import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';-import {- type AccountScope,- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';-import { getApiErrorMessage } from '@platform/transport/http';-import { Button, CloseButton, ConfirmDialog, JsonPreview, Scrollable } from '@platform/ui';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { lazy, Suspense, useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';+ ensureWorkflowLibraryBrowseLoaded,+ getWorkflowLibraryBrowseSnapshot,+ setWorkflowLibraryBrowseFilter,+ useWorkflowLibraryBrowseSelector,+} from '@features/workflow/data/libraryBrowseStore';+import { useMountEffect } from '@platform/react/useMountEffect';+import { CloseButton } from '@platform/ui';+import { useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { markLibraryGraphSynced } from './librarySyncBridge';-import { useSaveWorkflowToLibrary } from './useSaveWorkflowToLibrary';+import { useLoadLibraryWorkflow } from './useLoadLibraryWorkflow';+import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';+import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';/**- * Backend workflow library browser: list/search user and default workflows,- * preview one (read-only nodes / JSON) before loading it into the project- * graph (with an automatic graph-history snapshot of the current graph), and- * save the project graph back to the library. Lists serve from the session- * cache instantly and revalidate in the background.+ * Backend workflow library browser. Filtering and paging are server side and+ * live in the browse store, so this shell owns exactly two pieces of state:+ * the raw text in the search box (debounced into the store) and which card is+ * selected. Everything else is read back out of the store.*/-interface WorkflowPreviewState {- document: ProjectGraphState;- item: WorkflowLibraryListItem;- raw: Record<string, unknown>;- warnings: string[];-}+const SEARCH_DEBOUNCE_MS = 300;+const DETAIL_RAIL_WIDTH = '18rem';-type WorkflowLoadPhase = 'fetching' | 'applying';+const CATEGORY_ITEMS = [+ { labelKey: 'workflowLibrary.browse', value: 'default' },+ { labelKey: 'workflowLibrary.yours', value: 'user' },+] as const;-const GraphPreviewPane = lazy(() =>- import('@features/workflow/ui/graph-preview/GraphPreviewPane').then((module) => ({- default: module.GraphPreviewPane,- }))-);+/** Flat and shallow-comparable, so unrelated store patches do not re-render the shell. */+const selectBrowseView = (snapshot: WorkflowLibraryBrowseSnapshot) => ({+ category: snapshot.filter.category,+ entries: snapshot.entries,+ error: snapshot.error,+ status: snapshot.status,+ tag: snapshot.filter.tag,+ tagCounts: snapshot.tagCounts,+});-const WorkflowPreviewPane = ({- isLoadingWorkflow,- preview,- onBack,- onLoad,-}: {- isLoadingWorkflow: boolean;- preview: WorkflowPreviewState;- onBack: () => void;- onLoad: () => void;-}) => {- const [mode, setMode] = useState<'nodes' | 'json'>('nodes');+/**+ * Mounted only while the dialog is open, so its mount effect *is* the "dialog+ * opened" hook: it kicks the first page load and, on a fresh install with no+ * saved workflows, lands the user on the bundled defaults instead of an empty+ * "Yours". The switch is skipped if the user has already moved the filter+ * while the probe was in flight.+ */+const WorkflowLibraryBrowseSession = () => {+ useMountEffect(() => {+ void ensureWorkflowLibraryBrowseLoaded().then(() => {+ const { filter, userTotal } = getWorkflowLibraryBrowseSnapshot();- return (- <Stack gap="2">- <HStack gap="2" justify="space-between">- <HStack gap="2" minW="0">- <Button size="2xs" variant="ghost" onClick={onBack}>- ← Back- </Button>- <MiddleTruncate fontSize="xs" fontWeight="600" minW="0" text={preview.item.name || 'Untitled Workflow'} />- </HStack>- <HStack flexShrink={0} gap="2">- <SegmentGroup.Root- size="xs"- value={mode}- onValueChange={(event) => setMode(event.value === 'json' ? 'json' : 'nodes')}- >- <SegmentGroup.Indicator />- <SegmentGroup.Items- items={[- { label: 'Nodes', value: 'nodes' },- { label: 'JSON', value: 'json' },- ]}- />- </SegmentGroup.Root>- <Button loading={isLoadingWorkflow} size="2xs" onClick={onLoad}>- Load- </Button>- </HStack>- </HStack>- {mode === 'nodes' ? (- <Suspense fallback={<Box h="24rem" />}>- <GraphPreviewPane document={preview.document} />- </Suspense>- ) : (- <JsonPreview label={`${preview.item.name} JSON`} maxH="24rem" value={preview.raw} />- )}- </Stack>- );+ if (userTotal === 0 && filter.category === 'user' && !filter.search) {+ setWorkflowLibraryBrowseFilter({ category: 'default', tag: null });+ }+ });+ });++ return null;};export const WorkflowLibraryDialog = ({@@ -113,451 +71,149 @@ export const WorkflowLibraryDialog = ({onOpenChange: (isOpen: boolean) => void;}) => {const { t } = useTranslation();- const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);- const { replace } = useProjectGraphCommands();- const notify = useWorkflowNotifications();- const { saveAsNew, saveToLibrary: saveExistingToLibrary } = useSaveWorkflowToLibrary();- const [category, setCategory] = useState<WorkflowLibraryCategory>('user');- const [searchTerm, setSearchTerm] = useState('');- const [items, setItems] = useState<WorkflowLibraryListItem[]>([]);- const [pages, setPages] = useState(0);- const [page, setPage] = useState(0);- const [isLoading, setIsLoading] = useState(false);- const [workflowLoad, setWorkflowLoad] = useState<{ id: string; phase: WorkflowLoadPhase } | null>(null);- const [previewingWorkflowId, setPreviewingWorkflowId] = useState<string | null>(null);- const [preview, setPreview] = useState<WorkflowPreviewState | null>(null);- const [pendingDelete, setPendingDelete] = useState<WorkflowLibraryListItem | null>(null);- const [isSaving, setIsSaving] = useState(false);- const hasAutoSwitchedRef = useRef(false);- const refreshTokenRef = useRef(0);- const workflowLoadInFlightRef = useRef(false);- const isWorkflowLoadPending = workflowLoad !== null;-- const refresh = useCallback(- (nextPage: number, owner: AccountScope = captureAccountScope()) => {- const params = { category, page: nextPage, query: searchTerm, signal: owner.signal };- const cached = getCachedWorkflowPage(params);- const token = (refreshTokenRef.current += 1);-- // A cached page renders instantly; the fetch below only revalidates it.- if (cached) {- setItems(cached.items);- setPage(cached.page);- setPages(cached.pages);- } else {- setIsLoading(true);+ const { category, entries, error, status, tag, tagCounts } = useWorkflowLibraryBrowseSelector(selectBrowseView);+ const [searchInput, setSearchInput] = useState('');+ const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(null);+ const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const closeDialog = useCallback(() => onOpenChange(false), [onOpenChange]);+ const { load, loadPhase } = useLoadLibraryWorkflow(closeDialog);+ const isLoadPending = loadPhase !== 'idle';++ // Selection is derived, not stored: a filter change or a deletion can retire+ // the selected row, and the head of the list takes over without an effect.+ const activeWorkflowId = entries.some((entry) => entry.item.workflow_id === selectedWorkflowId)+ ? selectedWorkflowId+ : (entries[0]?.item.workflow_id ?? null);++ const handleDialogOpenChange = useCallback(+ (event: { open: boolean }) => {+ if (!isLoadPending) {+ onOpenChange(event.open);}-- listLibraryWorkflowsCached(params)- .then((result) => {- if (!isAccountScopeCurrent(owner) || token !== refreshTokenRef.current) {- return;- }-- setItems(result.items);- setPage(result.page);- setPages(result.pages);-- // A fresh install has no user workflows; land on the bundled- // defaults instead of an empty tab. Once per dialog open.- if (category === 'user' && result.total === 0 && !searchTerm && !hasAutoSwitchedRef.current) {- hasAutoSwitchedRef.current = true;- setCategory('default');- }- })- .catch((error: unknown) => {- if (!isAccountScopeCurrent(owner) || cached) {- return; // Stale-but-rendered beats an error toast on revalidation.- }-- notify.error('Workflow library unavailable', getApiErrorMessage(error, 'Failed to list workflows.'));- })- .finally(() => {- if (isAccountScopeCurrent(owner) && token === refreshTokenRef.current) {- setIsLoading(false);- }- });},- [category, notify, searchTerm]+ [isLoadPending, onOpenChange]);- useEffect(() => {- if (isOpen) {- refresh(0);- } else {- hasAutoSwitchedRef.current = false;- setPreview(null);- }- }, [isOpen, refresh]);-- const fetchParsedWorkflow = async (item: WorkflowLibraryListItem, owner: AccountScope) => {- const raw = await getLibraryWorkflowCached(item.workflow_id, owner.signal);+ const handleSearchChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {+ const { value } = event.currentTarget;- assertAccountScopeCurrent(owner);- const { document, warnings } = parseWorkflowJson(raw);+ setSearchInput(value);- return { document, raw, warnings };- };-- const loadWorkflow = async (- item: WorkflowLibraryListItem,- loaded?: { document: ProjectGraphState; warnings: string[] }- ) => {- const owner = captureAccountScope();-- if (workflowLoadInFlightRef.current) {- return;+ if (searchTimerRef.current !== null) {+ clearTimeout(searchTimerRef.current);}- workflowLoadInFlightRef.current = true;-- try {- let parsed = loaded;-- if (!parsed) {- setWorkflowLoad({ id: item.workflow_id, phase: 'fetching' });- parsed = await fetchParsedWorkflow(item, owner);- }-- assertAccountScopeCurrent(owner);- setWorkflowLoad({ id: item.workflow_id, phase: 'applying' });- // Synchronous graph replacement can be expensive for large workflows.- // Give React a full frame to commit and paint the busy overlay first.- await new Promise<void>((resolve) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolve()));- });- assertAccountScopeCurrent(owner);- replace(parsed.document, `Loaded "${item.name}" from library`);- // The freshly-loaded graph is already in sync with the library record it- // came from — mark it synced so the autosaver does not immediately- // queue a redundant (echo) save the moment the graph reference changes.- markLibraryGraphSynced(serializeWorkflowJson(parsed.document));+ // Deliberately not a `useEffect` cleanup: a debounce that fires after+ // unmount only patches the store the next open would reload anyway.+ searchTimerRef.current = setTimeout(() => setWorkflowLibraryBrowseFilter({ search: value }), SEARCH_DEBOUNCE_MS);+ }, []);- for (const warning of parsed.warnings) {- notify.info('Workflow load warning', warning);- }-- void touchLibraryWorkflowOpenedAt(item.workflow_id, owner.signal).catch(() => {- // Recency bookkeeping only; loading already succeeded.- });- onOpenChange(false);- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- notify.error('Failed to load workflow', getApiErrorMessage(error, `Could not load "${item.name}".`));- } finally {- if (isAccountScopeCurrent(owner)) {- workflowLoadInFlightRef.current = false;- setWorkflowLoad(null);- }+ const handleCategoryChange = useCallback((event: { value: string | null }) => {+ // The store applies filter patches literally, so clearing the tag when the+ // category changes (its chips do not carry over) is the UI's job.+ if (event.value === 'default' || event.value === 'user') {+ setWorkflowLibraryBrowseFilter({ category: event.value, tag: null });}- };-- const previewWorkflow = async (item: WorkflowLibraryListItem) => {- const owner = captureAccountScope();+ }, []);- setPreviewingWorkflowId(item.workflow_id);+ const handleTagSelect = useCallback((nextTag: string | null) => setWorkflowLibraryBrowseFilter({ tag: nextTag }), []);- try {- const { document, raw, warnings } = await fetchParsedWorkflow(item, owner);+ const handleOpenWorkflow = useCallback(+ (workflowId: string) => {+ const entry = getWorkflowLibraryBrowseSnapshot().entries.find(+ (candidate) => candidate.item.workflow_id === workflowId+ );- assertAccountScopeCurrent(owner);- setPreview({ document, item, raw, warnings });- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;+ if (entry) {+ void load(entry.item);}-- notify.error('Failed to preview workflow', getApiErrorMessage(error, `Could not preview "${item.name}".`));- } finally {- if (isAccountScopeCurrent(owner)) {- setPreviewingWorkflowId(null);- }- }- };-- const saveToLibrary = async (asNew: boolean) => {- const owner = captureAccountScope();-- setIsSaving(true);-- try {- // useSaveWorkflowToLibrary already notifies on success/failure and- // invalidates the library cache; this dialog only needs to refresh its- // own list once the save (and any resulting bind) has landed.- const workflowId = asNew ? await saveAsNew() : await saveExistingToLibrary();-- if (workflowId && isAccountScopeCurrent(owner)) {- refresh(page, owner);- }- } finally {- if (isAccountScopeCurrent(owner)) {- setIsSaving(false);- }- }- };+ },+ [load]+ );return (- <>- <Dialog.Root- placement="center"- open={isOpen}- size="lg"- onOpenChange={(event) => {- if (!isWorkflowLoadPending) {- onOpenChange(event.open);- }- }}- >- <Portal>- <Dialog.Backdrop />- <Dialog.Positioner>- <Dialog.Content- aria-busy={isWorkflowLoadPending}- bg="bg.subtle"- borderColor="border.subtle"- borderWidth="1px"- color="fg"- position="relative"- >- {workflowLoad ? (- <Stack- alignItems="center"- aria-live="polite"- bg="bg/85"- inset="0"- justifyContent="center"- position="absolute"- role="status"- zIndex="modal"- >- <Spinner color="accent.solid" size="lg" />- <Text fontSize="xs" fontWeight="600">- {workflowLoad.phase === 'fetching' ? 'Fetching workflow…' : 'Applying workflow…'}- </Text>- </Stack>- ) : null}- <Dialog.Header>- <Dialog.Title>Workflow Library</Dialog.Title>- </Dialog.Header>- <Dialog.Body>- {preview ? (- <WorkflowPreviewPane- isLoadingWorkflow={workflowLoad?.id === preview.item.workflow_id}- preview={preview}- onBack={() => setPreview(null)}- onLoad={() => void loadWorkflow(preview.item, preview)}+ <Dialog.Root open={isOpen} placement="center" size="xl" onOpenChange={handleDialogOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content+ aria-busy={isLoadPending}+ h="80vh"+ maxH="80vh"+ maxW="min(72rem, calc(100vw - 4rem))"+ position="relative"+ >+ {isLoadPending ? (+ <Stack+ alignItems="center"+ aria-live="polite"+ bg="bg/85"+ inset="0"+ justifyContent="center"+ position="absolute"+ role="status"+ zIndex="modal"+ >+ <Spinner color="accent.solid" size="lg" />+ <Text fontSize="xs" fontWeight="600">+ {loadPhase === 'fetching' ? t('workflowLibrary.fetching') : t('workflowLibrary.applying')}+ </Text>+ </Stack>+ ) : null}+ <Dialog.Header>+ <Stack gap="2" minW="0" w="full">+ <HStack gap="3" minW="0">+ <Dialog.Title flexShrink={0}>{t('workflowLibrary.title')}</Dialog.Title>+ <Input+ aria-label={t('workflowLibrary.searchPlaceholder')}+ flex="1"+ minW="0"+ placeholder={t('workflowLibrary.searchPlaceholder')}+ size="xs"+ type="search"+ value={searchInput}+ onChange={handleSearchChange}/>- ) : (- <Stack gap="3">- <HStack gap="2">- <Tabs.Root- size="sm"- value={category}- variant="enclosed"- onValueChange={(event) => setCategory(event.value as WorkflowLibraryCategory)}- >- <Tabs.List>- <Tabs.Trigger value="user">Yours</Tabs.Trigger>- <Tabs.Trigger value="default">Defaults</Tabs.Trigger>- </Tabs.List>- </Tabs.Root>- <Input- aria-label="Search workflows"- placeholder="Search workflows…"- size="xs"- value={searchTerm}- onChange={(event: ChangeEvent<HTMLInputElement>) => setSearchTerm(event.currentTarget.value)}- />- </HStack>- <Scrollable label="Workflow library results" maxH="20rem" minH="8rem">- <Stack gap="1" minW="0" w="full">- {items.map((item) => (- <Box- key={item.workflow_id}- _hover={{ bg: 'bg.muted/60' }}- alignItems="center"- display="grid"- gap="2"- gridTemplateColumns={- category === 'user' ? 'minmax(0, 1fr) auto auto auto' : 'minmax(0, 1fr) auto auto'- }- minW="0"- overflow="hidden"- px="1"- rounded="md"- transition="background var(--wb-motion-duration-fast) ease"- w="full"- >- <Box- as="button"- _focusVisible={{ outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' }}- aria-disabled={previewingWorkflowId !== null || isWorkflowLoadPending}- cursor="pointer"- flex="1"- minW="0"- px="1"- py="1.5"- rounded="md"- textAlign="start"- title={`Preview "${item.name || 'Untitled Workflow'}"`}- onClick={() => {- if (previewingWorkflowId === null && !isWorkflowLoadPending) {- void previewWorkflow(item);- }- }}- >- <Stack gap="0" minW="0">- <MiddleTruncate- fontSize="xs"- fontWeight="600"- text={item.name || 'Untitled Workflow'}- />- {item.description ? (- <Text color="fg.subtle" fontSize="2xs" truncate>- {item.description}- </Text>- ) : null}- </Stack>- </Box>- <Button- disabled={previewingWorkflowId !== null || isWorkflowLoadPending}- flexShrink={0}- loading={previewingWorkflowId === item.workflow_id}- size="2xs"- variant="outline"- onClick={() => void previewWorkflow(item)}- >- Preview- </Button>- <Button- disabled={previewingWorkflowId !== null || isWorkflowLoadPending}- flexShrink={0}- loading={workflowLoad?.id === item.workflow_id}- size="2xs"- variant="outline"- onClick={() => void loadWorkflow(item)}- >- Load- </Button>- {category === 'user' ? (- <Button- colorPalette="red"- flexShrink={0}- size="2xs"- variant="ghost"- onClick={() => setPendingDelete(item)}- >- Delete- </Button>- ) : null}- </Box>- ))}- {!isLoading && items.length === 0 ? (- <Text color="fg.subtle" fontSize="2xs" px="2" py="4" textAlign="center">- {category === 'user'- ? 'No saved workflows yet. Save the project graph below to start your library.'- : 'No default workflows are installed on this backend.'}- </Text>- ) : null}- {isLoading ? (- <Text color="fg.subtle" fontSize="2xs" px="2" py="1.5">- Loading workflows…- </Text>- ) : null}- </Stack>- </Scrollable>- {pages > 1 ? (- <HStack gap="2" justify="center">- <Button disabled={page === 0} size="2xs" variant="ghost" onClick={() => refresh(page - 1)}>- Previous- </Button>- <Text color="fg.subtle" fontSize="2xs">- Page {page + 1} of {pages}- </Text>- <Button- disabled={page >= pages - 1}- size="2xs"- variant="ghost"- onClick={() => refresh(page + 1)}- >- Next- </Button>- </HStack>- ) : null}- <Box borderColor="border.subtle" borderTopWidth="1px" pt="3">- <HStack gap="2" justify="space-between">- <Text color="fg.muted" fontSize="2xs" minW="0" truncate>- Project graph: {projectGraph.name || 'Untitled Workflow'}- {projectGraph.libraryWorkflowId ? ' (linked to library)' : ''}- </Text>- <HStack flexShrink={0} gap="2">- {projectGraph.libraryWorkflowId ? (- <Text color="fg.subtle" fontSize="2xs">- {t('widgets.workflow.autosavesToLibrary')}- </Text>- ) : (- <Button- loading={isSaving}- size="2xs"- variant="outline"- onClick={() => void saveToLibrary(false)}- >- {t('widgets.workflow.saveToLibrary')}- </Button>- )}- <Button- loading={isSaving}- size="2xs"- variant="outline"- onClick={() => void saveToLibrary(true)}- >- Save as new- </Button>- </HStack>- </HStack>- </Box>- </Stack>- )}- </Dialog.Body>- <Dialog.CloseTrigger asChild>- <CloseButton color="fg.muted" disabled={isWorkflowLoadPending} size="sm" />- </Dialog.CloseTrigger>- </Dialog.Content>- </Dialog.Positioner>- </Portal>- </Dialog.Root>- <ConfirmDialog- body={`Delete "${pendingDelete?.name || 'Untitled Workflow'}" from the workflow library? This cannot be undone.`}- confirmLabel="Delete"- isOpen={pendingDelete !== null}- title="Delete workflow"- onClose={() => setPendingDelete(null)}- onConfirm={async () => {- if (!pendingDelete) {- return;- }-- const owner = captureAccountScope();- const workflowId = pendingDelete.workflow_id;-- try {- await deleteLibraryWorkflow(workflowId, owner.signal);-- assertAccountScopeCurrent(owner);- invalidateWorkflowLibraryCache();- refresh(page, owner);- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- notify.error('Failed to delete workflow', getApiErrorMessage(error, 'The workflow could not be deleted.'));- }- }}- />- </>+ <SegmentGroup.Root flexShrink={0} size="xs" value={category} onValueChange={handleCategoryChange}>+ <SegmentGroup.Indicator />+ {CATEGORY_ITEMS.map((item) => (+ <SegmentGroup.Item key={item.value} value={item.value}>+ <SegmentGroup.ItemHiddenInput />+ <SegmentGroup.ItemText>{t(item.labelKey)}</SegmentGroup.ItemText>+ </SegmentGroup.Item>+ ))}+ </SegmentGroup.Root>+ </HStack>+ <WorkflowLibraryTagChips selectedTag={tag} tagCounts={tagCounts} onSelect={handleTagSelect} />+ </Stack>+ </Dialog.Header>+ <Dialog.Body display="flex" flex="1" gap="3" minH="0">+ <WorkflowLibraryGrid+ entries={entries}+ error={error}+ selectedWorkflowId={activeWorkflowId}+ status={status}+ onOpen={handleOpenWorkflow}+ onSelect={setSelectedWorkflowId}+ />+ {/* Task 7 fills this rail with the selected workflow's detail panel. */}+ <Box+ borderColor="border.subtle"+ borderWidth="1px"+ flexShrink={0}+ minH="0"+ rounded="md"+ w={DETAIL_RAIL_WIDTH}+ />+ </Dialog.Body>+ {isOpen ? <WorkflowLibraryBrowseSession /> : null}+ <Dialog.CloseTrigger asChild>+ <CloseButton color="fg.muted" disabled={isLoadPending} size="sm" />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>);};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsxnew file mode 100644index 0000000000..8749b25763--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx@@ -0,0 +1,133 @@+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 { useMountEffect } from '@platform/react/useMountEffect';+import { Scrollable } from '@platform/ui';+import { useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import { WorkflowLibraryCard } from './WorkflowLibraryCard';++/**+ * The scrolling card grid. Paging is server side and append-only: reaching the+ * bottom of the accumulated pages asks the browse store for the next one,+ * which no-ops once the last page has landed.+ */++/** How close to the bottom (in viewports) counts as "fetch the next page". */+const NEAR_BOTTOM_VIEWPORTS = 1.5;+const GRID_TEMPLATE_COLUMNS = 'repeat(2, minmax(0, 1fr))';+const NO_MISSING_COUNTS: ReadonlyMap<string, number> = new Map();++export interface WorkflowLibraryGridProps {+ entries: readonly WorkflowLibraryEntry[];+ error: string | null;+ /** Missing-model counts by workflow id; absent ids render no badge. */+ missingCounts?: ReadonlyMap<string, number>;+ selectedWorkflowId: string | null;+ status: WorkflowLibraryBrowseSnapshot['status'];+ 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.+ */+const dedupeByWorkflowId = (entries: readonly WorkflowLibraryEntry[]): WorkflowLibraryEntry[] => {+ const seen = new Set<string>();+ const unique: WorkflowLibraryEntry[] = [];++ for (const entry of entries) {+ if (!seen.has(entry.item.workflow_id)) {+ seen.add(entry.item.workflow_id);+ unique.push(entry);+ }+ }++ return unique;+};++export const WorkflowLibraryGrid = ({+ entries,+ error,+ missingCounts = NO_MISSING_COUNTS,+ onOpen,+ onSelect,+ selectedWorkflowId,+ 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).+ useMountEffect(() => {+ const viewport = viewportRef.current;++ if (!viewport) {+ return;+ }++ const handleScroll = () => {+ const remaining = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;++ if (remaining <= viewport.clientHeight * NEAR_BOTTOM_VIEWPORTS) {+ loadNextWorkflowLibraryPage();+ }+ };++ viewport.addEventListener('scroll', handleScroll, { passive: true });++ return () => viewport.removeEventListener('scroll', handleScroll);+ });++ const visibleEntries = useMemo(() => dedupeByWorkflowId(entries), [entries]);+ const hasEntries = visibleEntries.length > 0;++ return (+ <Scrollable flex="1" label={t('workflowLibrary.title')} minH="0" minW="0" viewportRef={viewportRef}>+ <Box display="flex" flexDirection="column" gap="3" minW="0" pr="2" w="full">+ {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}+ isSelected={entry.item.workflow_id === selectedWorkflowId}+ missingCount={missingCounts.get(entry.item.workflow_id) ?? 0}+ onOpen={onOpen}+ onSelect={onSelect}+ />+ ))}+ </Box>+ ) : null}+ {!hasEntries && status === 'loading' ? (+ <Text color="fg.subtle" fontSize="xs" py="6" textAlign="center">+ {t('workflowLibrary.loading')}+ </Text>+ ) : null}+ {!hasEntries && status !== 'loading' ? (+ <Text color="fg.subtle" fontSize="xs" py="6" textAlign="center">+ {error ?? t('workflowLibrary.empty')}+ </Text>+ ) : null}+ {hasEntries && status === 'loadingMore' ? (+ <HStack color="fg.subtle" gap="2" justify="center" py="2">+ <Spinner size="xs" />+ <Text fontSize="2xs">{t('workflowLibrary.loadingMore')}</Text>+ </HStack>+ ) : null}+ {hasEntries && error ? (+ // A failed page append never blanks the pages already loaded.+ <Text color="fg.subtle" fontSize="2xs" py="2" textAlign="center">+ {error}+ </Text>+ ) : null}+ </Box>+ </Scrollable>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsxnew file mode 100644index 0000000000..5cc8b619d6--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx@@ -0,0 +1,95 @@+import type { WorkflowTagCount } from '@features/workflow/data/libraryBrowseStore';++import { HStack, Text } from '@chakra-ui/react';+import { Button, Scrollable } from '@platform/ui';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * Single-select tag filter for the library grid. The counts come from the+ * backend for the whole category, not the loaded page, so a chip's number+ * still means "how many workflows carry this tag" after infinite scroll has+ * only fetched the first page.+ */++// A ScrollArea root defaults to `height: 100%` and grows to its content's+// max-content width, so a chip strip needs both an explicit height and an+// inline-size containment or it stretches the dialog header.+const CHIP_STRIP_CONTAIN_CSS = { contain: 'inline-size' } as const;+const CHIP_STRIP_CONTENT_PROPS = { h: 'full' } as const;++interface WorkflowLibraryTagChipsProps {+ selectedTag: string | null;+ tagCounts: readonly WorkflowTagCount[];+ onSelect: (tag: string | null) => void;+}++const TagChip = ({+ count,+ isSelected,+ label,+ tag,+ onSelect,+}: {+ count: number | null;+ isSelected: boolean;+ label: string;+ tag: string | null;+ onSelect: (tag: string | null) => void;+}) => {+ const handleClick = useCallback(() => onSelect(tag), [onSelect, tag]);++ return (+ <Button+ aria-pressed={isSelected}+ flexShrink={0}+ rounded="full"+ size="2xs"+ variant={isSelected ? 'subtle' : 'ghost'}+ onClick={handleClick}+ >+ {label}+ {count === null ? null : (+ <Text as="span" color="fg.subtle" fontSize="2xs">+ {count}+ </Text>+ )}+ </Button>+ );+};++export const WorkflowLibraryTagChips = ({ selectedTag, tagCounts, onSelect }: WorkflowLibraryTagChipsProps) => {+ const { t } = useTranslation();++ // A lone "All" chip filters nothing. The strip stays while a tag is still+ // applied, so a category whose counts failed to load can always be cleared.+ if (tagCounts.length === 0 && selectedTag === null) {+ return null;+ }++ return (+ <Scrollable+ contentProps={CHIP_STRIP_CONTENT_PROPS}+ css={CHIP_STRIP_CONTAIN_CSS}+ flexShrink={0}+ h="1.75rem"+ label={t('workflowLibrary.tagsLabel')}+ minW="0"+ orientation="horizontal"+ w="full"+ >+ <HStack align="center" gap="1" h="full" minW="0">+ <TagChip+ count={null}+ isSelected={selectedTag === null}+ label={t('workflowLibrary.allTag')}+ tag={null}+ onSelect={onSelect}+ />+ {tagCounts.map(({ count, tag }) => (+ <TagChip key={tag} count={count} isSelected={selectedTag === tag} label={tag} tag={tag} onSelect={onSelect} />+ ))}+ </HStack>+ </Scrollable>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.tsnew file mode 100644index 0000000000..278559818f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts@@ -0,0 +1,101 @@+import type { WorkflowLibraryListItem } from '@features/workflow/queries';++import { getLibraryWorkflowCached, touchLibraryWorkflowOpenedAt } from '@features/workflow/queries';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';+import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';+import { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { markLibraryGraphSynced } from './librarySyncBridge';++/**+ * The library's "open this workflow into the project graph" sequence, shared+ * by every surface that can start it (the library grid's double-click and its+ * Open action). Two loads can never overlap — a second call while one is in+ * flight is dropped rather than queued, because the winner would silently+ * replace the graph the first one just applied.+ */++export type WorkflowLoadPhase = 'applying' | 'fetching' | 'idle';++export interface LoadLibraryWorkflow {+ load: (item: WorkflowLibraryListItem) => Promise<void>;+ /** Drives the caller's busy overlay; `applying` is the expensive half. */+ loadPhase: WorkflowLoadPhase;+}++export const useLoadLibraryWorkflow = (onLoaded: () => void): LoadLibraryWorkflow => {+ const { t } = useTranslation();+ const { replace } = useProjectGraphCommands();+ const notify = useWorkflowNotifications();+ const [loadPhase, setLoadPhase] = useState<WorkflowLoadPhase>('idle');+ const isInFlightRef = useRef(false);++ const load = useCallback(+ async (item: WorkflowLibraryListItem): Promise<void> => {+ const owner = captureAccountScope();++ if (isInFlightRef.current) {+ return;+ }+ isInFlightRef.current = true;++ try {+ setLoadPhase('fetching');++ const raw = await getLibraryWorkflowCached(item.workflow_id, owner.signal);++ assertAccountScopeCurrent(owner);+ const { document, warnings } = parseWorkflowJson(raw);++ assertAccountScopeCurrent(owner);+ setLoadPhase('applying');+ // Synchronous graph replacement can be expensive for large workflows.+ // Give React a full frame to commit and paint the busy overlay first.+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });++ assertAccountScopeCurrent(owner);+ replace(document, t('workflowLibrary.loadedLabel', { name: item.name }));+ // The freshly-loaded graph is already in sync with the library record+ // it came from — mark it synced so the autosaver does not immediately+ // queue a redundant (echo) save the moment the graph reference changes.+ markLibraryGraphSynced(serializeWorkflowJson(document));++ for (const warning of warnings) {+ notify.info(t('workflowLibrary.loadWarning'), warning);+ }++ void touchLibraryWorkflowOpenedAt(item.workflow_id, owner.signal).catch(() => {+ // Recency bookkeeping only; loading already succeeded.+ });+ onLoaded();+ } catch (error) {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ notify.error(+ t('workflowLibrary.loadFailed'),+ getApiErrorMessage(error, t('workflowLibrary.loadFailedBody', { name: item.name }))+ );+ } finally {+ if (isAccountScopeCurrent(owner)) {+ isInFlightRef.current = false;+ setLoadPhase('idle');+ }+ }+ },+ [notify, onLoaded, replace, t]+ );++ return { load, loadPhase };+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsxindex e5ac8f2aaa..fd0f958be3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsx@@ -45,8 +45,9 @@ const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {};/**- * Regression coverage for the "save as new" echo-autosave bug: on the create- * path, `bindLibraryWorkflow` synchronously adds `libraryWorkflowId` to the+ * Regression coverage for the create-path echo-autosave bug (`saveToLibrary`+ * on a graph with no `libraryWorkflowId` yet):+ * `bindLibraryWorkflow` synchronously adds `libraryWorkflowId` to the* stored project graph, but the hook used to mark the autosaver's baseline* with the JSON it had serialized *before* the bind — which* `serializeWorkflowJson` does not include `id` (added only once@@ -108,12 +109,12 @@ describe('useSaveWorkflowToLibrary bind-then-sync', () => {project: project.port,} as unknown as WorkflowUiAdapter;- let saveAsNew: (() => Promise<string | null>) | null = null;+ let saveToLibrary: (() => Promise<string | null>) | null = null;const Harness = () => {const hook = useSaveWorkflowToLibrary();useEffect(() => {- saveAsNew = hook.saveAsNew;+ saveToLibrary = hook.saveToLibrary;});return null;@@ -134,7 +135,7 @@ describe('useSaveWorkflowToLibrary bind-then-sync', () => {try {await act(async () => {- await saveAsNew?.();+ await saveToLibrary?.();});expect(bindLibraryWorkflow).toHaveBeenCalledWith('library-workflow-99');@@ -157,7 +158,7 @@ describe('useSaveWorkflowToLibrary bind-then-sync', () => {/*** `saveDocumentAsNew` saves an arbitrary document (e.g. a preview payload* that never became the active project graph) to the library. Unlike- * `saveAsNew`, it must not bind the result to the project or mark the+ * `saveToLibrary`, it must not bind the result to the project or mark the* autosaver's synced baseline — the active project graph is untouched.*/describe('useSaveWorkflowToLibrary saveDocumentAsNew', () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.tsindex b1837aaed6..d4ea00fbb2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts@@ -24,14 +24,13 @@ import { markLibraryGraphSynced } from './librarySyncBridge';import { setWorkflowLibrarySyncStatus } from './workflowLibrarySyncStore';/**- * Saves the project graph to the backend workflow library — shared by the- * library dialog's Save/Save as new buttons and the header's one-click save- * for unbound graphs. A successful save also marks the autosaver's baseline- * (`markLibraryGraphSynced`) so the freshly-saved content is not immediately- * queued for another autosave pass.+ * Saves the project graph to the backend workflow library — the chrome+ * header's one-click save for unbound graphs, and the graph preview's "save+ * this document as a new entry". A successful save also marks the autosaver's+ * baseline (`markLibraryGraphSynced`) so the freshly-saved content is not+ * immediately queued for another autosave pass.*/export const useSaveWorkflowToLibrary = (): {- saveAsNew: () => Promise<string | null>;saveDocumentAsNew: (document: ProjectGraphState) => Promise<string | null>;saveToLibrary: () => Promise<string | null>;} => {@@ -40,62 +39,56 @@ export const useSaveWorkflowToLibrary = (): {const { bindLibraryWorkflow } = useProjectGraphCommands();const notify = useWorkflowNotifications();- const save = useCallback(- async (asNew: boolean): Promise<string | null> => {- const owner = captureAccountScope();+ const saveToLibrary = useCallback(async (): Promise<string | null> => {+ const owner = captureAccountScope();- try {- const serialized = serializeWorkflowJson(projectGraph);- let workflowId: string;- let syncedSerialized = serialized;-- if (!asNew && projectGraph.libraryWorkflowId) {- workflowId = projectGraph.libraryWorkflowId;- await updateLibraryWorkflow(workflowId, serialized, owner.signal);-- assertAccountScopeCurrent(owner);- notify.success('Workflow saved', `Updated "${projectGraph.name || 'Untitled Workflow'}" in the library.`);- } else {- workflowId = await createLibraryWorkflow(serialized, owner.signal);-- assertAccountScopeCurrent(owner);- bindLibraryWorkflow(workflowId);- notify.success('Workflow saved', `Saved "${projectGraph.name || 'Untitled Workflow'}" to the library.`);-- // bindLibraryWorkflow dispatches synchronously, so the store already- // reflects the bound `libraryWorkflowId`. Re-serialize from that- // post-bind graph (rather than reusing the pre-bind `serialized`,- // which has no `id`) so the autosaver's synced baseline matches- // exactly what its own read() will produce next — otherwise the id- // key `serializeWorkflowJson` adds on bind reads as a dirty edit and- // triggers a redundant echo save on the next debounce.- syncedSerialized = serializeWorkflowJson(projectStore.getSnapshot().projectGraph);- }+ try {+ const serialized = serializeWorkflowJson(projectGraph);+ let workflowId: string;+ let syncedSerialized = serialized;- markLibraryGraphSynced(syncedSerialized);- setWorkflowLibrarySyncStatus('saved');- invalidateWorkflowLibraryCache();+ if (projectGraph.libraryWorkflowId) {+ workflowId = projectGraph.libraryWorkflowId;+ await updateLibraryWorkflow(workflowId, serialized, owner.signal);- return workflowId;- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return null;- }+ assertAccountScopeCurrent(owner);+ notify.success('Workflow saved', `Updated "${projectGraph.name || 'Untitled Workflow'}" in the library.`);+ } else {+ workflowId = await createLibraryWorkflow(serialized, owner.signal);- notify.error('Failed to save workflow', getApiErrorMessage(error, 'The workflow could not be saved.'));+ assertAccountScopeCurrent(owner);+ bindLibraryWorkflow(workflowId);+ notify.success('Workflow saved', `Saved "${projectGraph.name || 'Untitled Workflow'}" to the library.`);++ // bindLibraryWorkflow dispatches synchronously, so the store already+ // reflects the bound `libraryWorkflowId`. Re-serialize from that+ // post-bind graph (rather than reusing the pre-bind `serialized`,+ // which has no `id`) so the autosaver's synced baseline matches+ // exactly what its own read() will produce next — otherwise the id+ // key `serializeWorkflowJson` adds on bind reads as a dirty edit and+ // triggers a redundant echo save on the next debounce.+ syncedSerialized = serializeWorkflowJson(projectStore.getSnapshot().projectGraph);+ }++ markLibraryGraphSynced(syncedSerialized);+ setWorkflowLibrarySyncStatus('saved');+ invalidateWorkflowLibraryCache();++ return workflowId;+ } catch (error) {+ if (!isAccountScopeCurrent(owner)) {return null;}- },- [bindLibraryWorkflow, notify, projectGraph, projectStore]- );- const saveToLibrary = useCallback(() => save(false), [save]);- const saveAsNew = useCallback(() => save(true), [save]);+ notify.error('Failed to save workflow', getApiErrorMessage(error, 'The workflow could not be saved.'));+ return null;+ }+ }, [bindLibraryWorkflow, notify, projectGraph, projectStore]);// Saves an arbitrary document — not necessarily the active project graph —// as a new library entry. Used by "Open as → Save to workflow library" for// a preview payload that may never have become the active project. Unlike- // `saveAsNew`, this never binds the result to the project or marks the+ // `saveToLibrary`, this never binds the result to the project or marks the// autosaver's synced baseline: the active project graph is left alone.const saveDocumentAsNew = useCallback(async (document: ProjectGraphState): Promise<string | null> => {@@ -121,5 +114,5 @@ export const useSaveWorkflowToLibrary = (): {[notify]);- return { saveAsNew, saveDocumentAsNew, saveToLibrary };+ return { saveDocumentAsNew, saveToLibrary };};