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): customizable workflow library thumbnails

Josh Corbettea25a4a4d50a
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index b3b6c066f1..5d8c751839 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1208,6 +1208,7 @@
"source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx",
"source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx",
"source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",
+ "source:src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx",
"source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx",
"source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx",
"source:src/features/workflow/ui/library/libraryPreviewSource.ts",
@@ -2268,6 +2269,7 @@
"source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx",
"source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx",
"source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",
+ "source:src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx",
"source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx",
"source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx",
"source:src/features/workflow/ui/library/libraryPreviewSource.ts",
@@ -3538,6 +3540,7 @@
"source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx",
"source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx",
"source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",
+ "source:src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx",
"source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx",
"source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx",
"source:src/features/workflow/ui/library/libraryPreviewSource.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 314f907502..b32399a47f 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4311,6 +4311,17 @@
"templateName": "Template name",
"thisProject": "This project",
"thisProjectHint": "Workflows saved with this project. Edits autosave here; the library changes only when you save to it.",
+ "thumbnail": "Thumbnail",
+ "thumbnailChooseTitle": "Choose a thumbnail from the gallery",
+ "thumbnailFromGallery": "From gallery",
+ "thumbnailNotAnImage": "The chosen file is not an image.",
+ "thumbnailRemove": "Remove thumbnail",
+ "thumbnailRemoveFailed": "Failed to remove thumbnail",
+ "thumbnailRemoved": "Thumbnail removed",
+ "thumbnailUpdateFailed": "Failed to update thumbnail",
+ "thumbnailUpdated": "Thumbnail updated",
+ "thumbnailUpdating": "Updating thumbnail…",
+ "thumbnailUpload": "Upload",
"title": "Workflows",
"unavailableBundledBody": "\"{{name}}\" came from a bundled template, which cannot be changed. Save it as a new template instead.",
"unavailableForbiddenBody": "The library template behind \"{{name}}\" belongs to someone else. Save it as a new template instead.",
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
index 590d04848e..b01242007f 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
@@ -764,3 +764,46 @@ test('the image map serves videos only on request and keeps its two endpoints co
assert.equal(crossed.status, 404);
});
});
+
+test('workflow thumbnails round-trip their bytes and refresh the listed URL on every replacement', async () => {
+ await withRepresentativeBackend(async (backend) => {
+ const path = '/api/v1/workflows/i/fixture-workflow-002/thumbnail';
+ const upload = (bytes, type) => {
+ const body = new FormData();
+
+ body.append('image', new Blob([bytes], { type }), 'thumbnail.png');
+ return fetch(`${backend.origin}${path}`, { body, method: 'PUT' });
+ };
+ const listedUrl = async () =>
+ (await getJson(backend, '/api/v1/workflows/?categories=user&per_page=100')).items.find(
+ (item) => item.workflow_id === 'fixture-workflow-002'
+ ).thumbnail_url;
+
+ assert.equal(await listedUrl(), null);
+ assert.equal((await fetch(`${backend.origin}${path}`)).status, 404);
+
+ assert.equal((await upload(new Uint8Array([1, 2, 3]), 'image/png')).status, 200);
+ const first = await listedUrl();
+ const served = await fetch(`${backend.origin}${first}`);
+ assert.equal(served.headers.get('content-type'), 'image/png');
+ assert.deepEqual(new Uint8Array(await served.arrayBuffer()), new Uint8Array([1, 2, 3]));
+
+ assert.equal((await upload(new Uint8Array([4]), 'image/webp')).status, 200);
+ const second = await listedUrl();
+ assert.notEqual(second, first);
+ assert.equal((await getJson(backend, '/api/v1/workflows/i/fixture-workflow-002')).thumbnail_url, second);
+
+ assert.equal((await upload(new Uint8Array([5]), 'text/plain')).status, 415);
+ const misnamed = new FormData();
+ misnamed.append('file', new Blob([new Uint8Array([6])], { type: 'image/png' }), 'image');
+ assert.equal((await fetch(`${backend.origin}${path}`, { body: misnamed, method: 'PUT' })).status, 415);
+ assert.equal(
+ (await fetch(`${backend.origin}/api/v1/workflows/i/default_fixture-workflow-001/thumbnail`, { method: 'DELETE' }))
+ .status,
+ 403
+ );
+
+ await getJson(backend, path, { method: 'DELETE' });
+ assert.equal(await listedUrl(), null);
+ });
+});
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 7e7845513b..c6e0cb1726 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -133,6 +133,9 @@ const createState = (profile) => {
videos: new Map(fixture.videos.map((video) => [video.video_name, clone(video)])),
workflows: new Map(fixture.workflows.map((workflow) => [workflow.workflow_id, clone(workflow)])),
nextWorkflowNumber: fixture.workflows.length + 1,
+ /** Custom workflow thumbnails by workflow id; the version stands in for the server's cache-busting query. */
+ workflowThumbnails: new Map(),
+ nextWorkflowThumbnailVersion: 1,
/** Every workflow-library request since the last reset, so journeys can prove which writes happened. */
workflowRequests: [],
};
@@ -207,6 +210,51 @@ const readBody = (request) =>
request.on('error', reject);
});
+const readRawBody = (request) =>
+ new Promise((resolve, reject) => {
+ const chunks = [];
+
+ request.on('data', (chunk) => chunks.push(chunk));
+ request.on('end', () => resolve(Buffer.concat(chunks)));
+ request.on('error', reject);
+ });
+
+/** The bytes and declared type of one named part of a multipart/form-data body, or null. */
+const readMultipartFile = async (request, fieldName) => {
+ const boundary = /boundary=(?:"([^"]+)"|([^;]+))/.exec(request.headers['content-type'] ?? '');
+
+ if (!boundary) {
+ return null;
+ }
+
+ const body = await readRawBody(request);
+ const delimiter = Buffer.from(`--${boundary[1] ?? boundary[2]}`);
+ let start = body.indexOf(delimiter);
+
+ while (start !== -1) {
+ const next = body.indexOf(delimiter, start + delimiter.length);
+ const headerEnd = body.indexOf('\r\n\r\n', start);
+
+ if (next === -1 || headerEnd === -1 || headerEnd > next) {
+ return null;
+ }
+
+ const headers = body.subarray(start + delimiter.length, headerEnd).toString('utf8');
+
+ if (new RegExp(`;\\s*name="${fieldName.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`).test(headers)) {
+ return {
+ contentType: /content-type:\s*([^\r\n]+)/i.exec(headers)?.[1]?.trim() ?? '',
+ // The part's data ends at the CRLF that precedes the next delimiter.
+ data: body.subarray(headerEnd + 4, next - 2),
+ };
+ }
+
+ start = next;
+ }
+
+ return null;
+};
+
const readJsonBody = async (request, fallback = {}) => {
const body = await readBody(request);
@@ -1924,7 +1972,16 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, { requests: state.workflowRequests });
}
- const workflowRecord = (workflow) => ({ ...workflow, thumbnail_url: workflow.thumbnail_url ?? null });
+ const workflowRecord = (workflow) => {
+ const thumbnail = state.workflowThumbnails.get(workflow.workflow_id);
+
+ return {
+ ...workflow,
+ thumbnail_url: thumbnail
+ ? `/api/v1/workflows/i/${encodeURIComponent(workflow.workflow_id)}/thumbnail?v=${String(thumbnail.version)}`
+ : (workflow.thumbnail_url ?? null),
+ };
+ };
const workflowListItem = ({ workflow: _workflow, ...item }) => workflowRecord(item);
const workflowTags = (workflow) =>
String(workflow.tags ?? '')
@@ -1960,7 +2017,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, counts);
}
- const workflowMatch = /^\/api\/v1\/workflows\/i\/([^/]+)(\/opened_at)?$/.exec(path);
+ const workflowMatch = /^\/api\/v1\/workflows\/i\/([^/]+)(\/opened_at|\/thumbnail)?$/.exec(path);
if (workflowMatch) {
const workflowId = decodeURIComponent(workflowMatch[1]);
const suffix = workflowMatch[2] ?? '';
@@ -1975,6 +2032,45 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, null);
}
+ if (suffix === '/thumbnail') {
+ const thumbnail = state.workflowThumbnails.get(workflowId);
+
+ if (method === 'GET') {
+ return thumbnail
+ ? writeBinary(response, 200, thumbnail.data, { 'content-type': thumbnail.contentType })
+ : json(404, { detail: 'Workflow thumbnail not found' });
+ }
+ if (workflow.category === 'default') {
+ return json(403, { detail: 'Bundled workflows cannot be modified' });
+ }
+ if (method === 'PUT') {
+ const file = await readMultipartFile(request, 'image');
+
+ if (!file?.contentType.startsWith('image') || file.data.length === 0) {
+ return json(415, { detail: 'Not an image' });
+ }
+
+ state.workflowThumbnails.set(workflowId, {
+ contentType: file.contentType,
+ data: file.data,
+ version: state.nextWorkflowThumbnailVersion++,
+ });
+ return json(200, null);
+ }
+ if (method === 'DELETE') {
+ // Fixture workflows can carry a seeded thumbnail URL without stored bytes; removing clears either.
+ const removedUpload = state.workflowThumbnails.delete(workflowId);
+ const removedFixture = Boolean(workflow.thumbnail_url);
+
+ workflow.thumbnail_url = null;
+ return removedUpload || removedFixture
+ ? json(200, null)
+ : json(404, { detail: 'Workflow thumbnail not found' });
+ }
+
+ return json(405, { detail: `No mock for ${method} ${path}` });
+ }
+
if (method === 'GET') {
return json(200, workflowRecord(workflow));
}
@@ -1984,6 +2080,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(403, { detail: 'Bundled workflows cannot be deleted' });
}
state.workflows.delete(workflowId);
+ state.workflowThumbnails.delete(workflowId);
return json(200, null);
}
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.ts
index bbfc841b2f..3da988bb07 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.ts
@@ -232,6 +232,25 @@ export const deleteLibraryWorkflow = async (workflowId: string, signal?: AbortSi
await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, { method: 'DELETE', signal });
};
+/**
+ * The server stores a 256px copy and serves it from a fixed path; every list/get response appends a fresh query to
+ * `thumbnail_url`, so invalidating the library cache is what makes a replaced image load.
+ */
+export const setLibraryWorkflowThumbnail = async (
+ workflowId: string,
+ image: Blob,
+ signal?: AbortSignal
+): Promise<void> => {
+ const body = new FormData();
+
+ body.append('image', image);
+ await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/thumbnail`, { body, method: 'PUT', signal });
+};
+
+export const deleteLibraryWorkflowThumbnail = async (workflowId: string, signal?: AbortSignal): Promise<void> => {
+ await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/thumbnail`, { method: 'DELETE', signal });
+};
+
export const touchLibraryWorkflowOpenedAt = async (workflowId: string, signal?: AbortSignal): Promise<void> => {
await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/opened_at`, { method: 'PUT', signal });
};
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
index 74338db949..870b4e32be 100644
--- 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
@@ -8,7 +8,7 @@ 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 { act, StrictMode, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -60,6 +60,7 @@ const queries = vi.hoisted(() => ({
Promise.resolve('wf-copy')
),
deleteLibraryWorkflow: vi.fn((_workflowId: string, _signal?: AbortSignal) => Promise.resolve()),
+ deleteLibraryWorkflowThumbnail: vi.fn((_workflowId: string, _signal?: AbortSignal) => Promise.resolve()),
getLibraryWorkflowCached: vi.fn((_workflowId: string, _signal?: AbortSignal) =>
Promise.resolve({} as Record<string, unknown>)
),
@@ -70,6 +71,7 @@ const queries = vi.hoisted(() => ({
Promise.resolve({} as Record<string, unknown>)
),
invalidateWorkflowLibraryCache: vi.fn(),
+ setLibraryWorkflowThumbnail: vi.fn((_workflowId: string, _image: Blob, _signal?: AbortSignal) => Promise.resolve()),
updateLibraryWorkflow: vi.fn(
(_workflowId: string, _workflow: Record<string, unknown>, _options?: { expectedRevision?: number }) =>
Promise.resolve({} as Record<string, unknown>)
@@ -81,6 +83,21 @@ vi.mock('@features/workflow/queries', async (importOriginal) => ({
...queries,
}));
+/** The picker's own view is covered by its tests; here a pick hands over an item whose thumbnail is a data URL. */
+const pickedGalleryItem = vi.hoisted(() => ({
+ current: { kind: 'image', name: 'picked.gif', thumbnailUrl: '' } as Record<string, unknown>,
+}));
+
+vi.mock('@features/gallery/picker', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ GalleryPickerPopover: ({ children, onPick }: { children: ReactNode; onPick: (item: unknown) => void }) => (
+ <>
+ {children}
+ <button aria-label="Pick" data-gallery-pick type="button" onClick={() => onPick(pickedGalleryItem.current)} />
+ </>
+ ),
+}));
+
const downloadText = vi.hoisted(() => vi.fn((_contents: string, _fileName: string, _mimeType: string) => {}));
vi.mock('@platform/browser/downloadBlob', () => ({ downloadText }));
@@ -106,6 +123,16 @@ const TRANSLATIONS: Record<string, string> = {
'workflowLibrary.renameWithEllipsis': 'Rename…',
'workflowLibrary.renamed': 'Template renamed',
'workflowLibrary.templateName': 'Template name',
+ 'workflowLibrary.thumbnail': 'Thumbnail',
+ 'workflowLibrary.thumbnailFromGallery': 'From gallery',
+ 'workflowLibrary.thumbnailNotAnImage': 'The chosen file is not an image.',
+ 'workflowLibrary.thumbnailRemove': 'Remove thumbnail',
+ 'workflowLibrary.thumbnailRemoveFailed': 'Failed to remove thumbnail',
+ 'workflowLibrary.thumbnailRemoved': 'Thumbnail removed',
+ 'workflowLibrary.thumbnailUpdateFailed': 'Failed to update thumbnail',
+ 'workflowLibrary.thumbnailUpdated': 'Thumbnail updated',
+ 'workflowLibrary.thumbnailUpdating': 'Updating thumbnail…',
+ 'workflowLibrary.thumbnailUpload': 'Upload',
'workflowLibrary.duplicateHint': 'Saves a copy under Yours, original untouched',
'workflowLibrary.duplicateName': '{{name}} copy',
'workflowLibrary.duplicated': 'Saved a copy under Yours',
@@ -418,6 +445,8 @@ describe('WorkflowLibraryDetailPanel', () => {
queries.getLibraryWorkflowRecordCached.mockClear();
queries.getLibraryWorkflowRecordCached.mockResolvedValue(RAW_RECORD);
queries.invalidateWorkflowLibraryCache.mockClear();
+ queries.setLibraryWorkflowThumbnail.mockReset().mockResolvedValue(undefined);
+ queries.deleteLibraryWorkflowThumbnail.mockReset().mockResolvedValue(undefined);
downloadText.mockClear();
OPEN_DOCUMENT_IN_NEW_PROJECT.mockClear();
@@ -582,14 +611,21 @@ describe('WorkflowLibraryDetailPanel', () => {
expect(buttonWithText('Open')).not.toBeUndefined();
});
- it('captions the thumbnail with the last run, the sample output, or nothing', async () => {
+ it('captions the thumbnail with the last run, a bundled sample output, or nothing', async () => {
await renderPanel(TEXT_TO_IMAGE);
expect(panel()?.textContent).toContain('Your last run · 2 days ago');
+ // A user template's image is one the user set, not a sample of what the workflow makes.
await renderPanel(IMAGE_TO_VIDEO);
- expect(panel()?.textContent).toContain('Sample output');
+ expect(panel()?.textContent).not.toContain('Sample output');
expect(panel()?.textContent).not.toContain('Your last run');
+ await renderPanel({
+ ...DEFAULT_CATEGORY,
+ item: { ...DEFAULT_CATEGORY.item, thumbnail_url: IMAGE_TO_VIDEO.item.thumbnail_url },
+ });
+ expect(panel()?.textContent).toContain('Sample output');
+
await renderPanel(DEFAULT_CATEGORY);
expect(panel()?.textContent).not.toContain('Sample output');
expect(panel()?.textContent).toContain('Not run yet');
@@ -904,6 +940,180 @@ describe('WorkflowLibraryDetailPanel', () => {
expect(OPEN_ADD_MODELS).toHaveBeenCalledWith('wan');
});
+ describe('thumbnail', () => {
+ const thumbnailGroup = () => document.querySelector<HTMLElement>('[role="group"][aria-label="Thumbnail"]');
+ const thumbnailButton = (text: string) =>
+ [...(thumbnailGroup()?.querySelectorAll('button') ?? [])].find(
+ (candidate) => (candidate.getAttribute('aria-label') ?? candidate.textContent ?? '').trim() === text
+ );
+
+ const chooseFile = async (file: File) => {
+ const input = thumbnailGroup()?.querySelector<HTMLInputElement>('input[type="file"]');
+ expect(input).not.toBeNull();
+
+ const transfer = new DataTransfer();
+ transfer.items.add(file);
+
+ await act(async () => {
+ input!.files = transfer.files;
+ input!.dispatchEvent(new Event('change', { bubbles: true }));
+ await settleFrame();
+ });
+ };
+
+ it("is editable only on the account's own templates, and offers Remove only once one is set", async () => {
+ await renderPanel(DEFAULT_CATEGORY);
+ expect(thumbnailGroup()).toBeNull();
+
+ await renderPanel(entry({ name: 'Plain', workflow_id: 'wf-plain' }, readyEnrichment(SDXL_REQUIREMENTS)));
+ expect(thumbnailButton('From gallery')).not.toBeUndefined();
+ expect(thumbnailButton('Upload')).not.toBeUndefined();
+ expect(thumbnailButton('Remove thumbnail')).toBeUndefined();
+
+ await renderPanel(TEXT_TO_IMAGE);
+ expect(thumbnailButton('Remove thumbnail')).not.toBeUndefined();
+ });
+
+ it('uploads a chosen file, holding the controls busy until the library answers', async () => {
+ let answer: () => void = NOOP;
+ queries.setLibraryWorkflowThumbnail.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ answer = resolve;
+ })
+ );
+ const file = new File([new Uint8Array([1, 2, 3])], 'cover.png', { type: 'image/png' });
+
+ await renderPanel(TEXT_TO_IMAGE);
+ const status = panel()?.querySelector('[role="status"]');
+ expect(status?.textContent).toBe('');
+ thumbnailButton('Upload')?.focus();
+ await chooseFile(file);
+
+ expect(queries.setLibraryWorkflowThumbnail).toHaveBeenCalledWith('wf-text-to-image', file, expect.anything());
+ // The same live region carries the change, and the busy control keeps focus.
+ expect(panel()?.querySelector('[role="status"]')).toBe(status);
+ expect(status?.textContent).toBe('Updating thumbnail…');
+ expect(document.activeElement).toBe(thumbnailButton('Upload'));
+ expect(thumbnailButton('Upload')?.getAttribute('aria-disabled')).toBe('true');
+ expect(thumbnailButton('Remove thumbnail')?.getAttribute('aria-disabled')).toBe('true');
+ await act(async () => {
+ thumbnailButton('Remove thumbnail')?.click();
+ await settleFrame();
+ });
+ expect(queries.deleteLibraryWorkflowThumbnail).not.toHaveBeenCalled();
+ expect(panel()?.querySelector('[aria-busy="true"]')).not.toBeNull();
+ expect(queries.invalidateWorkflowLibraryCache).not.toHaveBeenCalled();
+
+ await act(async () => {
+ answer();
+ await settleFrame();
+ });
+
+ expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledWith('wf-text-to-image');
+ expect(thumbnailButton('Upload')?.hasAttribute('aria-disabled')).toBe(false);
+ expect(panel()?.querySelector('[aria-busy="true"]')).toBeNull();
+ expect(status?.textContent).toBe('Thumbnail updated');
+ expect(document.activeElement).toBe(thumbnailButton('Upload'));
+ });
+
+ it('does not carry a busy upload over to the next selected workflow', async () => {
+ queries.setLibraryWorkflowThumbnail.mockImplementation(() => new Promise<void>(NOOP));
+
+ await renderPanel(TEXT_TO_IMAGE);
+ await chooseFile(new File([new Uint8Array([1])], 'cover.png', { type: 'image/png' }));
+ expect(panel()?.querySelector('[aria-busy="true"]')).not.toBeNull();
+
+ await renderPanel(IMAGE_TO_VIDEO);
+ expect(panel()?.querySelector('[aria-busy="true"]')).toBeNull();
+ expect(thumbnailButton('Upload')?.hasAttribute('aria-disabled')).toBe(false);
+ expect(panel()?.querySelector('[role="status"]')?.textContent).toBe('');
+ });
+
+ it('reports a refused upload without refreshing the library', async () => {
+ queries.setLibraryWorkflowThumbnail.mockRejectedValue(new Error('Not an image'));
+
+ await renderPanel(TEXT_TO_IMAGE);
+ await chooseFile(new File([new Uint8Array([1])], 'cover.png', { type: 'image/png' }));
+
+ expect(NOTIFICATIONS.error).toHaveBeenCalledWith('Failed to update thumbnail', 'Not an image');
+ expect(queries.invalidateWorkflowLibraryCache).not.toHaveBeenCalled();
+ expect(panel()?.querySelector('[role="status"]')?.textContent).toBe('');
+ });
+ it('refuses a file that is not an image before sending anything', async () => {
+ await renderPanel(TEXT_TO_IMAGE);
+ await chooseFile(new File(['{}'], 'workflow.json', { type: 'application/json' }));
+
+ expect(queries.setLibraryWorkflowThumbnail).not.toHaveBeenCalled();
+ expect(NOTIFICATIONS.error).toHaveBeenCalledWith(
+ 'Failed to update thumbnail',
+ 'The chosen file is not an image.'
+ );
+ });
+
+ it('uploads the picked gallery image', async () => {
+ pickedGalleryItem.current = {
+ kind: 'image',
+ name: 'picked.gif',
+ thumbnailUrl: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
+ };
+
+ await renderPanel(TEXT_TO_IMAGE);
+ await act(async () => {
+ document.querySelector<HTMLElement>('[data-gallery-pick]')?.click();
+ await vi.waitFor(() => expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalled());
+ });
+
+ const [workflowId, image] = queries.setLibraryWorkflowThumbnail.mock.calls[0]!;
+ expect(workflowId).toBe('wf-text-to-image');
+ expect(image.type).toBe('image/gif');
+ expect(image.size).toBeGreaterThan(0);
+ });
+
+ it('does not upload a gallery image that failed to load', async () => {
+ pickedGalleryItem.current = { kind: 'image', name: 'gone.png', thumbnailUrl: '/gone-thumbnail.webp' };
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValueOnce(new Response(null, { status: 404, statusText: 'Not Found' }));
+
+ await renderPanel(TEXT_TO_IMAGE);
+ await act(async () => {
+ document.querySelector<HTMLElement>('[data-gallery-pick]')?.click();
+ await vi.waitFor(() => expect(NOTIFICATIONS.error).toHaveBeenCalled());
+ });
+
+ expect(NOTIFICATIONS.error).toHaveBeenCalledWith('Failed to update thumbnail', expect.stringContaining('404'));
+ expect(fetchSpy).toHaveBeenCalledWith('/gone-thumbnail.webp', expect.anything());
+ expect(queries.setLibraryWorkflowThumbnail).not.toHaveBeenCalled();
+ fetchSpy.mockRestore();
+ });
+
+ it('removes the custom image, and reports a failure without refreshing the library', async () => {
+ await renderPanel(TEXT_TO_IMAGE);
+ thumbnailButton('Remove thumbnail')?.focus();
+ await act(async () => {
+ thumbnailButton('Remove thumbnail')?.click();
+ await settleFrame();
+ });
+
+ expect(queries.deleteLibraryWorkflowThumbnail).toHaveBeenCalledWith('wf-text-to-image', expect.anything());
+ expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledWith('wf-text-to-image');
+ // Remove disappears with the refreshed record, so focus has already moved on.
+ expect(document.activeElement).toBe(thumbnailButton('Upload'));
+ expect(panel()?.querySelector('[role="status"]')?.textContent).toBe('Thumbnail removed');
+
+ queries.invalidateWorkflowLibraryCache.mockClear();
+ queries.deleteLibraryWorkflowThumbnail.mockRejectedValue(new Error('network down'));
+ await act(async () => {
+ thumbnailButton('Remove thumbnail')?.click();
+ await settleFrame();
+ });
+
+ expect(NOTIFICATIONS.error).toHaveBeenCalledWith('Failed to remove thumbnail', expect.any(String));
+ expect(queries.invalidateWorkflowLibraryCache).not.toHaveBeenCalled();
+ });
+ });
+
it('renders nothing actionable without a selection', async () => {
await renderPanel(null);
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
index 70df297482..5c0463c777 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx
@@ -3,7 +3,7 @@ import type { ProjectWorkflowEntry } from '@features/workflow/core/types';
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 { Badge, Box, HStack, Menu, Portal, Stack, Text } from '@chakra-ui/react';
import { getStarterModelInstallSources, useInstallActions } from '@features/models';
import {
createLibraryWorkflow,
@@ -44,7 +44,6 @@ import {
DownloadIcon,
EllipsisIcon,
GitForkIcon,
- ImageOffIcon,
PencilIcon,
Trash2Icon,
WorkflowIcon,
@@ -54,7 +53,6 @@ import { useTranslation } from 'react-i18next';
import type { OpenLibraryWorkflowMode } from './useOpenLibraryWorkflow';
-import { formatRelativeTime } from './relativeTime';
import { planLibraryWorkflowOpen } from './useOpenLibraryWorkflow';
import {
getWorkflowLibraryCardId,
@@ -62,6 +60,7 @@ import {
keepCardMenuOpenForRetarget,
type WorkflowCardMenuAnchor,
} from './WorkflowLibraryCard';
+import { WorkflowLibraryThumbnail } from './WorkflowLibraryThumbnail';
import {
resolveEntryRequirements,
useModelRequirementDeps,
@@ -71,7 +70,6 @@ import {
/** Install missing models before offering Open; keep the detail rail mounted across selections to prevent flashing. */
const DETAIL_RAIL_WIDTH = '18rem';
-const THUMBNAIL_ASPECT_RATIO = 3 / 2;
const INSTALL_HOVER = { opacity: 0.85 } as const;
export interface WorkflowLibraryDetailPanelProps {
@@ -137,9 +135,6 @@ export const WorkflowLibraryDetailPanel = ({
const { openDocumentInNewProject } = useWorkflowGraphPreview();
const openAddModels = useOpenAddModels();
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);
// Guard duplicate creation until the copy exists, including copies landing outside the visible category.
const [isDuplicatePending, setIsDuplicatePending] = useState(false);
@@ -191,8 +186,6 @@ export const WorkflowLibraryDetailPanel = ({
}
}, [entry, onPreview]);
- const handleThumbnailError = useCallback(() => setFailedThumbnailUrl(entry?.item.thumbnail_url ?? null), [entry]);
-
// Close the library before navigating to Add Models.
const handleFindModel = useCallback(
(query: string) => {
@@ -440,14 +433,6 @@ export const WorkflowLibraryDetailPanel = ({
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;
-
const hasCopies = openPlan !== null && openPlan.kind !== 'add';
const openLabel = hasCopies ? t('workflowLibrary.openProjectCopy') : t('workflowLibrary.open');
@@ -528,32 +513,7 @@ export const WorkflowLibraryDetailPanel = ({
>
<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>
+ <WorkflowLibraryThumbnail key={item.workflow_id} item={item} />
{/*
* Wrap full names, including delimiter-free strings, in the detail rail; zero content min-width permits
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx
new file mode 100644
index 0000000000..6a7f6d637f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx
@@ -0,0 +1,258 @@
+import type { GalleryItem } from '@features/gallery';
+import type { WorkflowLibraryListItem } from '@features/workflow/queries';
+
+import { Box, Flex, HStack, Icon, Image, Spinner, Stack, Text } from '@chakra-ui/react';
+import { GalleryPickerPopover, getGalleryUploadAccept } from '@features/gallery/picker';
+import {
+ deleteLibraryWorkflowThumbnail,
+ invalidateWorkflowLibraryCache,
+ setLibraryWorkflowThumbnail,
+} from '@features/workflow/queries';
+import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';
+import {
+ type AccountScope,
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
+import { getApiErrorMessage } from '@platform/transport/http';
+import { Button, IconButton, Tooltip } from '@platform/ui';
+import { ChevronDownIcon, ImageOffIcon, ImagePlusIcon, Trash2Icon, UploadIcon } from 'lucide-react';
+import { useCallback, useRef, useState, type ChangeEvent, type MouseEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatRelativeTime } from './relativeTime';
+
+const THUMBNAIL_ASPECT_RATIO = 3 / 2;
+const IMAGE_ONLY = ['image'] as const;
+const UPLOAD_ACCEPT = getGalleryUploadAccept(IMAGE_ONLY);
+/** Busy controls stay focusable (`aria-disabled`), so focus the picker or file dialog returns to survives the action. */
+const preventClick = (event: MouseEvent) => event.preventDefault();
+
+/** Key by workflow id: an action in flight for one workflow must not show as busy on the next selection. */
+export const WorkflowLibraryThumbnail = ({ item }: { item: WorkflowLibraryListItem }) => {
+ const { t } = useTranslation();
+ const notify = useWorkflowNotifications();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ // Keyed by URL: a replaced image arrives under a fresh URL and re-arms the thumbnail.
+ const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);
+ // Local rather than `useScopedAction`: the library ships in the editor boot graph, and a second importer of that
+ // models-only hook splits it into its own startup chunk.
+ const [isBusy, setIsBusy] = useState(false);
+ const isBusyRef = useRef(false);
+ // One always-mounted live region: a region inserted together with its text is often not announced.
+ const [announcement, setAnnouncement] = useState('');
+ const uploadButtonRef = useRef<HTMLButtonElement | null>(null);
+ const run = useCallback(
+ async (
+ action: (owner: AccountScope) => Promise<void>,
+ successAnnouncement: string,
+ onError: (error: unknown) => void
+ ) => {
+ if (isBusyRef.current) {
+ return;
+ }
+
+ const owner = captureAccountScope();
+
+ isBusyRef.current = true;
+ setIsBusy(true);
+ setAnnouncement(t('workflowLibrary.thumbnailUpdating'));
+
+ try {
+ await action(owner);
+ setAnnouncement(successAnnouncement);
+ } catch (error) {
+ if (isAccountScopeCurrent(owner)) {
+ setAnnouncement('');
+ onError(error);
+ }
+ } finally {
+ isBusyRef.current = false;
+ if (isAccountScopeCurrent(owner)) {
+ setIsBusy(false);
+ }
+ }
+ },
+ [t]
+ );
+ // Bundled defaults are not the account's to change; the same rule gates rename and delete.
+ const isEditable = item.category === 'user';
+ const workflowId = item.workflow_id;
+
+ const handleThumbnailError = useCallback(() => setFailedThumbnailUrl(item.thumbnail_url ?? null), [item]);
+
+ const upload = useCallback(
+ (getImage: (signal: AbortSignal) => Promise<Blob>) =>
+ run(
+ async (owner) => {
+ const image = await getImage(owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ await setLibraryWorkflowThumbnail(workflowId, image, owner.signal);
+ assertAccountScopeCurrent(owner);
+ invalidateWorkflowLibraryCache(workflowId);
+ },
+ t('workflowLibrary.thumbnailUpdated'),
+ (error) =>
+ notify.error(t('workflowLibrary.thumbnailUpdateFailed'), getApiErrorMessage(error, t('common.unknownError')))
+ ),
+ [notify, run, t, workflowId]
+ );
+
+ // The server keeps a 256px copy, so the gallery's own thumbnail carries everything it will store.
+ const handlePick = useCallback(
+ (picked: GalleryItem) =>
+ void upload(async (signal) => {
+ const response = await fetch(picked.thumbnailUrl, { signal });
+
+ if (!response.ok) {
+ throw new Error(`${response.status} ${response.statusText}`);
+ }
+
+ return response.blob();
+ }),
+ [upload]
+ );
+
+ const openFilePicker = useCallback(() => inputRef.current?.click(), []);
+ const handleFileChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+
+ event.currentTarget.value = '';
+
+ if (!file) {
+ return;
+ }
+
+ // `accept` is advisory; the server takes only parts typed as images.
+ if (!file.type.startsWith('image/')) {
+ notify.error(t('workflowLibrary.thumbnailUpdateFailed'), t('workflowLibrary.thumbnailNotAnImage'));
+ return;
+ }
+
+ void upload(() => Promise.resolve(file));
+ },
+ [notify, t, upload]
+ );
+
+ const handleRemove = useCallback(
+ () =>
+ void run(
+ async (owner) => {
+ await deleteLibraryWorkflowThumbnail(workflowId, owner.signal);
+ assertAccountScopeCurrent(owner);
+ // Remove unmounts once the refreshed record arrives; hand focus on before it takes focus down with it.
+ if (document.activeElement?.closest('[data-thumbnail-remove]')) {
+ uploadButtonRef.current?.focus();
+ }
+ invalidateWorkflowLibraryCache(workflowId);
+ },
+ t('workflowLibrary.thumbnailRemoved'),
+ (error) =>
+ notify.error(t('workflowLibrary.thumbnailRemoveFailed'), getApiErrorMessage(error, t('common.unknownError')))
+ ),
+ [notify, run, t, workflowId]
+ );
+
+ const showThumbnail = Boolean(item.thumbnail_url) && item.thumbnail_url !== failedThumbnailUrl;
+ const lastRun = item.last_run_at ? formatRelativeTime(item.last_run_at, new Date()) : '';
+ // A user template's thumbnail is always one someone set; only bundled defaults ship a sample output.
+ const caption = lastRun
+ ? t('workflowLibrary.lastRun', { when: lastRun })
+ : showThumbnail && item.category === 'default'
+ ? t('workflowLibrary.sampleOutput')
+ : null;
+
+ return (
+ <Stack gap="1" minW="0">
+ <Box
+ aria-busy={isBusy || undefined}
+ aspectRatio={THUMBNAIL_ASPECT_RATIO}
+ bg="bg.muted"
+ overflow="hidden"
+ position="relative"
+ 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>
+ )}
+ {isBusy ? (
+ <Flex align="center" bg="bg.muted/90" inset="0" justify="center" position="absolute">
+ <Spinner size="sm" />
+ </Flex>
+ ) : null}
+ </Box>
+ <Text role="status" srOnly>
+ {announcement}
+ </Text>
+ {caption ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ {caption}
+ </Text>
+ ) : null}
+ {isEditable ? (
+ <HStack aria-label={t('workflowLibrary.thumbnail')} flexWrap="wrap" gap="0.5" role="group">
+ <GalleryPickerPopover
+ accept={IMAGE_ONLY}
+ label={t('workflowLibrary.thumbnailChooseTitle')}
+ onPick={handlePick}
+ >
+ <Button
+ aria-disabled={isBusy || undefined}
+ size="xs"
+ variant="ghost"
+ onClickCapture={isBusy ? preventClick : undefined}
+ >
+ <Icon as={ImagePlusIcon} boxSize="3.5" />
+ {t('workflowLibrary.thumbnailFromGallery')}
+ <Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />
+ </Button>
+ </GalleryPickerPopover>
+ <Button
+ ref={uploadButtonRef}
+ aria-disabled={isBusy || undefined}
+ size="xs"
+ variant="ghost"
+ onClick={isBusy ? undefined : openFilePicker}
+ >
+ <Icon as={UploadIcon} boxSize="3" />
+ {t('workflowLibrary.thumbnailUpload')}
+ </Button>
+ {item.thumbnail_url ? (
+ <Tooltip content={t('workflowLibrary.thumbnailRemove')}>
+ <IconButton
+ aria-disabled={isBusy || undefined}
+ aria-label={t('workflowLibrary.thumbnailRemove')}
+ data-thumbnail-remove
+ ms="auto"
+ size="xs"
+ variant="ghost"
+ onClick={isBusy ? undefined : handleRemove}
+ >
+ <Trash2Icon />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ <input ref={inputRef} accept={UPLOAD_ACCEPT} hidden type="file" onChange={handleFileChange} />
+ </HStack>
+ ) : null}
+ </Stack>
+ );
+};