Skip to content

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

feat(webv2): honour seed modes on layer workflow runs

Josh Corbett3c95e1c58f06
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
index a875466654..7b1294ae0e 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
@@ -351,6 +351,37 @@ describe('buildLayerWorkflowGraph', () => {
expect(Object.values(built.graph.nodes).every((graphNode) => graphNode.is_intermediate === true)).toBe(true);
});
+ it('writes reserved seeds into the built graph without touching the document', () => {
+ const seededTemplate = template(
+ 'seeded',
+ {
+ image: input('image', { input: 'direct', required: true, title: 'Layer image' }),
+ seed: input('seed', {
+ default: 0,
+ maximum: 4_294_967_295,
+ minimum: 0,
+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },
+ }),
+ },
+ { result: output('result', { title: 'Result image' }) }
+ );
+ const seeded = node('seeded', seededTemplate);
+ seeded.data.inputs.seed = { label: '', name: 'seed', seedMode: 'increment', value: 42 };
+ const doc = document([seeded]);
+ const before = structuredClone(doc);
+ const built = buildLayerWorkflowGraph({
+ document: doc,
+ imageName: 'layer.png',
+ input: binding('seeded', 'image'),
+ output: binding('seeded', 'result'),
+ seeds: [{ fieldName: 'seed', nodeId: 'seeded', seed: 900, seedStep: 1 }],
+ templatesSnapshot: loaded({ seeded: seededTemplate }),
+ });
+
+ expect(built.graph.nodes.seeded).toMatchObject({ seed: 900 });
+ expect(doc).toEqual(before);
+ });
+
it('externally satisfies only the selected connection input and appends collision-safe source and capture nodes', () => {
const sinkTemplate = template('sink', {
image: input('image', { input: 'connection', required: true, title: 'Layer image' }),
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
index 51f0abf160..8160c1cc09 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
@@ -8,7 +8,7 @@ import type {
WorkflowInvocationNode,
} from './types';
-import { compileProjectGraph, getProjectGraphReadiness } from './buildGraph';
+import { compileProjectGraph, getProjectGraphReadiness, type WorkflowSeedAssignment } from './buildGraph';
import { getResolvedWorkflowEdgesIndexed } from './connectors';
import { createWorkflowGraphIndex } from './graphIndex';
import { isInvocationNode } from './types';
@@ -39,6 +39,8 @@ export interface BuildLayerWorkflowGraphOptions {
input: WorkflowImageBinding;
output: WorkflowImageBinding;
imageName: string;
+ /** Seeds the caller reserved for this run (`planWorkflowSeeds`); each replaces its field's authored value. */
+ seeds?: readonly WorkflowSeedAssignment[];
}
export interface BuiltLayerWorkflowGraph {
@@ -209,6 +211,18 @@ export const buildLayerWorkflowGraph = (options: BuildLayerWorkflowGraphOptions)
const templates = templatesSnapshot.templates;
const cloned = structuredClone(document);
+
+ for (const seed of options.seeds ?? []) {
+ const seededNode = cloned.nodes.find(
+ (candidate): candidate is WorkflowInvocationNode => candidate.id === seed.nodeId && isInvocationNode(candidate)
+ );
+ const instance = seededNode?.data.inputs[seed.fieldName];
+
+ if (seededNode && instance) {
+ seededNode.data.inputs[seed.fieldName] = { ...instance, value: seed.seed };
+ }
+ }
+
const availableInput = getAvailableBinding(getLayerWorkflowInputs(cloned, templates), input);
if (!availableInput) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
index 4d06871100..44a38c926b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
@@ -32,6 +32,7 @@ import { useTranslation } from 'react-i18next';
import { createLayerActionSession } from './layerActionSession';
import {
+ reserveLayerWorkflowSeeds,
runLayerWorkflow,
type LayerWorkflowDestination,
type LayerWorkflowFailureStage,
@@ -194,7 +195,7 @@ export const RunLayerWorkflowDialog = ({
}: RunLayerWorkflowDialogProps) => {
const { t } = useTranslation();
const notify = useNotify();
- const { canvas } = useWorkbenchCommands();
+ const { canvas, workflows } = useWorkbenchCommands();
const queryClient = useQueryClient();
const projectId = useActiveProjectSelector((project) => project.id);
const [session] = useState(createLayerActionSession);
@@ -333,13 +334,26 @@ export const RunLayerWorkflowDialog = ({
selection,
session,
t,
+ workflows,
}),
- [availability, canvas, close, engine, layerId, notify, projectId, queryClient, selection, session, t]
+ [availability, canvas, close, engine, layerId, notify, projectId, queryClient, selection, session, t, workflows]
);
const run = useCallback(async (): Promise<void> => {
- const { availability, canvas, close, engine, layerId, notify, projectId, queryClient, selection, session, t } =
- runContext;
+ const {
+ availability,
+ canvas,
+ close,
+ engine,
+ layerId,
+ notify,
+ projectId,
+ queryClient,
+ selection,
+ session,
+ t,
+ workflows,
+ } = runContext;
const { input, output } = selection;
if (!engine || !input || !output) {
@@ -361,6 +375,7 @@ export const RunLayerWorkflowDialog = ({
const operations = getCanvasOperations(engine);
const result = await runLayerWorkflow({
deps: {
+ advanceSeeds: (advances) => workflows.editGraph({ advances, type: 'advanceSeedFields' }),
appendStaging: (targetProjectId, candidate) =>
canvas.appendStagingCandidate({ candidate, projectId: targetProjectId }),
buildGraph: buildLayerWorkflowGraph,
@@ -370,6 +385,7 @@ export const RunLayerWorkflowDialog = ({
getImage: galleryImages.resolve,
isGuardCurrent: (guard) => engine.exports.isLayerExportGuardCurrent(guard),
makeDurable: galleryDurability.makeCanvasAsset,
+ reserveSeeds: () => reserveLayerWorkflowSeeds(availability.document, availability.templatesSnapshot),
runGraph: (options) => runUtilityGraph({ ...options, hub: socketHub }),
saveToGallery: galleryDurability.save,
touchGallery: () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts
index 8fd770f2b2..75c0357d09 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.test.ts
@@ -7,6 +7,7 @@ import type { CommitGeneratedImageResult, LayerExportGuard } from '@workbench/ca
import { describe, expect, it, vi } from 'vitest';
import {
+ reserveLayerWorkflowSeeds,
runLayerWorkflow,
type LayerWorkflowDestination,
type RunLayerWorkflowDeps,
@@ -41,6 +42,7 @@ const image: GalleryImage = {
const createDeps = () => {
const order: string[] = [];
const deps: RunLayerWorkflowDeps = {
+ advanceSeeds: vi.fn(() => order.push('advance-seeds')),
appendStaging: vi.fn(() => order.push('append-staging')),
buildGraph: vi.fn(() => {
order.push('build-graph');
@@ -64,6 +66,10 @@ const createDeps = () => {
order.push('make-durable');
return Promise.resolve();
}),
+ reserveSeeds: vi.fn(() => {
+ order.push('reserve-seeds');
+ return { seedAdvances: [], seeds: [] };
+ }),
runGraph: vi.fn<RunLayerWorkflowDeps['runGraph']>(() => {
order.push('run-graph');
return Promise.resolve({ imageName: image.imageName, origin: 'webv2:util:test' });
@@ -97,7 +103,132 @@ const createOptions = (
templatesSnapshot,
});
+describe('reserveLayerWorkflowSeeds', () => {
+ const seedTemplate = {
+ category: 'noise',
+ classification: 'stable',
+ description: '',
+ inputs: {
+ seed: {
+ default: 0,
+ description: '',
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ fieldKind: 'input',
+ input: 'any',
+ maximum: 4_294_967_295,
+ minimum: 0,
+ multipleOf: null,
+ name: 'seed',
+ options: null,
+ required: false,
+ title: 'Seed',
+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },
+ uiChoiceLabels: null,
+ uiComponent: null,
+ uiHidden: false,
+ uiModelBase: null,
+ uiModelFormat: null,
+ uiModelType: null,
+ uiOrder: null,
+ },
+ },
+ nodePack: 'invokeai',
+ outputs: {},
+ outputType: 'noise_output',
+ tags: [],
+ title: 'Noise',
+ type: 'noise',
+ useCache: true,
+ version: '1.0.0',
+ };
+ const seededDocument = {
+ ...document,
+ edges: [],
+ nodes: [
+ {
+ data: {
+ inputs: { seed: { label: '', name: 'seed', seedMode: 'increment', value: 42 } },
+ isIntermediate: true,
+ isOpen: true,
+ label: '',
+ nodePack: 'invokeai',
+ notes: '',
+ type: 'noise',
+ useCache: true,
+ version: '1.0.0',
+ },
+ id: 'noise-1',
+ position: { x: 0, y: 0 },
+ type: 'invocation',
+ },
+ ],
+ } as ProjectGraphState;
+
+ it('plans one run: the authored seed goes into the graph and the field moves on by one', () => {
+ expect(
+ reserveLayerWorkflowSeeds(seededDocument, {
+ error: null,
+ status: 'loaded',
+ templates: { noise: seedTemplate },
+ } as InvocationTemplatesSnapshot)
+ ).toEqual({
+ seedAdvances: [{ fieldName: 'seed', fromSeed: 42, nodeId: 'noise-1', seedMode: 'increment', toSeed: 43 }],
+ seeds: [{ fieldName: 'seed', nodeId: 'noise-1', seed: 42, seedStep: 1 }],
+ });
+ });
+
+ it('reserves nothing while node definitions are not loaded', () => {
+ expect(reserveLayerWorkflowSeeds(seededDocument, { error: null, status: 'loading', templates: {} })).toEqual({
+ seedAdvances: [],
+ seeds: [],
+ });
+ });
+});
+
describe('runLayerWorkflow', () => {
+ it('reserves seeds only once the layer is exported and uploaded, in the same turn as the graph build', async () => {
+ const { deps, order } = createDeps();
+ const seeds = [{ fieldName: 'seed', nodeId: 'noise-1', seed: 42, seedStep: 1 as const }];
+ const seedAdvances = [
+ { fieldName: 'seed', fromSeed: 42, nodeId: 'noise-1', seedMode: 'increment' as const, toSeed: 43 },
+ ];
+ vi.mocked(deps.reserveSeeds).mockImplementation(() => {
+ order.push('reserve-seeds');
+ return { seedAdvances, seeds };
+ });
+ vi.mocked(deps.runGraph).mockImplementation(() => {
+ order.push('run-graph');
+ return Promise.reject(new Error('run failed'));
+ });
+
+ // A failure after the reservation has consumed the seed, like a cancelled queue item.
+ expect(await runLayerWorkflow(createOptions('gallery', deps))).toMatchObject({ stage: 'graph', status: 'failed' });
+ expect(order.slice(0, 5)).toEqual(['export', 'upload', 'reserve-seeds', 'advance-seeds', 'build-graph']);
+ expect(deps.advanceSeeds).toHaveBeenCalledWith(seedAdvances);
+ expect(deps.buildGraph).toHaveBeenCalledWith(expect.objectContaining({ seeds }));
+ });
+
+ it('consumes no seed when the layer cannot be exported', async () => {
+ const { deps } = createDeps();
+ vi.mocked(deps.exportLayer).mockResolvedValue({ status: 'locked' } as never);
+
+ expect(await runLayerWorkflow(createOptions('gallery', deps))).toMatchObject({ status: 'locked' });
+ expect(deps.reserveSeeds).not.toHaveBeenCalled();
+ expect(deps.advanceSeeds).not.toHaveBeenCalled();
+ });
+
+ it('skips the advance when nothing steps', async () => {
+ const { deps } = createDeps();
+ const seeds = [{ fieldName: 'seed', nodeId: 'noise-1', seed: 42, seedStep: 1 as const }];
+ vi.mocked(deps.reserveSeeds).mockReturnValue({ seedAdvances: [], seeds });
+
+ await runLayerWorkflow(createOptions('gallery', deps));
+
+ expect(deps.buildGraph).toHaveBeenCalledWith(expect.objectContaining({ seeds }));
+ expect(deps.advanceSeeds).not.toHaveBeenCalled();
+ });
+
it('runs the captured output to Gallery and refreshes the captured project', async () => {
const { deps, order } = createDeps();
@@ -109,6 +240,7 @@ describe('runLayerWorkflow', () => {
expect(order).toEqual([
'export',
'upload',
+ 'reserve-seeds',
'build-graph',
'run-graph',
'get-image',
@@ -120,6 +252,7 @@ describe('runLayerWorkflow', () => {
imageName: 'layer-input.png',
input,
output,
+ seeds: [],
templatesSnapshot,
});
expect(deps.touchGallery).toHaveBeenCalledWith('project-1');
@@ -137,6 +270,7 @@ describe('runLayerWorkflow', () => {
expect(order).toEqual([
'export',
'upload',
+ 'reserve-seeds',
'build-graph',
'run-graph',
'get-image',
@@ -164,6 +298,7 @@ describe('runLayerWorkflow', () => {
expect(order).toEqual([
'export',
'upload',
+ 'reserve-seeds',
'build-graph',
'run-graph',
'get-image',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts
index 237cffaa6c..94fe06a08d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/runLayerWorkflow.ts
@@ -1,11 +1,12 @@
import type { GalleryImage } from '@features/gallery';
import type { RunUtilityGraphOptions, UtilityGraphResult } from '@features/queue/utility';
-import type { ProjectGraphState } from '@features/workflow/contracts';
+import type { ProjectGraphState, WorkflowSeedFieldAdvance } from '@features/workflow/contracts';
import type {
BuildLayerWorkflowGraphOptions,
BuiltLayerWorkflowGraph,
LayerWorkflowDestination,
WorkflowImageBinding,
+ WorkflowSeedPlan,
} from '@features/workflow/graph';
import type { InvocationTemplatesSnapshot } from '@features/workflow/react';
import type {
@@ -16,6 +17,8 @@ import type {
LayerExportGuard,
} from '@workbench/canvas-engine/api';
+import { planWorkflowSeeds } from '@features/workflow/graph';
+
export type { LayerWorkflowDestination } from '@features/workflow/graph';
export type LayerWorkflowFailureStage =
@@ -46,6 +49,10 @@ export type RunLayerWorkflowResult =
| { status: 'failed'; message: string; stage: LayerWorkflowFailureStage };
export interface RunLayerWorkflowDeps {
+ /** Plans this run's seeds from the project graph; see `reserveLayerWorkflowSeeds`. */
+ reserveSeeds(): WorkflowSeedPlan;
+ /** Moves the stepping fields the plan named; dispatched before anything asynchronous starts. */
+ advanceSeeds(advances: readonly WorkflowSeedFieldAdvance[]): void;
exportLayer(layerId: string): Promise<ExportBakedLayerBlobResult>;
uploadIntermediate(blob: Blob, signal?: AbortSignal): Promise<{ imageName: string }>;
buildGraph(options: BuildLayerWorkflowGraphOptions): BuiltLayerWorkflowGraph;
@@ -93,6 +100,26 @@ const stopped = (
return null;
};
+/**
+ * A layer run is one run of the project graph, so its seeds follow the same
+ * rules as a queued submission of one: a random input draws now, a stepping
+ * input takes its authored seed. The runner plans once the layer has been
+ * exported and uploaded, and applies `seedAdvances` to the project graph in the
+ * same turn as the graph build — that is the reservation. The dialog's action
+ * session serialises layer runs, so two runs take consecutive seeds; a refusal
+ * before the build consumes nothing, a failure after it has. The project graph
+ * is the owning document: the dialog runs it, not a library record, and the
+ * reducer fences each advance on the value and mode the plan read, so an edit
+ * made meanwhile wins.
+ */
+export const reserveLayerWorkflowSeeds = (
+ document: ProjectGraphState,
+ templatesSnapshot: InvocationTemplatesSnapshot
+): WorkflowSeedPlan =>
+ templatesSnapshot.status === 'loaded'
+ ? planWorkflowSeeds(document, templatesSnapshot.templates, 1)
+ : { seedAdvances: [], seeds: [] };
+
export const runLayerWorkflow = async (options: RunLayerWorkflowOptions): Promise<RunLayerWorkflowResult> => {
const { deps, signal } = options;
let failureStage: LayerWorkflowFailureStage = 'export';
@@ -122,11 +149,21 @@ export const runLayerWorkflow = async (options: RunLayerWorkflowOptions): Promis
}
failureStage = 'graph';
+ // The layer is exported and uploaded, so the run will be submitted: reserve its seeds
+ // now, in the same turn as the graph build. A refusal above consumed nothing, like a
+ // queue route that fails validation; a failure below has, like a cancelled queue item.
+ const seedPlan = deps.reserveSeeds();
+
+ if (seedPlan.seedAdvances.length > 0) {
+ deps.advanceSeeds(seedPlan.seedAdvances);
+ }
+
const built = deps.buildGraph({
document: options.document,
imageName: uploaded.imageName,
input: options.input,
output: options.output,
+ seeds: seedPlan.seeds,
templatesSnapshot: options.templatesSnapshot,
});
canceled = stopped(signal, exported.guard, deps.isGuardCurrent);