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(canvas): move layer workflows into canvas controls

joshistoast8e5ca43bd9d8
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts
index 9d631721d0..df8c92c569 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/canvasOperationController.ts
@@ -2,7 +2,8 @@ import type { LayerExportGuard } from './engine';
export type CanvasOperationIdentity =
| { kind: 'select-object'; projectId: string; layerId: string }
- | { kind: 'filter'; projectId: string; layerId: string };
+ | { kind: 'filter'; projectId: string; layerId: string }
+ | { kind: 'workflow'; projectId: string; layerId: string };
export type CanvasOperationState =
| { status: 'idle' }
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 58fe81bd9b..24dd4016e8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -9294,6 +9294,35 @@ describe('guarded filter previews', () => {
engine.dispose();
});
+ it('starts and runs a guarded workflow operation independently of the launching menu', async () => {
+ const document = { ...emptyDoc(), layers: [guardableLayer('L')] };
+ const { store } = createReactiveStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ expect((await engine.exportLayerPixels('L')).status).toBe('ok');
+
+ expect(engine.startWorkflowOperation('L')).toBe('started');
+ expect(engine.canvasOperations.getSnapshot()).toMatchObject({
+ identity: { kind: 'workflow', layerId: 'L', projectId: 'p1' },
+ phase: 'ready',
+ status: 'active',
+ });
+ expect(engine.stores.documentEditingLocked.get()).toBe(true);
+
+ const work = vi.fn((_signal: AbortSignal) => Promise.resolve());
+ await expect(engine.runWorkflowOperation(work)).resolves.toBe('published');
+ expect(work).toHaveBeenCalledOnce();
+
+ engine.cancelWorkflowOperation();
+ expect(engine.canvasOperations.getSnapshot()).toEqual({ status: 'idle' });
+ expect(engine.stores.documentEditingLocked.get()).toBe(false);
+ engine.dispose();
+ });
+
it('refuses ordinary structural editing while a filter operation is active', async () => {
const document = { ...emptyDoc(), layers: [guardableLayer('L')] };
const { store } = createReactiveStore(document);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index a27c4a24e1..149babf463 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -137,7 +137,12 @@ import { createSelectObjectSession } from '@workbench/widgets/layers/selectObjec
import type { StrokeCommittedEvent, Tool, ToolContext } from './tools/tool';
import { uploadCanvasImage } from './backend/canvasImages';
-import { createCanvasOperationController, type CanvasOperationController } from './canvasOperationController';
+import {
+ createCanvasOperationController,
+ type CanvasOperationController,
+ type CanvasOperationRunResult,
+ type CanvasOperationSession,
+} from './canvasOperationController';
import { createBitmapStore, type BitmapStore } from './document/bitmapStore';
import { createDocumentMirror, type DocumentMirror } from './document/documentMirror';
import { mergeDownMatrix } from './document/mergeDown';
@@ -366,6 +371,7 @@ export interface CanvasEngineOptions {
export type StartSelectObjectSessionResult = 'started' | 'missing' | 'disabled' | 'unsupported' | 'not-ready';
export type StartFilterOperationResult = 'started' | 'missing' | 'disabled' | 'locked' | 'unsupported' | 'not-ready';
+export type StartWorkflowOperationResult = StartFilterOperationResult;
export type SelectObjectSaveTarget = 'raster' | 'control' | MaskImageResultTarget;
export type SaveSelectObjectSessionResult = CommitGeneratedImageResult | CommitMaskImageResult;
@@ -411,6 +417,10 @@ export interface CanvasEngine {
startSelectObject(layerId: string): StartSelectObjectSessionResult;
/** Starts one engine-owned guarded filter operation for a raster or control layer. */
startFilterOperation(layerId: string): StartFilterOperationResult;
+ /** Starts one guarded layer-workflow operation rendered in the canvas controls. */
+ startWorkflowOperation(layerId: string): StartWorkflowOperationResult;
+ runWorkflowOperation(work: (signal: AbortSignal) => Promise<void>): Promise<CanvasOperationRunResult>;
+ cancelWorkflowOperation(): void;
updateFilterOperation(draft: LayerFilterSettings): void;
processFilterOperation(): Promise<void>;
resetFilterOperation(settings: Record<string, unknown>): void;
@@ -899,6 +909,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
let filterSession: FilterOperationSession | null = null;
let filterUnsubscribe: (() => void) | null = null;
let filterControllerUnsubscribe: (() => void) | null = null;
+ let workflowOperation: CanvasOperationSession | null = null;
+ let workflowControllerUnsubscribe: (() => void) | null = null;
// The brush/eraser cursor ring, drawn on the overlay (set by the active tool).
let overlayCursor: OverlayCursor | null = null;
@@ -2692,6 +2704,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
cancelFilterOperation();
return;
}
+ if (!gestureWasActive && workflowOperation) {
+ cancelWorkflowOperation();
+ return;
+ }
if (!gestureWasActive && selectObjectSession) {
cancelSelectObjectSession();
return;
@@ -2939,6 +2955,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
clearOwnedFilterSession();
+ clearOwnedWorkflowOperation();
clearOwnedSelectObjectSession();
selectObjectGuard = guard;
selectObjectSourceRect = sourceRect;
@@ -3242,6 +3259,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
clearOwnedSelectObjectSession();
clearOwnedFilterSession();
+ clearOwnedWorkflowOperation();
if (document.selectedLayerId !== layer.id) {
store.dispatch({ id: layer.id, type: 'setCanvasSelectedLayer' });
}
@@ -3328,6 +3346,65 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
const cancelFilterOperation = (): void => clearOwnedFilterSession();
+ const clearOwnedWorkflowOperation = (): void => {
+ const operation = workflowOperation;
+ workflowOperation = null;
+ workflowControllerUnsubscribe?.();
+ workflowControllerUnsubscribe = null;
+ operation?.cancel();
+ };
+
+ const startWorkflowOperation = (layerId: string): StartWorkflowOperationResult => {
+ const document = mirror.getDocument();
+ const layer = document?.layers.find((candidate) => candidate.id === layerId);
+ if (!document || !layer) {
+ return 'missing';
+ }
+ if (layer.type !== 'raster' && layer.type !== 'control') {
+ return 'unsupported';
+ }
+ if (!layer.isEnabled) {
+ return 'disabled';
+ }
+ if (layer.isLocked) {
+ return 'locked';
+ }
+ const guard = captureCurrentLayerExportGuard(layer.id);
+ if (!guard) {
+ return 'not-ready';
+ }
+
+ clearOwnedSelectObjectSession();
+ clearOwnedFilterSession();
+ clearOwnedWorkflowOperation();
+ if (document.selectedLayerId !== layer.id) {
+ store.dispatch({ id: layer.id, type: 'setCanvasSelectedLayer' });
+ }
+ const operation = canvasOperations.start({
+ cleanupPreview: () => undefined,
+ guard,
+ identity: { kind: 'workflow', layerId: layer.id, projectId },
+ });
+ if (!operation) {
+ return 'not-ready';
+ }
+ workflowOperation = operation;
+ workflowControllerUnsubscribe = canvasOperations.subscribe(() => {
+ if (workflowOperation === operation && canvasOperations.getSnapshot().status === 'idle') {
+ workflowOperation = null;
+ workflowControllerUnsubscribe?.();
+ workflowControllerUnsubscribe = null;
+ }
+ });
+ setTool('view');
+ return 'started';
+ };
+
+ const runWorkflowOperation = (work: (signal: AbortSignal) => Promise<void>): Promise<CanvasOperationRunResult> =>
+ workflowOperation?.run(work, () => undefined) ?? Promise.resolve('stale');
+
+ const cancelWorkflowOperation = (): void => clearOwnedWorkflowOperation();
+
// ---- Public API ---------------------------------------------------------
function setTool(toolId: ToolId, opts?: { temporary?: boolean }): void {
@@ -6031,6 +6108,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
}
disposed = true;
clearOwnedFilterSession();
+ clearOwnedWorkflowOperation();
clearOwnedSelectObjectSession();
canvasOperations.dispose();
cancelAllLayerRasterizations();
@@ -6206,6 +6284,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
saveSelectObjectSession,
startSelectObject,
startFilterOperation,
+ startWorkflowOperation,
+ runWorkflowOperation,
+ cancelWorkflowOperation,
updateFilterOperation,
updateSelectObjectSession,
openTextCreate,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOperationBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOperationBar.tsx
index 43bf5a363b..e304d0937f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOperationBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOperationBar.tsx
@@ -4,6 +4,7 @@ import type { CanvasEngine } from '@workbench/canvas-engine/engine';
import { CanvasOptionsBar } from './CanvasOptionsBar';
import { FilterOptions } from './FilterOptions';
import { SamOptions } from './SamOptions';
+import { WorkflowOptions } from './WorkflowOptions';
/** Bottom-center controls for the active guarded operation, independent of temporary tools. */
export const CanvasOperationBar = ({
@@ -16,5 +17,8 @@ export const CanvasOperationBar = ({
<CanvasOptionsBar>
{operation.identity.kind === 'select-object' ? <SamOptions engine={engine} /> : null}
{operation.identity.kind === 'filter' ? <FilterOptions engine={engine} /> : null}
+ {operation.identity.kind === 'workflow' ? (
+ <WorkflowOptions engine={engine} layerId={operation.identity.layerId} />
+ ) : null}
</CanvasOptionsBar>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/WorkflowOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/WorkflowOptions.test.ts
new file mode 100644
index 0000000000..2554ec2079
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/WorkflowOptions.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+
+import { getWorkflowActionEligibility } from './WorkflowOptions';
+
+describe('getWorkflowActionEligibility', () => {
+ it('allows a ready, fully-bound workflow to run', () => {
+ expect(getWorkflowActionEligibility({ hasInput: true, hasOutput: true, isRunning: false })).toEqual({
+ canCancel: true,
+ canEdit: true,
+ canRun: true,
+ });
+ });
+
+ it('blocks edits and duplicate runs while the workflow is running', () => {
+ expect(getWorkflowActionEligibility({ hasInput: true, hasOutput: true, isRunning: true })).toEqual({
+ canCancel: true,
+ canEdit: false,
+ canRun: false,
+ });
+ });
+
+ it('requires both an input and an output', () => {
+ expect(getWorkflowActionEligibility({ hasInput: false, hasOutput: true, isRunning: false }).canRun).toBe(false);
+ expect(getWorkflowActionEligibility({ hasInput: true, hasOutput: false, isRunning: false }).canRun).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/WorkflowOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/WorkflowOptions.tsx
new file mode 100644
index 0000000000..e0fe2eeec1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/WorkflowOptions.tsx
@@ -0,0 +1,263 @@
+import type { CanvasEngine } from '@workbench/canvas-engine/engine';
+import type { LayerWorkflowSelection, WorkflowImageBinding } from '@workbench/workflows/layerWorkflow';
+import type { ChangeEvent } from 'react';
+
+import { HStack, NativeSelect, Text } from '@chakra-ui/react';
+import { socketHub } from '@workbench/backend/socketHub';
+import { runUtilityGraph } from '@workbench/canvas-engine/backend/utilityQueue';
+import { Button } from '@workbench/components/ui';
+import { getGalleryImageByName, makeImageDurable, saveImageToGallery } from '@workbench/gallery/api';
+import { useNotify } from '@workbench/useNotify';
+import {
+ createDefaultLayerWorkflowSelection,
+ getLayerWorkflowFailureKey,
+ layerWorkflowBindingKey,
+ reconcileLayerWorkflowOperationSelection,
+ useLayerWorkflowAvailability,
+ type LayerWorkflowAvailability,
+} from '@workbench/widgets/layers/layerWorkflowAvailability';
+import {
+ runLayerWorkflow,
+ type LayerWorkflowDestination,
+ type RunLayerWorkflowResult,
+} from '@workbench/widgets/layers/runLayerWorkflow';
+import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
+import { buildLayerWorkflowGraph, reconcileLayerWorkflowSelection } from '@workbench/workflows/layerWorkflow';
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const SUCCESS_KEYS: Record<LayerWorkflowDestination, string> = {
+ 'copy-raster': 'widgets.layers.runWorkflow.copySuccess',
+ gallery: 'widgets.layers.runWorkflow.gallerySuccess',
+ replace: 'widgets.layers.runWorkflow.replaceSuccess',
+ staging: 'widgets.layers.runWorkflow.stagingSuccess',
+};
+
+const FAILURE_KEYS: Record<Exclude<RunLayerWorkflowResult['status'], 'completed' | 'failed'>, string> = {
+ aborted: 'widgets.layers.runWorkflow.aborted',
+ busy: 'widgets.layers.runWorkflow.busy',
+ disabled: 'widgets.layers.runWorkflow.disabled',
+ empty: 'widgets.layers.runWorkflow.empty',
+ locked: 'widgets.layers.runWorkflow.locked',
+ missing: 'widgets.layers.runWorkflow.missing',
+ 'not-ready': 'widgets.layers.runWorkflow.notReady',
+ stale: 'widgets.layers.runWorkflow.stale',
+ unsupported: 'widgets.layers.runWorkflow.unsupported',
+};
+
+const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+const EMPTY_BINDINGS: readonly WorkflowImageBinding[] = [];
+
+interface SelectionState {
+ availability: LayerWorkflowAvailability;
+ selection: LayerWorkflowSelection;
+}
+
+export interface WorkflowActionEligibility {
+ canCancel: boolean;
+ canEdit: boolean;
+ canRun: boolean;
+}
+
+export const getWorkflowActionEligibility = ({
+ hasInput,
+ hasOutput,
+ isRunning,
+}: {
+ hasInput: boolean;
+ hasOutput: boolean;
+ isRunning: boolean;
+}): WorkflowActionEligibility => ({
+ canCancel: true,
+ canEdit: !isRunning,
+ canRun: !isRunning && hasInput && hasOutput,
+});
+
+const findBinding = (bindings: readonly WorkflowImageBinding[], value: string): WorkflowImageBinding | undefined =>
+ bindings.find((binding) => layerWorkflowBindingKey(binding) === value);
+
+export const WorkflowOptions = ({ engine, layerId }: { engine: CanvasEngine; layerId: string }) => {
+ const { t } = useTranslation();
+ const notify = useNotify();
+ const dispatch = useWorkbenchDispatch();
+ const projectId = useActiveProjectSelector((project) => project.id);
+ const availability = useLayerWorkflowAvailability();
+ const [selectionState, setSelectionState] = useState<SelectionState>(() => ({
+ availability,
+ selection: createDefaultLayerWorkflowSelection(availability),
+ }));
+ const [isRunning, setIsRunning] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ let selection = selectionState.selection;
+ if (selectionState.availability !== availability) {
+ selection = reconcileLayerWorkflowOperationSelection(
+ selection,
+ availability.outputs,
+ availability.getRunnableInputs
+ );
+ setSelectionState({ availability, selection });
+ }
+ const runnableInputs = selection.output ? availability.getRunnableInputs(selection.output) : EMPTY_BINDINGS;
+ const eligibility = getWorkflowActionEligibility({
+ hasInput: selection.input !== null,
+ hasOutput: selection.output !== null,
+ isRunning,
+ });
+
+ const updateSelection = useCallback(
+ (next: LayerWorkflowSelection) => {
+ setSelectionState({ availability, selection: next });
+ setError(null);
+ },
+ [availability]
+ );
+ const handleOutput = useCallback(
+ (event: ChangeEvent<HTMLSelectElement>) => {
+ const output = findBinding(availability.outputs, event.currentTarget.value);
+ if (output) {
+ updateSelection(reconcileLayerWorkflowSelection(selection, output, availability.getRunnableInputs(output)));
+ }
+ },
+ [availability, selection, updateSelection]
+ );
+ const handleInput = useCallback(
+ (event: ChangeEvent<HTMLSelectElement>) => {
+ const input = findBinding(runnableInputs, event.currentTarget.value);
+ if (input) {
+ updateSelection({ ...selection, input });
+ }
+ },
+ [runnableInputs, selection, updateSelection]
+ );
+ const handleDestination = useCallback(
+ (event: ChangeEvent<HTMLSelectElement>) => {
+ updateSelection({ ...selection, destination: event.currentTarget.value as LayerWorkflowDestination });
+ },
+ [selection, updateSelection]
+ );
+ const cancel = useCallback(() => engine.cancelWorkflowOperation(), [engine]);
+ const run = useCallback(async () => {
+ const { input, output } = selection;
+ if (!input || !output || isRunning) {
+ return;
+ }
+ setError(null);
+ setIsRunning(true);
+ const destination = selection.destination;
+ try {
+ const operationResult = await engine.runWorkflowOperation(async (signal) => {
+ const executorDeps = engine.getCompositeExecutorDeps();
+ const result = await runLayerWorkflow({
+ deps: {
+ appendStaging: (targetProjectId, candidate) =>
+ dispatch({ candidate, projectId: targetProjectId, type: 'appendCanvasStagingCandidate' }),
+ buildGraph: buildLayerWorkflowGraph,
+ commitGenerated: (options) => engine.commitGeneratedImageResult(options),
+ createRequestId: () => crypto.randomUUID(),
+ exportLayer: (targetLayerId) => engine.exportBakedLayerBlob(targetLayerId, { includeDisabled: true }),
+ getImage: getGalleryImageByName,
+ isGuardCurrent: (guard) => engine.isLayerExportGuardCurrent(guard),
+ makeDurable: makeImageDurable,
+ runGraph: (options) => runUtilityGraph({ ...options, hub: socketHub }),
+ saveToGallery: saveImageToGallery,
+ touchGallery: (targetProjectId) =>
+ dispatch({ projectId: targetProjectId, type: 'touchGalleryImagesRefresh' }),
+ uploadIntermediate: async (blob, uploadSignal) => {
+ if (uploadSignal?.aborted) {
+ throw new DOMException('Layer workflow aborted', 'AbortError');
+ }
+ const uploaded = await executorDeps.uploadImage(blob);
+ if (uploadSignal?.aborted) {
+ throw new DOMException('Layer workflow aborted', 'AbortError');
+ }
+ return { imageName: uploaded.imageName };
+ },
+ },
+ destination,
+ document: availability.document,
+ input,
+ layerId,
+ output,
+ projectId,
+ signal,
+ templatesSnapshot: availability.templatesSnapshot,
+ });
+ if (result.status === 'completed') {
+ notify.success(t(SUCCESS_KEYS[destination]));
+ engine.cancelWorkflowOperation();
+ } else if (result.status === 'failed') {
+ setError(t(getLayerWorkflowFailureKey(result.stage), { message: result.message }));
+ } else {
+ setError(t(FAILURE_KEYS[result.status]));
+ }
+ });
+ if (operationResult === 'error') {
+ const operation = engine.canvasOperations.getSnapshot();
+ setError(operation.status === 'active' ? operation.error : t('widgets.layers.runWorkflow.failed'));
+ }
+ } catch (cause) {
+ setError(t('widgets.layers.runWorkflow.failed', { message: messageOf(cause) }));
+ } finally {
+ setIsRunning(false);
+ }
+ }, [availability, dispatch, engine, isRunning, layerId, notify, projectId, selection, t]);
+ const handleRun = useCallback(() => void run(), [run]);
+
+ return (
+ <HStack align="center" gap="2" maxW="calc(100vw - 2rem)" overflowX="auto">
+ <NativeSelect.Root disabled={!eligibility.canEdit} size="xs" w="12rem">
+ <NativeSelect.Field
+ aria-label={t('widgets.layers.runWorkflow.output')}
+ value={selection.output ? layerWorkflowBindingKey(selection.output) : ''}
+ onChange={handleOutput}
+ >
+ {availability.outputs.map((binding) => (
+ <option key={layerWorkflowBindingKey(binding)} value={layerWorkflowBindingKey(binding)}>
+ {binding.label}
+ </option>
+ ))}
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ <NativeSelect.Root disabled={!eligibility.canEdit} size="xs" w="12rem">
+ <NativeSelect.Field
+ aria-label={t('widgets.layers.runWorkflow.input')}
+ value={selection.input ? layerWorkflowBindingKey(selection.input) : ''}
+ onChange={handleInput}
+ >
+ {runnableInputs.map((binding) => (
+ <option key={layerWorkflowBindingKey(binding)} value={layerWorkflowBindingKey(binding)}>
+ {binding.label}
+ </option>
+ ))}
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ <NativeSelect.Root disabled={!eligibility.canEdit} size="xs" w="9rem">
+ <NativeSelect.Field
+ aria-label={t('widgets.layers.runWorkflow.destination')}
+ value={selection.destination}
+ onChange={handleDestination}
+ >
+ <option value="gallery">{t('widgets.layers.runWorkflow.gallery')}</option>
+ <option value="staging">{t('widgets.layers.runWorkflow.staging')}</option>
+ <option value="replace">{t('widgets.layers.runWorkflow.replace')}</option>
+ <option value="copy-raster">{t('widgets.layers.runWorkflow.copyRaster')}</option>
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ <Button disabled={!eligibility.canRun} loading={isRunning} size="xs" onClick={handleRun}>
+ {t('widgets.layers.runWorkflow.run')}
+ </Button>
+ <Button disabled={!eligibility.canCancel} size="xs" variant="ghost" onClick={cancel}>
+ {t('widgets.layers.runWorkflow.cancel')}
+ </Button>
+ {error ? (
+ <Text color="fg.error" fontSize="2xs" role="alert">
+ {error}
+ </Text>
+ ) : null}
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 5df161734f..9e5f0084ca 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -71,7 +71,7 @@ import {
getRegionalGuidanceReferenceImagePatch,
} from './layerOps';
import { requestLayerProperties } from './layerPropertiesRequestStore';
-import { RunLayerWorkflowDialog, useLayerWorkflowAvailability } from './RunLayerWorkflowDialog';
+import { useLayerWorkflowAvailability } from './layerWorkflowAvailability';
type MenuPositioning = ComponentProps<typeof Menu.Root>['positioning'];
type MenuOpenChange = ComponentProps<typeof Menu.Root>['onOpenChange'];
@@ -389,7 +389,18 @@ const LayerMenu = ({
const openRename = useCallback(() => setDialogKind('rename'), [setDialogKind]);
const closeDialog = useCallback(() => setDialogKind(null), [setDialogKind]);
- const openRunWorkflow = useCallback(() => setDialogKind('run-workflow'), [setDialogKind]);
+ const startWorkflow = useCallback(
+ (layerId: string) => {
+ if (!engine) {
+ throw makeStatusError('not-ready');
+ }
+ const result = engine.startWorkflowOperation(layerId);
+ if (result !== 'started') {
+ throw makeStatusError(result);
+ }
+ },
+ [engine, makeStatusError]
+ );
const startSelectObject = useCallback(
(layerId: string) => {
if (!engine) {
@@ -626,7 +637,7 @@ const LayerMenu = ({
mergeDown: handleMerge,
openProperties: handleOpenProperties,
openRename,
- openRunWorkflow,
+ startWorkflow,
startSelectObject,
startFilter,
patchConfig: handleLayerConfigAction,
@@ -657,7 +668,7 @@ const LayerMenu = ({
handleToggleVisibility,
handleTransform,
openRename,
- openRunWorkflow,
+ startWorkflow,
startSelectObject,
startFilter,
reorder,
@@ -716,15 +727,6 @@ const LayerMenu = ({
onClose={closeDialog}
onSubmit={submitRename}
/>
- {dialogKind === 'run-workflow' ? (
- <RunLayerWorkflowDialog
- availability={workflowAvailability}
- engine={engine}
- isOpen
- layerId={layer.id}
- onClose={closeDialog}
- />
- ) : null}
</>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
deleted file mode 100644
index a674cb9a49..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
+++ /dev/null
@@ -1,512 +0,0 @@
-import type { SelectValueChangeDetails } from '@chakra-ui/react';
-import type { CanvasEngine } from '@workbench/canvas-engine/engine';
-import type { ProjectGraphState } from '@workbench/workflows/types';
-import type { FormEvent } from 'react';
-
-import { chakra, createListCollection, Dialog, Portal, Stack, Text } from '@chakra-ui/react';
-import { socketHub } from '@workbench/backend/socketHub';
-import { runUtilityGraph } from '@workbench/canvas-engine/backend/utilityQueue';
-import { Button, CloseButton, Field, Select } from '@workbench/components/ui';
-import { getGalleryImageByName, makeImageDurable, saveImageToGallery } from '@workbench/gallery/api';
-import { useNotify } from '@workbench/useNotify';
-import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
-import {
- buildLayerWorkflowGraph,
- getDefaultLayerWorkflowSelection,
- getLayerWorkflowInputs,
- getLayerWorkflowOutputs,
- getRunnableLayerWorkflowInputs,
- reconcileLayerWorkflowSelection,
- type GetRunnableLayerWorkflowInputs,
- type LayerWorkflowSelection,
- type WorkflowImageBinding,
-} from '@workbench/workflows/layerWorkflow';
-import { useInvocationTemplatesSnapshot, type InvocationTemplatesSnapshot } from '@workbench/workflows/templates';
-import { useCallback, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { createLayerActionSession } from './layerActionSession';
-import {
- runLayerWorkflow,
- type LayerWorkflowDestination,
- type LayerWorkflowFailureStage,
- type RunLayerWorkflowResult,
-} from './runLayerWorkflow';
-
-const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;
-const EMPTY_BINDINGS: readonly WorkflowImageBinding[] = [];
-
-const bindingKey = (binding: WorkflowImageBinding): string => JSON.stringify([binding.nodeId, binding.fieldName]);
-const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
-
-export interface LayerWorkflowAvailability {
- canRunWorkflow: boolean;
- document: ProjectGraphState;
- getRunnableInputs(output: WorkflowImageBinding): readonly WorkflowImageBinding[];
- hasWorkflowBindings: boolean;
- inputs: readonly WorkflowImageBinding[];
- outputs: readonly WorkflowImageBinding[];
- templatesSnapshot: InvocationTemplatesSnapshot;
-}
-
-/**
- * Every layer row observes the same immutable graph/template objects. Cache the
- * expensive injected-graph readiness probes by those identities so a long
- * layer list does the work once, while each row still gets live eligibility.
- */
-const availabilityCache = new WeakMap<
- ProjectGraphState,
- WeakMap<InvocationTemplatesSnapshot, LayerWorkflowAvailability>
->();
-
-const getLayerWorkflowAvailability = (
- document: ProjectGraphState,
- templatesSnapshot: InvocationTemplatesSnapshot
-): LayerWorkflowAvailability => {
- let byTemplates = availabilityCache.get(document);
-
- if (!byTemplates) {
- byTemplates = new WeakMap();
- availabilityCache.set(document, byTemplates);
- }
-
- const cached = byTemplates.get(templatesSnapshot);
-
- if (cached) {
- return cached;
- }
-
- const inputs =
- templatesSnapshot.status === 'loaded'
- ? getLayerWorkflowInputs(document, templatesSnapshot.templates)
- : EMPTY_BINDINGS;
- const outputs =
- templatesSnapshot.status === 'loaded'
- ? getLayerWorkflowOutputs(document, templatesSnapshot.templates)
- : EMPTY_BINDINGS;
- const runnableByOutput = new Map<string, readonly WorkflowImageBinding[]>();
-
- for (const output of outputs) {
- runnableByOutput.set(bindingKey(output), getRunnableLayerWorkflowInputs(document, templatesSnapshot, output));
- }
-
- const availability: LayerWorkflowAvailability = {
- canRunWorkflow: [...runnableByOutput.values()].some((runnableInputs) => runnableInputs.length > 0),
- document,
- getRunnableInputs: (output) => runnableByOutput.get(bindingKey(output)) ?? EMPTY_BINDINGS,
- hasWorkflowBindings: inputs.length > 0 && outputs.length > 0,
- inputs,
- outputs,
- templatesSnapshot,
- };
-
- byTemplates.set(templatesSnapshot, availability);
- return availability;
-};
-
-export const useLayerWorkflowAvailability = (): LayerWorkflowAvailability => {
- const document = useActiveProjectSelector((project) => project.projectGraph, Object.is);
- const templatesSnapshot = useInvocationTemplatesSnapshot();
-
- return getLayerWorkflowAvailability(document, templatesSnapshot);
-};
-
-interface RunLayerWorkflowDialogProps {
- availability: LayerWorkflowAvailability;
- engine: CanvasEngine | null;
- isOpen: boolean;
- layerId: string;
- onClose(): void;
-}
-
-interface SelectionState {
- availability: LayerWorkflowAvailability;
- selection: LayerWorkflowSelection;
-}
-
-const createDefaultSelection = (availability: LayerWorkflowAvailability): LayerWorkflowSelection =>
- getDefaultLayerWorkflowSelection(availability.outputs, availability.getRunnableInputs);
-
-export const reconcileLayerWorkflowDialogSelection = (
- current: LayerWorkflowSelection,
- outputs: readonly WorkflowImageBinding[],
- getRunnableInputs: GetRunnableLayerWorkflowInputs
-): LayerWorkflowSelection => {
- const selectedOutput = current.output;
- const currentOutput = selectedOutput
- ? outputs.find((output) => bindingKey(output) === bindingKey(selectedOutput))
- : undefined;
-
- if (currentOutput) {
- return reconcileLayerWorkflowSelection(current, currentOutput, getRunnableInputs(currentOutput));
- }
-
- return {
- ...getDefaultLayerWorkflowSelection(outputs, getRunnableInputs),
- destination: current.destination,
- };
-};
-
-const SUCCESS_KEYS: Record<LayerWorkflowDestination, string> = {
- 'copy-raster': 'widgets.layers.runWorkflow.copySuccess',
- gallery: 'widgets.layers.runWorkflow.gallerySuccess',
- replace: 'widgets.layers.runWorkflow.replaceSuccess',
- staging: 'widgets.layers.runWorkflow.stagingSuccess',
-};
-
-const FAILURE_KEYS: Record<Exclude<RunLayerWorkflowResult['status'], 'completed' | 'failed'>, string> = {
- aborted: 'widgets.layers.runWorkflow.aborted',
- busy: 'widgets.layers.runWorkflow.busy',
- disabled: 'widgets.layers.runWorkflow.disabled',
- empty: 'widgets.layers.runWorkflow.empty',
- locked: 'widgets.layers.runWorkflow.locked',
- missing: 'widgets.layers.runWorkflow.missing',
- 'not-ready': 'widgets.layers.runWorkflow.notReady',
- stale: 'widgets.layers.runWorkflow.stale',
- unsupported: 'widgets.layers.runWorkflow.unsupported',
-};
-
-export const getLayerWorkflowFailureKey = (stage: LayerWorkflowFailureStage): string => {
- switch (stage) {
- case 'graph':
- return 'widgets.layers.runWorkflow.graphFailure';
- case 'hydrate':
- return 'widgets.layers.runWorkflow.hydrationFailure';
- case 'durability':
- return 'widgets.layers.runWorkflow.durabilityFailure';
- default:
- return 'widgets.layers.runWorkflow.failed';
- }
-};
-
-export const RunLayerWorkflowDialog = ({
- availability,
- engine,
- isOpen,
- layerId,
- onClose,
-}: RunLayerWorkflowDialogProps) => {
- const { t } = useTranslation();
- const notify = useNotify();
- const dispatch = useWorkbenchDispatch();
- const projectId = useActiveProjectSelector((project) => project.id);
- const [session] = useState(createLayerActionSession);
- const [selectionState, setSelectionState] = useState<SelectionState>(() => ({
- availability,
- selection: createDefaultSelection(availability),
- }));
- const [isRunning, setIsRunning] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- let selection = selectionState.selection;
-
- if (selectionState.availability !== availability) {
- selection = reconcileLayerWorkflowDialogSelection(selection, availability.outputs, availability.getRunnableInputs);
- setSelectionState({ availability, selection });
- }
-
- const runnableInputs = selection.output ? availability.getRunnableInputs(selection.output) : EMPTY_BINDINGS;
- const inputCollection = useMemo(
- () =>
- createListCollection({
- items: runnableInputs.map((binding) => ({ label: binding.label, value: bindingKey(binding) })),
- }),
- [runnableInputs]
- );
- const outputCollection = useMemo(
- () =>
- createListCollection({
- items: availability.outputs.map((binding) => ({ label: binding.label, value: bindingKey(binding) })),
- }),
- [availability.outputs]
- );
- const destinationCollection = useMemo(
- () =>
- createListCollection<{ label: string; value: LayerWorkflowDestination }>({
- items: [
- { label: t('widgets.layers.runWorkflow.gallery'), value: 'gallery' },
- { label: t('widgets.layers.runWorkflow.staging'), value: 'staging' },
- { label: t('widgets.layers.runWorkflow.replace'), value: 'replace' },
- { label: t('widgets.layers.runWorkflow.copyRaster'), value: 'copy-raster' },
- ],
- }),
- [t]
- );
- const inputValue = useMemo(() => (selection.input ? [bindingKey(selection.input)] : []), [selection.input]);
- const outputValue = useMemo(() => (selection.output ? [bindingKey(selection.output)] : []), [selection.output]);
- const destinationValue = useMemo(() => [selection.destination], [selection.destination]);
-
- const close = useCallback(() => {
- session.cancel();
- onClose();
- }, [onClose, session]);
-
- const contentRef = useCallback(
- (node: HTMLDivElement | null) => {
- if (!node) {
- return;
- }
- return () => {
- session.cancel();
- };
- },
- [session]
- );
-
- const handleOpenChange = useCallback(
- ({ open }: { open: boolean }) => {
- if (!open) {
- close();
- }
- },
- [close]
- );
-
- const handleInputChange = useCallback(
- ({ value }: SelectValueChangeDetails) => {
- const input = runnableInputs.find((binding) => bindingKey(binding) === value[0]);
-
- if (!input) {
- return;
- }
-
- setSelectionState((current) => ({
- availability,
- selection: { ...current.selection, input },
- }));
- setError(null);
- },
- [availability, runnableInputs]
- );
-
- const handleOutputChange = useCallback(
- ({ value }: SelectValueChangeDetails) => {
- const output = availability.outputs.find((binding) => bindingKey(binding) === value[0]);
-
- if (!output) {
- return;
- }
-
- setSelectionState((current) => ({
- availability,
- selection: reconcileLayerWorkflowSelection(current.selection, output, availability.getRunnableInputs(output)),
- }));
- setError(null);
- },
- [availability]
- );
-
- const handleDestinationChange = useCallback(
- ({ value }: SelectValueChangeDetails) => {
- const destination = value[0] as LayerWorkflowDestination | undefined;
-
- if (!destination || !destinationCollection.items.some((item) => item.value === destination)) {
- return;
- }
-
- setSelectionState((current) => ({
- availability,
- selection: { ...current.selection, destination },
- }));
- setError(null);
- },
- [availability, destinationCollection.items]
- );
-
- const runContext = useMemo(
- () => ({
- availability,
- close,
- dispatch,
- engine,
- layerId,
- notify,
- projectId,
- selection,
- session,
- t,
- }),
- [availability, close, dispatch, engine, layerId, notify, projectId, selection, session, t]
- );
-
- const run = useCallback(async (): Promise<void> => {
- const { availability, close, dispatch, engine, layerId, notify, projectId, selection, session, t } = runContext;
- const { input, output } = selection;
-
- if (!engine || !input || !output) {
- return;
- }
-
- const request = session.begin();
-
- if (!request) {
- return;
- }
-
- const destination = selection.destination;
- setError(null);
- setIsRunning(true);
-
- try {
- const executorDeps = engine.getCompositeExecutorDeps();
- const result = await runLayerWorkflow({
- deps: {
- appendStaging: (targetProjectId, candidate) =>
- dispatch({ candidate, projectId: targetProjectId, type: 'appendCanvasStagingCandidate' }),
- buildGraph: buildLayerWorkflowGraph,
- commitGenerated: (options) => engine.commitGeneratedImageResult(options),
- createRequestId: () => crypto.randomUUID(),
- exportLayer: (targetLayerId) => engine.exportBakedLayerBlob(targetLayerId, { includeDisabled: true }),
- getImage: getGalleryImageByName,
- isGuardCurrent: (guard) => engine.isLayerExportGuardCurrent(guard),
- makeDurable: makeImageDurable,
- runGraph: (options) => runUtilityGraph({ ...options, hub: socketHub }),
- saveToGallery: saveImageToGallery,
- touchGallery: (targetProjectId) =>
- dispatch({ projectId: targetProjectId, type: 'touchGalleryImagesRefresh' }),
- uploadIntermediate: async (blob, signal) => {
- if (signal?.aborted) {
- throw new DOMException('Layer workflow aborted', 'AbortError');
- }
- const uploaded = await executorDeps.uploadImage(blob);
- if (signal?.aborted) {
- throw new DOMException('Layer workflow aborted', 'AbortError');
- }
- return { imageName: uploaded.imageName };
- },
- },
- destination,
- document: availability.document,
- input,
- layerId,
- output,
- projectId,
- signal: request.signal,
- templatesSnapshot: availability.templatesSnapshot,
- });
-
- if (!session.isCurrent(request.token)) {
- return;
- }
-
- if (result.status === 'completed') {
- notify.success(t(SUCCESS_KEYS[destination]));
- close();
- return;
- }
-
- if (result.status === 'failed') {
- setError(t(getLayerWorkflowFailureKey(result.stage), { message: result.message }));
- return;
- }
-
- setError(t(FAILURE_KEYS[result.status]));
- } catch (error) {
- if (session.isCurrent(request.token)) {
- setError(t('widgets.layers.runWorkflow.failed', { message: messageOf(error) }));
- }
- } finally {
- if (session.isCurrent(request.token)) {
- setIsRunning(false);
- }
- session.finish(request.token);
- }
- }, [runContext]);
-
- const handleSubmit = useCallback(
- (event: FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- void run();
- },
- [run]
- );
-
- const readinessMessage = !availability.hasWorkflowBindings
- ? t('widgets.layers.runWorkflow.noBindings')
- : !selection.input || !selection.output
- ? t('widgets.layers.runWorkflow.notReady')
- : null;
- const canRun = engine !== null && !isRunning && readinessMessage === null;
-
- return (
- <Dialog.Root lazyMount open={isOpen} placement="center" size="sm" unmountOnExit onOpenChange={handleOpenChange}>
- <Portal>
- <Dialog.Backdrop />
- <Dialog.Positioner>
- <Dialog.Content ref={contentRef} bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" color="fg">
- <chakra.form onSubmit={handleSubmit}>
- <Dialog.Header>
- <Dialog.Title fontSize="sm" fontWeight="700">
- {t('widgets.layers.runWorkflow.title')}
- </Dialog.Title>
- </Dialog.Header>
- <Dialog.Body>
- <Stack gap="4">
- <Field id="layer-workflow-output" label={t('widgets.layers.runWorkflow.output')}>
- <Select
- aria-label={t('widgets.layers.runWorkflow.output')}
- collection={outputCollection}
- disabled={isRunning || availability.outputs.length === 0}
- positioning={SELECT_POSITIONING}
- size="sm"
- value={outputValue}
- onValueChange={handleOutputChange}
- />
- </Field>
- <Field id="layer-workflow-input" label={t('widgets.layers.runWorkflow.input')}>
- <Select
- aria-label={t('widgets.layers.runWorkflow.input')}
- collection={inputCollection}
- disabled={isRunning || runnableInputs.length === 0}
- positioning={SELECT_POSITIONING}
- size="sm"
- value={inputValue}
- onValueChange={handleInputChange}
- />
- </Field>
- <Field id="layer-workflow-destination" label={t('widgets.layers.runWorkflow.destination')}>
- <Select
- aria-label={t('widgets.layers.runWorkflow.destination')}
- collection={destinationCollection}
- disabled={isRunning}
- positioning={SELECT_POSITIONING}
- size="sm"
- value={destinationValue}
- onValueChange={handleDestinationChange}
- />
- </Field>
- {readinessMessage ? (
- <Text color="fg.error" fontSize="xs" role="alert">
- {readinessMessage}
- </Text>
- ) : null}
- {error ? (
- <Text color="fg.error" fontSize="xs" role="alert">
- {error}
- </Text>
- ) : null}
- {isRunning ? (
- <Text color="fg.muted" fontSize="xs" role="status">
- {t('widgets.layers.runWorkflow.running')}
- </Text>
- ) : null}
- </Stack>
- </Dialog.Body>
- <Dialog.Footer gap="2">
- <Button size="xs" type="button" variant="ghost" onClick={close}>
- {t('widgets.layers.runWorkflow.cancel')}
- </Button>
- <Button disabled={!canRun} loading={isRunning} size="xs" type="submit" variant="solid">
- {t('widgets.layers.runWorkflow.run')}
- </Button>
- </Dialog.Footer>
- </chakra.form>
- <Dialog.CloseTrigger asChild>
- <CloseButton aria-label={t('widgets.layers.runWorkflow.cancel')} color="fg.muted" size="sm" />
- </Dialog.CloseTrigger>
- </Dialog.Content>
- </Dialog.Positioner>
- </Portal>
- </Dialog.Root>
- );
-};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index 949d5cf6ca..b2029ffb01 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -90,7 +90,7 @@ const makeEffects = (): LayerContextActionEffects => ({
mergeDown: vi.fn(),
openProperties: vi.fn(),
openRename: vi.fn(),
- openRunWorkflow: vi.fn(),
+ startWorkflow: vi.fn(),
startSelectObject: vi.fn(),
startFilter: vi.fn(),
patchConfig: vi.fn(),
@@ -269,14 +269,14 @@ describe('layer context action registry', () => {
]);
});
- it('opens Run Workflow through the registry without starting work itself', () => {
+ it('starts Run Workflow for the action layer through the registry', () => {
const effects = makeEffects();
const context = makeRuntimeContext(rasterLayer, { effects });
getLayerContextActionDefinition('run-workflow').handler(context);
- expect(effects.openRunWorkflow).toHaveBeenCalledOnce();
- expect(Object.values(effects).filter((effect) => effect.mock.calls.length > 0)).toEqual([effects.openRunWorkflow]);
+ expect(effects.startWorkflow).toHaveBeenCalledWith(rasterLayer.id);
+ expect(Object.values(effects).filter((effect) => effect.mock.calls.length > 0)).toEqual([effects.startWorkflow]);
});
it('dispatches parameterized registry handlers through injected effects', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index b05af07daa..eefe40eb8b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -91,7 +91,7 @@ export interface LayerContextActionEffects {
reorder(kind: LayerMoveKind, actionId: LayerContextActionId): void;
duplicate(): void;
openRename(): void;
- openRunWorkflow(): void;
+ startWorkflow(layerId: string): void;
startSelectObject(layerId: string): void;
startFilter(layerId: string): void;
transform(): void;
@@ -437,7 +437,7 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
},
{
defaultLabel: 'Run workflow',
- handler: ({ effects }) => effects.openRunWorkflow(),
+ handler: ({ effects, layer }) => effects.startWorkflow(layer.id),
icon: WorkflowIcon,
id: 'run-workflow',
isEnabled: (context) => context.canRunWorkflow && hasMutablePixels(context),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.test.ts
index db5eafb88d..ea7a43d87f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.test.ts
@@ -2,11 +2,7 @@ import { describe, expect, it } from 'vitest';
import type { CanvasLayerContextMenuTarget } from './LayerContextMenu';
-import {
- createLayerMenuTargetFromContextEvent,
- type LayerMenuDialogKind,
- resolveMenuTargetForRender,
-} from './layerMenuState';
+import { createLayerMenuTargetFromContextEvent, resolveMenuTargetForRender } from './layerMenuState';
const target = (layerId: string): CanvasLayerContextMenuTarget => ({ layerId, x: 10, y: 20 });
@@ -20,13 +16,10 @@ describe('resolveMenuTargetForRender', () => {
expect(resolveMenuTargetForRender(null, null)).toBeNull();
});
- it.each(['rename', 'run-workflow'] as const)(
- 'falls back to the captured %s target after the menu closes',
- (kind: LayerMenuDialogKind) => {
- const dialogTarget = target('a');
- expect(resolveMenuTargetForRender(null, { kind, target: dialogTarget })).toBe(dialogTarget);
- }
- );
+ it('falls back to the captured rename target after the menu closes', () => {
+ const dialogTarget = target('a');
+ expect(resolveMenuTargetForRender(null, { kind: 'rename', target: dialogTarget })).toBe(dialogTarget);
+ });
it('prefers the live target over a pending dialog target when both exist', () => {
const live = target('b');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts
index ce89e751b2..cd9a8ccb7b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMenuState.ts
@@ -7,7 +7,7 @@ import type { CanvasLayerContextMenuTarget } from './LayerContextMenu';
* wrapper keeps a captured dialog target until that dialog closes so the shared
* subtree remains mounted for rename and workflow actions.
*/
-export type LayerMenuDialogKind = 'rename' | 'run-workflow';
+export type LayerMenuDialogKind = 'rename';
export interface LayerMenuDialogState {
kind: LayerMenuDialogKind;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerWorkflowAvailability.test.ts
similarity index 89%
rename from invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.ts
rename to invokeai/frontend/webv2/src/workbench/widgets/layers/layerWorkflowAvailability.test.ts
index 8f9115ada3..d8370e3518 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerWorkflowAvailability.test.ts
@@ -2,7 +2,7 @@ import type { WorkflowImageBinding } from '@workbench/workflows/layerWorkflow';
import { describe, expect, it } from 'vitest';
-import { getLayerWorkflowFailureKey, reconcileLayerWorkflowDialogSelection } from './RunLayerWorkflowDialog';
+import { getLayerWorkflowFailureKey, reconcileLayerWorkflowOperationSelection } from './layerWorkflowAvailability';
const binding = (nodeId: string, fieldName = 'image', label = `${nodeId} → ${fieldName}`): WorkflowImageBinding => ({
fieldName,
@@ -10,13 +10,13 @@ const binding = (nodeId: string, fieldName = 'image', label = `${nodeId} → ${f
nodeId,
});
-describe('reconcileLayerWorkflowDialogSelection', () => {
+describe('reconcileLayerWorkflowOperationSelection', () => {
it('preserves a still-runnable input and output by field identity when availability refreshes', () => {
const refreshedInput = binding('input', 'image', 'Refreshed input');
const refreshedOutput = binding('output', 'image', 'Refreshed output');
expect(
- reconcileLayerWorkflowDialogSelection(
+ reconcileLayerWorkflowOperationSelection(
{
destination: 'staging',
input: binding('input', 'image', 'Old input'),
@@ -34,7 +34,7 @@ describe('reconcileLayerWorkflowDialogSelection', () => {
const fallbackInput = binding('fallback-input');
expect(
- reconcileLayerWorkflowDialogSelection(
+ reconcileLayerWorkflowOperationSelection(
{ destination: 'copy-raster', input: binding('stale-input'), output: selectedOutput },
[selectedOutput, fallbackOutput],
(output) => (output.nodeId === fallbackOutput.nodeId ? [fallbackInput] : [])
@@ -47,7 +47,7 @@ describe('reconcileLayerWorkflowDialogSelection', () => {
const fallbackInput = binding('fallback-input');
expect(
- reconcileLayerWorkflowDialogSelection(
+ reconcileLayerWorkflowOperationSelection(
{ destination: 'replace', input: binding('stale-input'), output: binding('removed-output') },
[fallbackOutput],
() => [fallbackInput]
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerWorkflowAvailability.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerWorkflowAvailability.ts
new file mode 100644
index 0000000000..f25b59ee01
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerWorkflowAvailability.ts
@@ -0,0 +1,119 @@
+import type { InvocationTemplatesSnapshot } from '@workbench/workflows/templates';
+import type { ProjectGraphState } from '@workbench/workflows/types';
+
+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import {
+ getDefaultLayerWorkflowSelection,
+ getLayerWorkflowInputs,
+ getLayerWorkflowOutputs,
+ getRunnableLayerWorkflowInputs,
+ reconcileLayerWorkflowSelection,
+ type GetRunnableLayerWorkflowInputs,
+ type LayerWorkflowSelection,
+ type WorkflowImageBinding,
+} from '@workbench/workflows/layerWorkflow';
+import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';
+
+import type { LayerWorkflowFailureStage } from './runLayerWorkflow';
+
+const EMPTY_BINDINGS: readonly WorkflowImageBinding[] = [];
+
+export const layerWorkflowBindingKey = (binding: WorkflowImageBinding): string =>
+ JSON.stringify([binding.nodeId, binding.fieldName]);
+
+export interface LayerWorkflowAvailability {
+ canRunWorkflow: boolean;
+ document: ProjectGraphState;
+ getRunnableInputs(output: WorkflowImageBinding): readonly WorkflowImageBinding[];
+ hasWorkflowBindings: boolean;
+ inputs: readonly WorkflowImageBinding[];
+ outputs: readonly WorkflowImageBinding[];
+ templatesSnapshot: InvocationTemplatesSnapshot;
+}
+
+const availabilityCache = new WeakMap<
+ ProjectGraphState,
+ WeakMap<InvocationTemplatesSnapshot, LayerWorkflowAvailability>
+>();
+
+const getLayerWorkflowAvailability = (
+ document: ProjectGraphState,
+ templatesSnapshot: InvocationTemplatesSnapshot
+): LayerWorkflowAvailability => {
+ let byTemplates = availabilityCache.get(document);
+ if (!byTemplates) {
+ byTemplates = new WeakMap();
+ availabilityCache.set(document, byTemplates);
+ }
+ const cached = byTemplates.get(templatesSnapshot);
+ if (cached) {
+ return cached;
+ }
+
+ const inputs =
+ templatesSnapshot.status === 'loaded'
+ ? getLayerWorkflowInputs(document, templatesSnapshot.templates)
+ : EMPTY_BINDINGS;
+ const outputs =
+ templatesSnapshot.status === 'loaded'
+ ? getLayerWorkflowOutputs(document, templatesSnapshot.templates)
+ : EMPTY_BINDINGS;
+ const runnableByOutput = new Map<string, readonly WorkflowImageBinding[]>();
+ for (const output of outputs) {
+ runnableByOutput.set(
+ layerWorkflowBindingKey(output),
+ getRunnableLayerWorkflowInputs(document, templatesSnapshot, output)
+ );
+ }
+ const availability: LayerWorkflowAvailability = {
+ canRunWorkflow: [...runnableByOutput.values()].some((runnableInputs) => runnableInputs.length > 0),
+ document,
+ getRunnableInputs: (output) => runnableByOutput.get(layerWorkflowBindingKey(output)) ?? EMPTY_BINDINGS,
+ hasWorkflowBindings: inputs.length > 0 && outputs.length > 0,
+ inputs,
+ outputs,
+ templatesSnapshot,
+ };
+ byTemplates.set(templatesSnapshot, availability);
+ return availability;
+};
+
+export const useLayerWorkflowAvailability = (): LayerWorkflowAvailability => {
+ const document = useActiveProjectSelector((project) => project.projectGraph, Object.is);
+ const templatesSnapshot = useInvocationTemplatesSnapshot();
+ return getLayerWorkflowAvailability(document, templatesSnapshot);
+};
+
+export const createDefaultLayerWorkflowSelection = (availability: LayerWorkflowAvailability): LayerWorkflowSelection =>
+ getDefaultLayerWorkflowSelection(availability.outputs, availability.getRunnableInputs);
+
+export const reconcileLayerWorkflowOperationSelection = (
+ current: LayerWorkflowSelection,
+ outputs: readonly WorkflowImageBinding[],
+ getRunnableInputs: GetRunnableLayerWorkflowInputs
+): LayerWorkflowSelection => {
+ const selectedOutput = current.output;
+ const currentOutput = selectedOutput
+ ? outputs.find((output) => layerWorkflowBindingKey(output) === layerWorkflowBindingKey(selectedOutput))
+ : undefined;
+ if (currentOutput) {
+ return reconcileLayerWorkflowSelection(current, currentOutput, getRunnableInputs(currentOutput));
+ }
+ return {
+ ...getDefaultLayerWorkflowSelection(outputs, getRunnableInputs),
+ destination: current.destination,
+ };
+};
+
+export const getLayerWorkflowFailureKey = (stage: LayerWorkflowFailureStage): string => {
+ switch (stage) {
+ case 'graph':
+ return 'widgets.layers.runWorkflow.graphFailure';
+ case 'hydrate':
+ return 'widgets.layers.runWorkflow.hydrationFailure';
+ case 'durability':
+ return 'widgets.layers.runWorkflow.durabilityFailure';
+ default:
+ return 'widgets.layers.runWorkflow.failed';
+ }
+};