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(gallery): load an image's embedded workflow

Josh Corbett78cc4fc7fc51
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index cae82e1744..3289e56b30 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3644,6 +3644,12 @@
"imageSort": "Image Sort",
"infinite": "Infinite",
"itemActions": {
+ "loadWorkflow": {
+ "editorUnavailable": "The Workflow editor is not available in this layout.",
+ "failed": "Could not load the image's workflow",
+ "loadedLabel": "Loaded “{{name}}” from image",
+ "missing": "This image has no workflow embedded."
+ },
"delete": {
"failure_one": "Could not delete {{count}} item.",
"failure_other": "Could not delete {{count}} items.",
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index f1c8407e86..028997cdcb 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -1450,6 +1450,15 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return state.images.has(imageName) ? writePng(response) : json(404, { detail: 'Image not found' });
}
+ const imageWorkflowMatch = /^\/api\/v1\/images\/i\/([^/]+)\/workflow$/.exec(path);
+ if (method === 'GET' && imageWorkflowMatch) {
+ const image = state.images.get(decodeURIComponent(imageWorkflowMatch[1]));
+
+ return image
+ ? json(200, { graph: image.graph ?? null, workflow: image.workflow ?? null })
+ : json(404, { detail: 'Image not found' });
+ }
+
const imageMetadataMatch = /^\/api\/v1\/images\/i\/([^/]+)\/metadata$/.exec(path);
if (method === 'GET' && imageMetadataMatch) {
return json(200, {});
diff --git a/invokeai/frontend/webv2/src/features/gallery/core/types.ts b/invokeai/frontend/webv2/src/features/gallery/core/types.ts
index 35490875de..e94145323f 100644
--- a/invokeai/frontend/webv2/src/features/gallery/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/core/types.ts
@@ -55,6 +55,8 @@ export interface GalleryImage extends GeneratedImageContract {
boardId: string;
imageCategory: 'general' | 'control' | 'mask' | 'user' | 'other';
starred: boolean;
+ /** Whether the image embeds the workflow that made it. Image records say; the mixed-media items listing does not, so grid images leave it unset. */
+ hasWorkflow?: boolean;
}
export type GalleryImageMetadata = Record<string, unknown>;
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
index e7ded80991..959bacd2c5 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts
@@ -24,6 +24,7 @@ import {
getGalleryImageByName,
getGalleryImagesByNames,
getGalleryVideoMetadata,
+ getGalleryImageWorkflow,
getGalleryVideoWorkflow,
imageMakeCanvasAssetChanges,
imageMakeDurableChanges,
@@ -168,6 +169,7 @@ describe('getGalleryImageByName', () => {
mocks.apiFetchJson.mockResolvedValue({
board_id: 'board-1',
created_at: '2026-07-09T12:00:00.000Z',
+ has_workflow: true,
height: 360,
image_category: 'general',
image_name: 'folder/workflow result.png',
@@ -181,6 +183,7 @@ describe('getGalleryImageByName', () => {
await expect(getGalleryImageByName('folder/workflow result.png', controller.signal)).resolves.toEqual({
boardId: 'board-1',
createdAt: '2026-07-09T12:00:00.000Z',
+ hasWorkflow: true,
height: 360,
imageCategory: 'general',
imageName: 'folder/workflow result.png',
@@ -196,6 +199,18 @@ describe('getGalleryImageByName', () => {
});
});
+ it('reads the embedded workflow of an image, encoded like the record lookup', async () => {
+ mocks.apiFetchJson.mockResolvedValue({ graph: null, workflow: '{"nodes":[]}' });
+
+ await expect(getGalleryImageWorkflow('folder/workflow result.png')).resolves.toEqual({
+ graph: null,
+ workflow: '{"nodes":[]}',
+ });
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/images/i/folder%2Fworkflow%20result.png/workflow', {
+ signal: undefined,
+ });
+ });
+
it('propagates backend lookup errors', async () => {
const error = new Error('404 image not found');
mocks.apiFetchJson.mockRejectedValue(error);
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index fe1104f3d8..80e0b09715 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -88,6 +88,7 @@ interface BackendImageDTO {
is_intermediate: boolean;
starred?: boolean;
board_id?: string | null;
+ has_workflow?: boolean;
}
export interface BackendGalleryItemDTO {
@@ -236,6 +237,7 @@ const getGalleryVideoTotal = async ({
const mapImage = (image: BackendImageDTO): GalleryImage => ({
boardId: image.board_id ?? 'none',
createdAt: image.created_at,
+ hasWorkflow: image.has_workflow,
height: image.height,
imageCategory: image.image_category,
imageName: image.image_name,
@@ -498,13 +500,17 @@ export const getGalleryVideoMetadata = async (
return body && typeof body === 'object' && !Array.isArray(body) ? (body as Record<string, unknown>) : null;
};
-export interface GalleryVideoWorkflow {
+/** The workflow and graph a piece of media embeds, each as stringified JSON, when it has them. */
+export interface GalleryMediaWorkflow {
graph: string | null;
workflow: string | null;
}
-export const getGalleryVideoWorkflow = (videoName: string, signal?: AbortSignal): Promise<GalleryVideoWorkflow> =>
- apiFetchJson<GalleryVideoWorkflow>(`/api/v1/videos/i/${encodeURIComponent(videoName)}/workflow`, { signal });
+export const getGalleryVideoWorkflow = (videoName: string, signal?: AbortSignal): Promise<GalleryMediaWorkflow> =>
+ apiFetchJson<GalleryMediaWorkflow>(`/api/v1/videos/i/${encodeURIComponent(videoName)}/workflow`, { signal });
+
+export const getGalleryImageWorkflow = (imageName: string, signal?: AbortSignal): Promise<GalleryMediaWorkflow> =>
+ apiFetchJson<GalleryMediaWorkflow>(`/api/v1/images/i/${encodeURIComponent(imageName)}/workflow`, { signal });
interface PaletteDateBoardImageNames {
imageNames: string[];
diff --git a/invokeai/frontend/webv2/src/features/gallery/index.ts b/invokeai/frontend/webv2/src/features/gallery/index.ts
index 5fc40a1e4e..70ed032177 100644
--- a/invokeai/frontend/webv2/src/features/gallery/index.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/index.ts
@@ -46,6 +46,7 @@ import {
getGalleryImageByName,
getGalleryImageMetadata,
getGalleryImagesByNames,
+ getGalleryImageWorkflow,
getGalleryItemByRef,
getGalleryVideoMetadata,
getGalleryVideoWorkflow,
@@ -71,6 +72,7 @@ export const galleryImages = {
metadata: getGalleryImageMetadata,
resolve: getGalleryImageByName,
resolveMany: getGalleryImagesByNames,
+ workflow: getGalleryImageWorkflow,
} as const;
/** Resolve either media kind while keeping the legacy image port strictly image-only. */
diff --git a/invokeai/frontend/webv2/src/features/workflow/react.ts b/invokeai/frontend/webv2/src/features/workflow/react.ts
index 07a80e046b..c768921064 100644
--- a/invokeai/frontend/webv2/src/features/workflow/react.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/react.ts
@@ -1,4 +1,8 @@
export * from './data/templates';
-export { clearPendingLibraryWorkflowLoad, requestLibraryWorkflowLoad } from './ui/workflowUiStore';
+export {
+ clearPendingWorkflowLoad,
+ requestLibraryWorkflowLoad,
+ requestWorkflowDocumentLoad,
+} from './ui/workflowUiStore';
export { WorkflowGraphPreviewProvider, WorkflowUiProvider } from './ui/WorkflowUiContext';
export type { WorkflowGraphPreviewPort, WorkflowReadPort, WorkflowUiAdapter } from './ui/WorkflowUiContext';
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
index 3927750081..32eecd376d 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx
@@ -16,41 +16,59 @@ import { markLibraryGraphSynced } from './library/librarySyncBridge';
import { startWorkflowUiPendingLoadRuntime } from './pendingLibraryWorkflowLoadRuntime';
/**
- * Consumes `pendingLibraryWorkflowId` requests from shell surfaces (the
- * command palette) that cannot reach the graph context themselves: fetches
- * the library record, parses it, and replaces the project graph — the same
- * load path as WorkflowLibraryDialog, minus the dialog.
+ * Consumes pending workflow-load requests from surfaces that cannot reach the
+ * graph context themselves: the command palette names a library record, an
+ * image's context menu hands over the workflow it embeds. Either way the
+ * document is parsed and replaces the project graph — the same load path as
+ * WorkflowLibraryDialog, minus the dialog.
*/
-export const PendingLibraryWorkflowLoader = () => {
+export const PendingWorkflowLoader = () => {
const { t } = useTranslation();
const { replace } = useProjectGraphCommands();
const notify = useWorkflowNotifications();
useMountEffect(() => {
const owner = captureAccountScope();
- return startWorkflowUiPendingLoadRuntime(async (workflowId) => {
+ return startWorkflowUiPendingLoadRuntime(async (source) => {
try {
assertAccountScopeCurrent(owner);
- const raw = await getLibraryWorkflow(workflowId, owner.signal);
+
+ let raw: unknown = null;
+ let label = '';
+
+ if (source.kind === 'library') {
+ const record = await getLibraryWorkflow(source.workflowId, owner.signal);
+ const name = typeof record.name === 'string' && record.name.length > 0 ? record.name : 'workflow';
+
+ raw = record;
+ label = t('commandPalette.workflowLoad.loaded', { name });
+ } else {
+ raw = source.raw;
+ label = source.label;
+ }
assertAccountScopeCurrent(owner);
- const { document, warnings } = parseWorkflowJson(raw);
- const name = typeof raw.name === 'string' && raw.name.length > 0 ? raw.name : 'workflow';
+ const { document: parsed, warnings } = parseWorkflowJson(raw);
+ // An embedded document may still carry the id of the library record it was
+ // saved from; loading it must not start autosaving over that record.
+ const document = source.kind === 'library' ? parsed : { ...parsed, libraryWorkflowId: undefined };
- replace(document, t('commandPalette.workflowLoad.loaded', { name }));
+ replace(document, label);
requestWorkflowFitView(document.nodes);
- // Same reasoning as the library dialog's load path: the graph just
- // loaded is already in sync with the library record it came from, so
- // mark it synced before the autosaver's graph-changed effect sees it.
- markLibraryGraphSynced(serializeWorkflowJson(document));
+
+ if (source.kind === 'library') {
+ // Same reasoning as the library dialog's load path: the graph just
+ // loaded is already in sync with the library record it came from, so
+ // mark it synced before the autosaver's graph-changed effect sees it.
+ markLibraryGraphSynced(serializeWorkflowJson(document));
+ void touchLibraryWorkflowOpenedAt(source.workflowId, owner.signal).catch(() => {
+ // Recency bookkeeping only; loading already succeeded.
+ });
+ }
for (const warning of warnings) {
notify.info(t('commandPalette.workflowLoad.warning'), warning);
}
-
- void touchLibraryWorkflowOpenedAt(workflowId, owner.signal).catch(() => {
- // Recency bookkeeping only; loading already succeeded.
- });
} catch (error) {
if (!isAccountScopeCurrent(owner)) {
return;
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx
index d28eaf600f..65d3264932 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx
@@ -28,7 +28,7 @@ const deferred = <T,>() => {
// them out so this stays a focused wiring-layer test.
vi.mock('./editor/AddNodeDialog', () => ({ AddNodeDialog: () => null }));
vi.mock('./library/WorkflowLibraryDialog', () => ({ WorkflowLibraryDialog: () => null }));
-vi.mock('./PendingLibraryWorkflowLoader', () => ({ PendingLibraryWorkflowLoader: () => null }));
+vi.mock('./PendingLibraryWorkflowLoader', () => ({ PendingWorkflowLoader: () => null }));
import { onWorkflowLibraryCacheInvalidated } from '@features/workflow/queries';
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
index db929947cf..624db27dc9 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
@@ -40,7 +40,7 @@ import { registerLibraryGraphSyncedHandler, releaseLibraryGraphSyncedHandler } f
import { useSaveWorkflowToLibrary } from './library/useSaveWorkflowToLibrary';
import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';
import { setWorkflowLibrarySyncStatus, workflowLibrarySyncStore } from './library/workflowLibrarySyncStore';
-import { PendingLibraryWorkflowLoader } from './PendingLibraryWorkflowLoader';
+import { PendingWorkflowLoader } from './PendingLibraryWorkflowLoader';
import { copyWorkflowJson, downloadWorkflowJson } from './workflowTransfer';
import {
useWorkflowHostCommands,
@@ -532,7 +532,7 @@ export const WorkflowDialogHost = () => {
onOpenChange={setAddNodeOpen}
/>
<WorkflowLibraryDialog isOpen={isLibraryOpen} onOpenChange={setWorkflowLibraryOpen} />
- <PendingLibraryWorkflowLoader />
+ <PendingWorkflowLoader />
<ConfirmDialog
body="Replace the project graph with an empty workflow? You can undo this change during this session. Save the current workflow to the library first if you need a permanent copy."
confirmLabel="New workflow"
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.test.ts
index f1629434dc..1560afb239 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
-import type { LibraryWorkflowLoadRequest } from './workflowUiStore';
+import type { WorkflowLoadRequest, WorkflowLoadSource } from './workflowUiStore';
-import { startPendingLibraryWorkflowLoadRuntime } from './pendingLibraryWorkflowLoadRuntime';
+import { startPendingWorkflowLoadRuntime } from './pendingLibraryWorkflowLoadRuntime';
const deferred = () => {
let resolve!: () => void;
@@ -13,43 +13,45 @@ const deferred = () => {
return { promise, resolve };
};
-describe('pending library workflow load runtime', () => {
+describe('pending workflow load runtime', () => {
it('serializes loads, keeps only the latest queued request, and compare-clears completions', async () => {
const listeners = new Set<() => void>();
const loads = new Map<string, ReturnType<typeof deferred>>();
- const load = vi.fn((workflowId: string) => {
+ const load = vi.fn((source: WorkflowLoadSource) => {
const pending = deferred();
- loads.set(workflowId, pending);
+ loads.set(source.kind === 'library' ? source.workflowId : source.label, pending);
return pending.promise;
});
- let request: LibraryWorkflowLoadRequest | null = null;
+ const loadedIds = () =>
+ load.mock.calls.map(([source]) => (source.kind === 'library' ? source.workflowId : source.label));
+ let request: WorkflowLoadRequest | null = null;
const clearRequest = vi.fn((requestId: number) => {
if (request?.requestId === requestId) {
request = null;
}
});
- const emit = (next: LibraryWorkflowLoadRequest) => {
+ const emit = (next: WorkflowLoadRequest) => {
request = next;
listeners.forEach((listener) => listener());
};
- const stop = startPendingLibraryWorkflowLoadRuntime({
+ const stop = startPendingWorkflowLoadRuntime({
clearRequest,
getRequest: () => request,
load,
- subscribe: (listener) => {
+ subscribe: (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
});
- emit({ requestId: 1, workflowId: 'first' });
- emit({ requestId: 2, workflowId: 'superseded' });
- emit({ requestId: 3, workflowId: 'latest' });
- expect(load.mock.calls.map(([workflowId]) => workflowId)).toEqual(['first']);
+ emit({ requestId: 1, source: { kind: 'library', workflowId: 'first' } });
+ emit({ requestId: 2, source: { kind: 'library', workflowId: 'superseded' } });
+ emit({ requestId: 3, source: { kind: 'document', label: 'latest', raw: {} } });
+ expect(loadedIds()).toEqual(['first']);
loads.get('first')?.resolve();
- await vi.waitFor(() => expect(load.mock.calls.map(([workflowId]) => workflowId)).toEqual(['first', 'latest']));
- expect(request).toEqual({ requestId: 3, workflowId: 'latest' });
+ await vi.waitFor(() => expect(loadedIds()).toEqual(['first', 'latest']));
+ expect(request).toEqual({ requestId: 3, source: { kind: 'document', label: 'latest', raw: {} } });
loads.get('latest')?.resolve();
await vi.waitFor(() => expect(request).toBeNull());
@@ -60,9 +62,9 @@ describe('pending library workflow load runtime', () => {
it('does not clear shared state when an in-flight load settles after the runtime stops', async () => {
const pending = deferred();
const clearRequest = vi.fn();
- const stop = startPendingLibraryWorkflowLoadRuntime({
+ const stop = startPendingWorkflowLoadRuntime({
clearRequest,
- getRequest: () => ({ requestId: 1, workflowId: 'user-a-workflow' }),
+ getRequest: () => ({ requestId: 1, source: { kind: 'library', workflowId: 'user-a-workflow' } }),
load: () => pending.promise,
subscribe: () => () => undefined,
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts b/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts
index b05ab7a548..433fe7af78 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts
@@ -1,11 +1,11 @@
-import type { LibraryWorkflowLoadRequest } from './workflowUiStore';
+import type { WorkflowLoadRequest, WorkflowLoadSource } from './workflowUiStore';
-import { clearPendingLibraryWorkflowLoad, workflowUiStore } from './workflowUiStore';
+import { clearPendingWorkflowLoad, workflowUiStore } from './workflowUiStore';
-export interface PendingLibraryWorkflowLoadRuntimeDeps {
+export interface PendingWorkflowLoadRuntimeDeps {
clearRequest: (requestId: number) => void;
- getRequest: () => LibraryWorkflowLoadRequest | null;
- load: (workflowId: string) => Promise<void>;
+ getRequest: () => WorkflowLoadRequest | null;
+ load: (source: WorkflowLoadSource) => Promise<void>;
subscribe: (listener: () => void) => () => void;
}
@@ -14,7 +14,7 @@ export interface PendingLibraryWorkflowLoadRuntimeDeps {
* is in flight, and compare-and-clear prevents an old completion from
* consuming that newer request.
*/
-export const startPendingLibraryWorkflowLoadRuntime = (deps: PendingLibraryWorkflowLoadRuntimeDeps): (() => void) => {
+export const startPendingWorkflowLoadRuntime = (deps: PendingWorkflowLoadRuntimeDeps): (() => void) => {
let isRunning = true;
let inFlight = false;
@@ -27,7 +27,7 @@ export const startPendingLibraryWorkflowLoadRuntime = (deps: PendingLibraryWorkf
inFlight = true;
void deps
- .load(request.workflowId)
+ .load(request.source)
.catch(() => undefined)
.finally(() => {
if (!isRunning) {
@@ -49,10 +49,10 @@ export const startPendingLibraryWorkflowLoadRuntime = (deps: PendingLibraryWorkf
};
};
-export const startWorkflowUiPendingLoadRuntime = (load: (workflowId: string) => Promise<void>): (() => void) =>
- startPendingLibraryWorkflowLoadRuntime({
- clearRequest: clearPendingLibraryWorkflowLoad,
- getRequest: () => workflowUiStore.getSnapshot().pendingLibraryWorkflowLoad,
+export const startWorkflowUiPendingLoadRuntime = (load: (source: WorkflowLoadSource) => Promise<void>): (() => void) =>
+ startPendingWorkflowLoadRuntime({
+ clearRequest: clearPendingWorkflowLoad,
+ getRequest: () => workflowUiStore.getSnapshot().pendingWorkflowLoad,
load,
subscribe: workflowUiStore.subscribe,
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.test.ts
index 5529919589..ed0b2b6b5c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.test.ts
@@ -1,23 +1,41 @@
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { describe, expect, it } from 'vitest';
-import { requestLibraryWorkflowLoad, workflowUiStore } from './workflowUiStore';
+import { requestLibraryWorkflowLoad, requestWorkflowDocumentLoad, workflowUiStore } from './workflowUiStore';
describe('workflow UI account ownership', () => {
it('clears pending UI state without reusing request identities across accounts', () => {
accountLifecycle.activate('user-a');
requestLibraryWorkflowLoad('workflow-a');
- const firstRequestId = workflowUiStore.getSnapshot().pendingLibraryWorkflowLoad?.requestId;
+ const firstRequestId = workflowUiStore.getSnapshot().pendingWorkflowLoad?.requestId;
accountLifecycle.invalidate();
accountLifecycle.activate('user-b');
- expect(workflowUiStore.getSnapshot().pendingLibraryWorkflowLoad).toBeNull();
+ expect(workflowUiStore.getSnapshot().pendingWorkflowLoad).toBeNull();
requestLibraryWorkflowLoad('workflow-b');
- const secondRequestId = workflowUiStore.getSnapshot().pendingLibraryWorkflowLoad?.requestId;
+ const secondRequestId = workflowUiStore.getSnapshot().pendingWorkflowLoad?.requestId;
expect(firstRequestId).toEqual(expect.any(Number));
expect(secondRequestId).toEqual(expect.any(Number));
expect(secondRequestId).toBeGreaterThan(firstRequestId ?? 0);
});
});
+
+describe('workflow load requests', () => {
+ it('carries a library id or an already-fetched document as the source', () => {
+ accountLifecycle.activate('user-c');
+ requestLibraryWorkflowLoad('workflow-a');
+ expect(workflowUiStore.getSnapshot().pendingWorkflowLoad?.source).toEqual({
+ kind: 'library',
+ workflowId: 'workflow-a',
+ });
+
+ requestWorkflowDocumentLoad({ nodes: [] }, 'Load workflow from image.png');
+ expect(workflowUiStore.getSnapshot().pendingWorkflowLoad?.source).toEqual({
+ kind: 'document',
+ label: 'Load workflow from image.png',
+ raw: { nodes: [] },
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts
index e57a5cfd11..0c94fa1b97 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts
@@ -34,16 +34,21 @@ export interface WorkflowUiSnapshot {
isNewWorkflowConfirmOpen: boolean;
/** Bumped to ask the dialog host to open the JSON file picker. */
importRequestCount: number;
- /** Library workflow a shell surface (command palette) asked to load; consumed by the widget chrome. */
- pendingLibraryWorkflowLoad: LibraryWorkflowLoadRequest | null;
+ /** A workflow a shell surface (command palette, an image's context menu) asked to load; consumed by the widget chrome. */
+ pendingWorkflowLoad: WorkflowLoadRequest | null;
}
-export interface LibraryWorkflowLoadRequest {
+export type WorkflowLoadSource =
+ | { kind: 'library'; workflowId: string }
+ /** An already-fetched workflow document (an image's embedded workflow); `label` names the undo step. */
+ | { kind: 'document'; label: string; raw: unknown };
+
+export interface WorkflowLoadRequest {
requestId: number;
- workflowId: string;
+ source: WorkflowLoadSource;
}
-let nextLibraryWorkflowLoadRequestId = 0;
+let nextWorkflowLoadRequestId = 0;
const INITIAL_WORKFLOW_UI_SNAPSHOT: WorkflowUiSnapshot = {
addNodeConnection: null,
@@ -53,7 +58,7 @@ const INITIAL_WORKFLOW_UI_SNAPSHOT: WorkflowUiSnapshot = {
isAddNodeOpen: false,
isLibraryOpen: false,
isNewWorkflowConfirmOpen: false,
- pendingLibraryWorkflowLoad: null,
+ pendingWorkflowLoad: null,
};
export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>(INITIAL_WORKFLOW_UI_SNAPSHOT);
@@ -85,16 +90,20 @@ export const setNewWorkflowConfirmOpen = (isOpen: boolean): void => {
workflowUiStore.patchSnapshot({ isNewWorkflowConfirmOpen: isOpen });
};
-export const requestLibraryWorkflowLoad = (workflowId: string): void => {
- nextLibraryWorkflowLoadRequestId += 1;
- workflowUiStore.patchSnapshot({
- pendingLibraryWorkflowLoad: { requestId: nextLibraryWorkflowLoadRequestId, workflowId },
- });
+const requestWorkflowLoad = (source: WorkflowLoadSource): void => {
+ nextWorkflowLoadRequestId += 1;
+ workflowUiStore.patchSnapshot({ pendingWorkflowLoad: { requestId: nextWorkflowLoadRequestId, source } });
};
-export const clearPendingLibraryWorkflowLoad = (requestId: number): void => {
- if (workflowUiStore.getSnapshot().pendingLibraryWorkflowLoad?.requestId === requestId) {
- workflowUiStore.patchSnapshot({ pendingLibraryWorkflowLoad: null });
+export const requestLibraryWorkflowLoad = (workflowId: string): void =>
+ requestWorkflowLoad({ kind: 'library', workflowId });
+
+export const requestWorkflowDocumentLoad = (raw: unknown, label: string): void =>
+ requestWorkflowLoad({ kind: 'document', label, raw });
+
+export const clearPendingWorkflowLoad = (requestId: number): void => {
+ if (workflowUiStore.getSnapshot().pendingWorkflowLoad?.requestId === requestId) {
+ workflowUiStore.patchSnapshot({ pendingWorkflowLoad: null });
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index ee7e9236fa..1e537bdeef 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -98,6 +98,7 @@ const implemented = new Set([
'gallery.toggleStarredOnly',
'viewer.nextComparisonMode',
'viewer.deleteImage',
+ 'viewer.loadWorkflow',
'viewer.recallAll',
'viewer.recallPrompts',
'viewer.recallSeed',
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.test.ts
index e2f59143ad..84269d3fa7 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.test.ts
@@ -27,6 +27,7 @@ describe('first-party hotkey commands', () => {
it('registers handlers for implemented app and shared image recall commands', () => {
const sharedImageRecallCommands = new Set([
'gallery.remix',
+ 'viewer.loadWorkflow',
'viewer.recallAll',
'viewer.recallPrompts',
'viewer.recallSeed',
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
index 598635c29e..1bedb46d0f 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
@@ -76,8 +76,14 @@ export const FIRST_PARTY_APP_COMMAND_IDS = [
] as const;
export const FIRST_PARTY_IMAGE_RECALL_COMMAND_IDS = Object.keys(imageRecallCommands);
+/** Loads the selected image's embedded workflow; shares the recall commands' selected-image lookup. */
+const LOAD_WORKFLOW_COMMAND_ID = 'viewer.loadWorkflow';
-export const FIRST_PARTY_COMMAND_IDS = [...FIRST_PARTY_APP_COMMAND_IDS, ...Object.keys(imageRecallCommands)] as const;
+export const FIRST_PARTY_COMMAND_IDS = [
+ ...FIRST_PARTY_APP_COMMAND_IDS,
+ ...Object.keys(imageRecallCommands),
+ LOAD_WORKFLOW_COMMAND_ID,
+] as const;
const getAvailableModels = () => {
const snapshot = getModelsSnapshot();
@@ -106,6 +112,47 @@ export const useRegisterFirstPartyCommands = () => {
await submitActiveInvocation({ commands, destinationOverride, getModels: getAvailableModels, queries });
};
+ const notifyNoImageSelected = () =>
+ notifications.add({
+ kind: 'info',
+ message: 'Select an image in Gallery or Preview first.',
+ title: 'No image selected',
+ });
+
+ const loadSelectedImageWorkflow = async () => {
+ const owner = captureAccountScope();
+ const [{ executeLoadImageWorkflow }, { getSelectedGalleryImage }] = await Promise.all([
+ import('@workbench/image-actions/executeImageRecall'),
+ import('@workbench/image-actions/selectedImage'),
+ ]);
+
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ const activeProject = queries.getSnapshot().activeProject;
+ const image = getSelectedGalleryImage(activeProject);
+
+ if (!image) {
+ notifyNoImageSelected();
+ return;
+ }
+
+ await executeLoadImageWorkflow({
+ image,
+ isProjectActive: () => queries.isActiveProject(activeProject.id),
+ notifications,
+ openWorkflowEditor: () =>
+ openWidgetPlacement({
+ getWidgetsForRegion,
+ options: { preferredRegions: ['center'], requireCenterView: true },
+ typeId: 'workflow',
+ widgets,
+ }).ok,
+ t,
+ });
+ };
+
const recallSelectedImage = async (kind: ImageRecallKind) => {
const owner = captureAccountScope();
@@ -120,11 +167,7 @@ export const useRegisterFirstPartyCommands = () => {
const image = getSelectedGalleryImage(activeProject);
if (!image) {
- notifications.add({
- kind: 'info',
- message: 'Select an image in Gallery or Preview first.',
- title: 'No image selected',
- });
+ notifyNoImageSelected();
return;
}
@@ -378,6 +421,11 @@ export const useRegisterFirstPartyCommands = () => {
...Object.entries(imageRecallCommands).map(([id, kind]) =>
commandApi.register({ handler: () => recallSelectedImage(kind), id, title: id })
),
+ commandApi.register({
+ handler: () => loadSelectedImageWorkflow(),
+ id: LOAD_WORKFLOW_COMMAND_ID,
+ title: 'Load workflow from image',
+ }),
];
return () => {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
index 0dcd17da16..bd31dff956 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
@@ -49,6 +49,7 @@ const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions =
downloadImage: vi.fn(() => Promise.resolve()),
downloadImages: vi.fn(() => Promise.resolve()),
getImageRecallCapabilities: vi.fn(() => Promise.resolve(EMPTY_IMAGE_RECALL_CAPABILITIES)),
+ loadImageWorkflow: vi.fn(() => Promise.resolve()),
moveItemsToBoard: vi.fn(() => Promise.resolve()),
moveImagesToBoard: vi.fn(() => Promise.resolve()),
openItemInNewTab: vi.fn(),
@@ -216,6 +217,32 @@ describe('ImageContextMenu deletion delegation', () => {
});
});
+describe('ImageContextMenu load workflow', () => {
+ it('enables Load Workflow once the image is known to embed one and hands the image to the action', async () => {
+ const actions = createActions(vi.fn());
+ actions.getImageRecallCapabilities = vi.fn(() =>
+ Promise.resolve({ ...EMPTY_IMAGE_RECALL_CAPABILITIES, workflow: true })
+ );
+ await renderMenu(actions, [image('made-by-workflow.png')]);
+
+ await vi.waitFor(() => expect(getMenuItem('Load Workflow').getAttribute('aria-disabled')).not.toBe('true'));
+ await interact(() => getMenuItem('Load Workflow').click());
+
+ expect(actions.loadImageWorkflow).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ imageName: 'made-by-workflow.png' })
+ );
+ });
+
+ it('keeps Load Workflow disabled for an image without one', async () => {
+ const actions = createActions(vi.fn());
+ await renderMenu(actions, [image('plain.png')]);
+
+ await vi.waitFor(() => expect(actions.getImageRecallCapabilities).toHaveBeenCalled());
+ expect(getMenuItem('Load Workflow').getAttribute('aria-disabled')).toBe('true');
+ expect(actions.loadImageWorkflow).not.toHaveBeenCalled();
+ });
+});
+
describe('ImageContextMenu starred state', () => {
const starIconFill = (label: string): string =>
getComputedStyle(document.querySelector<HTMLElement>(`[aria-label="${label}"] svg`)!).fill;
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 4ccdfa736e..14253c2805 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -721,6 +721,7 @@ const SingleImageMenuItems = ({
const handleSelectForCompare = useSelectForCompareHandler(actions, image);
const handleSavePromptAsTemplate = useCallback(() => void actions.savePromptAsTemplate(image), [actions, image]);
const handleUseAsReferenceImage = useUseAsReferenceImageHandler(actions, image);
+ const handleLoadWorkflow = useCallback(() => void actions.loadImageWorkflow(image), [actions, image]);
const { generation, widgets } = useWorkbenchCommands();
const openWidget = useOpenWorkbenchWidget();
const handleSendToUpscale = useCallback(() => {
@@ -752,7 +753,13 @@ const SingleImageMenuItems = ({
<ToggleStarQuickMenuItem actions={actions} image={image} />
</HStack>
<Menu.Separator borderColor="border.subtle" />
- <ContextMenuItem disabled icon={WorkflowIcon} label="Load Workflow" value="load-workflow" />
+ <ContextMenuItem
+ disabled={isLoadingRecallCapabilities || !recallCapabilities.workflow}
+ icon={WorkflowIcon}
+ label="Load Workflow"
+ value="load-workflow"
+ onClick={handleLoadWorkflow}
+ />
<ContextSubMenu icon={AsteriskIcon} label="Recall Metadata">
<ContextMenuItem
disabled={isLoadingRecallCapabilities || !recallCapabilities.all}
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
index 3cd1b7b477..1bafd46cf4 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
@@ -18,6 +18,7 @@ import {
isVaeModelConfig,
normalizeGenerateWidgetValues,
} from '@features/generation/settings';
+import { requestWorkflowDocumentLoad } from '@features/workflow/react';
import {
assertAccountScopeCurrent,
captureAccountScope,
@@ -34,6 +35,68 @@ import {
type ImageRecallKind,
} from './imageRecall';
+/**
+ * Replaces the project graph with the workflow embedded in `image`. The editor's
+ * always-mounted chrome consumes the request, so `openWorkflowEditor` runs first to
+ * mount it in layouts that had it hidden; a `false` result means nowhere to load.
+ */
+export const executeLoadImageWorkflow = async ({
+ image,
+ isProjectActive,
+ notifications,
+ openWorkflowEditor,
+ t,
+}: {
+ image: GalleryImage;
+ /** Re-checked after the fetch: a store-resident request must not land on another project's editor. */
+ isProjectActive: () => boolean;
+ notifications: Pick<WorkbenchCommands['notifications'], 'add'>;
+ openWorkflowEditor: () => boolean;
+ t: TFunction;
+}): Promise<void> => {
+ const owner = captureAccountScope();
+
+ try {
+ const { workflow } = await galleryImages.workflow(image.imageName, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+
+ if (!workflow) {
+ notifications.add({ kind: 'info', title: t('widgets.gallery.itemActions.loadWorkflow.missing') });
+ return;
+ }
+
+ if (!isProjectActive()) {
+ return;
+ }
+
+ if (!openWorkflowEditor()) {
+ throw new Error(t('widgets.gallery.itemActions.loadWorkflow.editorUnavailable'));
+ }
+
+ const raw: unknown = JSON.parse(workflow);
+ const name =
+ typeof raw === 'object' && raw !== null && typeof (raw as { name?: unknown }).name === 'string'
+ ? (raw as { name: string }).name
+ : '';
+
+ requestWorkflowDocumentLoad(
+ raw,
+ t('widgets.gallery.itemActions.loadWorkflow.loadedLabel', { name: name || image.imageName })
+ );
+ } catch (error) {
+ if (!isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ notifications.add({
+ kind: 'error',
+ message: toErrorMessage(error),
+ title: t('widgets.gallery.itemActions.loadWorkflow.failed'),
+ });
+ }
+};
+
const imageMetadataRequests = new Map<string, { owner: AccountScope; promise: Promise<unknown> }>();
registerAccountOwnedResource({
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
index 153c1c6644..3188d4197a 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
@@ -38,6 +38,8 @@ export interface ImageRecallCapabilities {
seed: boolean;
dimensions: boolean;
clipSkip: boolean;
+ /** The image embeds the workflow that made it, so it can be loaded into the editor. */
+ workflow: boolean;
}
export const EMPTY_IMAGE_RECALL_CAPABILITIES: ImageRecallCapabilities = {
@@ -47,6 +49,7 @@ export const EMPTY_IMAGE_RECALL_CAPABILITIES: ImageRecallCapabilities = {
prompts: false,
remix: false,
seed: false,
+ workflow: false,
};
type RecalledField =
@@ -533,6 +536,7 @@ export const getImageRecallCapabilities = ({
prompts: hasPrompts,
remix: hasNonSeedMetadata && isImageRecallKindAvailable('remix'),
seed: hasSeed,
+ workflow: image.hasWorkflow === true,
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
index f9cbd66e24..e9dd353f0f 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
@@ -37,7 +37,12 @@ const mocks = vi.hoisted(() => ({
gallerySelectItem: vi.fn(),
gallerySetItemMultiSelection: vi.fn(),
imageMetadata: vi.fn(),
+ imageResolve: vi.fn((..._args: unknown[]): Promise<unknown> => Promise.reject(new Error('no record'))),
imageResolveMany: vi.fn((..._args: unknown[]) => Promise.resolve([])),
+ imageWorkflow: vi.fn((..._args: unknown[]): Promise<{ graph: string | null; workflow: string | null }> =>
+ Promise.resolve({ graph: null, workflow: null })
+ ),
+ requestWorkflowDocumentLoad: vi.fn(),
videoMetadata: vi.fn((..._args: unknown[]) => Promise.resolve(null)),
invalidateGallery: vi.fn(),
invalidateGalleryItems: vi.fn(),
@@ -46,7 +51,10 @@ const mocks = vi.hoisted(() => ({
itemSetStarred: vi.fn(),
notificationsAdd: vi.fn(),
onImagesDeleted: vi.fn(),
- openWorkbenchWidget: vi.fn(),
+ openWorkbenchWidget: vi.fn((..._args: unknown[]): { ok: boolean; reason?: string; region?: string } => ({
+ ok: true,
+ region: 'center',
+ })),
patchGalleryItemCaches: vi.fn((..._args: unknown[]) => vi.fn()),
removeFromBoard: vi.fn(),
reportError: vi.fn(),
@@ -59,7 +67,9 @@ const preferences = vi.hoisted(() => ({ confirmImageDeletion: false }));
vi.mock('@features/gallery', () => ({
galleryImages: {
metadata: (...args: unknown[]) => mocks.imageMetadata(...args),
+ resolve: (...args: unknown[]) => mocks.imageResolve(...args),
resolveMany: (...args: unknown[]) => mocks.imageResolveMany(...args),
+ workflow: (...args: unknown[]) => mocks.imageWorkflow(...args),
},
galleryItemOrganization: {
delete: (...args: unknown[]) => mocks.itemDelete(...args),
@@ -85,6 +95,10 @@ vi.mock('@features/gallery', () => ({
toGalleryItemRef: ({ kind, name }: { kind: 'image' | 'video'; name: string }) => ({ kind, name }),
}));
+vi.mock('@features/workflow/react', () => ({
+ requestWorkflowDocumentLoad: (...args: unknown[]) => mocks.requestWorkflowDocumentLoad(...args),
+}));
+
vi.mock('@features/gallery/queries', () => ({
getGalleryItemBoardIdsFromCaches: (...args: unknown[]) => mocks.getItemBoardIds(...args),
getGalleryItemStarredFromCaches: (...args: unknown[]) => mocks.getItemStarred(...args),
@@ -174,6 +188,9 @@ vi.mock('react-i18next', () => ({
if (key === 'widgets.gallery.itemActions.move.success') {
return `Moved to ${String(values?.board)}`;
}
+ if (key === 'widgets.gallery.itemActions.loadWorkflow.loadedLabel') {
+ return `${key}:${String(values?.name)}`;
+ }
return key;
},
@@ -417,6 +434,85 @@ describe('image recall capability cancellation', () => {
});
});
+describe('load workflow from image', () => {
+ const image: GalleryImage = {
+ boardId: 'none',
+ height: 512,
+ imageCategory: 'general',
+ imageName: 'made-by-workflow.png',
+ imageUrl: '/full/made-by-workflow.png',
+ queuedAt: '2026-07-30T00:00:00.000Z',
+ sourceQueueItemId: 'queue-workflow',
+ starred: false,
+ thumbnailUrl: '/thumb/made-by-workflow.png',
+ width: 512,
+ };
+
+ it('offers the action only once the image record says a workflow is embedded', async () => {
+ mocks.imageMetadata.mockResolvedValue(null);
+ mocks.imageResolve.mockResolvedValueOnce({ ...image, hasWorkflow: true });
+
+ await expect(actionsRef.current?.getImageRecallCapabilities(image)).resolves.toMatchObject({ workflow: true });
+
+ mocks.imageResolve.mockResolvedValueOnce({ ...image, hasWorkflow: false });
+
+ await expect(actionsRef.current?.getImageRecallCapabilities(image)).resolves.toMatchObject({ workflow: false });
+
+ // An image that came through a record endpoint already knows; no second round trip.
+ mocks.imageResolve.mockClear();
+ await expect(
+ actionsRef.current?.getImageRecallCapabilities({ ...image, hasWorkflow: true })
+ ).resolves.toMatchObject({ workflow: true });
+ expect(mocks.imageResolve).not.toHaveBeenCalled();
+ });
+
+ it('reports, instead of queueing a load for a later editor, when the workflow widget cannot open', async () => {
+ mocks.imageWorkflow.mockResolvedValueOnce({ graph: null, workflow: JSON.stringify({ nodes: [] }) });
+ mocks.openWorkbenchWidget.mockReturnValueOnce({ ok: false, reason: 'unavailable' });
+
+ await act(async () => {
+ await actionsRef.current?.loadImageWorkflow(image);
+ });
+
+ expect(mocks.requestWorkflowDocumentLoad).not.toHaveBeenCalled();
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'error', title: 'widgets.gallery.itemActions.loadWorkflow.failed' })
+ );
+ });
+
+ it('hands the embedded workflow to the editor and opens it', async () => {
+ mocks.imageWorkflow.mockResolvedValueOnce({
+ graph: null,
+ workflow: JSON.stringify({ name: 'Embedded', nodes: [] }),
+ });
+
+ await act(async () => {
+ await actionsRef.current?.loadImageWorkflow(image);
+ });
+
+ expect(mocks.openWorkbenchWidget).toHaveBeenCalledWith('workflow', {
+ preferredRegions: ['center'],
+ requireCenterView: true,
+ });
+ expect(mocks.requestWorkflowDocumentLoad).toHaveBeenCalledWith(
+ { name: 'Embedded', nodes: [] },
+ 'widgets.gallery.itemActions.loadWorkflow.loadedLabel:Embedded'
+ );
+ });
+
+ it('says so, and leaves the editor alone, when the image embeds no workflow', async () => {
+ await act(async () => {
+ await actionsRef.current?.loadImageWorkflow(image);
+ });
+
+ expect(mocks.requestWorkflowDocumentLoad).not.toHaveBeenCalled();
+ expect(mocks.openWorkbenchWidget).not.toHaveBeenCalled();
+ expect(mocks.notificationsAdd).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'info', title: 'widgets.gallery.itemActions.loadWorkflow.missing' })
+ );
+ });
+});
+
describe('partial image mutation outcomes', () => {
it('moves optimistically, then rolls back and re-applies only backend-confirmed images', async () => {
mocks.getItemBoardIds.mockReturnValue(new Map([['image:locked.png', 'board-0']]));
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 13ce924ee9..199737d479 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -56,7 +56,7 @@ import type { RequestDeletionConfirmation } from './useDeletionConfirmation';
import { appendReferenceImage } from './appendReferenceImage';
import { recordCanvasImportError } from './canvasImportError';
-import { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';
+import { executeImageRecall, executeLoadImageWorkflow, getCurrentGenerateValues } from './executeImageRecall';
import { executeVideoRecall } from './executeVideoRecall';
import {
captureGalleryWidgetKeyValues,
@@ -100,6 +100,8 @@ export interface ImageActions extends GalleryItemActions {
downloadImage: (image: GalleryImage) => Promise<void>;
downloadImages: (imageNames: string[]) => Promise<void>;
getImageRecallCapabilities: (image: GalleryImage, signal?: AbortSignal) => Promise<ImageRecallCapabilities>;
+ /** Replaces the project graph with the workflow embedded in the image and opens the editor on it. */
+ loadImageWorkflow: (image: GalleryImage) => Promise<void>;
/** Recall availability for a gallery video, from its recorded core_metadata. */
getVideoRecallCapabilities: (item: GalleryVideoItem, signal?: AbortSignal) => Promise<VideoRecallCapabilities>;
moveImagesToBoard: (imageNames: string[], boardId: string) => Promise<void>;
@@ -820,17 +822,29 @@ export const useImageActions = ({
downloadImages: (imageNames) => downloadItems(imageNames.map((name) => ({ kind: 'image', name }))),
getImageRecallCapabilities: async (image, signal) => {
const owner = captureAccountScope();
+ const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;
+ // Grid listings do not say whether an image embeds a workflow; images that
+ // came through the record endpoints already do.
+ const hasWorkflow =
+ image.hasWorkflow !== undefined
+ ? Promise.resolve(image.hasWorkflow)
+ : galleryImages
+ .resolve(image.imageName, requestSignal)
+ .then((record) => record.hasWorkflow === true)
+ .catch(() => false);
if (!currentGenerateValues) {
- return EMPTY_IMAGE_RECALL_CAPABILITIES;
+ return { ...EMPTY_IMAGE_RECALL_CAPABILITIES, workflow: await hasWorkflow };
}
try {
- const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;
- const metadata = await galleryImages.metadata(image.imageName, requestSignal);
+ const [metadata, workflow] = await Promise.all([
+ galleryImages.metadata(image.imageName, requestSignal),
+ hasWorkflow,
+ ]);
assertAccountScopeCurrent(owner);
- return deriveImageRecallCapabilities(image, metadata);
+ return deriveImageRecallCapabilities({ ...image, hasWorkflow: workflow }, metadata);
} catch {
if (!isAccountScopeCurrent(owner)) {
return EMPTY_IMAGE_RECALL_CAPABILITIES;
@@ -840,9 +854,19 @@ export const useImageActions = ({
...EMPTY_IMAGE_RECALL_CAPABILITIES,
dimensions:
Number.isFinite(image.width) && image.width >= 64 && Number.isFinite(image.height) && image.height >= 64,
+ workflow: await hasWorkflow,
};
}
},
+ loadImageWorkflow: (image) =>
+ executeLoadImageWorkflow({
+ image,
+ isProjectActive: () => !projectId || queries.isActiveProject(projectId),
+ notifications,
+ openWorkflowEditor: () =>
+ openWorkbenchWidget('workflow', { preferredRegions: ['center'], requireCenterView: true }).ok,
+ t,
+ }),
getVideoRecallCapabilities: async (item, signal) => {
const owner = captureAccountScope();
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts
index 3923a47ff6..384e383ae1 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts
@@ -36,6 +36,7 @@ describe('getQueueRecallCapabilities', () => {
prompts: true,
remix: true,
seed: true,
+ workflow: false,
});
});
@@ -47,6 +48,7 @@ describe('getQueueRecallCapabilities', () => {
prompts: true,
remix: false,
seed: true,
+ workflow: false,
});
});
@@ -179,6 +181,7 @@ describe('buildVideoQueueRecallPatch', () => {
seed: true,
dimensions: false,
clipSkip: false,
+ workflow: false,
});
expect(
planQueueRecall('all', { current: null, isVideoItem: true, meta: {}, snapshot: null, videoSnapshot: snapshot })
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
index 84f5b8566d..384e0b42bb 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
@@ -23,6 +23,7 @@ export const getQueueRecallCapabilities = (
prompts: snapshot !== null || meta.positivePrompt !== undefined,
remix: snapshot !== null,
seed: meta.seed !== undefined || (snapshot !== null && snapshot.seedMode !== 'random'),
+ workflow: false,
});
export const getVideoQueueRecallCapabilities = (
@@ -35,6 +36,7 @@ export const getVideoQueueRecallCapabilities = (
prompts: snapshot !== null || meta.positivePrompt !== undefined,
remix: snapshot !== null,
seed: meta.seed !== undefined || (snapshot !== null && snapshot.seedMode !== 'random'),
+ workflow: false,
});
export const buildQueueRecallValues = (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
index 9e34348199..de6a030608 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
@@ -98,6 +98,7 @@ const ALL_RECALL_CAPABILITIES: ImageRecallCapabilities = {
prompts: true,
remix: true,
seed: true,
+ workflow: true,
};
const NO_RECALL_CAPABILITIES: ImageRecallCapabilities = {
all: false,
@@ -106,6 +107,7 @@ const NO_RECALL_CAPABILITIES: ImageRecallCapabilities = {
prompts: false,
remix: false,
seed: false,
+ workflow: false,
};
const i18n = createInstance();