Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): workflow library detail panel with model requirements and install action

joshistoastd6868bd2d0ae
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 0e4dbf1ebb..0e66e839d9 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2979,8 +2979,10 @@
"delete": "Delete",
"deleteConfirmBody": "Delete \"{{name}}\" from the workflow library? This cannot be undone.",
"deleteConfirmTitle": "Delete workflow",
+ "deleteFailed": "Failed to delete workflow",
"downloadJson": "Download JSON",
"duplicate": "Duplicate",
+ "duplicateFailed": "Failed to duplicate workflow",
"duplicateName": "{{name}} copy",
"empty": "No workflows match these filters.",
"fetching": "Fetching workflow…",
@@ -3001,6 +3003,10 @@
"notRunYet": "Not run yet",
"open": "Open",
"previewGraph": "Preview graph",
+ "requirementInstallable": "Not installed",
+ "requirementInstalled": "Installed",
+ "requirementInstalling": "Installing…",
+ "requirementMissing": "Not available to install",
"requires": "Requires",
"sampleOutput": "Sample output",
"searchPlaceholder": "Search names, tags, or descriptions",
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx
new file mode 100644
index 0000000000..05aaf2f15e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx
@@ -0,0 +1,623 @@
+import type { StarterModel } from '@features/models';
+import type { WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';
+import type { WorkflowLibraryEntry, WorkflowLibraryEntryEnrichment } from '@features/workflow/data/libraryBrowseStore';
+import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';
+import { createProjectGraph, serializeWorkflowJson } 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 { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';
+
+/**
+ * The panel is the only surface that turns "what does this workflow need" into
+ * an action, so the model stores it resolves against are replaced by mutable
+ * fixtures: installed models, the starter catalog, and the set of sources
+ * already installing. `getStarterModelInstallSources` stays real — the install
+ * action's contract is that it hands the *catalog's* sources to `installMany`,
+ * deduped across requirements.
+ */
+const models = vi.hoisted(() => ({
+ activeInstallSources: { current: new Set<string>() },
+ ensureModelsLoaded: vi.fn(() => Promise.resolve()),
+ ensureStartersLoaded: vi.fn(),
+ installedModels: { current: [] as unknown[] },
+ installMany: vi.fn((requests: readonly unknown[]) => Promise.resolve(requests.length)),
+ starterModels: { current: [] as unknown[] },
+}));
+
+vi.mock('@features/models', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ensureModelsLoaded: models.ensureModelsLoaded,
+ ensureStartersLoaded: models.ensureStartersLoaded,
+ useActiveInstallSources: () => models.activeInstallSources.current,
+ useInstallActions: () => ({
+ install: models.installMany,
+ installMany: models.installMany,
+ pendingSources: new Set(),
+ }),
+ useModelsSelector: (selector: (snapshot: unknown) => unknown) =>
+ selector({
+ coverImageVersions: {},
+ error: null,
+ missingModelKeys: new Set(),
+ models: models.installedModels.current,
+ modelsByKey: new Map(),
+ modelsDir: null,
+ status: 'loaded',
+ }),
+ useStartersSelector: (selector: (snapshot: unknown) => unknown) =>
+ selector({
+ error: null,
+ response: { starter_bundles: {}, starter_models: models.starterModels.current },
+ status: 'loaded',
+ }),
+}));
+
+const queries = vi.hoisted(() => ({
+ createLibraryWorkflow: vi.fn((_workflow: Record<string, unknown>, _signal?: AbortSignal) =>
+ Promise.resolve('wf-copy')
+ ),
+ deleteLibraryWorkflow: vi.fn((_workflowId: string, _signal?: AbortSignal) => Promise.resolve()),
+ getLibraryWorkflowCached: vi.fn((_workflowId: string, _signal?: AbortSignal) =>
+ Promise.resolve({} as Record<string, unknown>)
+ ),
+ invalidateWorkflowLibraryCache: vi.fn(),
+}));
+
+vi.mock('@features/workflow/queries', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ...queries,
+}));
+
+const downloadText = vi.hoisted(() => vi.fn((_contents: string, _fileName: string, _mimeType: string) => {}));
+
+vi.mock('@platform/browser/downloadBlob', () => ({ downloadText }));
+
+const TRANSLATIONS: Record<string, string> = {
+ 'common.unknownError': 'Something went wrong',
+ 'workflowLibrary.delete': 'Delete',
+ 'workflowLibrary.deleteConfirmBody': 'Delete "{{name}}" from the workflow library? This cannot be undone.',
+ 'workflowLibrary.deleteConfirmTitle': 'Delete workflow',
+ 'workflowLibrary.deleteFailed': 'Failed to delete workflow',
+ 'workflowLibrary.downloadJson': 'Download JSON',
+ 'workflowLibrary.duplicate': 'Duplicate',
+ 'workflowLibrary.duplicateFailed': 'Failed to duplicate workflow',
+ 'workflowLibrary.duplicateName': '{{name}} copy',
+ 'workflowLibrary.forkIntoProject': 'Fork into new project',
+ 'workflowLibrary.installModels_one': 'Install 1 model',
+ 'workflowLibrary.installModels_other': 'Install {{count}} models',
+ 'workflowLibrary.installQueued': 'Model installs queued',
+ 'workflowLibrary.lastRun': 'Your last run · {{when}}',
+ 'workflowLibrary.loadFailed': 'Failed to load workflow',
+ 'workflowLibrary.moreActions': 'More actions',
+ 'workflowLibrary.notRunYet': 'Not run yet',
+ 'workflowLibrary.open': 'Open',
+ 'workflowLibrary.previewGraph': 'Preview graph',
+ 'workflowLibrary.requirementInstallable': 'Not installed',
+ 'workflowLibrary.requirementInstalled': 'Installed',
+ 'workflowLibrary.requirementInstalling': 'Installing…',
+ 'workflowLibrary.requirementMissing': 'Not available to install',
+ 'workflowLibrary.requires': 'Requires',
+ 'workflowLibrary.sampleOutput': 'Sample output',
+ 'workflowLibrary.untitled': 'Untitled Workflow',
+};
+
+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;
+
+// #region Fixtures
+
+const WAN_VAE_DEPENDENCY = {
+ base: 'wan',
+ description: 'Wan VAE',
+ is_installed: false,
+ name: 'Wan VAE',
+ source: 'https://models.test/wan-vae',
+ type: 'vae',
+} as const;
+
+/** Two starters sharing one dependency — the install action must send it once. */
+const WAN_MAIN_STARTER: StarterModel = {
+ base: 'wan',
+ dependencies: [{ ...WAN_VAE_DEPENDENCY }],
+ description: 'Wan 2.2 I2V A14B',
+ is_installed: false,
+ name: 'Wan 2.2 I2V A14B',
+ source: 'https://models.test/wan-i2v',
+ type: 'main',
+};
+
+const WAN_LORA_STARTER: StarterModel = {
+ base: 'wan',
+ dependencies: [{ ...WAN_VAE_DEPENDENCY }],
+ description: 'Lightning LoRA',
+ is_installed: false,
+ name: 'Lightning LoRA',
+ source: 'https://models.test/lightning-lora',
+ type: 'lora',
+};
+
+const INSTALLED_WAN_VAE = {
+ base: 'wan',
+ hash: 'hash-wan-vae',
+ key: 'installed-wan-vae',
+ name: 'Wan VAE',
+ type: 'vae',
+};
+
+const INSTALLED_SDXL_MAIN = {
+ base: 'sdxl',
+ hash: 'hash-sdxl',
+ key: 'installed-sdxl',
+ name: 'SDXL 1.0',
+ type: 'main',
+};
+
+const slot = (base: string, modelType: string, label: string): WorkflowModelRequirement => ({
+ base,
+ kind: 'slot',
+ label,
+ modelType,
+});
+
+const SDXL_REQUIREMENTS: readonly WorkflowModelRequirement[] = [slot('sdxl', 'main', 'SDXL 1.0')];
+const WAN_REQUIREMENTS: readonly WorkflowModelRequirement[] = [
+ slot('wan', 'main', 'Wan 2.2 I2V A14B'),
+ slot('wan', 'lora', 'Lightning LoRA'),
+ slot('wan', 'vae', 'Wan VAE'),
+];
+
+const readyEnrichment = (requirements: readonly WorkflowModelRequirement[]): WorkflowLibraryEntryEnrichment => ({
+ document: createProjectGraph('library-fixture'),
+ nodeCount: requirements.length,
+ requirements: { primaryBase: null, requirements },
+ status: 'ready',
+});
+
+const entry = (
+ overrides: Partial<WorkflowLibraryEntry['item']> & { workflow_id: string; name: string },
+ enrichment: WorkflowLibraryEntryEnrichment,
+ tags: readonly string[] = []
+): WorkflowLibraryEntry => ({
+ enrichment,
+ item: {
+ category: 'user',
+ description: `${overrides.name} description`,
+ thumbnail_url: null,
+ ...overrides,
+ },
+ tags,
+});
+
+const TEXT_TO_IMAGE = entry(
+ {
+ description: 'The baseline SDXL graph.',
+ last_run_at: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
+ name: 'Text to image',
+ thumbnail_url: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
+ workflow_id: 'wf-text-to-image',
+ },
+ readyEnrichment(SDXL_REQUIREMENTS),
+ ['SDXL', 'text to image']
+);
+
+const IMAGE_TO_VIDEO = entry(
+ {
+ description: 'Animates a still image.',
+ name: 'Image to video',
+ thumbnail_url: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
+ workflow_id: 'wf-image-to-video',
+ },
+ readyEnrichment(WAN_REQUIREMENTS),
+ ['Wan 2.2']
+);
+
+const DEFAULT_CATEGORY = entry(
+ { category: 'default', name: 'Bundled default', workflow_id: 'wf-default' },
+ readyEnrichment(SDXL_REQUIREMENTS)
+);
+
+const RAW_WORKFLOW: Record<string, unknown> = {
+ ...serializeWorkflowJson({ ...createProjectGraph('raw-fixture'), name: 'Image to video' }),
+ id: 'wf-image-to-video',
+ meta: { category: 'default', version: '3.0.0' },
+};
+
+// #endregion
+
+const NOTIFICATIONS = { error: vi.fn(), info: vi.fn(), success: vi.fn() };
+const ADAPTER = { notifications: NOTIFICATIONS } as unknown as WorkflowUiAdapter;
+const OPEN_DOCUMENT_IN_NEW_PROJECT = vi.fn();
+const GRAPH_PREVIEW = {
+ openDocumentInNewProject: OPEN_DOCUMENT_IN_NEW_PROJECT,
+} as unknown as WorkflowGraphPreviewPort;
+
+describe('WorkflowLibraryDetailPanel', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ let onClose: () => void;
+ let onDeleted: () => void;
+ let onDuplicated: (workflowId: string) => void;
+ let onOpen: (item: WorkflowLibraryEntry['item']) => void;
+ let onPreview: (selected: WorkflowLibraryEntry) => void;
+
+ /** See `WorkflowLibraryDialog.browser.test.tsx`: keeps Chakra's observer-driven commits inside the act scope. */
+ const settleFrame = () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+ const renderPanel = async (selected: WorkflowLibraryEntry | null) => {
+ await act(async () => {
+ root.render(
+ <StrictMode>
+ <ChakraProvider value={system}>
+ <WorkflowUiProvider adapter={ADAPTER}>
+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
+ <WorkflowLibraryDetailPanel
+ entry={selected}
+ onClose={onClose}
+ onDeleted={onDeleted}
+ onDuplicated={onDuplicated}
+ onOpen={onOpen}
+ onPreview={onPreview}
+ />
+ </WorkflowGraphPreviewProvider>
+ </WorkflowUiProvider>
+ </ChakraProvider>
+ </StrictMode>
+ );
+ await settleFrame();
+ });
+ };
+
+ const panel = () => document.querySelector<HTMLElement>('[data-workflow-detail]');
+ const buttonWithText = (text: string) =>
+ [...document.querySelectorAll('button')].find((candidate) => (candidate.textContent ?? '').trim() === text);
+ const requirementRows = () => [...document.querySelectorAll<HTMLElement>('[data-requirement-status]')];
+ const requirementStatuses = () => requirementRows().map((row) => row.dataset.requirementStatus);
+
+ const clickButton = async (text: string) => {
+ const button = buttonWithText(text);
+ expect(button, `no button labelled "${text}"`).not.toBeUndefined();
+
+ await act(async () => {
+ button?.click();
+ await settleFrame();
+ });
+ };
+
+ const openMenu = async () => {
+ const trigger = document.querySelector<HTMLElement>('[aria-label="More actions"]');
+ expect(trigger).not.toBeNull();
+
+ await act(async () => {
+ trigger?.click();
+ await settleFrame();
+ });
+ };
+
+ const menuItem = (value: string) => document.querySelector<HTMLElement>(`[data-menu-item="${value}"]`);
+
+ const clickMenuItem = async (value: string) => {
+ await openMenu();
+
+ const item = menuItem(value);
+ expect(item, `no menu item "${value}"`).not.toBeNull();
+
+ await act(async () => {
+ item?.click();
+ await settleFrame();
+ });
+ };
+
+ beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ onClose = vi.fn();
+ onDeleted = vi.fn();
+ onDuplicated = vi.fn((_workflowId: string) => {});
+ onOpen = vi.fn();
+ onPreview = vi.fn();
+
+ models.activeInstallSources.current = new Set();
+ models.installedModels.current = [INSTALLED_SDXL_MAIN, INSTALLED_WAN_VAE];
+ models.starterModels.current = [WAN_MAIN_STARTER, WAN_LORA_STARTER];
+ models.ensureModelsLoaded.mockClear();
+ models.ensureStartersLoaded.mockClear();
+ models.installMany.mockClear();
+
+ queries.createLibraryWorkflow.mockClear();
+ queries.createLibraryWorkflow.mockResolvedValue('wf-copy');
+ queries.deleteLibraryWorkflow.mockClear();
+ queries.deleteLibraryWorkflow.mockResolvedValue(undefined);
+ queries.getLibraryWorkflowCached.mockClear();
+ queries.getLibraryWorkflowCached.mockResolvedValue(RAW_WORKFLOW);
+ queries.invalidateWorkflowLibraryCache.mockClear();
+
+ downloadText.mockClear();
+ OPEN_DOCUMENT_IN_NEW_PROJECT.mockClear();
+ NOTIFICATIONS.error.mockClear();
+ NOTIFICATIONS.info.mockClear();
+ NOTIFICATIONS.success.mockClear();
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ });
+
+ it('renders the workflow facts and loads the model data it resolves against', async () => {
+ await renderPanel(TEXT_TO_IMAGE);
+
+ const text = panel()?.textContent ?? '';
+
+ expect(text).toContain('Text to image');
+ expect(text).toContain('The baseline SDXL graph.');
+ expect(text).toContain('SDXL');
+ expect(text).toContain('text to image');
+ expect(text).toContain('Requires');
+ expect(models.ensureModelsLoaded).toHaveBeenCalled();
+ expect(models.ensureStartersLoaded).toHaveBeenCalled();
+ });
+
+ it('offers Open as the primary action when every requirement is installed', async () => {
+ await renderPanel(TEXT_TO_IMAGE);
+
+ expect(requirementStatuses()).toEqual(['installed']);
+ expect(buttonWithText('Open')).not.toBeUndefined();
+ expect(buttonWithText('Install 1 model')).toBeUndefined();
+
+ await clickButton('Open');
+
+ expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item);
+ });
+
+ it('opens the workflow from the keyboard, the path the double-click-only cards do not offer', async () => {
+ await renderPanel(TEXT_TO_IMAGE);
+
+ const open = buttonWithText('Open');
+ expect(open?.tagName).toBe('BUTTON');
+
+ await act(async () => {
+ open?.focus();
+ expect(document.activeElement).toBe(open);
+ open?.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));
+ // A real Enter on a focused button dispatches a click; jsdom-style
+ // synthesis does not, so the click is what the browser would send next.
+ open?.click();
+ await settleFrame();
+ });
+
+ expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item);
+ });
+
+ it('swaps the primary action for an install when starter models can fill the gaps', async () => {
+ await renderPanel(IMAGE_TO_VIDEO);
+
+ expect(requirementStatuses()).toEqual(['installable', 'installable', 'installed']);
+ // The rows say which state they are in, not just how they are styled.
+ expect(document.querySelectorAll('[aria-label="Not installed"]')).toHaveLength(2);
+ expect(document.querySelectorAll('[aria-label="Installed"]')).toHaveLength(1);
+ expect(buttonWithText('Install 2 models')).not.toBeUndefined();
+ expect(buttonWithText('Open')).toBeUndefined();
+ });
+
+ it('queues one install per source, deduped across requirements that share a dependency', async () => {
+ await renderPanel(IMAGE_TO_VIDEO);
+
+ await clickButton('Install 2 models');
+
+ expect(models.installMany).toHaveBeenCalledTimes(1);
+
+ const requests = models.installMany.mock.calls[0]?.[0] as { source: string }[];
+
+ expect(requests.map((request) => request.source)).toEqual([
+ 'https://models.test/wan-vae',
+ 'https://models.test/wan-i2v',
+ 'https://models.test/lightning-lora',
+ ]);
+ expect(NOTIFICATIONS.success).toHaveBeenCalledWith('Model installs queued');
+ });
+
+ it('shows the in-flight rows as installing and drops the install action', async () => {
+ models.activeInstallSources.current = new Set(['https://models.test/wan-i2v', 'https://models.test/wan-vae']);
+
+ await renderPanel(IMAGE_TO_VIDEO);
+
+ expect(requirementStatuses()).toEqual(['installing', 'installing', 'installed']);
+ expect(document.querySelectorAll('[aria-label="Installing…"]')).toHaveLength(2);
+ expect(buttonWithText('Install 2 models')).toBeUndefined();
+ expect(buttonWithText('Open')).not.toBeUndefined();
+ });
+
+ it('marks a requirement with no installed model and no starter as unresolvable', async () => {
+ models.starterModels.current = [];
+
+ await renderPanel(IMAGE_TO_VIDEO);
+
+ expect(requirementStatuses()).toEqual(['unresolvable', 'unresolvable', 'installed']);
+ // Nothing to install, so the panel keeps its Open action rather than
+ // offering an install that cannot run.
+ expect(buttonWithText('Open')).not.toBeUndefined();
+ });
+
+ it('captions the thumbnail with the last run, the sample output, or nothing', async () => {
+ await renderPanel(TEXT_TO_IMAGE);
+ expect(panel()?.textContent).toContain('Your last run · 2 days ago');
+
+ await renderPanel(IMAGE_TO_VIDEO);
+ expect(panel()?.textContent).toContain('Sample output');
+ expect(panel()?.textContent).not.toContain('Your last run');
+
+ await renderPanel(DEFAULT_CATEGORY);
+ expect(panel()?.textContent).not.toContain('Sample output');
+ expect(panel()?.textContent).toContain('Not run yet');
+ });
+
+ it('updates in place when the selection changes', async () => {
+ await renderPanel(TEXT_TO_IMAGE);
+
+ const before = panel();
+ expect(before?.dataset.workflowDetail).toBe('wf-text-to-image');
+
+ await renderPanel(IMAGE_TO_VIDEO);
+
+ // Same element, new content: a keyed remount would flash the whole rail.
+ expect(panel()).toBe(before);
+ expect(panel()?.dataset.workflowDetail).toBe('wf-image-to-video');
+ });
+
+ it('renders placeholder rows while enrichment is pending and a quiet line when it failed', async () => {
+ await renderPanel(entry({ name: 'Pending', workflow_id: 'wf-pending' }, { status: 'pending' }));
+
+ expect(document.querySelectorAll('[data-requirement-placeholder]').length).toBeGreaterThan(0);
+ expect(requirementRows()).toHaveLength(0);
+
+ await renderPanel(
+ entry({ name: 'Broken', workflow_id: 'wf-broken' }, { message: 'Failed to read this workflow.', status: 'error' })
+ );
+
+ expect(panel()?.textContent).toContain('Failed to read this workflow.');
+ expect(document.querySelectorAll('[data-requirement-placeholder]')).toHaveLength(0);
+ });
+
+ it('hides Delete for bundled defaults but still offers Duplicate', async () => {
+ await renderPanel(DEFAULT_CATEGORY);
+ await openMenu();
+
+ expect(menuItem('delete')).toBeNull();
+ expect(menuItem('duplicate')).not.toBeNull();
+
+ await renderPanel(TEXT_TO_IMAGE);
+ await openMenu();
+
+ expect(menuItem('delete')).not.toBeNull();
+ });
+
+ it('duplicates the library record without its id, renamed, and owned by the user', async () => {
+ await renderPanel(DEFAULT_CATEGORY);
+
+ await clickMenuItem('duplicate');
+
+ expect(queries.getLibraryWorkflowCached).toHaveBeenCalledWith('wf-default', expect.anything());
+ expect(queries.createLibraryWorkflow).toHaveBeenCalledTimes(1);
+
+ const created = queries.createLibraryWorkflow.mock.calls[0]?.[0] as Record<string, unknown>;
+
+ expect(created).not.toHaveProperty('id');
+ expect(created.name).toBe('Bundled default copy');
+ expect(created.meta).toStrictEqual({ category: 'user', version: '3.0.0' });
+ // The original record is untouched — only a copy is written.
+ expect(RAW_WORKFLOW.meta).toStrictEqual({ category: 'default', version: '3.0.0' });
+ expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledTimes(1);
+ expect(onDuplicated).toHaveBeenCalledWith('wf-copy');
+ });
+
+ it('forks the cached workflow into a fresh project', async () => {
+ await renderPanel(IMAGE_TO_VIDEO);
+
+ await clickMenuItem('fork-into-project');
+
+ expect(OPEN_DOCUMENT_IN_NEW_PROJECT).toHaveBeenCalledTimes(1);
+
+ const [document_, label] = OPEN_DOCUMENT_IN_NEW_PROJECT.mock.calls[0] as [{ name: string }, string];
+
+ expect(document_.name).toBe('Image to video');
+ expect(label).toBe('Image to video');
+ // The fork lands the user in a new project, so the library gets out of the way.
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(queries.createLibraryWorkflow).not.toHaveBeenCalled();
+ });
+
+ it('downloads the raw workflow JSON under a slugged file name', async () => {
+ await renderPanel(IMAGE_TO_VIDEO);
+
+ await clickMenuItem('download-json');
+
+ expect(downloadText).toHaveBeenCalledTimes(1);
+
+ const [contents, fileName, mimeType] = downloadText.mock.calls[0] as [string, string, string];
+
+ expect(JSON.parse(contents)).toStrictEqual(RAW_WORKFLOW);
+ expect(fileName).toBe('image-to-video.json');
+ expect(mimeType).toBe('application/json');
+ });
+
+ it('deletes only after the confirmation is accepted', async () => {
+ await renderPanel(TEXT_TO_IMAGE);
+
+ await clickMenuItem('delete');
+
+ const confirm = document.querySelector<HTMLElement>('[role="alertdialog"]');
+ expect(confirm?.textContent).toContain('Delete workflow');
+ expect(queries.deleteLibraryWorkflow).not.toHaveBeenCalled();
+
+ const confirmButton = [...(confirm?.querySelectorAll('button') ?? [])].find(
+ (candidate) => (candidate.textContent ?? '').trim() === 'Delete'
+ );
+ expect(confirmButton).not.toBeUndefined();
+
+ await act(async () => {
+ confirmButton?.click();
+ await settleFrame();
+ });
+
+ expect(queries.deleteLibraryWorkflow).toHaveBeenCalledWith('wf-text-to-image', expect.anything());
+ expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledTimes(1);
+ expect(onDeleted).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports a failed delete without claiming the workflow is gone', async () => {
+ queries.deleteLibraryWorkflow.mockRejectedValue(new Error('network down'));
+
+ await renderPanel(TEXT_TO_IMAGE);
+ await clickMenuItem('delete');
+
+ const confirm = document.querySelector<HTMLElement>('[role="alertdialog"]');
+ const confirmButton = [...(confirm?.querySelectorAll('button') ?? [])].find(
+ (candidate) => (candidate.textContent ?? '').trim() === 'Delete'
+ );
+
+ await act(async () => {
+ confirmButton?.click();
+ await settleFrame();
+ });
+
+ expect(NOTIFICATIONS.error).toHaveBeenCalledWith('Failed to delete workflow', expect.any(String));
+ expect(onDeleted).not.toHaveBeenCalled();
+ expect(queries.invalidateWorkflowLibraryCache).not.toHaveBeenCalled();
+ });
+
+ it('hands the selected entry to the preview action', async () => {
+ await renderPanel(IMAGE_TO_VIDEO);
+
+ await clickButton('Preview graph');
+
+ expect(onPreview).toHaveBeenCalledWith(IMAGE_TO_VIDEO);
+ });
+
+ it('renders nothing actionable without a selection', async () => {
+ await renderPanel(null);
+
+ expect(buttonWithText('Open')).toBeUndefined();
+ expect(document.querySelector('[aria-label="More actions"]')).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
new file mode 100644
index 0000000000..84b468f412
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
@@ -0,0 +1,440 @@
+import type { StarterInstallSource } from '@features/models';
+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';
+import type { WorkflowLibraryListItem } from '@features/workflow/queries';
+
+import { Badge, Box, Flex, HStack, Icon, Image, Menu, Portal, Stack, Text } from '@chakra-ui/react';
+import { getStarterModelInstallSources, useInstallActions } from '@features/models';
+import { resolveWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';
+import {
+ createLibraryWorkflow,
+ deleteLibraryWorkflow,
+ getLibraryWorkflowCached,
+ invalidateWorkflowLibraryCache,
+} from '@features/workflow/queries';
+import { useWorkflowGraphPreview, useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';
+import { parseWorkflowJson } from '@features/workflow/utility';
+import { downloadText } from '@platform/browser/downloadBlob';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { getApiErrorMessage } from '@platform/transport/http';
+import { Button, ConfirmDialog, IconButton, MenuContent, Scrollable } from '@platform/ui';
+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
+import {
+ CopyIcon,
+ DownloadIcon,
+ EllipsisIcon,
+ GitForkIcon,
+ ImageOffIcon,
+ Trash2Icon,
+ WorkflowIcon,
+} from 'lucide-react';
+import { useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatRelativeTime } from './relativeTime';
+import { useModelRequirementDeps, WorkflowRequirementsList } from './WorkflowRequirementsList';
+
+/**
+ * The library's right rail: everything about the selected workflow that
+ * decides whether to open it — sample output, description, tags, and the
+ * models it needs — plus the one action that follows from that answer. When
+ * models are missing the primary button installs them instead of opening a
+ * workflow that would fail on its first run; everything rarer (duplicate,
+ * fork, download, delete) lives behind the overflow menu.
+ *
+ * The panel updates in place across selection changes: no keys, no remounts,
+ * so switching cards never flashes the rail.
+ */
+
+const DETAIL_RAIL_WIDTH = '18rem';
+const THUMBNAIL_ASPECT_RATIO = 3 / 2;
+const INSTALL_HOVER = { opacity: 0.85 } as const;
+const MENU_ITEM_LAYOUT = { alignItems: 'center', gap: '2.5', py: '1' } as const;
+const MENU_ITEM_ICON_PROPS = { boxSize: '3.5', flexShrink: 0 } as const;
+
+export interface WorkflowLibraryDetailPanelProps {
+ entry: WorkflowLibraryEntry | null;
+ /** The shell closes the library when a fork takes the user to a new project. */
+ onClose: () => void;
+ onDeleted: () => void;
+ /** Carries the copy's id so the shell can select it once the list refreshes. */
+ onDuplicated: (workflowId: string) => void;
+ onOpen: (item: WorkflowLibraryListItem) => void;
+ onPreview: (entry: WorkflowLibraryEntry) => void;
+}
+
+const toFileSlug = (name: string): string => name.trim().replaceAll(/\s+/g, '-').toLowerCase() || 'workflow';
+
+export const WorkflowLibraryDetailPanel = ({
+ entry,
+ onClose,
+ onDeleted,
+ onDuplicated,
+ onOpen,
+ onPreview,
+}: WorkflowLibraryDetailPanelProps) => {
+ const { t } = useTranslation();
+ const deps = useModelRequirementDeps();
+ const notify = useWorkflowNotifications();
+ const { openDocumentInNewProject } = useWorkflowGraphPreview();
+ const { installMany } = useInstallActions();
+ // Keyed by URL rather than a boolean, so a selection change re-arms the
+ // thumbnail without an effect resetting the flag.
+ const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);
+ const [isDeleteConfirmOpen, setIsDeleteConfirmOpen] = useState(false);
+
+ const enrichment = entry?.enrichment ?? null;
+ const resolved = useMemo(
+ () =>
+ enrichment?.status === 'ready'
+ ? resolveWorkflowModelRequirements(enrichment.requirements.requirements, deps)
+ : null,
+ [deps, enrichment]
+ );
+ const installableCount = resolved?.filter((requirement) => requirement.status === 'installable').length ?? 0;
+
+ const handleOpen = useCallback(() => {
+ if (entry) {
+ onOpen(entry.item);
+ }
+ }, [entry, onOpen]);
+
+ const handlePreview = useCallback(() => {
+ if (entry) {
+ onPreview(entry);
+ }
+ }, [entry, onPreview]);
+
+ const handleThumbnailError = useCallback(() => setFailedThumbnailUrl(entry?.item.thumbnail_url ?? null), [entry]);
+
+ const install = useCallback(async () => {
+ const owner = captureAccountScope();
+ const starterBySource = new Map(deps.starterModels.map((starter) => [starter.source, starter]));
+ const requests: StarterInstallSource[] = [];
+ const seen = new Set<string>();
+
+ for (const requirement of resolved ?? []) {
+ const starter = requirement.starterMatch ? starterBySource.get(requirement.starterMatch.source) : undefined;
+
+ if (requirement.status !== 'installable' || !starter) {
+ continue;
+ }
+
+ for (const source of getStarterModelInstallSources(starter)) {
+ // Two requirements routinely share a dependency (an encoder, a VAE),
+ // and an install may have started between this render and the click.
+ if (seen.has(source.source) || deps.activeInstallSources.has(source.source)) {
+ continue;
+ }
+
+ seen.add(source.source);
+ requests.push(source);
+ }
+ }
+
+ if (requests.length === 0) {
+ return;
+ }
+
+ const queued = await installMany(requests);
+
+ // One notice for the whole set; `installMany` toasts its own failures.
+ if (queued > 0 && isAccountScopeCurrent(owner)) {
+ notify.success(t('workflowLibrary.installQueued'));
+ }
+ }, [deps, installMany, notify, resolved, t]);
+ const handleInstall = useCallback(() => void install(), [install]);
+
+ /**
+ * Copies the library *record* — not the project graph, and never the
+ * original — so a bundled default can be adapted without the editor ever
+ * loading it.
+ */
+ const duplicate = useCallback(async () => {
+ if (!entry) {
+ return;
+ }
+
+ const owner = captureAccountScope();
+ const { name } = entry.item;
+
+ try {
+ const raw = await getLibraryWorkflowCached(entry.item.workflow_id, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+
+ const { id: _id, ...copy } = raw;
+ const meta = typeof copy.meta === 'object' && copy.meta !== null ? (copy.meta as Record<string, unknown>) : {};
+ const workflowId = await createLibraryWorkflow(
+ {
+ ...copy,
+ // A copy of a default is still the user's own workflow.
+ meta: { ...meta, category: 'user' },
+ name: t('workflowLibrary.duplicateName', { name: name || t('workflowLibrary.untitled') }),
+ },
+ owner.signal
+ );
+
+ assertAccountScopeCurrent(owner);
+ invalidateWorkflowLibraryCache();
+ onDuplicated(workflowId);
+ } catch (error) {
+ if (isAccountScopeCurrent(owner)) {
+ notify.error(t('workflowLibrary.duplicateFailed'), getApiErrorMessage(error, t('common.unknownError')));
+ }
+ }
+ }, [entry, notify, onDuplicated, t]);
+ const handleDuplicate = useCallback(() => void duplicate(), [duplicate]);
+
+ const fork = useCallback(async () => {
+ if (!entry) {
+ return;
+ }
+
+ const owner = captureAccountScope();
+
+ try {
+ const raw = await getLibraryWorkflowCached(entry.item.workflow_id, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+
+ const { document } = parseWorkflowJson(raw);
+
+ // The port creates and activates a fresh project first, so the project
+ // the library was opened from is left exactly as it was.
+ openDocumentInNewProject(document, entry.item.name);
+ onClose();
+ } catch (error) {
+ if (isAccountScopeCurrent(owner)) {
+ notify.error(t('workflowLibrary.loadFailed'), getApiErrorMessage(error, t('common.unknownError')));
+ }
+ }
+ }, [entry, notify, onClose, openDocumentInNewProject, t]);
+ const handleFork = useCallback(() => void fork(), [fork]);
+
+ const download = useCallback(async () => {
+ if (!entry) {
+ return;
+ }
+
+ const owner = captureAccountScope();
+
+ try {
+ const raw = await getLibraryWorkflowCached(entry.item.workflow_id, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ downloadText(JSON.stringify(raw, null, 2), `${toFileSlug(entry.item.name)}.json`, 'application/json');
+ } catch (error) {
+ if (isAccountScopeCurrent(owner)) {
+ notify.error(t('workflowLibrary.loadFailed'), getApiErrorMessage(error, t('common.unknownError')));
+ }
+ }
+ }, [entry, notify, t]);
+ const handleDownload = useCallback(() => void download(), [download]);
+
+ const openDeleteConfirm = useCallback(() => setIsDeleteConfirmOpen(true), []);
+ const closeDeleteConfirm = useCallback(() => setIsDeleteConfirmOpen(false), []);
+
+ const confirmDelete = useCallback(async () => {
+ if (!entry) {
+ return;
+ }
+
+ const owner = captureAccountScope();
+
+ try {
+ await deleteLibraryWorkflow(entry.item.workflow_id, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ // The invalidation refetches the visible pages; the shell only has to
+ // let go of the selection this row held.
+ invalidateWorkflowLibraryCache();
+ onDeleted();
+ } catch (error) {
+ if (isAccountScopeCurrent(owner)) {
+ notify.error(t('workflowLibrary.deleteFailed'), getApiErrorMessage(error, t('common.unknownError')));
+ }
+ }
+ }, [entry, notify, onDeleted, t]);
+
+ if (!entry) {
+ return (
+ <Box borderColor="border.subtle" borderWidth="1px" flexShrink={0} minH="0" rounded="md" w={DETAIL_RAIL_WIDTH} />
+ );
+ }
+
+ const { item, tags } = entry;
+ const name = item.name || t('workflowLibrary.untitled');
+ const showThumbnail = Boolean(item.thumbnail_url) && item.thumbnail_url !== failedThumbnailUrl;
+ const lastRun = item.last_run_at ? formatRelativeTime(item.last_run_at, new Date()) : '';
+ const caption = lastRun
+ ? t('workflowLibrary.lastRun', { when: lastRun })
+ : showThumbnail
+ ? t('workflowLibrary.sampleOutput')
+ : null;
+
+ return (
+ <Stack
+ borderColor="border.subtle"
+ borderWidth="1px"
+ data-workflow-detail={item.workflow_id}
+ flexShrink={0}
+ gap="0"
+ minH="0"
+ rounded="md"
+ w={DETAIL_RAIL_WIDTH}
+ >
+ <Scrollable flex="1" label={name} minH="0">
+ <Stack gap="2" minW="0" p="2.5">
+ <Stack gap="1" minW="0">
+ <Box aspectRatio={THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" rounded="md" 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>
+ {caption ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ {caption}
+ </Text>
+ ) : null}
+ </Stack>
+
+ <MiddleTruncate fontSize="sm" fontWeight="600" minW="0" text={name} />
+
+ {item.description ? (
+ <Text color="fg.muted" fontSize="2xs" lineClamp={4}>
+ {item.description}
+ </Text>
+ ) : null}
+
+ {tags.length > 0 ? (
+ <HStack flexWrap="wrap" gap="1" minW="0">
+ {tags.map((tag) => (
+ <Badge key={tag} size="xs" variant="subtle">
+ {tag}
+ </Badge>
+ ))}
+ </HStack>
+ ) : null}
+
+ <WorkflowRequirementsList
+ errorMessage={enrichment?.status === 'error' ? enrichment.message : null}
+ resolved={resolved}
+ />
+ </Stack>
+ </Scrollable>
+
+ <Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" p="2.5">
+ <HStack gap="2" minW="0">
+ {installableCount > 0 ? (
+ // The theme's amber, with the ramp's darkest step for text — that
+ // step is dark in both light and dark schemes, so the one warning
+ // token carries the whole treatment.
+ <Button
+ bg="fg.warning"
+ color="neutral.950"
+ flex="1"
+ minW="0"
+ size="sm"
+ _hover={INSTALL_HOVER}
+ onClick={handleInstall}
+ >
+ {t('workflowLibrary.installModels', { count: installableCount })}
+ </Button>
+ ) : (
+ <Button flex="1" minW="0" size="sm" onClick={handleOpen}>
+ {t('workflowLibrary.open')}
+ </Button>
+ )}
+ <Menu.Root>
+ <Menu.Trigger asChild>
+ <IconButton aria-label={t('workflowLibrary.moreActions')} size="sm" variant="outline">
+ <EllipsisIcon />
+ </IconButton>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="12rem">
+ <Menu.Item {...MENU_ITEM_LAYOUT} data-menu-item="open" value="open" onClick={handleOpen}>
+ <Icon as={WorkflowIcon} {...MENU_ITEM_ICON_PROPS} />
+ <Menu.ItemText>{t('workflowLibrary.open')}</Menu.ItemText>
+ </Menu.Item>
+ <Menu.Item
+ {...MENU_ITEM_LAYOUT}
+ data-menu-item="duplicate"
+ value="duplicate"
+ onClick={handleDuplicate}
+ >
+ <Icon as={CopyIcon} {...MENU_ITEM_ICON_PROPS} />
+ <Menu.ItemText>{t('workflowLibrary.duplicate')}</Menu.ItemText>
+ </Menu.Item>
+ <Menu.Item
+ {...MENU_ITEM_LAYOUT}
+ data-menu-item="fork-into-project"
+ value="fork-into-project"
+ onClick={handleFork}
+ >
+ <Icon as={GitForkIcon} {...MENU_ITEM_ICON_PROPS} />
+ <Menu.ItemText>{t('workflowLibrary.forkIntoProject')}</Menu.ItemText>
+ </Menu.Item>
+ <Menu.Item
+ {...MENU_ITEM_LAYOUT}
+ data-menu-item="download-json"
+ value="download-json"
+ onClick={handleDownload}
+ >
+ <Icon as={DownloadIcon} {...MENU_ITEM_ICON_PROPS} />
+ <Menu.ItemText>{t('workflowLibrary.downloadJson')}</Menu.ItemText>
+ </Menu.Item>
+ {item.category === 'user' ? (
+ // Bundled defaults are not the account's to delete.
+ <Menu.Item
+ {...MENU_ITEM_LAYOUT}
+ color="fg.error"
+ data-menu-item="delete"
+ value="delete"
+ onClick={openDeleteConfirm}
+ >
+ <Icon as={Trash2Icon} {...MENU_ITEM_ICON_PROPS} />
+ <Menu.ItemText>{t('workflowLibrary.delete')}</Menu.ItemText>
+ </Menu.Item>
+ ) : null}
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ </HStack>
+ <Button size="sm" variant="outline" w="full" onClick={handlePreview}>
+ <WorkflowIcon />
+ {t('workflowLibrary.previewGraph')}
+ </Button>
+ </Stack>
+
+ <ConfirmDialog
+ body={t('workflowLibrary.deleteConfirmBody', { name })}
+ confirmLabel={t('workflowLibrary.delete')}
+ isOpen={isDeleteConfirmOpen}
+ title={t('workflowLibrary.deleteConfirmTitle')}
+ onClose={closeDeleteConfirm}
+ onConfirm={confirmDelete}
+ />
+ </Stack>
+ );
+};
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.tsx
index dbfc99700b..17203b857c 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
@@ -1,10 +1,14 @@
+import type { StarterModel } from '@features/models';
+import type { WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';
import type {
WorkflowLibraryBrowseSnapshot,
WorkflowLibraryEntry,
WorkflowLibraryEntryEnrichment,
} from '@features/workflow/data/libraryBrowseStore';
+import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';
import { ChakraProvider } from '@chakra-ui/react';
+import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';
import { createProjectGraph } from '@features/workflow/utility';
import { system } from '@theme/system';
import { act, StrictMode } from 'react';
@@ -64,6 +68,30 @@ vi.mock('./useLoadLibraryWorkflow', () => ({
useLoadLibraryWorkflow: () => ({ load: loader.load, loadPhase: loader.phase.current }),
}));
+// The detail panel resolves every entry's requirements against the model
+// stores to feed the cards' missing-model badges. Those stores are the models
+// feature's; here they are fixed data so the badge under test comes from the
+// dialog's own wiring, not a live catalog.
+const FLUX_STARTER: StarterModel = {
+ base: 'flux',
+ description: 'FLUX.1 dev',
+ is_installed: false,
+ name: 'FLUX.1 dev',
+ source: 'https://models.test/flux-dev',
+ type: 'main',
+};
+
+vi.mock('@features/models', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ensureModelsLoaded: vi.fn(() => Promise.resolve()),
+ ensureStartersLoaded: vi.fn(),
+ useActiveInstallSources: () => new Set<string>(),
+ useInstallActions: () => ({ install: vi.fn(), installMany: vi.fn(), pendingSources: new Set() }),
+ useModelsSelector: (selector: (snapshot: unknown) => unknown) => selector({ models: [] }),
+ useStartersSelector: (selector: (snapshot: unknown) => unknown) =>
+ selector({ response: { starter_models: [FLUX_STARTER] } }),
+}));
+
// 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.
@@ -72,15 +100,28 @@ const TRANSLATIONS: Record<string, string> = {
'workflowLibrary.allTag': 'All',
'workflowLibrary.applying': 'Applying workflow…',
'workflowLibrary.browse': 'Browse',
+ 'workflowLibrary.delete': 'Delete',
+ 'workflowLibrary.downloadJson': 'Download JSON',
+ 'workflowLibrary.duplicate': 'Duplicate',
'workflowLibrary.empty': 'No workflows match these filters.',
'workflowLibrary.fetching': 'Fetching workflow…',
+ 'workflowLibrary.forkIntoProject': 'Fork into new project',
+ '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.nodeCount_one': '{{count}} node',
'workflowLibrary.nodeCount_other': '{{count}} nodes',
'workflowLibrary.notRunYet': 'Not run yet',
+ 'workflowLibrary.open': 'Open',
+ 'workflowLibrary.previewGraph': 'Preview graph',
+ 'workflowLibrary.requirementInstallable': 'Not installed',
+ 'workflowLibrary.requires': 'Requires',
+ 'workflowLibrary.sampleOutput': 'Sample output',
'workflowLibrary.searchPlaceholder': 'Search names, tags, or descriptions',
'workflowLibrary.title': 'Workflows',
+ 'workflowLibrary.untitled': 'Untitled Workflow',
'workflowLibrary.yours': 'Yours',
};
@@ -100,10 +141,16 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));
const EMPTY_DOCUMENT = createProjectGraph('library-fixture');
-const readyEnrichment = (nodeCount: number, primaryBase: string | null): WorkflowLibraryEntryEnrichment => ({
+const NO_REQUIREMENTS: readonly WorkflowModelRequirement[] = [];
+
+const readyEnrichment = (
+ nodeCount: number,
+ primaryBase: string | null,
+ requirements: readonly WorkflowModelRequirement[] = NO_REQUIREMENTS
+): WorkflowLibraryEntryEnrichment => ({
document: EMPTY_DOCUMENT,
nodeCount,
- requirements: { primaryBase, requirements: [] },
+ requirements: { primaryBase, requirements },
status: 'ready',
});
@@ -128,7 +175,14 @@ const PORTRAIT = entry('wf-portrait', 'Portrait Studio', readyEnrichment(12, 'sd
tags: ['portrait'],
thumbnailUrl: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
});
-const LANDSCAPE = entry('wf-landscape', 'Landscape Pass', readyEnrichment(7, 'flux'), { tags: ['landscape'] });
+// Its one requirement has no installed match but a starter that can fetch it,
+// so the grid should badge it as one model to install.
+const LANDSCAPE = entry(
+ 'wf-landscape',
+ 'Landscape Pass',
+ readyEnrichment(7, 'flux', [{ base: 'flux', kind: 'slot', label: 'FLUX checkpoint', modelType: 'main' }]),
+ { tags: ['landscape'] }
+);
const SKETCH = entry('wf-sketch', 'Sketch To Render', { status: 'pending' });
const UPSCALE = entry(
'wf-upscale',
@@ -159,6 +213,13 @@ const withSnapshot = (patch: Partial<WorkflowLibraryBrowseSnapshot>): WorkflowLi
...patch,
});
+// The detail panel's ports. The dialog only has to compose them; their own
+// suites cover what they do.
+const UI_ADAPTER = {
+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },
+} as unknown as WorkflowUiAdapter;
+const GRAPH_PREVIEW = { openDocumentInNewProject: vi.fn() } as unknown as WorkflowGraphPreviewPort;
+
describe('WorkflowLibraryDialog', () => {
let host: HTMLDivElement;
let root: Root;
@@ -182,7 +243,11 @@ describe('WorkflowLibraryDialog', () => {
root.render(
<StrictMode>
<ChakraProvider value={system}>
- <WorkflowLibraryDialog isOpen={isOpen} onOpenChange={onOpenChange} />
+ <WorkflowUiProvider adapter={UI_ADAPTER}>
+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>
+ <WorkflowLibraryDialog isOpen={isOpen} onOpenChange={onOpenChange} />
+ </WorkflowGraphPreviewProvider>
+ </WorkflowUiProvider>
</ChakraProvider>
</StrictMode>
);
@@ -467,6 +532,46 @@ describe('WorkflowLibraryDialog', () => {
expect(document.body.textContent ?? '').toContain('No workflows match these filters.');
});
+ it('shows the selected workflow in the rail and follows the selection', async () => {
+ await openWith(LOADED_SNAPSHOT);
+
+ const detail = () => document.querySelector<HTMLElement>('[data-workflow-detail]');
+
+ expect(detail()?.dataset.workflowDetail).toBe('wf-portrait');
+
+ await act(() => card('wf-landscape')?.click());
+
+ expect(detail()?.dataset.workflowDetail).toBe('wf-landscape');
+ expect(detail()?.textContent).toContain('Landscape Pass');
+ });
+
+ it('opens the selected workflow from the rail, the keyboard-reachable path', async () => {
+ await openWith(LOADED_SNAPSHOT);
+
+ // Portrait needs nothing installed, so the rail's primary action is Open.
+ await clickText('Open');
+
+ expect(loader.load).toHaveBeenCalledWith(PORTRAIT.item);
+ });
+
+ it('badges the cards with the models their workflows still need', async () => {
+ await openWith(LOADED_SNAPSHOT);
+
+ // Resolved from the same model data the rail uses: the FLUX slot has no
+ // installed match but a starter that can fetch it.
+ expect(card('wf-landscape')?.textContent).toContain('Install 1 model');
+ expect(card('wf-portrait')?.textContent).not.toContain('Install');
+ });
+
+ it('records the workflow the rail asked to preview', async () => {
+ await openWith(LOADED_SNAPSHOT);
+
+ await clickText('Preview graph');
+
+ // Task 8 mounts the preview dialog from this pending selection.
+ expect(document.querySelector('[data-pending-preview="wf-portrait"]')).not.toBeNull();
+ });
+
it('shows the busy overlay while a workflow is being applied', async () => {
loader.phase.current = 'applying';
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
index c76d9bdde4..d092af1799 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx
@@ -1,7 +1,8 @@
-import type { WorkflowLibraryBrowseSnapshot } from '@features/workflow/data/libraryBrowseStore';
+import type { WorkflowLibraryBrowseSnapshot, WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';
+import type { WorkflowLibraryListItem } from '@features/workflow/queries';
import type { ChangeEvent } from 'react';
-import { Box, Dialog, HStack, Input, Portal, SegmentGroup, Spinner, Stack, Text } from '@chakra-ui/react';
+import { Dialog, HStack, Input, Portal, SegmentGroup, Spinner, Stack, Text } from '@chakra-ui/react';
import {
ensureWorkflowLibraryBrowseLoaded,
getWorkflowLibraryBrowseSnapshot,
@@ -14,8 +15,10 @@ import { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLoadLibraryWorkflow } from './useLoadLibraryWorkflow';
+import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';
import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';
import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';
+import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';
/**
* Backend workflow library browser. Filtering and paging are server side and
@@ -25,7 +28,6 @@ import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';
*/
const SEARCH_DEBOUNCE_MS = 300;
-const DETAIL_RAIL_WIDTH = '18rem';
const CATEGORY_ITEMS = [
{ labelKey: 'workflowLibrary.browse', value: 'default' },
@@ -74,17 +76,22 @@ export const WorkflowLibraryDialog = ({
const { category, entries, error, status, tag, tagCounts } = useWorkflowLibraryBrowseSelector(selectBrowseView);
const [searchInput, setSearchInput] = useState('');
const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(null);
+ // Task 8 mounts the real preview dialog from this; until then it is only the
+ // record of which workflow the rail asked to preview.
+ const [previewEntry, setPreviewEntry] = useState<WorkflowLibraryEntry | 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';
+ const missingCounts = useWorkflowLibraryMissingCounts(entries);
// 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 activeEntry = entries.find((entry) => entry.item.workflow_id === activeWorkflowId) ?? null;
const handleDialogOpenChange = useCallback(
(event: { open: boolean }) => {
@@ -132,6 +139,12 @@ export const WorkflowLibraryDialog = ({
[load]
);
+ const handleOpenItem = useCallback((item: WorkflowLibraryListItem) => void load(item), [load]);
+
+ // The deleted row is gone from the next refresh; dropping the selection lets
+ // the head of the list take over, the same way a filter change does.
+ const handleDeleted = useCallback(() => setSelectedWorkflowId(null), []);
+
return (
<Dialog.Root open={isOpen} placement="center" size="xl" onOpenChange={handleDialogOpenChange}>
<Portal>
@@ -188,23 +201,23 @@ export const WorkflowLibraryDialog = ({
<WorkflowLibraryTagChips selectedTag={tag} tagCounts={tagCounts} onSelect={handleTagSelect} />
</Stack>
</Dialog.Header>
- <Dialog.Body display="flex" flex="1" gap="3" minH="0">
+ <Dialog.Body data-pending-preview={previewEntry?.item.workflow_id} display="flex" flex="1" gap="3" minH="0">
<WorkflowLibraryGrid
entries={entries}
error={error}
+ missingCounts={missingCounts}
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}
+ <WorkflowLibraryDetailPanel
+ entry={activeEntry}
+ onClose={closeDialog}
+ onDeleted={handleDeleted}
+ onDuplicated={setSelectedWorkflowId}
+ onOpen={handleOpenItem}
+ onPreview={setPreviewEntry}
/>
</Dialog.Body>
{isOpen ? <WorkflowLibraryBrowseSession /> : null}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx
new file mode 100644
index 0000000000..86856ee6ee
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx
@@ -0,0 +1,184 @@
+import type { ModelConfig, StarterModel } from '@features/models';
+import type {
+ ModelRequirementStatus,
+ ResolvedModelRequirement,
+ WorkflowModelRequirement,
+} from '@features/workflow/core/modelRequirements';
+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';
+import type { ElementType } from 'react';
+
+import { DataList, Icon, Skeleton, Spinner, Stack, Text } from '@chakra-ui/react';
+import {
+ ensureModelsLoaded,
+ ensureStartersLoaded,
+ useActiveInstallSources,
+ useModelsSelector,
+ useStartersSelector,
+} from '@features/models';
+import { resolveWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { CheckIcon, DownloadIcon, TriangleAlertIcon } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * "Requires": one row per model a workflow needs, resolved against what is
+ * installed, what the starter catalog can fetch, and what is already
+ * downloading. The rows stay neutral — only the *installable* state earns the
+ * amber download treatment, because it is the only one the user can act on.
+ */
+
+const SKELETON_ROW_COUNT = 2;
+const EMPTY_STARTERS: readonly StarterModel[] = [];
+const EMPTY_COUNTS: ReadonlyMap<string, number> = new Map();
+
+const selectInstalledModels = (snapshot: { models: ModelConfig[] }): readonly ModelConfig[] => snapshot.models;
+const selectStarterModels = (snapshot: {
+ response: { starter_models: StarterModel[] } | null;
+}): readonly StarterModel[] => snapshot.response?.starter_models ?? EMPTY_STARTERS;
+
+interface StatusPresentation {
+ color: string;
+ icon: ElementType | null;
+ labelKey: string;
+}
+
+const STATUS_PRESENTATION: Record<ModelRequirementStatus, StatusPresentation> = {
+ // Amber, per the mock, is the "you can fix this" signal and nothing else.
+ installable: { color: 'fg.warning', icon: DownloadIcon, labelKey: 'workflowLibrary.requirementInstallable' },
+ installed: { color: 'fg.muted', icon: CheckIcon, labelKey: 'workflowLibrary.requirementInstalled' },
+ installing: { color: 'fg.muted', icon: null, labelKey: 'workflowLibrary.requirementInstalling' },
+ unresolvable: { color: 'fg.muted', icon: TriangleAlertIcon, labelKey: 'workflowLibrary.requirementMissing' },
+};
+
+/** The extractor's own dedupe identity, reused so rows keep stable React keys. */
+const getRequirementKey = (requirement: WorkflowModelRequirement): string =>
+ requirement.kind === 'exact'
+ ? `exact:${requirement.identifier.key}:${requirement.identifier.hash ?? ''}`
+ : `slot:${requirement.base ?? ''}:${requirement.modelType ?? ''}`;
+
+export interface ModelRequirementDeps {
+ installedModels: readonly ModelConfig[];
+ starterModels: readonly StarterModel[];
+ activeInstallSources: ReadonlySet<string>;
+}
+
+/**
+ * The three inputs every requirement resolution needs, plus the one-time load
+ * of the two catalogs behind them. Both the detail panel and the grid's
+ * missing-model badges read them through here, so they always resolve against
+ * the same data.
+ */
+export const useModelRequirementDeps = (): ModelRequirementDeps => {
+ const installedModels = useModelsSelector(selectInstalledModels);
+ const starterModels = useStartersSelector(selectStarterModels);
+ const activeInstallSources = useActiveInstallSources();
+
+ useMountEffect(() => {
+ void ensureModelsLoaded();
+ ensureStartersLoaded();
+ });
+
+ return useMemo(
+ () => ({ activeInstallSources, installedModels, starterModels }),
+ [activeInstallSources, installedModels, starterModels]
+ );
+};
+
+/**
+ * How many models each card would have to *download* to run — the count the
+ * grid badges and, on the selected card, exactly what the panel's Install
+ * button offers to fetch. Requirements nothing in the catalog can satisfy are
+ * deliberately excluded: an "Install 3 models" badge that installs 2 is worse
+ * than a quiet card.
+ */
+export const useWorkflowLibraryMissingCounts = (
+ entries: readonly WorkflowLibraryEntry[]
+): ReadonlyMap<string, number> => {
+ const deps = useModelRequirementDeps();
+
+ return useMemo(() => {
+ const counts = new Map<string, number>();
+
+ for (const entry of entries) {
+ if (entry.enrichment.status !== 'ready') {
+ continue;
+ }
+
+ const installable = resolveWorkflowModelRequirements(entry.enrichment.requirements.requirements, deps).filter(
+ (resolved) => resolved.status === 'installable'
+ ).length;
+
+ if (installable > 0) {
+ counts.set(entry.item.workflow_id, installable);
+ }
+ }
+
+ return counts.size > 0 ? counts : EMPTY_COUNTS;
+ }, [deps, entries]);
+};
+
+const RequirementRow = ({ resolved }: { resolved: ResolvedModelRequirement }) => {
+ const { t } = useTranslation();
+ const presentation = STATUS_PRESENTATION[resolved.status];
+ const statusLabel = t(presentation.labelKey);
+
+ return (
+ <DataList.Item alignItems="center" data-requirement-status={resolved.status} gap="1.5">
+ <DataList.ItemLabel flex="0 0 auto" minW="0">
+ {presentation.icon ? (
+ <Icon aria-label={statusLabel} as={presentation.icon} boxSize="3" color={presentation.color} />
+ ) : (
+ <Spinner aria-label={statusLabel} borderWidth="1.5px" color={presentation.color} size="xs" />
+ )}
+ </DataList.ItemLabel>
+ <DataList.ItemValue color={presentation.color} fontSize="2xs" minW="0">
+ <Text truncate title={resolved.requirement.label}>
+ {resolved.requirement.label}
+ </Text>
+ </DataList.ItemValue>
+ </DataList.Item>
+ );
+};
+
+export interface WorkflowRequirementsListProps {
+ /** Quiet line shown instead of rows when the workflow itself could not be read. */
+ errorMessage: string | null;
+ /** `null` while the workflow is still being parsed in the background. */
+ resolved: readonly ResolvedModelRequirement[] | null;
+}
+
+export const WorkflowRequirementsList = ({ errorMessage, resolved }: WorkflowRequirementsListProps) => {
+ const { t } = useTranslation();
+
+ // A readable workflow that needs no models says so by omission, not by an
+ // empty section header.
+ if (!errorMessage && resolved?.length === 0) {
+ return null;
+ }
+
+ return (
+ <Stack gap="1" minW="0">
+ <Text color="fg.muted" fontSize="2xs" fontWeight="600">
+ {t('workflowLibrary.requires')}
+ </Text>
+ {errorMessage ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ {errorMessage}
+ </Text>
+ ) : null}
+ {!errorMessage && resolved === null
+ ? Array.from({ length: SKELETON_ROW_COUNT }, (_unused, index) => (
+ <Skeleton key={index} data-requirement-placeholder h="3" rounded="sm" variant="pulse" w="24" />
+ ))
+ : null}
+ {!errorMessage && resolved !== null && resolved.length > 0 ? (
+ <DataList.Root gap="1.5" orientation="horizontal" size="sm">
+ {resolved.map((requirement) => (
+ <RequirementRow key={getRequirementKey(requirement.requirement)} resolved={requirement} />
+ ))}
+ </DataList.Root>
+ ) : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.test.ts
new file mode 100644
index 0000000000..c2d1c00e2f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatRelativeTime } from './relativeTime';
+
+const SECOND = 1000;
+const MINUTE = 60 * SECOND;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+const WEEK = 7 * DAY;
+
+const NOW = new Date('2026-08-18T12:00:00.000Z');
+
+const ago = (elapsed: number): string => new Date(NOW.getTime() - elapsed).toISOString();
+const ahead = (remaining: number): string => new Date(NOW.getTime() + remaining).toISOString();
+
+describe('formatRelativeTime', () => {
+ it('reports sub-minute distances in seconds', () => {
+ expect(formatRelativeTime(ago(0), NOW)).toBe('now');
+ expect(formatRelativeTime(ago(45 * SECOND), NOW)).toBe('45 seconds ago');
+ });
+
+ it('climbs to minutes up to the hour boundary', () => {
+ expect(formatRelativeTime(ago(5 * MINUTE), NOW)).toBe('5 minutes ago');
+ expect(formatRelativeTime(ago(59 * MINUTE), NOW)).toBe('59 minutes ago');
+ });
+
+ it('climbs to hours up to the day boundary', () => {
+ expect(formatRelativeTime(ago(3 * HOUR), NOW)).toBe('3 hours ago');
+ expect(formatRelativeTime(ago(23 * HOUR), NOW)).toBe('23 hours ago');
+ });
+
+ it('climbs to days up to the week boundary', () => {
+ // The caption the mock shows verbatim.
+ expect(formatRelativeTime(ago(2 * DAY), NOW)).toBe('2 days ago');
+ expect(formatRelativeTime(ago(6 * DAY), NOW)).toBe('6 days ago');
+ });
+
+ it('climbs to weeks, months, and years', () => {
+ expect(formatRelativeTime(ago(3 * WEEK), NOW)).toBe('3 weeks ago');
+ expect(formatRelativeTime(ago(150 * DAY), NOW)).toBe('5 months ago');
+ expect(formatRelativeTime(ago(800 * DAY), NOW)).toBe('2 years ago');
+ });
+
+ it('uses the natural phrasing for the single-unit steps', () => {
+ expect(formatRelativeTime(ago(DAY), NOW)).toBe('yesterday');
+ expect(formatRelativeTime(ago(8 * DAY), NOW)).toBe('last week');
+ });
+
+ it('handles clock skew from the server without reading as the past', () => {
+ expect(formatRelativeTime(ahead(2 * HOUR), NOW)).toBe('in 2 hours');
+ });
+
+ it('returns an empty string for values it cannot read, so callers can drop the caption', () => {
+ expect(formatRelativeTime('not-a-timestamp', NOW)).toBe('');
+ expect(formatRelativeTime('', NOW)).toBe('');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.ts
new file mode 100644
index 0000000000..539e920dce
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/relativeTime.ts
@@ -0,0 +1,40 @@
+/**
+ * "2 days ago" captions for the library's `last_run_at` stamps. The clock is
+ * injected rather than read here, so the caption a test asserts is the caption
+ * the panel renders — `Date.now()` lives at the call site only.
+ */
+
+const DIVISIONS: readonly { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [
+ { amount: 60, unit: 'second' },
+ { amount: 60, unit: 'minute' },
+ { amount: 24, unit: 'hour' },
+ { amount: 7, unit: 'day' },
+ { amount: 4.345, unit: 'week' },
+ { amount: 12, unit: 'month' },
+ { amount: Number.POSITIVE_INFINITY, unit: 'year' },
+];
+
+// `numeric: 'auto'` so the single-unit steps read as "yesterday"/"last week"
+// instead of "1 day ago" — matching the Launchpad's project timestamps.
+const formatter = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
+
+/** Empty string for timestamps that cannot be read, so callers drop the caption entirely. */
+export const formatRelativeTime = (timestamp: string, now: Date): string => {
+ const date = new Date(timestamp);
+
+ if (Number.isNaN(date.getTime())) {
+ return '';
+ }
+
+ let duration = (date.getTime() - now.getTime()) / 1000;
+
+ for (const division of DIVISIONS) {
+ if (Math.abs(duration) < division.amount) {
+ return formatter.format(Math.round(duration), division.unit);
+ }
+
+ duration /= division.amount;
+ }
+
+ return '';
+};