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): let projects own a collection of workflows

Josh Corbett6394f59a8656
diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
index d71da75d7e..c16b1cf2e9 100644
--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx
@@ -2,7 +2,6 @@ import { invalidateGallery } from '@features/gallery/queries';
import { modelLoadActivitySink } from '@features/models';
import { nodeExecutionStore } from '@features/nodes';
import { createProductionQueueRuntime, createProductionQueueReceiptAcknowledgements } from '@features/queue';
-import { createWorkflowRunCaptureSink } from '@features/workflow/queries';
import { ensureInvocationTemplatesLoaded } from '@features/workflow/react';
import { useMountEffect } from '@platform/react/useMountEffect';
import {
@@ -150,7 +149,6 @@ export const QueueRuntimeAdapter = () => {
locks: createQueueRunLockPort(owner.storageSuffix),
modelLoads: modelLoadActivitySink,
nodeExecution: nodeExecutionStore,
- workflowRuns: createWorkflowRunCaptureSink(),
});
runtime.start();
};
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index e75050b3ab..46739094d6 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -127,6 +127,7 @@
"projectContracts.ts": "workbench",
"projectEventContracts.ts": "workbench",
"projectEvents.ts": "workbench",
+ "projectWorkflows.ts": "workbench",
"queueHistoryContracts.ts": "workbench",
"useCanvasProjectMutationDispatch.ts": "workbench",
"useNotify.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts
index da9bc2f894..932876974f 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts
@@ -93,3 +93,23 @@ describe('node execution lifecycle', () => {
});
});
});
+
+describe('node execution origin', () => {
+ it('names the run it reflects, notifies origin subscribers, and forgets the origin with the nodes', () => {
+ const listener = vi.fn();
+ const unsubscribe = nodeExecutionStore.subscribeOrigin(listener);
+
+ nodeExecutionStore.setOrigin({ projectId: 'p', workflowId: 'a' });
+ nodeExecutionStore.setOrigin({ projectId: 'p', workflowId: 'a' });
+ expect(nodeExecutionStore.getOrigin()).toEqual({ projectId: 'p', workflowId: 'a' });
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ nodeExecutionStore.started({ invocation_source_id: 'node-1' });
+ nodeExecutionStore.clearAll();
+ expect(nodeExecutionStore.getOrigin()).toBeNull();
+ expect(nodeExecutionStore.get('node-1')).toBeNull();
+ expect(listener).toHaveBeenCalledTimes(2);
+
+ unsubscribe();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
index 2d6edc71c3..38e1b9483c 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
@@ -6,7 +6,7 @@ import type {
import { getFirstOutputImageName } from '@platform/core/outputImages';
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
-import { createKeyedTransientStore } from '@platform/state/externalStore';
+import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';
import { browserNodesDataPort } from './transport';
@@ -32,11 +32,33 @@ export interface NodeExecutionState {
error: string | null;
}
+/** The project workflow whose run the store reflects; editors showing another copy ignore the node states. */
+export interface NodeExecutionOrigin {
+ projectId: string;
+ workflowId: string;
+}
+
const stateByNodeId = createKeyedTransientStore<string, NodeExecutionState>();
+const originStore = createExternalStore<{ origin: NodeExecutionOrigin | null }>({ origin: null });
export const nodeExecutionStore = {
clearAll(): void {
stateByNodeId.clear();
+ if (originStore.getSnapshot().origin !== null) {
+ originStore.setSnapshot({ origin: null });
+ }
+ },
+ getOrigin(): NodeExecutionOrigin | null {
+ return originStore.getSnapshot().origin;
+ },
+ setOrigin(origin: NodeExecutionOrigin | null): void {
+ const current = originStore.getSnapshot().origin;
+ if (current?.projectId !== origin?.projectId || current?.workflowId !== origin?.workflowId) {
+ originStore.setSnapshot({ origin });
+ }
+ },
+ subscribeOrigin(listener: () => void): () => void {
+ return originStore.subscribe(listener);
},
get(nodeId: string): NodeExecutionState | null {
return stateByNodeId.get(nodeId) ?? null;
@@ -128,6 +150,9 @@ export interface NodeExecutionSink {
completed(event: NodeInvocationCompleteEvent): void;
failed(event: NodeInvocationErrorEvent): void;
get(nodeId: string): NodeExecutionState | null;
+ getOrigin(): NodeExecutionOrigin | null;
+ setOrigin(origin: NodeExecutionOrigin | null): void;
+ subscribeOrigin(listener: () => void): () => void;
progress(nodeId: string, percentage: number | null, message: string): void;
settleRunning(nodeIds: Iterable<string>, outcome: NodeExecutionOutcome, error?: string): void;
started(event: NodeInvocationStartedEvent): void;
diff --git a/invokeai/frontend/webv2/src/features/nodes/index.ts b/invokeai/frontend/webv2/src/features/nodes/index.ts
index 8f562e0e68..2869c481e1 100644
--- a/invokeai/frontend/webv2/src/features/nodes/index.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/index.ts
@@ -14,6 +14,7 @@ export {
export {
nodeExecutionStore,
useNodeExecutionState,
+ type NodeExecutionOrigin,
type NodeExecutionSink,
type NodeExecutionState,
type NodeExecutionStatus,
diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.ts
index 8730a5271c..e858b6d8b0 100644
--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts
@@ -25,8 +25,6 @@ export type {
QueueSourceId,
QueueStatusReadModel,
QueueSubmissionPresentation,
- QueueWorkflowRunCompletedEvent,
- QueueWorkflowRunSink,
TerminalQueueItemStatus,
} from './core/types';
export {
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index d253a32f34..d45c7517e0 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -93,8 +93,11 @@ export type QueueCompiledSubmission =
seeds?: QueueWorkflowSeed[];
/** Batch-node value lists resolved at compile time: outer groups multiply, inner datums zip. */
batchData?: QueueWorkflowBatchDatum[][];
- /** Capture the bound library ID at compile time so completion attribution survives later editor changes. */
- libraryWorkflowId?: string;
+ /**
+ * The project workflow the graph was compiled from, so results return to it whatever is active later. Absent
+ * on records queued before projects owned several workflows; those results keep their destination only.
+ */
+ projectWorkflowId?: string;
}
| {
batchCount: number;
@@ -139,20 +142,6 @@ export interface QueueResultImage {
width: number;
}
-/** A settled run of a library-bound workflow, reported once its results are routed. */
-export interface QueueWorkflowRunCompletedEvent {
- /** Result images in run order; the last one is the run's final output. */
- imageNames: readonly string[];
- libraryWorkflowId: string;
- projectId: string;
- queueItemId: string;
-}
-
-/** App injects optional completed-library-run capture; Queue owns neither library nor gallery. */
-export interface QueueWorkflowRunSink {
- onWorkflowRunCompleted(event: QueueWorkflowRunCompletedEvent): void;
-}
-
export type QueueItemStatus = 'pending' | 'in_progress' | 'waiting' | 'completed' | 'failed' | 'canceled';
export type TerminalQueueItemStatus = Extract<QueueItemStatus, 'completed' | 'failed' | 'canceled'>;
export type QueueConnectionStatus = 'connecting' | 'connected' | 'disconnected';
@@ -261,6 +250,12 @@ export interface QueueResultImageOptions {
resultNodeIds?: readonly string[];
}
+/** The project workflow a run was compiled from; node progress is shown only in that editor. */
+export interface QueueRunOrigin {
+ projectId: string;
+ workflowId: string;
+}
+
export interface QueueResultVideoOptions extends QueueResultImageOptions {
/** Drop videos whose DTO reports is_intermediate — the video analogue of filterIntermediateResults. */
excludeIntermediate?: boolean;
diff --git a/invokeai/frontend/webv2/src/features/queue/publicApi.ts b/invokeai/frontend/webv2/src/features/queue/publicApi.ts
index fe1cee9592..cac51c48f0 100644
--- a/invokeai/frontend/webv2/src/features/queue/publicApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/publicApi.ts
@@ -1,4 +1,4 @@
-import type { QueueFeatureCommands, QueueQueryScope, QueueReadModel, QueueWorkflowRunSink } from './core/types';
+import type { QueueFeatureCommands, QueueQueryScope, QueueReadModel } from './core/types';
import type { QueueItemProgressPort, QueueRealtimeRuntime } from './data/realtimeRuntime';
import type {
QueueHistoryPort,
@@ -63,7 +63,6 @@ export const createProductionQueueRuntime = ({
locks,
modelLoads,
nodeExecution,
- workflowRuns,
}: {
destinations: QueueResultDestinationPort;
ensureProjectPersisted?(projectId: string): Promise<'ready' | 'refused' | 'retry'>;
@@ -73,7 +72,6 @@ export const createProductionQueueRuntime = ({
locks?: QueueRunLockPort;
modelLoads: QueueModelLoadPort;
nodeExecution: QueueNodeExecutionPort;
- workflowRuns?: QueueWorkflowRunSink;
}): QueueRuntime =>
createQueueRuntime({
backend: queueBackend,
@@ -85,5 +83,4 @@ export const createProductionQueueRuntime = ({
locks,
modelLoads,
nodeExecution,
- workflowRuns,
});
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index b11ec40a85..7b0bfe3b85 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -1,10 +1,5 @@
import type { QueueItem } from '@features/queue/core/historyTypes';
-import type {
- QueueBackendInvocation,
- QueueBackendPort,
- QueueResultImage,
- QueueWorkflowRunSink,
-} from '@features/queue/core/types';
+import type { QueueBackendInvocation, QueueBackendPort, QueueResultImage } from '@features/queue/core/types';
import type { BackendConnectionStatus } from '@platform/transport/types';
import { buildQueueItemOrigin } from '@features/queue/data/events';
@@ -110,6 +105,7 @@ const runtimeServices = {
completed: vi.fn(),
failed: vi.fn(),
progress: vi.fn(),
+ setOrigin: vi.fn(),
settleRunning: vi.fn(),
started: vi.fn(),
},
@@ -197,6 +193,25 @@ describe('queue runtime', () => {
expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([seed, seed]))).toEqual(invalid);
});
+ it('keeps workflow provenance off the backend request, including the binding older records carry', () => {
+ const queueItem = createPendingQueueItem();
+ queueItem.snapshot.backendSubmission = {
+ batchCount: 1,
+ graph: { edges: [], id: 'backend-graph', nodes: {} },
+ kind: 'workflow',
+ libraryWorkflowId: 'lib-1',
+ projectWorkflowId: 'wf-1',
+ } as never;
+ queueItem.snapshot.sourceId = 'workflow';
+
+ const submission = createQueueItemBackendSubmission({ id: 'project-1' }, queueItem);
+
+ expect(submission).toMatchObject({ kind: 'workflow', request: { batchCount: 1, projectId: 'project-1' } });
+ expect(submission).toHaveProperty('request');
+ expect((submission as { request: object }).request).not.toHaveProperty('projectWorkflowId');
+ expect((submission as { request: object }).request).not.toHaveProperty('libraryWorkflowId');
+ });
+
it('replays persisted batch groups and rejects ones the graph or the backend would refuse', () => {
const asWorkflow = (batchData: unknown, seeds?: unknown) => {
const queueItem = createPendingQueueItem();
@@ -341,6 +356,7 @@ describe('queue runtime', () => {
completed: vi.fn(),
failed: vi.fn(),
progress: vi.fn(),
+ setOrigin: vi.fn(),
settleRunning: vi.fn(),
started: vi.fn(),
},
@@ -2094,6 +2110,7 @@ describe('queue runtime video board routing', () => {
completed: vi.fn(),
failed: vi.fn(),
progress: vi.fn(),
+ setOrigin: vi.fn(),
settleRunning: vi.fn(),
started: vi.fn(),
},
@@ -2256,209 +2273,3 @@ describe('queue runtime video board routing', () => {
runtime.dispose();
});
});
-
-describe('queue runtime workflow run capture', () => {
- const resultImage = (imageName: string): QueueResultImage => ({
- height: 512,
- imageName,
- imageUrl: `http://test/i/${imageName}`,
- isIntermediate: false,
- queuedAt: '2026-07-17T00:00:00.000Z',
- sourceQueueItemId: 'local-queue-item',
- thumbnailUrl: `http://test/t/${imageName}`,
- width: 512,
- });
-
- const createHarness = (options: {
- images?: QueueResultImage[];
- /** Replaces the item's generate submission with a workflow one. */
- libraryWorkflowId?: string | null;
- onWorkflowRunCompleted?: QueueWorkflowRunSink['onWorkflowRunCompleted'];
- }) => {
- const queueItem = createPendingQueueItem();
-
- queueItem.snapshot.destination = 'gallery';
- queueItem.snapshot.galleryBoardId = null;
- if (options.libraryWorkflowId !== undefined) {
- queueItem.snapshot.backendSubmission = {
- batchCount: 1,
- graph: { edges: [], id: 'backend-graph', nodes: {} },
- kind: 'workflow',
- ...(options.libraryWorkflowId ? { libraryWorkflowId: options.libraryWorkflowId } : {}),
- };
- queueItem.snapshot.sourceId = 'workflow';
- }
-
- const project = { id: 'project-1', queue: { items: [queueItem] } };
- const backend: QueueBackendPort = {
- cancelCurrentItem: vi.fn(),
- cancelItem: vi.fn(),
- cancelQueueItems: vi.fn(),
- cancelQueueItemsByBatchIds: vi.fn(),
- cancelScopedItems: vi.fn(),
- clearFailedItems: vi.fn(),
- clearItems: vi.fn(),
- emit: vi.fn(),
- enqueueGenerate: vi.fn(),
- enqueueWorkflow: vi.fn(),
- getItem: vi.fn(),
- getResultImages: vi.fn().mockResolvedValue(options.images ?? [resultImage('generated.png')]),
- getResultVideoNames: vi.fn().mockResolvedValue([]),
- listItems: vi.fn().mockResolvedValue([
- {
- batchId: 'backend-batch',
- id: 77,
- origin: buildQueueItemOrigin(queueItem.id, project.id),
- status: 'completed',
- },
- ]),
- on: vi.fn(() => vi.fn()),
- onConnectionChange: vi.fn(() => vi.fn()),
- pauseProcessor: vi.fn(),
- readCurrent: vi.fn().mockResolvedValue(null),
- readItemIds: vi.fn().mockResolvedValue({ itemIds: [], totalCount: 0 }),
- readItemsById: vi.fn().mockResolvedValue([]),
- readNext: vi.fn().mockResolvedValue(null),
- readStatus: vi.fn().mockResolvedValue({
- processor: { isProcessing: false, isStarted: true },
- queue: {
- canceled: 0,
- completed: 0,
- failed: 0,
- inProgress: 0,
- pending: 0,
- queueId: 'default',
- total: 0,
- waiting: 0,
- },
- }),
- resumeProcessor: vi.fn(),
- retryItems: vi.fn(),
- };
- const commands: QueueHistoryCommands = {
- markBackendCancelled: vi.fn(),
- markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {
- queueItem.backendBatchId = backendBatchId;
- queueItem.backendItemIds = backendItemIds;
- queueItem.status = 'running';
- },
- setCancellationPending: ({ pending }) => {
- queueItem.cancellationPending = pending || undefined;
- },
- setLocalRecoveryState: vi.fn(),
- recordError: vi.fn(),
- refreshBackendData: vi.fn(),
- restoreFromJournal: vi.fn(),
- routePartialResults: vi.fn(),
- routeResults: vi.fn(),
- setConnectionStatus: vi.fn(),
- setStatus: vi.fn(),
- };
- const onWorkflowRunCompleted = vi.fn(options.onWorkflowRunCompleted);
- const runtime = createQueueRuntime({
- backend,
- destinations: { addImagesToGalleryBoard: vi.fn(), addVideosToGalleryBoard: vi.fn() },
- ensureTemplatesLoaded: vi.fn(),
- history: {
- commands,
- getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: [project] }),
- subscribe: vi.fn(() => vi.fn()),
- },
- modelLoads: { completed: vi.fn(), reset: vi.fn(), started: vi.fn() },
- nodeExecution: {
- clearAll: vi.fn(),
- completed: vi.fn(),
- failed: vi.fn(),
- progress: vi.fn(),
- settleRunning: vi.fn(),
- started: vi.fn(),
- },
- workflowRuns: { onWorkflowRunCompleted },
- });
-
- return { commands, onWorkflowRunCompleted, queueItem, runtime };
- };
-
- it('notifies the capture sink once with the completed run and its result image names', async () => {
- const { commands, onWorkflowRunCompleted, runtime } = createHarness({
- images: [resultImage('early.png'), resultImage('final.png')],
- libraryWorkflowId: 'library-workflow-1',
- });
-
- runtime.start();
-
- await vi.waitFor(() => {
- expect(commands.routeResults).toHaveBeenCalled();
- });
- expect(onWorkflowRunCompleted).toHaveBeenCalledTimes(1);
- expect(onWorkflowRunCompleted).toHaveBeenCalledWith({
- imageNames: ['early.png', 'final.png'],
- libraryWorkflowId: 'library-workflow-1',
- projectId: 'project-1',
- queueItemId: 'local-queue-item',
- });
-
- runtime.dispose();
- });
-
- it('never notifies for a workflow run that is not bound to a library record', async () => {
- const { commands, onWorkflowRunCompleted, runtime } = createHarness({ libraryWorkflowId: null });
-
- runtime.start();
-
- await vi.waitFor(() => {
- expect(commands.routeResults).toHaveBeenCalled();
- });
- expect(onWorkflowRunCompleted).not.toHaveBeenCalled();
-
- runtime.dispose();
- });
-
- it('never notifies for a generate run', async () => {
- const { commands, onWorkflowRunCompleted, runtime } = createHarness({});
-
- runtime.start();
-
- await vi.waitFor(() => {
- expect(commands.routeResults).toHaveBeenCalled();
- });
- expect(onWorkflowRunCompleted).not.toHaveBeenCalled();
-
- runtime.dispose();
- });
-
- it('never notifies for a bound workflow run that produced no images', async () => {
- const { commands, onWorkflowRunCompleted, runtime } = createHarness({
- images: [],
- libraryWorkflowId: 'library-workflow-1',
- });
-
- runtime.start();
-
- await vi.waitFor(() => {
- expect(commands.routeResults).toHaveBeenCalled();
- });
- expect(onWorkflowRunCompleted).not.toHaveBeenCalled();
-
- runtime.dispose();
- });
-
- it('settles the run normally when the capture sink throws', async () => {
- const { commands, onWorkflowRunCompleted, runtime } = createHarness({
- libraryWorkflowId: 'library-workflow-1',
- onWorkflowRunCompleted: () => {
- throw new Error('capture exploded');
- },
- });
-
- runtime.start();
-
- await vi.waitFor(() => {
- expect(onWorkflowRunCompleted).toHaveBeenCalled();
- });
- expect(commands.routeResults).toHaveBeenCalled();
- expect(commands.setStatus).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'failed' }));
-
- runtime.dispose();
- });
-});
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index 1c73044a4e..d0c7229e45 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -5,7 +5,7 @@ import type {
QueueEnqueueWorkflowRequest,
QueueResultImage,
QueueResultImageOptions,
- QueueWorkflowRunSink,
+ QueueRunOrigin,
} from '@features/queue/core/types';
import type { BackendConnectionStatus } from '@platform/transport/types';
@@ -115,6 +115,15 @@ export const getQueueItemResultImageOptions = (queueItem: QueueItem): QueueResul
return queueItem.snapshot.resultNodeIds ? { resultNodeIds: queueItem.snapshot.resultNodeIds } : undefined;
};
+/** Where a run's node progress belongs; records queued before projects owned several workflows have none. */
+const getQueueRunOrigin = (projectId: string, queueItem: QueueItem): QueueRunOrigin | undefined => {
+ const submission = (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;
+
+ return submission?.kind === 'workflow' && typeof submission.projectWorkflowId === 'string'
+ ? { projectId, workflowId: submission.projectWorkflowId }
+ : undefined;
+};
+
/** Read compiled graphs to identify input passthroughs; legacy or invalid snapshots may lack them. */
const getQueueItemCompiledGraph = (queueItem: QueueItem): unknown => {
const submission = (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;
@@ -272,9 +281,16 @@ export const createQueueItemBackendSubmission = (
return { error: 'Queue item has malformed workflow batch metadata.', kind: 'invalid' };
}
- // `libraryWorkflowId` is provenance for the completed-run sink, not something
- // the backend enqueue accepts; it stays on the snapshot and off the request.
- const { kind: _, libraryWorkflowId: _libraryWorkflowId, ...compiled } = submission;
+ // Workflow provenance stays on the snapshot: the backend enqueue accepts neither the originating project
+ // workflow nor the library binding older records still carry.
+ const {
+ kind: _,
+ projectWorkflowId: _projectWorkflowId,
+ ...compiled
+ } = submission as typeof submission & {
+ libraryWorkflowId?: string;
+ };
+ delete (compiled as { libraryWorkflowId?: string }).libraryWorkflowId;
return {
kind: 'workflow',
request: {
@@ -336,7 +352,6 @@ export const createQueueRuntime = ({
locks,
modelLoads,
nodeExecution,
- workflowRuns,
}: {
backend: QueueBackendPort;
destinations: QueueResultDestinationPort;
@@ -347,7 +362,6 @@ export const createQueueRuntime = ({
locks?: QueueRunLockPort;
modelLoads: QueueModelLoadPort;
nodeExecution: QueueNodeExecutionPort;
- workflowRuns?: QueueWorkflowRunSink;
}): QueueRuntime => {
const owner = captureAccountScope();
const commands = history.commands;
@@ -906,34 +920,6 @@ export const createQueueRuntime = ({
return images;
};
- /**
- * Notify the optional library sink only for bound workflows. Capture is decoration: sink failure must not fail
- * settlement or prevent gallery refresh.
- */
- const notifyWorkflowRunCompleted = (projectId: string, queueItem: QueueItem, images: QueueResultImage[]): void => {
- const submission = (queueItem.snapshot as Partial<QueueItem['snapshot']>).backendSubmission;
-
- if (
- !workflowRuns ||
- submission?.kind !== 'workflow' ||
- typeof submission.libraryWorkflowId !== 'string' ||
- images.length === 0
- ) {
- return;
- }
-
- try {
- workflowRuns.onWorkflowRunCompleted({
- imageNames: images.map((image) => image.imageName),
- libraryWorkflowId: submission.libraryWorkflowId,
- projectId,
- queueItemId: queueItem.id,
- });
- } catch {
- // The sink owns its own error reporting; the run is already complete.
- }
- };
-
const routeRunResults = async (
coordinator: QueueCoordinator,
projectId: string,
@@ -971,7 +957,6 @@ export const createQueueRuntime = ({
}
commands.routeResults({ images, projectId, queueItemId: queueItem.id });
- notifyWorkflowRunCompleted(projectId, queueItem, images);
if (queueItem.snapshot.destination === 'gallery') {
commands.refreshBackendData();
}
@@ -1242,7 +1227,11 @@ export const createQueueRuntime = ({
const request =
submission.kind === 'generate'
? coordinator.submitGenerate(currentQueueItem.id, submission.request)
- : coordinator.submitWorkflow(currentQueueItem.id, submission.request);
+ : coordinator.submitWorkflow(
+ currentQueueItem.id,
+ submission.request,
+ getQueueRunOrigin(project.id, currentQueueItem)
+ );
submissionOperations.set(runKey, request);
await request
@@ -1559,6 +1548,7 @@ export const createQueueRuntime = ({
backendBatchId: queueItem.backendBatchId,
backendItemIds: queueItem.backendItemIds,
id: queueItem.id,
+ origin: getQueueRunOrigin(project.id, queueItem),
projectId: project.id,
status: queueItem.status === 'running' ? 'running' : 'pending',
}));
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
index 123c192115..5589ec43e0 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
@@ -261,6 +261,7 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Har
completed: vi.fn(),
failed: vi.fn(),
progress: vi.fn(),
+ setOrigin: vi.fn(),
settleRunning: vi.fn(),
started: vi.fn(),
};
@@ -1250,6 +1251,47 @@ describe('queueCoordinator', () => {
expect(harness.nodeExecution.settleRunning).toHaveBeenLastCalledWith(new Set(['node-1']), 'canceled');
});
+ it('names the project workflow a run came from when its nodes start, and forgets it for unattributed runs', async () => {
+ harness.api.enqueueWorkflow
+ .mockResolvedValueOnce({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })
+ .mockResolvedValueOnce({ batchId: 'batch-2', enqueued: 1, itemIds: [2], requested: 1 });
+ harness.coordinator.connect();
+ await harness.coordinator.submitWorkflow('local-1', workflowRequest, {
+ projectId: 'project-1',
+ workflowId: 'wf-a',
+ });
+ await harness.coordinator.submitWorkflow('local-2', { ...workflowRequest, sourceQueueItemId: 'local-2' });
+
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 1 }), invocation_source_id: 'node-1' });
+ expect(harness.nodeExecution.setOrigin).toHaveBeenLastCalledWith({ projectId: 'project-1', workflowId: 'wf-a' });
+
+ // A second copy with the same node id starts: the store is cleared and re-attributed before its state lands.
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 2 }), invocation_source_id: 'node-1' });
+ expect(harness.nodeExecution.clearAll).toHaveBeenCalled();
+ expect(harness.nodeExecution.setOrigin).toHaveBeenLastCalledWith(null);
+ });
+
+ it('attributes reconciled runs from their recorded origin', async () => {
+ harness.api.getItem.mockResolvedValue(
+ createQueueBackendItem({ id: 7, origin: buildQueueItemOrigin('local-7', 'project-1'), status: 'in_progress' })
+ );
+ harness.coordinator.connect();
+ await harness.coordinator.reconcile([
+ {
+ backendBatchId: 'batch-1',
+ backendItemIds: [7],
+ id: 'local-7',
+ origin: { projectId: 'project-1', workflowId: 'wf-b' },
+ projectId: 'project-1',
+ status: 'running',
+ },
+ ]);
+
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 7 }), invocation_source_id: 'node-1' });
+
+ expect(harness.nodeExecution.setOrigin).toHaveBeenLastCalledWith({ projectId: 'project-1', workflowId: 'wf-b' });
+ });
+
it('preserves a root failure when queue status precedes the root invocation error', async () => {
harness.api.enqueueWorkflow.mockResolvedValue({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 });
harness.coordinator.connect();
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
index c23bd59867..36a1d14855 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
@@ -6,6 +6,7 @@ import type {
QueueEnqueueWorkflowRequest,
QueueResultImage,
QueueResultImageOptions,
+ QueueRunOrigin,
TerminalQueueItemStatus,
} from '@features/queue/core/types';
import type { BackendConnectionStatus } from '@platform/transport/types';
@@ -59,7 +60,10 @@ export interface QueueModelLoadPort {
}
export interface QueueNodeExecutionPort {
+ /** Forgets every node and the origin of the run they belonged to. */
clearAll(): void;
+ /** Names the project workflow whose run the store now reflects; null when it cannot be attributed. */
+ setOrigin(origin: QueueRunOrigin | null): void;
completed(event: InvocationCompleteEvent): void;
failed(event: InvocationErrorEvent): void;
progress(nodeId: string, percentage: number | null, message: string): void;
@@ -125,6 +129,7 @@ export interface ReconcileInput {
status: 'pending' | 'running';
backendItemIds?: number[];
backendBatchId?: string;
+ origin?: QueueRunOrigin;
}
export type ReconcileOutcome =
@@ -151,7 +156,11 @@ export interface QueueCoordinator {
/** Enqueue a generate batch and track its backend items for event-driven settlement. */
submitGenerate(localQueueItemId: string, request: QueueEnqueueGenerateRequest): Promise<QueueEnqueueResult>;
/** Enqueue a compiled workflow graph and track its backend items the same way. */
- submitWorkflow(localQueueItemId: string, request: QueueEnqueueWorkflowRequest): Promise<QueueEnqueueResult>;
+ submitWorkflow(
+ localQueueItemId: string,
+ request: QueueEnqueueWorkflowRequest,
+ origin?: QueueRunOrigin
+ ): Promise<QueueEnqueueResult>;
/**
* Await every backend item's terminal state via sockets and safety sweeps; return images or throw
* failure/cancellation.
@@ -182,6 +191,7 @@ interface RunProgressState {
interface WaitState {
frameGates: Map<number, { revision: number | null; sessionId: string }>;
localQueueItemId: string;
+ origin: QueueRunOrigin | null;
settle: (outcome: TerminalOutcome) => void;
}
@@ -383,6 +393,7 @@ export const createQueueCoordinator = (
nodeExecutionRootItemId = backendItemId;
nodeExecutionRootItemSequence = sequence;
nodeExecution.clearAll();
+ nodeExecution.setOrigin(waits.get(backendItemId)?.origin ?? null);
}
const nodeIds = nodeIdsByBackendItem.get(backendItemId);
@@ -602,7 +613,11 @@ export const createQueueCoordinator = (
const isTrackedEvent = (event: { item_id: number; root_item_id?: number | null }): boolean =>
waits.has(getTrackedBackendItemId(event));
- const trackBackendItem = (localQueueItemId: string, backendItemId: number): Promise<TerminalOutcome> => {
+ const trackBackendItem = (
+ localQueueItemId: string,
+ backendItemId: number,
+ origin: QueueRunOrigin | null
+ ): Promise<TerminalOutcome> => {
const bufferedOutcome = recentTerminalOutcomes.get(backendItemId);
if (bufferedOutcome) {
@@ -615,13 +630,18 @@ export const createQueueCoordinator = (
}
return new Promise<TerminalOutcome>((settle) => {
- waits.set(backendItemId, { frameGates: new Map(), localQueueItemId, settle });
+ waits.set(backendItemId, { frameGates: new Map(), localQueueItemId, origin, settle });
replayNodeEvents(backendItemId);
replayProgressEvent(backendItemId);
});
};
- const beginRun = (localQueueItemId: string, backendItemIds: number[], backendBatchId?: string): void => {
+ const beginRun = (
+ localQueueItemId: string,
+ backendItemIds: number[],
+ backendBatchId?: string,
+ origin: QueueRunOrigin | null = null
+ ): void => {
if (!isActive()) {
throw new QueueItemCancelledError(localQueueItemId);
}
@@ -636,7 +656,7 @@ export const createQueueCoordinator = (
runs.set(localQueueItemId, {
backendBatchId,
backendItemIds,
- outcomePromises: backendItemIds.map((backendItemId) => trackBackendItem(localQueueItemId, backendItemId)),
+ outcomePromises: backendItemIds.map((backendItemId) => trackBackendItem(localQueueItemId, backendItemId, origin)),
});
publishRunProgress(localQueueItemId);
@@ -1060,7 +1080,7 @@ export const createQueueCoordinator = (
const backendItemIds = foundBackendItems.map((backendItem) => backendItem.id);
const backendBatchId = item.backendBatchId ?? foundBackendItems[0]?.batchId;
- beginRun(item.id, backendItemIds, backendBatchId);
+ beginRun(item.id, backendItemIds, backendBatchId, item.origin ?? null);
for (const backendItem of foundBackendItems) {
settleFromQueueItem(backendItem);
@@ -1092,13 +1112,14 @@ export const createQueueCoordinator = (
const adoptEnqueueResult = (
localQueueItemId: string,
result: QueueEnqueueResult,
- workKind: 'generation' | 'workflow'
+ workKind: 'generation' | 'workflow',
+ origin: QueueRunOrigin | null = null
): QueueEnqueueResult => {
if (result.enqueued === 0) {
throw new QueueEnqueueNotAcceptedError(workKind);
}
- beginRun(localQueueItemId, result.itemIds, result.batchId);
+ beginRun(localQueueItemId, result.itemIds, result.batchId, origin);
return result;
};
@@ -1118,14 +1139,15 @@ export const createQueueCoordinator = (
const submitWorkflow = async (
localQueueItemId: string,
- request: QueueEnqueueWorkflowRequest
+ request: QueueEnqueueWorkflowRequest,
+ origin?: QueueRunOrigin
): Promise<QueueEnqueueResult> => {
if (!isActive()) {
throw new QueueItemCancelledError(localQueueItemId);
}
return await withSubmissionInFlight(async () =>
- adoptEnqueueResult(localQueueItemId, await backend.enqueueWorkflow(request), 'workflow')
+ adoptEnqueueResult(localQueueItemId, await backend.enqueueWorkflow(request), 'workflow', origin ?? null)
);
};
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts
index 9be01df8fb..2555c05c9e 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts
@@ -53,6 +53,7 @@ describe('Upscale snapshot submission', () => {
state = workbenchReducer(state, {
backendSupportsCancellation: true,
models: MODELS,
+ projectId: state.activeProjectId,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'upscale', sourceLocked: false },
type: 'submitResolvedInvocationSnapshot',
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
index 6198aa8724..39a84b79e4 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
@@ -11,7 +11,6 @@ import {
getProjectGraphUndoEntry,
getUpdatableNodeIds,
isFieldExposed,
- normalizeProjectGraph,
projectGraphReducer,
updateWorkflowNodes,
} from './document';
@@ -333,23 +332,6 @@ describe('projectGraphReducer', () => {
});
});
-describe('normalizeProjectGraph', () => {
- it('passes through current documents', () => {
- const doc = createProjectGraph('keep-me');
-
- expect(normalizeProjectGraph(doc)).toBe(doc);
- });
-
- it('replaces the Phase-1 placeholder graph with an empty document, preserving the id', () => {
- const normalized = normalizeProjectGraph({ edges: [], id: 'legacy-id', label: 'Old', nodes: [], version: 1 });
-
- expect(normalized.version).toBe(2);
- expect(normalized.id).toBe('legacy-id');
- expect(normalized.nodes).toEqual([]);
- expect(normalized.form.elements[normalized.form.rootElementId]?.type).toBe('container');
- });
-});
-
describe('seed modes', () => {
it('stores a mode on the instance and clears it again for fixed, the absent default', () => {
const { doc, nodeAId } = createDocWithNodes();
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.ts
index 30bb2d1882..aef2d8eeb2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts
@@ -66,16 +66,125 @@ export const createProjectGraph = (id: string, name = 'Untitled Workflow'): Proj
export const cloneProjectGraph = (document: ProjectGraphState): ProjectGraphState => structuredClone(document);
-/** Accepts any persisted `projectGraph` shape and yields a current document, preserving the id. */
-export const normalizeProjectGraph = (candidate: unknown): ProjectGraphState => {
- if (typeof candidate === 'object' && candidate !== null && (candidate as ProjectGraphState).version === 2) {
- return candidate as ProjectGraphState;
+const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;
+
+const isNodeLike = (value: unknown): boolean =>
+ isRecord(value) &&
+ typeof value.id === 'string' &&
+ typeof value.type === 'string' &&
+ isRecord(value.position) &&
+ typeof value.position.x === 'number' &&
+ typeof value.position.y === 'number' &&
+ isRecord(value.data) &&
+ (value.type !== 'invocation' || (typeof value.data.type === 'string' && isRecord(value.data.inputs)));
+
+const isFormElementLike = (value: unknown): boolean => {
+ if (!isRecord(value) || typeof value.id !== 'string' || typeof value.type !== 'string') {
+ return false;
}
- const legacyId =
- typeof (candidate as { id?: unknown } | null)?.id === 'string' ? (candidate as { id: string }).id : null;
+ const data = value.data;
- return createProjectGraph(legacyId ?? createWorkflowId('workflow'));
+ switch (value.type) {
+ case 'container':
+ return (
+ isRecord(data) &&
+ (data.layout === 'row' || data.layout === 'column') &&
+ Array.isArray(data.children) &&
+ data.children.every((child) => typeof child === 'string')
+ );
+ case 'node-field':
+ return (
+ isRecord(data) &&
+ isRecord(data.fieldIdentifier) &&
+ typeof data.fieldIdentifier.nodeId === 'string' &&
+ typeof data.fieldIdentifier.fieldName === 'string'
+ );
+ case 'heading':
+ case 'text':
+ return isRecord(data) && typeof data.content === 'string';
+ case 'divider':
+ return true;
+ default:
+ return false;
+ }
+};
+
+const isEdgeLike = (value: unknown): boolean =>
+ isRecord(value) &&
+ typeof value.id === 'string' &&
+ typeof value.source === 'string' &&
+ typeof value.target === 'string';
+
+const isFormLike = (value: unknown): boolean =>
+ isRecord(value) &&
+ typeof value.rootElementId === 'string' &&
+ isRecord(value.elements) &&
+ isRecord(value.elements[value.rootElementId]) &&
+ (value.elements[value.rootElementId] as Record<string, unknown>).type === 'container' &&
+ Object.values(value.elements).every(isFormElementLike);
+
+const METADATA_KEYS = ['author', 'contact', 'description', 'name', 'notes', 'tags', 'workflowVersion'] as const;
+
+/**
+ * Reads a persisted version-2 document. Authored content (nodes, edges, form) must carry the structure the editor
+ * and the linear form read, or the document is refused (`null`), never quietly replaced; missing metadata strings
+ * are the only thing filled in.
+ */
+export const readPersistedProjectGraph = (candidate: unknown): ProjectGraphState | null => {
+ if (
+ !isRecord(candidate) ||
+ candidate.version !== 2 ||
+ typeof candidate.id !== 'string' ||
+ candidate.id.length === 0 ||
+ !Array.isArray(candidate.nodes) ||
+ !candidate.nodes.every(isNodeLike) ||
+ !Array.isArray(candidate.edges) ||
+ !candidate.edges.every(isEdgeLike) ||
+ !isFormLike(candidate.form)
+ ) {
+ return null;
+ }
+
+ if (METADATA_KEYS.every((key) => typeof candidate[key] === 'string') && typeof candidate.updatedAt === 'string') {
+ return candidate as unknown as ProjectGraphState;
+ }
+
+ const filled: Record<string, unknown> = { ...candidate };
+
+ for (const key of METADATA_KEYS) {
+ if (typeof filled[key] !== 'string') {
+ filled[key] = key === 'workflowVersion' ? '1.0.0' : '';
+ }
+ }
+
+ if (typeof filled.updatedAt !== 'string') {
+ filled.updatedAt = now();
+ }
+
+ return filled as unknown as ProjectGraphState;
+};
+
+/**
+ * The only pre-version-2 shape ever persisted was the Phase-1 placeholder: no nodes, nothing authored. It becomes a
+ * blank under its own id; any other unrecognised graph is refused (`null`) rather than replaced.
+ */
+export const readLegacyPlaceholderGraph = (candidate: unknown): ProjectGraphState | null => {
+ if (!isRecord(candidate)) {
+ return createProjectGraph(createWorkflowId('workflow'));
+ }
+
+ const hasAuthoredContent = Array.isArray(candidate.nodes)
+ ? candidate.nodes.length > 0
+ : candidate.nodes !== undefined;
+
+ if ((candidate.version !== undefined && candidate.version !== 1) || hasAuthoredContent) {
+ return null;
+ }
+
+ return createProjectGraph(
+ typeof candidate.id === 'string' && candidate.id ? candidate.id : createWorkflowId('workflow')
+ );
};
export const buildInvocationNode = (template: InvocationTemplate, position: XYPosition): WorkflowInvocationNode => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/types.ts b/invokeai/frontend/webv2/src/features/workflow/core/types.ts
index c117687f2f..1de6749022 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/types.ts
@@ -250,16 +250,40 @@ export interface WorkflowMetadata {
/** The project-owned workflow document. `version: 2` distinguishes it from the Phase-1 placeholder graph. */
export interface ProjectGraphState extends WorkflowMetadata {
+ /** Identifies this project copy; a library template id never becomes a document id. */
id: string;
version: 2;
- /** Backend workflow-library binding when the document was loaded from or saved to the library. */
- libraryWorkflowId?: string;
nodes: WorkflowNode[];
edges: WorkflowEdge[];
form: WorkflowForm;
updatedAt: string;
}
+/**
+ * The library template a project workflow was opened from or last explicitly saved to. Kept beside the document,
+ * outside its edit history, so undoing an edit never undoes a save or restores an obsolete write target.
+ */
+export interface ProjectWorkflowSource {
+ libraryWorkflowId: string;
+ /** The template content revision loaded or last written; null when unknown (documents migrated from older schemas). */
+ revision: number | null;
+}
+
+/** The newest successful run's final output, owned by the project workflow that submitted it. */
+export interface ProjectWorkflowRunPreview {
+ imageName: string;
+ /** Submission instant; a newer submission wins over an older run that finishes later. */
+ submittedAt: string;
+ completedAt: string;
+}
+
+/** One workflow a project owns: its editable document plus metadata that is not part of graph editing. */
+export interface ProjectWorkflowEntry {
+ document: ProjectGraphState;
+ source?: ProjectWorkflowSource;
+ lastRun?: ProjectWorkflowRunPreview;
+}
+
export interface InvocationTemplatesSnapshot {
status: 'idle' | 'loading' | 'loaded' | 'error';
error: string | null;
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts
index f537ea3fbd..ccf0d56642 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts
@@ -407,7 +407,6 @@ export const parseWorkflowJson = (raw: unknown): ParsedWorkflow => {
edges,
form: parseForm(parsed.data.form, parsed.data.exposedFields, nodeIds, warnings),
id: createWorkflowId('workflow'),
- libraryWorkflowId: parsed.data.id,
name: parsed.data.name,
nodes,
notes: parsed.data.notes,
@@ -431,8 +430,14 @@ const serializeInvocationNode = (node: Extract<WorkflowNode, { type: 'invocation
};
};
-/** Serializes the document to legacy WorkflowV3 JSON (loadable by the v6 editor and the library backend). */
-export const serializeWorkflowJson = (document: ProjectGraphState): Record<string, unknown> => ({
+/**
+ * Serializes the document to legacy WorkflowV3 JSON (loadable by the v6 editor and the library backend). The JSON
+ * carries a library record id only when the caller names one: a portable file or a new template has none.
+ */
+export const serializeWorkflowJson = (
+ document: ProjectGraphState,
+ options: { libraryWorkflowId?: string } = {}
+): Record<string, unknown> => ({
author: document.author,
contact: document.contact,
description: document.description,
@@ -442,7 +447,7 @@ export const serializeWorkflowJson = (document: ProjectGraphState): Record<strin
elements: structuredClone(document.form.elements),
rootElementId: document.form.rootElementId,
},
- ...(document.libraryWorkflowId ? { id: document.libraryWorkflowId } : {}),
+ ...(options.libraryWorkflowId ? { id: options.libraryWorkflowId } : {}),
meta: { category: 'user', version: '3.0.0' },
name: document.name,
nodes: document.nodes.map((node) =>
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index 1582c3283e..08e8b2672f 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -27,6 +27,7 @@ import { areArraysEqual, createStableSelector } from '@platform/state/selectors'
import { compileContributingLayers } from '@workbench/canvas-engine/api';
import { getBlockingControlLayerIssues } from './controlLayerChecks';
+import { getActiveProjectGraph } from './projectWorkflows';
import { getProjectWidgetValues } from './widgetState';
export interface InvocationSourceMeta {
@@ -136,7 +137,7 @@ export const getInvocationRouteInput = (project: Project): InvocationRouteInput
workflowValues: getProjectWidgetValues(project, 'workflow'),
invocation: project.invocation,
mountedWidgetIds: getMountedWidgetIds(project),
- projectGraph: project.projectGraph,
+ projectGraph: getActiveProjectGraph(project),
projectId: project.id,
});
@@ -182,8 +183,18 @@ export const resolveInvocationRoute = (
project: Project,
mode: InvocationMode = 'global',
route: InvocationRoute = project.invocation,
- models?: readonly ModelConfig[]
-): ResolvedInvocationRoute => resolveInvocationRouteInput(getInvocationRouteInput(project), mode, route, models);
+ models?: readonly ModelConfig[],
+ /** Validate a specific project workflow (a captured submission target) instead of the active one. */
+ workflowDocument?: ProjectGraphState
+): ResolvedInvocationRoute =>
+ resolveInvocationRouteInput(
+ workflowDocument
+ ? { ...getInvocationRouteInput(project), projectGraph: workflowDocument }
+ : getInvocationRouteInput(project),
+ mode,
+ route,
+ models
+ );
export const resolveInvocationRouteInput = (
input: InvocationRouteInput,
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
index 45f5d28ef8..eda50180dd 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
@@ -125,7 +125,7 @@ const buildProject = () => {
state = workbenchReducer(state, {
action: { node: invocationNode('gen', 'string_generator', { generator: generatorValue }), type: 'addNode' },
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
state = workbenchReducer(state, {
action: {
@@ -133,7 +133,7 @@ const buildProject = () => {
node: invocationNode('batch', 'string_batch', { batch_group_id: 'None' }),
type: 'addNodeAndEdge',
},
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
state = workbenchReducer(state, {
action: {
@@ -141,7 +141,7 @@ const buildProject = () => {
node: invocationNode('prompt', 'string', { value: 'static' }),
type: 'addNodeAndEdge',
},
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
return getActiveProject(state);
@@ -207,6 +207,51 @@ describe('submitResolvedInvocation with a workflow generator', () => {
});
});
+ it('carries the captured project and workflow through generator resolution to the dispatch', async () => {
+ generatorsMock.resolveWorkflowGenerators.mockImplementation(
+ (_client: unknown, pending: Array<{ key: string; nodeId: string }>) =>
+ Promise.resolve({
+ errors: [],
+ resolutions: Object.fromEntries(pending.map((item) => [item.nodeId, { items: ['a cat'], key: item.key }])),
+ })
+ );
+ const project = buildProject();
+ const workflowId = project.workflows.activeWorkflowId;
+ const commands = createWorkbenchStore().commands;
+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
+
+ await submitResolvedInvocation({
+ commands,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation: vi.fn(),
+ project,
+ route: resolveInvocationRoute(project, 'global', workflowRoute),
+ workflowId,
+ });
+
+ expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({ projectId: project.id, workflowId });
+ });
+
+ it('queues nothing for a workflow the captured project no longer owns', async () => {
+ const project = buildProject();
+ const commands = createWorkbenchStore().commands;
+ const submitResolved = vi.spyOn(commands.generation, 'submitResolved');
+
+ await submitResolvedInvocation({
+ commands,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation: vi.fn(),
+ project,
+ route: resolveInvocationRoute(project, 'global', workflowRoute),
+ workflowId: 'removed',
+ });
+
+ expect(generatorsMock.resolveWorkflowGenerators).not.toHaveBeenCalled();
+ expect(submitResolved).not.toHaveBeenCalled();
+ });
+
it('reports a generator that failed to resolve and queues nothing', async () => {
generatorsMock.resolveWorkflowGenerators.mockResolvedValue({
errors: ['string_generator: Unbalanced braces'],
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
index 2f59fe509e..4ea9ebd753 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.ts
@@ -6,6 +6,7 @@
import type { GenerateSettings } from '@features/generation/contracts';
import type { ParseDynamicPromptsResponse } from '@features/generation/prompts';
import type { ModelConfig } from '@features/models';
+import type { ProjectGraphState } from '@features/workflow/contracts';
import type { WorkflowGeneratorResolutions, WorkflowPendingGenerator } from '@features/workflow/utility';
import type { AccountScope } from '@platform/state/accountLifecycle';
import type { ResolvedInvocationRoute } from '@workbench/invocationContracts';
@@ -27,6 +28,7 @@ import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';
import type { WorkbenchCommands } from './workbenchStore';
+import { getActiveProjectWorkflow } from './projectWorkflows';
import { readCanvasCompositingSettings } from './widgets/canvas/invoke/canvasCompositing';
import { readCanvasDenoisingStrength } from './widgets/canvas/invoke/canvasStrength';
import { getProjectWidgetValues } from './widgetState';
@@ -43,6 +45,11 @@ export interface SubmitResolvedInvocationDeps {
project: Project;
/** Loaded models (or `undefined` while loading), forwarded verbatim to both paths. */
models: readonly ModelConfig[] | undefined;
+ /**
+ * The project workflow a workflow route submits. Captured with the project snapshot so a switch during
+ * generator resolution never submits another workflow; defaults to the snapshot's active workflow.
+ */
+ workflowId?: string;
/** Identity lifetime that initiated this submission. */
owner: AccountScope;
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
@@ -92,15 +99,23 @@ const resolveExpandedPrompts = async (settings: GenerateSettings): Promise<Parse
}
};
+const getSubmittedWorkflowDocument = (project: Project, workflowId: string | undefined): ProjectGraphState | null =>
+ workflowId
+ ? (project.workflows.entries.find((entry) => entry.document.id === workflowId)?.document ?? null)
+ : getActiveProjectWorkflow(project).document;
+
/** The async generators (dynamic prompts, board listings) a workflow submission still has to resolve. */
-const getPendingWorkflowGenerators = (project: Project, route: ResolvedInvocationRoute): WorkflowPendingGenerator[] => {
+const getPendingWorkflowGenerators = (
+ document: ProjectGraphState | null,
+ route: ResolvedInvocationRoute
+): WorkflowPendingGenerator[] => {
const templatesSnapshot = getInvocationTemplatesSnapshot();
- if (route.sourceId !== 'workflow' || templatesSnapshot.status !== 'loaded') {
+ if (!document || route.sourceId !== 'workflow' || templatesSnapshot.status !== 'loaded') {
return [];
}
- return planWorkflowBatch(project.projectGraph, templatesSnapshot.templates).pendingGenerators;
+ return planWorkflowBatch(document, templatesSnapshot.templates).pendingGenerators;
};
/**
@@ -109,6 +124,7 @@ const getPendingWorkflowGenerators = (project: Project, route: ResolvedInvocatio
*/
const resolveWorkflowGeneratorsForRoute = async (
project: Project,
+ document: ProjectGraphState,
pending: readonly WorkflowPendingGenerator[],
owner: AccountScope,
commands: Pick<WorkbenchCommands, 'notifications'>
@@ -133,7 +149,7 @@ const resolveWorkflowGeneratorsForRoute = async (
}
// Sizes were unknown until now: an empty board or a mismatched group only shows once the lists exist.
- const resolvedPlan = planWorkflowBatch(project.projectGraph, templatesSnapshot.templates, {
+ const resolvedPlan = planWorkflowBatch(document, templatesSnapshot.templates, {
generators: resolutions,
});
@@ -161,17 +177,30 @@ export const submitResolvedInvocation = async ({
prepareCanvasInvocation,
project,
route,
+ workflowId,
}: SubmitResolvedInvocationDeps): Promise<void> => {
if (!isAccountScopeCurrent(owner)) {
return;
}
+ const workflowDocument = route.sourceId === 'workflow' ? getSubmittedWorkflowDocument(project, workflowId) : null;
+
+ if (route.sourceId === 'workflow' && !workflowDocument) {
+ return;
+ }
+
// Only a workflow with unresolved generators needs this round trip; every other route dispatches synchronously.
- const pendingGenerators = getPendingWorkflowGenerators(project, route);
+ const pendingGenerators = getPendingWorkflowGenerators(workflowDocument, route);
let workflowGenerators: WorkflowGeneratorResolutions | undefined;
- if (pendingGenerators.length > 0) {
- const resolved = await resolveWorkflowGeneratorsForRoute(project, pendingGenerators, owner, commands);
+ if (pendingGenerators.length > 0 && workflowDocument) {
+ const resolved = await resolveWorkflowGeneratorsForRoute(
+ project,
+ workflowDocument,
+ pendingGenerators,
+ owner,
+ commands
+ );
if (resolved === null) {
return;
@@ -201,17 +230,19 @@ export const submitResolvedInvocation = async ({
}
await dispatchResolvedInvocation(
- { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },
+ { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route, workflowId },
expansion.prompts.length > 0 ? expansion.prompts : undefined,
- workflowGenerators
+ workflowGenerators,
+ workflowDocument?.id
);
return;
}
await dispatchResolvedInvocation(
- { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route },
+ { commands, formatControlLayerError, models, owner, prepareCanvasInvocation, project, route, workflowId },
undefined,
- workflowGenerators
+ workflowGenerators,
+ workflowDocument?.id
);
};
@@ -226,7 +257,8 @@ const dispatchResolvedInvocation = async (
route,
}: SubmitResolvedInvocationDeps,
positivePrompts: string[] | undefined,
- workflowGenerators: WorkflowGeneratorResolutions | undefined
+ workflowGenerators: WorkflowGeneratorResolutions | undefined,
+ workflowId: string | undefined
): Promise<void> => {
if (route.sourceId === 'canvas') {
// Await Canvas preparation to retain the submission guard until completion; pass the resolved destination so
@@ -252,7 +284,9 @@ const dispatchResolvedInvocation = async (
backendSupportsCancellation: true,
models,
positivePrompts,
+ projectId: project.id,
route,
...(workflowGenerators ? { workflowGenerators } : {}),
+ ...(workflowId ? { workflowId } : {}),
});
};
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
index d649d2ac64..00f7d82100 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.test.ts
@@ -101,6 +101,7 @@ const createAggregate = (initialState = createInitialWorkbenchState()) => {
reportLoadUnavailable: (error) => events.push(`load-unavailable:${error}`),
saveFailed: (error) => events.push(`save-failed:${error}`),
savePending: (error) => events.push(`save-pending:${error}`),
+ saveScheduled: () => events.push('save-scheduled'),
saveStarted: () => events.push('save-started'),
saveSucceeded: (savedAt) => events.push(`save-succeeded:${savedAt}`),
setHasHydrated: (next) => {
@@ -265,6 +266,44 @@ describe('Workbench persistence runtime', () => {
);
});
+ it('reports edits as pending from the moment they happen until their own save is acknowledged', async () => {
+ const aggregate = createAggregate();
+ const { persistence } = createPersistence(() => Promise.resolve(null));
+ const first = deferred<WorkbenchSaveResult>();
+ const second = deferred<WorkbenchSaveResult>();
+ vi.mocked(persistence.saveWorkbench)
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise);
+ const clock = new FakeClock();
+ const runtime = createWorkbenchPersistenceRuntime({ aggregate: aggregate.port, clock, persistence });
+
+ runtime.start();
+ await flushPromises();
+ aggregate.events.length = 0;
+
+ // Before the debounce fires, the edit is already reported, so nothing can claim it was saved.
+ aggregate.edit('First');
+ await flushPromises();
+ expect(aggregate.events).toEqual(['save-scheduled']);
+ expect(persistence.saveWorkbench).not.toHaveBeenCalled();
+
+ clock.runAll();
+ expect(aggregate.events).toEqual(['save-scheduled', 'save-started']);
+
+ // An edit made while the save runs makes that save's answer stale: nothing reports "saved" until the edit's
+ // own save is acknowledged.
+ aggregate.edit('Second');
+ await flushPromises();
+ first.resolve(saveResult(aggregate.state, 'first'));
+ await flushPromises();
+ expect(aggregate.events).toEqual(['save-scheduled', 'save-started']);
+
+ clock.runAll();
+ second.resolve(saveResult(aggregate.state, 'second'));
+ await flushPromises();
+ expect(aggregate.events).toEqual(['save-scheduled', 'save-started', 'save-started', 'save-succeeded:second']);
+ });
+
it('debounces edits and ignores stale completions after a newer revision', async () => {
const aggregate = createAggregate();
const { persistence } = createPersistence(() => Promise.resolve(null));
diff --git a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
index 66b2b89704..ac763910ee 100644
--- a/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistenceRuntime.ts
@@ -19,6 +19,8 @@ export interface PersistenceAggregatePort {
reportRefusedProjects(refused: readonly RefusedWorkbenchProject[]): void;
saveFailed(error: string): void;
savePending(error: string): void;
+ /** Persisted content changed and its save is scheduled: the workbench is dirty until that save is acknowledged. */
+ saveScheduled(): void;
saveStarted(): void;
saveSucceeded(savedAt: string): void;
setHasHydrated(hasHydrated: boolean): void;
@@ -239,6 +241,12 @@ export const createWorkbenchPersistenceRuntime = ({
generation += 1;
clearScheduledSave();
timeoutId = clock.setTimeout(() => save(false), saveDelayMs);
+ // Reported outside the aggregate's own notification, as a status change is itself an aggregate change.
+ queueMicrotask(() => {
+ if (!disposed && scheduledRevision === revision && !isSaveInFlight) {
+ aggregate.saveScheduled();
+ }
+ });
};
const onAggregateChange = (): void => {
diff --git a/invokeai/frontend/webv2/src/workbench/projectContracts.ts b/invokeai/frontend/webv2/src/workbench/projectContracts.ts
index a4dfba0617..1dd05fe0f4 100644
--- a/invokeai/frontend/webv2/src/workbench/projectContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/projectContracts.ts
@@ -1,4 +1,3 @@
-import type { ProjectGraphState } from '@features/workflow/contracts';
import type { BackendConnectionStatus } from '@platform/transport/types';
import type { CanvasStateContractV3 } from './canvas-engine/api';
@@ -17,6 +16,7 @@ import type {
WidgetRegionState,
} from './layoutContracts';
import type { ProjectEvent } from './projectEventContracts';
+import type { ProjectWorkflowCollection, ProjectWorkflowHistories } from './projectWorkflows';
import type { WorkbenchQueueState } from './queueHistoryContracts';
import type { ProjectSettings } from './settings/contracts';
import type { WidgetFailure, WidgetInstanceContract, WidgetInstanceId, WidgetTypeId } from './widgetContracts';
@@ -29,8 +29,10 @@ export interface Project {
settings: ProjectSettings;
layout: ProjectLayoutState;
invocation: InvocationControllerState;
- /** The one active project graph: an editable workflow document, compiled to a `GraphContract` at invoke time. */
- projectGraph: ProjectGraphState;
+ /** The project's workflows and which one is active; the active document compiles to a `GraphContract` at invoke time. */
+ workflows: ProjectWorkflowCollection;
+ /** Session-only graph edit histories by workflow id; never persisted. */
+ workflowHistories: ProjectWorkflowHistories;
widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;
widgetRegions: Record<WidgetRegion, WidgetRegionState>;
/** Floating instances leave their region's instanceIds; absent in older projects means no floating windows. */
@@ -43,13 +45,13 @@ export interface Project {
events: ProjectEvent[];
}
-/** A persisted project the canvas version gate refused. `raw` is the untouched document, kept for recovery. */
-export interface ProjectDocumentLoadRefusal {
- raw: unknown;
- scope: 'project-document';
- status: 'unsupported-version';
- version: number;
-}
+/**
+ * A persisted project document that was not loaded: written by a newer version, or structurally damaged. `raw` is
+ * the untouched document, kept for recovery; nothing is written back over it.
+ */
+export type ProjectDocumentLoadRefusal =
+ | { raw: unknown; scope: 'project-document'; status: 'unsupported-version'; version: number }
+ | { raw: unknown; scope: 'project-document'; status: 'malformed'; reason: string };
interface RefusedWorkbenchProjectBase {
projectId: string;
@@ -123,11 +125,10 @@ export interface UndoRedoEntry {
mergedAt?: string;
}
-/** Project undo preserves the live canvas; the engine owns pixel history. */
+/** Project undo preserves the live canvas and workflow documents; the engine and workflow histories own those. */
export interface ProjectUndoSnapshot {
layout: ProjectLayoutState;
invocation: InvocationControllerState;
- projectGraph: ProjectGraphState;
widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;
widgetRegions: Record<WidgetRegion, WidgetRegionState>;
/** Captured with widgetRegions: regions and floating windows are one placement fact. */
@@ -141,7 +142,8 @@ export interface UndoRedoHistory {
}
export interface AutosaveState {
- status: 'idle' | 'saving' | 'saved' | 'error';
+ /** `pending`: persisted content changed since the last acknowledged save and its save has not started yet. */
+ status: 'idle' | 'pending' | 'saving' | 'saved' | 'error';
lastSavedAt?: string;
error?: string;
}
diff --git a/invokeai/frontend/webv2/src/workbench/projectWorkflows.test.ts b/invokeai/frontend/webv2/src/workbench/projectWorkflows.test.ts
new file mode 100644
index 0000000000..847236e91a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projectWorkflows.test.ts
@@ -0,0 +1,392 @@
+import type { InvocationTemplate, ProjectGraphState } from '@features/workflow/contracts';
+
+import { buildInvocationNode, createProjectGraph } from '@features/workflow/utility';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ addProjectWorkflow,
+ applyProjectWorkflowAction,
+ createProjectWorkflowCollection,
+ duplicateProjectWorkflow,
+ getActiveProjectGraph,
+ isPlaceholderProjectWorkflow,
+ migrateProjectGraphToCollection,
+ normalizeProjectWorkflowCollection,
+ recordProjectWorkflowRun,
+ redoProjectWorkflow,
+ removeProjectWorkflow,
+ selectProjectWorkflow,
+ setProjectWorkflowSource,
+ stripProjectWorkflowSources,
+ undoProjectWorkflow,
+ WORKFLOW_HISTORY_LIMIT,
+ type ProjectWorkflowSession,
+} from './projectWorkflows';
+
+const template: InvocationTemplate = {
+ category: 'test',
+ classification: 'stable',
+ description: '',
+ inputs: {},
+ nodePack: 'invokeai',
+ outputs: {},
+ outputType: 'noise_output',
+ tags: [],
+ title: 'Noise',
+ type: 'noise',
+ useCache: true,
+ version: '1.0.0',
+};
+
+const session = (...documents: ProjectGraphState[]): ProjectWorkflowSession => ({
+ workflowHistories: {},
+ workflows: { activeWorkflowId: documents[0]!.id, entries: documents.map((document) => ({ document })) },
+});
+
+const ids = (project: ProjectWorkflowSession) => project.workflows.entries.map((entry) => entry.document.id);
+
+const addNode = (project: ProjectWorkflowSession, workflowId: string, nodeId = `node-${Math.random()}`) =>
+ applyProjectWorkflowAction(project, workflowId, {
+ node: { ...buildInvocationNode(template, { x: 0, y: 0 }), id: nodeId },
+ type: 'addNode',
+ }).project;
+
+describe('project workflow collection', () => {
+ it('keeps a blank that was edited and undone: its history is authored work', () => {
+ let project = session(createProjectGraph('blank'));
+
+ project = addNode(project, 'blank', 'n1');
+ project = applyProjectWorkflowAction(project, 'blank', { nodeIds: ['n1'], type: 'removeNodes' }).project;
+ expect(getActiveProjectGraph(project).nodes).toEqual([]);
+
+ const next = addProjectWorkflow(project, createProjectGraph('template'), { reusePlaceholder: true });
+
+ expect(ids(next)).toEqual(['blank', 'template']);
+ expect(next.workflowHistories.blank?.past).toHaveLength(2);
+ });
+
+ it('opens a template over the untouched blank a project starts with, but never over authored work', () => {
+ const blank = createProjectGraph('blank');
+ const template1 = createProjectGraph('template-1', 'Template');
+ const opened = addProjectWorkflow(session(blank), template1, {
+ reusePlaceholder: true,
+ source: { libraryWorkflowId: 'lib-1', revision: 3 },
+ });
+
+ expect(ids(opened)).toEqual(['template-1']);
+ expect(opened.workflows.activeWorkflowId).toBe('template-1');
+ expect(opened.workflows.entries[0]?.source).toEqual({ libraryWorkflowId: 'lib-1', revision: 3 });
+
+ const authored = addNode(session(blank), 'blank');
+ const beside = addProjectWorkflow(authored, template1, { reusePlaceholder: true });
+
+ expect(ids(beside)).toEqual(['blank', 'template-1']);
+
+ const renamed = applyProjectWorkflowAction(session(blank), 'blank', {
+ patch: { name: 'Mine' },
+ type: 'setMetadata',
+ }).project;
+
+ expect(isPlaceholderProjectWorkflow(renamed.workflows.entries[0]!)).toBe(false);
+ expect(ids(addProjectWorkflow(renamed, template1, { reusePlaceholder: true }))).toEqual(['blank', 'template-1']);
+ });
+
+ it('refuses a document id the project already owns', () => {
+ const project = session(createProjectGraph('a'));
+
+ expect(() => addProjectWorkflow(project, createProjectGraph('a'))).toThrow(/already owns/);
+ });
+
+ it('selects a neighbour on removal and leaves a fresh blank when the last workflow goes', () => {
+ let project = session(createProjectGraph('a'), createProjectGraph('b'), createProjectGraph('c'));
+
+ project = selectProjectWorkflow(project, 'b');
+ project = addNode(project, 'b');
+ expect(project.workflowHistories.b?.past).toHaveLength(1);
+
+ project = removeProjectWorkflow(project, 'b');
+ expect(ids(project)).toEqual(['a', 'c']);
+ expect(project.workflows.activeWorkflowId).toBe('c');
+ expect(project.workflowHistories.b).toBeUndefined();
+
+ project = removeProjectWorkflow(project, 'c');
+ expect(project.workflows.activeWorkflowId).toBe('a');
+
+ project = removeProjectWorkflow(project, 'a');
+ expect(project.workflows.entries).toHaveLength(1);
+ expect(project.workflows.entries[0]?.document.nodes).toEqual([]);
+ expect(project.workflows.activeWorkflowId).toBe(project.workflows.entries[0]?.document.id);
+ expect(project.workflows.entries[0]?.document.id).not.toBe('a');
+ });
+
+ it('removing an inactive workflow keeps the active selection', () => {
+ const project = removeProjectWorkflow(session(createProjectGraph('a'), createProjectGraph('b')), 'b');
+
+ expect(project.workflows.activeWorkflowId).toBe('a');
+ });
+
+ it('duplicates under a fresh id, beside the original, carrying the source but not the run preview', () => {
+ let project = session(createProjectGraph('a', 'Original'), createProjectGraph('b'));
+
+ project = setProjectWorkflowSource(project, 'a', { libraryWorkflowId: 'lib-1', revision: 2 });
+ project = recordProjectWorkflowRun(project, 'a', { completedAt: 't', imageName: 'out.png', submittedAt: 't' });
+ project = duplicateProjectWorkflow(project, 'a', 'copy', (name) => `${name} copy`);
+
+ expect(ids(project)).toEqual(['a', 'copy', 'b']);
+ expect(project.workflows.activeWorkflowId).toBe('copy');
+ expect(project.workflows.entries[1]).toMatchObject({
+ document: { name: 'Original copy' },
+ source: { libraryWorkflowId: 'lib-1', revision: 2 },
+ });
+ expect(project.workflows.entries[1]?.lastRun).toBeUndefined();
+ });
+
+ it('records the newest submitted successful run, not the run that finishes last', () => {
+ let project = session(createProjectGraph('a'), createProjectGraph('b'));
+
+ project = recordProjectWorkflowRun(project, 'a', {
+ completedAt: '2026-01-01T00:00:10.000Z',
+ imageName: 'newer.png',
+ submittedAt: '2026-01-01T00:00:02.000Z',
+ });
+ project = recordProjectWorkflowRun(project, 'a', {
+ completedAt: '2026-01-01T00:00:12.000Z',
+ imageName: 'older.png',
+ submittedAt: '2026-01-01T00:00:01.000Z',
+ });
+
+ expect(project.workflows.entries[0]?.lastRun?.imageName).toBe('newer.png');
+ expect(project.workflows.entries[1]?.lastRun).toBeUndefined();
+ expect(recordProjectWorkflowRun(project, 'missing', { completedAt: 't', imageName: 'x', submittedAt: 't' })).toBe(
+ project
+ );
+ });
+});
+
+describe('per-workflow edit history', () => {
+ it('keeps each workflow its own history and shares structure instead of cloning', () => {
+ let project = session(createProjectGraph('a'), createProjectGraph('b'));
+ const untouched = project.workflows.entries[1];
+ const before = getActiveProjectGraph(project);
+
+ project = addNode(project, 'a', 'n1');
+
+ expect(project.workflows.entries[1]).toBe(untouched);
+ expect(project.workflowHistories.a?.past[0]?.document).toBe(before);
+ expect(project.workflowHistories.b).toBeUndefined();
+
+ project = undoProjectWorkflow(project, 'a');
+ expect(getActiveProjectGraph(project)).toBe(before);
+ expect(project.workflowHistories.a?.future).toHaveLength(1);
+
+ project = redoProjectWorkflow(project, 'a');
+ expect(getActiveProjectGraph(project).nodes.map((node) => node.id)).toEqual(['n1']);
+ expect(undoProjectWorkflow(project, 'b')).toBe(project);
+ });
+
+ it('undoing an edit leaves the source and run metadata where they were', () => {
+ let project = session(createProjectGraph('a'));
+
+ project = addNode(project, 'a', 'n1');
+ project = setProjectWorkflowSource(project, 'a', { libraryWorkflowId: 'lib-1', revision: 5 });
+ project = undoProjectWorkflow(project, 'a');
+
+ expect(project.workflows.entries[0]).toMatchObject({
+ document: { nodes: [] },
+ source: { libraryWorkflowId: 'lib-1', revision: 5 },
+ });
+ });
+
+ it('folds a stream of same-key edits into one step and separates them after a pause', () => {
+ vi.useFakeTimers({ now: new Date('2026-06-10T00:00:00.000Z') });
+
+ try {
+ let project = addNode(session(createProjectGraph('a')), 'a', 'n1');
+ const type = (value: string) =>
+ applyProjectWorkflowAction(project, 'a', { patch: { notes: value }, type: 'setMetadata' }).project;
+
+ project = type('h');
+ project = type('he');
+ project = type('hel');
+ expect(project.workflowHistories.a?.past).toHaveLength(2);
+
+ vi.advanceTimersByTime(2000);
+ project = type('hell');
+ expect(project.workflowHistories.a?.past).toHaveLength(3);
+
+ project = undoProjectWorkflow(project, 'a');
+ expect(getActiveProjectGraph(project).notes).toBe('hel');
+ project = undoProjectWorkflow(project, 'a');
+ expect(getActiveProjectGraph(project).notes).toBe('');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('evicts the oldest entries across workflows once the project holds forty', () => {
+ let project = session(createProjectGraph('a'), createProjectGraph('b'));
+
+ for (let index = 0; index < 30; index += 1) {
+ project = addNode(project, 'a', `a-${index}`);
+ }
+ for (let index = 0; index < 15; index += 1) {
+ project = addNode(project, 'b', `b-${index}`);
+ }
+
+ const total = Object.values(project.workflowHistories).reduce((count, history) => count + history.past.length, 0);
+
+ expect(total).toBe(WORKFLOW_HISTORY_LIMIT);
+ // The five oldest steps belonged to `a`; `b`'s newer steps are all still there.
+ expect(project.workflowHistories.a?.past).toHaveLength(25);
+ expect(project.workflowHistories.b?.past).toHaveLength(15);
+ });
+
+ it('counts redo entries against the same budget and lets the oldest of them go first', () => {
+ let project = session(createProjectGraph('a'), createProjectGraph('b'));
+
+ for (let index = 0; index < 20; index += 1) {
+ project = addNode(project, 'a', `a-${index}`);
+ }
+ for (let index = 0; index < 20; index += 1) {
+ project = undoProjectWorkflow(project, 'a');
+ }
+
+ expect(project.workflowHistories.a).toMatchObject({ future: expect.any(Array), past: [] });
+ expect(project.workflowHistories.a?.future).toHaveLength(20);
+
+ for (let index = 0; index < 25; index += 1) {
+ project = addNode(project, 'b', `b-${index}`);
+ }
+
+ const total = Object.values(project.workflowHistories).reduce(
+ (count, history) => count + history.past.length + history.future.length,
+ 0
+ );
+
+ expect(total).toBe(WORKFLOW_HISTORY_LIMIT);
+ // The redo entries were created before any of b's steps, so five of them went; the nearest redo survives.
+ expect(project.workflowHistories.a?.future).toHaveLength(15);
+ expect(project.workflowHistories.b?.past).toHaveLength(25);
+ expect(getActiveProjectGraph(redoProjectWorkflow(project, 'a')).nodes.map((node) => node.id)).toEqual(['a-0']);
+ });
+});
+
+describe('persisted collections', () => {
+ it('migrates a single graph into the first, active workflow and turns a binding into an unknown-revision source', () => {
+ const graph = { ...createProjectGraph('legacy'), libraryWorkflowId: 'lib-9' };
+ const collection = migrateProjectGraphToCollection(graph)!;
+
+ expect(collection.activeWorkflowId).toBe('legacy');
+ expect(collection.entries[0]?.source).toEqual({ libraryWorkflowId: 'lib-9', revision: null });
+ expect('libraryWorkflowId' in collection.entries[0]!.document).toBe(false);
+ expect(migrateProjectGraphToCollection(undefined)?.entries[0]?.source).toBeUndefined();
+ });
+
+ it('refuses a damaged or unsupported legacy graph instead of replacing it, but blanks the Phase-1 placeholder', () => {
+ const authored = createProjectGraph('legacy');
+
+ expect(migrateProjectGraphToCollection({ ...authored, nodes: undefined })).toBeNull();
+ expect(migrateProjectGraphToCollection({ ...authored, form: { elements: {} } })).toBeNull();
+ // An authored graph from a newer client is not this build's to rewrite.
+ expect(migrateProjectGraphToCollection({ ...authored, version: 99 })).toBeNull();
+ expect(migrateProjectGraphToCollection({ id: 'old', nodes: [{ id: 'n1' }], version: 1 })).toBeNull();
+ // The placeholder never held content: it becomes a blank under its own id.
+ const placeholder = migrateProjectGraphToCollection({ edges: [], id: 'phase-1', nodes: [], version: 1 });
+
+ expect(placeholder?.entries[0]?.document).toMatchObject({ id: 'phase-1', nodes: [], version: 2 });
+ expect(migrateProjectGraphToCollection({ id: 'phase-1' })?.entries[0]?.document.id).toBe('phase-1');
+ });
+
+ it('refuses a collection whose authored document is damaged, never a blank in its place', () => {
+ const good = createProjectWorkflowCollection(createProjectGraph('a'));
+ const [entry] = good.entries;
+ const damaged = (document: Record<string, unknown>) =>
+ normalizeProjectWorkflowCollection({ ...good, entries: [{ ...entry, document }] });
+
+ // An unsupported document version is authored content this build cannot read.
+ expect(damaged({ ...entry!.document, version: 99 })).toBeNull();
+ expect(damaged({ ...entry!.document, nodes: undefined })).toBeNull();
+ expect(damaged({ ...entry!.document, nodes: [{ id: 'n1' }] })).toBeNull();
+ expect(damaged({ ...entry!.document, form: undefined })).toBeNull();
+ expect(damaged({ ...entry!.document, form: { elements: {}, rootElementId: 'missing' } })).toBeNull();
+ // The structures the editor and the linear form read must be there, not just ids and types.
+ const root = entry!.document.form.rootElementId;
+
+ expect(
+ damaged({
+ ...entry!.document,
+ form: { elements: { [root]: { id: root, type: 'container' } }, rootElementId: root },
+ })
+ ).toBeNull();
+ expect(
+ damaged({
+ ...entry!.document,
+ form: {
+ elements: {
+ [root]: { data: { children: ['f'], layout: 'column' }, id: root, type: 'container' },
+ f: { data: {}, id: 'f', type: 'node-field' },
+ },
+ rootElementId: root,
+ },
+ })
+ ).toBeNull();
+ expect(
+ damaged({
+ ...entry!.document,
+ form: { elements: { [root]: { data: { content: 'x' }, id: root, type: 'heading' } }, rootElementId: root },
+ })
+ ).toBeNull();
+ expect(
+ damaged({
+ ...entry!.document,
+ nodes: [{ data: { label: 'no inputs' }, id: 'n1', position: { x: 0, y: 0 }, type: 'invocation' }],
+ })
+ ).toBeNull();
+ // Missing metadata strings are filled in; the authored graph is kept as it is.
+ const { description: _description, ...withoutDescription } = entry!.document;
+ const filled = damaged(withoutDescription);
+
+ expect(filled?.entries[0]?.document.description).toBe('');
+ expect(filled?.entries[0]?.document.nodes).toBe(entry!.document.nodes);
+ });
+
+ it('accepts a well-formed collection and refuses one that would lose a workflow', () => {
+ const good = createProjectWorkflowCollection(createProjectGraph('a'));
+
+ expect(normalizeProjectWorkflowCollection(good)).toEqual(good);
+ expect(normalizeProjectWorkflowCollection({ ...good, activeWorkflowId: 'missing' })).toBeNull();
+ expect(normalizeProjectWorkflowCollection({ activeWorkflowId: 'a', entries: [] })).toBeNull();
+ expect(
+ normalizeProjectWorkflowCollection({ ...good, entries: [...good.entries, { document: { id: 'a' } }] })
+ ).toBeNull();
+ expect(normalizeProjectWorkflowCollection({ ...good, entries: [{ document: null }] })).toBeNull();
+ expect(
+ normalizeProjectWorkflowCollection({ ...good, entries: [{ ...good.entries[0], source: { revision: 1 } }] })
+ ).toBeNull();
+ // A run preview is decoration: a damaged one is dropped, never the project.
+ expect(
+ normalizeProjectWorkflowCollection({
+ ...good,
+ entries: [{ ...good.entries[0], lastRun: { imageName: 'a.png', submittedAt: 'now' } }],
+ })?.entries[0]
+ ).toEqual({ document: good.entries[0]!.document });
+ expect(
+ normalizeProjectWorkflowCollection({
+ ...good,
+ entries: [{ ...good.entries[0], source: { libraryWorkflowId: 'lib', revision: 'x' } }],
+ })?.entries[0]?.source
+ ).toEqual({ libraryWorkflowId: 'lib', revision: null });
+ });
+
+ it('strips write provenance for portable documents', () => {
+ const collection = createProjectWorkflowCollection(createProjectGraph('a'));
+
+ expect(stripProjectWorkflowSources(collection)).toBe(collection);
+ expect(
+ stripProjectWorkflowSources({
+ ...collection,
+ entries: [{ ...collection.entries[0]!, source: { libraryWorkflowId: 'lib', revision: 1 } }],
+ }).entries[0]
+ ).toEqual({ document: collection.entries[0]!.document });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/projectWorkflows.ts b/invokeai/frontend/webv2/src/workbench/projectWorkflows.ts
new file mode 100644
index 0000000000..9d4ecf12b0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/projectWorkflows.ts
@@ -0,0 +1,625 @@
+/**
+ * The project's workflow collection and its session edit histories. Documents are edited through structural
+ * sharing so an inactive workflow keeps its identity while another is edited, and histories keep previous document
+ * references rather than deep copies.
+ */
+
+import type {
+ ProjectGraphState,
+ ProjectWorkflowEntry,
+ ProjectWorkflowRunPreview,
+ ProjectWorkflowSource,
+} from '@features/workflow/contracts';
+import type { ProjectGraphAction } from '@features/workflow/utility';
+
+import {
+ createProjectGraph,
+ createWorkflowId,
+ getProjectGraphUndoEntry,
+ projectGraphReducer,
+ readLegacyPlaceholderGraph,
+ readPersistedProjectGraph,
+} from '@features/workflow/utility';
+
+export interface ProjectWorkflowCollection {
+ activeWorkflowId: string;
+ entries: ProjectWorkflowEntry[];
+}
+
+export interface WorkflowHistoryEntry {
+ id: string;
+ createdAt: string;
+ label: string;
+ /** The document as it was before the edit; the reference the collection held, never a clone. */
+ document: ProjectGraphState;
+ /** Edits that arrive as a stream (typing, dragging) share a key so they fold into one step. */
+ mergeKey?: string;
+ /** When the entry last absorbed a same-key edit; the merge window runs from here. */
+ mergedAt?: string;
+ /** Global order across the project's histories; the aggregate cap evicts the lowest first. */
+ sequence: number;
+}
+
+export interface WorkflowEditHistory {
+ past: WorkflowHistoryEntry[];
+ future: WorkflowHistoryEntry[];
+}
+
+export type ProjectWorkflowHistories = Record<string, WorkflowEditHistory>;
+
+/** Session-only state the project carries beside its persisted collection. */
+export interface ProjectWorkflowSession {
+ workflows: ProjectWorkflowCollection;
+ workflowHistories: ProjectWorkflowHistories;
+}
+
+/** One project keeps at most this many undo entries across all of its workflows. */
+export const WORKFLOW_HISTORY_LIMIT = 40;
+/** A pause this long between same-key edits (typing, dragging) starts a new undo step. */
+export const WORKFLOW_UNDO_MERGE_WINDOW_MS = 1500;
+
+const EMPTY_HISTORY: WorkflowEditHistory = { future: [], past: [] };
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+export const createBlankWorkflowDocument = (): ProjectGraphState => createProjectGraph(createWorkflowId('workflow'));
+
+export const createProjectWorkflowCollection = (document: ProjectGraphState): ProjectWorkflowCollection => ({
+ activeWorkflowId: document.id,
+ entries: [{ document }],
+});
+
+export const findProjectWorkflow = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string
+): ProjectWorkflowEntry | undefined => project.workflows.entries.find((entry) => entry.document.id === workflowId);
+
+export const getActiveProjectWorkflow = <Session extends ProjectWorkflowSession>(
+ project: Session
+): ProjectWorkflowEntry => {
+ const active = findProjectWorkflow(project, project.workflows.activeWorkflowId) ?? project.workflows.entries[0];
+
+ if (!active) {
+ throw new Error('A project always owns at least one workflow.');
+ }
+
+ return active;
+};
+
+/** The one active-workflow read: callers that need the editable graph go through here, never a second field. */
+export const getActiveProjectGraph = <Session extends ProjectWorkflowSession>(project: Session): ProjectGraphState =>
+ getActiveProjectWorkflow(project).document;
+
+export const getProjectWorkflowHistory = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string
+): WorkflowEditHistory => project.workflowHistories[workflowId] ?? EMPTY_HISTORY;
+
+// #region Persistence shapes
+
+const normalizeSource = (candidate: unknown): ProjectWorkflowSource | null | undefined => {
+ if (candidate === undefined) {
+ return undefined;
+ }
+
+ if (!isRecord(candidate) || typeof candidate.libraryWorkflowId !== 'string' || !candidate.libraryWorkflowId) {
+ return null;
+ }
+
+ const revision = candidate.revision;
+
+ return {
+ libraryWorkflowId: candidate.libraryWorkflowId,
+ revision: Number.isSafeInteger(revision) && (revision as number) > 0 ? (revision as number) : null,
+ };
+};
+
+/** A run preview is decoration: a damaged one is dropped rather than costing the project. */
+const normalizeRunPreview = (candidate: unknown): ProjectWorkflowRunPreview | undefined => {
+ if (
+ !isRecord(candidate) ||
+ typeof candidate.imageName !== 'string' ||
+ !candidate.imageName ||
+ typeof candidate.submittedAt !== 'string' ||
+ typeof candidate.completedAt !== 'string'
+ ) {
+ return undefined;
+ }
+
+ return { completedAt: candidate.completedAt, imageName: candidate.imageName, submittedAt: candidate.submittedAt };
+};
+
+/**
+ * Validates a persisted collection. Anything that would silently lose a workflow (a malformed entry, a repeated id,
+ * an active id naming nothing) is refused rather than repaired.
+ */
+export const normalizeProjectWorkflowCollection = (candidate: unknown): ProjectWorkflowCollection | null => {
+ if (!isRecord(candidate) || typeof candidate.activeWorkflowId !== 'string' || !Array.isArray(candidate.entries)) {
+ return null;
+ }
+
+ if (candidate.entries.length === 0) {
+ return null;
+ }
+
+ const entries: ProjectWorkflowEntry[] = [];
+ const ids = new Set<string>();
+
+ for (const raw of candidate.entries) {
+ if (!isRecord(raw)) {
+ return null;
+ }
+
+ // Authored content is refused when damaged, never replaced with a blank the user did not write.
+ const document = readPersistedProjectGraph(raw.document);
+
+ if (!document || ids.has(document.id)) {
+ return null;
+ }
+
+ ids.add(document.id);
+
+ const source = normalizeSource(raw.source);
+ const lastRun = normalizeRunPreview(raw.lastRun);
+
+ if (source === null) {
+ return null;
+ }
+
+ entries.push({ document, ...(source ? { source } : {}), ...(lastRun ? { lastRun } : {}) });
+ }
+
+ if (!ids.has(candidate.activeWorkflowId)) {
+ return null;
+ }
+
+ return { activeWorkflowId: candidate.activeWorkflowId, entries };
+};
+
+/**
+ * A schema-2 document owned one graph. It becomes the first, active workflow; a library binding becomes source
+ * metadata with an unknown revision, because nothing proves the old graph still matches the library's contents.
+ */
+/**
+ * A legacy single graph becomes the first, active workflow. Only the Phase-1 placeholder (no authored content) is
+ * converted into a blank; a damaged version-2 graph or any other unrecognised graph is refused (`null`).
+ */
+export const migrateProjectGraphToCollection = (projectGraph: unknown): ProjectWorkflowCollection | null => {
+ const graph = isRecord(projectGraph) ? projectGraph : {};
+ const { libraryWorkflowId, ...rest } = graph;
+ const document = rest.version === 2 ? readPersistedProjectGraph(rest) : readLegacyPlaceholderGraph(rest);
+
+ if (!document) {
+ return null;
+ }
+ const source =
+ typeof libraryWorkflowId === 'string' && libraryWorkflowId.length > 0
+ ? { libraryWorkflowId, revision: null }
+ : undefined;
+
+ return { activeWorkflowId: document.id, entries: [{ document, ...(source ? { source } : {}) }] };
+};
+
+/** Portable documents carry no library write target: an archive or file never inherits one from embedded ids. */
+export const stripProjectWorkflowSources = (collection: ProjectWorkflowCollection): ProjectWorkflowCollection =>
+ collection.entries.some((entry) => entry.source)
+ ? {
+ ...collection,
+ entries: collection.entries.map((entry) => {
+ const { source: _source, ...rest } = entry;
+
+ return rest;
+ }),
+ }
+ : collection;
+
+// #endregion
+
+// #region Collection edits
+
+const replaceEntry = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ update: (entry: ProjectWorkflowEntry) => ProjectWorkflowEntry
+): Session => {
+ const index = project.workflows.entries.findIndex((entry) => entry.document.id === workflowId);
+
+ if (index === -1) {
+ return project;
+ }
+
+ const entry = project.workflows.entries[index]!;
+ const nextEntry = update(entry);
+
+ if (nextEntry === entry) {
+ return project;
+ }
+
+ const entries = project.workflows.entries.slice();
+
+ entries[index] = nextEntry;
+
+ return { ...project, workflows: { ...project.workflows, entries } };
+};
+
+/** A workflow nobody has authored into: the blank a fresh project starts with. Opening a template may take it over. */
+export const isPlaceholderProjectWorkflow = (entry: ProjectWorkflowEntry): boolean => {
+ const { document } = entry;
+ const root = document.form.elements[document.form.rootElementId];
+
+ return (
+ entry.source === undefined &&
+ entry.lastRun === undefined &&
+ document.nodes.length === 0 &&
+ document.edges.length === 0 &&
+ document.description === '' &&
+ document.notes === '' &&
+ document.tags === '' &&
+ document.author === '' &&
+ document.contact === '' &&
+ (document.name === '' || document.name === 'Untitled Workflow') &&
+ Object.keys(document.form.elements).length === 1 &&
+ root?.type === 'container' &&
+ root.data.children.length === 0
+ );
+};
+
+export interface AddProjectWorkflowOptions {
+ source?: ProjectWorkflowSource;
+ /** Take over the active workflow when it is an untouched placeholder instead of adding beside it. */
+ reusePlaceholder?: boolean;
+}
+
+/** Adds and activates a workflow. The document id is the project copy's identity and must be new to the project. */
+export const addProjectWorkflow = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ document: ProjectGraphState,
+ options: AddProjectWorkflowOptions = {}
+): Session => {
+ if (findProjectWorkflow(project, document.id)) {
+ throw new Error(`The project already owns workflow ${document.id}.`);
+ }
+
+ const entry: ProjectWorkflowEntry = { document, ...(options.source ? { source: options.source } : {}) };
+ const active = getActiveProjectWorkflow(project);
+ const activeHistory = project.workflowHistories[active.document.id];
+ // A blank that was edited and undone back to blank still has authored history worth keeping.
+ const isUntouchedPlaceholder =
+ isPlaceholderProjectWorkflow(active) &&
+ (activeHistory === undefined || (activeHistory.past.length === 0 && activeHistory.future.length === 0));
+
+ if (options.reusePlaceholder && isUntouchedPlaceholder) {
+ const { [active.document.id]: _released, ...workflowHistories } = project.workflowHistories;
+
+ return {
+ ...project,
+ workflowHistories,
+ workflows: {
+ activeWorkflowId: document.id,
+ entries: project.workflows.entries.map((candidate) => (candidate === active ? entry : candidate)),
+ },
+ };
+ }
+
+ return {
+ ...project,
+ workflows: { activeWorkflowId: document.id, entries: [...project.workflows.entries, entry] },
+ };
+};
+
+export const selectProjectWorkflow = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string
+): Session =>
+ project.workflows.activeWorkflowId === workflowId || !findProjectWorkflow(project, workflowId)
+ ? project
+ : { ...project, workflows: { ...project.workflows, activeWorkflowId: workflowId } };
+
+/** Copies a workflow under a fresh document id. Node ids may repeat: editor and execution state are scoped by workflow. */
+export const duplicateProjectWorkflow = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ copyId: string,
+ copyName: (name: string) => string
+): Session => {
+ const entry = findProjectWorkflow(project, workflowId);
+
+ if (!entry) {
+ return project;
+ }
+
+ const index = project.workflows.entries.indexOf(entry);
+ const document: ProjectGraphState = structuredClone({
+ ...entry.document,
+ id: copyId,
+ name: copyName(entry.document.name),
+ updatedAt: new Date().toISOString(),
+ });
+ const copy: ProjectWorkflowEntry = { document, ...(entry.source ? { source: entry.source } : {}) };
+ const entries = project.workflows.entries.slice();
+
+ entries.splice(index + 1, 0, copy);
+
+ return { ...project, workflows: { activeWorkflowId: copyId, entries } };
+};
+
+/**
+ * Removes a workflow and releases its history. Selection moves to the next neighbour, or the previous one for the
+ * last entry; removing the only workflow leaves a fresh blank in its place.
+ */
+export const removeProjectWorkflow = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string
+): Session => {
+ const index = project.workflows.entries.findIndex((entry) => entry.document.id === workflowId);
+
+ if (index === -1) {
+ return project;
+ }
+
+ const { [workflowId]: _released, ...workflowHistories } = project.workflowHistories;
+ const remaining = project.workflows.entries.filter((entry) => entry.document.id !== workflowId);
+
+ if (remaining.length === 0) {
+ const blank = createBlankWorkflowDocument();
+
+ return { ...project, workflowHistories, workflows: createProjectWorkflowCollection(blank) };
+ }
+
+ const activeWorkflowId =
+ project.workflows.activeWorkflowId === workflowId
+ ? (remaining[Math.min(index, remaining.length - 1)]?.document.id ?? remaining[0]!.document.id)
+ : project.workflows.activeWorkflowId;
+
+ return { ...project, workflowHistories, workflows: { activeWorkflowId, entries: remaining } };
+};
+
+export const setProjectWorkflowSource = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ source: ProjectWorkflowSource | undefined
+): Session =>
+ replaceEntry(project, workflowId, (entry) => {
+ if (entry.source?.libraryWorkflowId === source?.libraryWorkflowId && entry.source?.revision === source?.revision) {
+ return entry;
+ }
+
+ const { source: _previous, ...rest } = entry;
+
+ return source ? { ...rest, source } : rest;
+ });
+
+/** Records a successful run's output. An older submission that finishes later never replaces a newer one. */
+export const recordProjectWorkflowRun = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ run: ProjectWorkflowRunPreview
+): Session =>
+ replaceEntry(project, workflowId, (entry) =>
+ entry.lastRun && entry.lastRun.submittedAt > run.submittedAt ? entry : { ...entry, lastRun: run }
+ );
+
+// #endregion
+
+// #region Document edits and history
+
+let nextHistorySequence = 0;
+
+/** Undo and redo entries share one budget; the entry created longest ago goes first, whichever side it sits on. */
+const evictOldestAcrossHistories = (histories: ProjectWorkflowHistories): ProjectWorkflowHistories => {
+ let total = 0;
+
+ for (const history of Object.values(histories)) {
+ total += history.past.length + history.future.length;
+ }
+
+ if (total <= WORKFLOW_HISTORY_LIMIT) {
+ return histories;
+ }
+
+ let next = histories;
+
+ while (total > WORKFLOW_HISTORY_LIMIT) {
+ let oldestId: string | null = null;
+ let oldestSide: 'future' | 'past' = 'past';
+ let oldestSequence = Number.POSITIVE_INFINITY;
+
+ for (const [workflowId, history] of Object.entries(next)) {
+ const first = history.past[0];
+ const deepest = history.future.at(-1);
+
+ if (first && first.sequence < oldestSequence) {
+ oldestSequence = first.sequence;
+ oldestId = workflowId;
+ oldestSide = 'past';
+ }
+
+ if (deepest && deepest.sequence < oldestSequence) {
+ oldestSequence = deepest.sequence;
+ oldestId = workflowId;
+ oldestSide = 'future';
+ }
+ }
+
+ if (oldestId === null) {
+ break;
+ }
+
+ const history = next[oldestId]!;
+
+ next = {
+ ...next,
+ [oldestId]:
+ oldestSide === 'past'
+ ? { ...history, past: history.past.slice(1) }
+ : { ...history, future: history.future.slice(0, -1) },
+ };
+ total -= 1;
+ }
+
+ return next;
+};
+
+const pushHistory = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ previous: ProjectGraphState,
+ label: string,
+ mergeKey: string | undefined,
+ timestamp: string
+): Session => {
+ const history = getProjectWorkflowHistory(project, workflowId);
+ const last = history.past.at(-1);
+
+ // An undo in between (`future` non-empty) ends the burst: the state the user just stood on must stay reachable as
+ // its own step.
+ if (
+ mergeKey &&
+ last?.mergeKey === mergeKey &&
+ history.future.length === 0 &&
+ Date.parse(timestamp) - Date.parse(last.mergedAt ?? last.createdAt) <= WORKFLOW_UNDO_MERGE_WINDOW_MS
+ ) {
+ return {
+ ...project,
+ workflowHistories: {
+ ...project.workflowHistories,
+ [workflowId]: { future: [], past: [...history.past.slice(0, -1), { ...last, mergedAt: timestamp }] },
+ },
+ };
+ }
+
+ nextHistorySequence += 1;
+
+ const entry: WorkflowHistoryEntry = {
+ createdAt: timestamp,
+ document: previous,
+ id: `undo-${nextHistorySequence.toString(36)}`,
+ label,
+ ...(mergeKey ? { mergeKey } : {}),
+ sequence: nextHistorySequence,
+ };
+
+ return {
+ ...project,
+ workflowHistories: evictOldestAcrossHistories({
+ ...project.workflowHistories,
+ [workflowId]: { future: [], past: [...history.past, entry] },
+ }),
+ };
+};
+
+export interface ApplyWorkflowActionResult<Session> {
+ project: Session;
+ /** True when the reducer produced a new document. */
+ didChange: boolean;
+}
+
+/** Applies a graph action to one workflow, recording an undo step when the action earns one. */
+export const applyProjectWorkflowAction = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ action: ProjectGraphAction,
+ timestamp = new Date().toISOString()
+): ApplyWorkflowActionResult<Session> => {
+ const entry = findProjectWorkflow(project, workflowId);
+
+ if (!entry) {
+ return { didChange: false, project };
+ }
+
+ const document = projectGraphReducer(entry.document, action);
+
+ if (document === entry.document) {
+ return { didChange: false, project };
+ }
+
+ const undoEntry = getProjectGraphUndoEntry(action);
+ const withHistory = undoEntry
+ ? pushHistory(project, workflowId, entry.document, undoEntry.label, undoEntry.mergeKey, timestamp)
+ : project;
+
+ return {
+ didChange: true,
+ project: replaceEntry(withHistory, workflowId, (current) => ({ ...current, document })),
+ };
+};
+
+export const undoProjectWorkflow = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ timestamp = new Date().toISOString()
+): Session => {
+ const entry = findProjectWorkflow(project, workflowId);
+ const history = getProjectWorkflowHistory(project, workflowId);
+ const undone = history.past.at(-1);
+
+ if (!entry || !undone) {
+ return project;
+ }
+
+ nextHistorySequence += 1;
+
+ const redoEntry: WorkflowHistoryEntry = {
+ createdAt: timestamp,
+ document: entry.document,
+ id: `redo-${nextHistorySequence.toString(36)}`,
+ label: undone.label,
+ sequence: nextHistorySequence,
+ };
+ const restored = replaceEntry(project, workflowId, (current) => ({ ...current, document: undone.document }));
+
+ return {
+ ...restored,
+ workflowHistories: {
+ ...restored.workflowHistories,
+ [workflowId]: {
+ future: [redoEntry, ...history.future],
+ past: history.past.slice(0, -1),
+ },
+ },
+ };
+};
+
+export const redoProjectWorkflow = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ timestamp = new Date().toISOString()
+): Session => {
+ const entry = findProjectWorkflow(project, workflowId);
+ const history = getProjectWorkflowHistory(project, workflowId);
+ const redone = history.future[0];
+
+ if (!entry || !redone) {
+ return project;
+ }
+
+ nextHistorySequence += 1;
+
+ const undoEntry: WorkflowHistoryEntry = {
+ createdAt: timestamp,
+ document: entry.document,
+ id: `undo-${nextHistorySequence.toString(36)}`,
+ label: redone.label,
+ sequence: nextHistorySequence,
+ };
+ const restored = replaceEntry(project, workflowId, (current) => ({ ...current, document: redone.document }));
+
+ return {
+ ...restored,
+ workflowHistories: evictOldestAcrossHistories({
+ ...restored.workflowHistories,
+ [workflowId]: { future: history.future.slice(1), past: [...history.past, undoEntry] },
+ }),
+ };
+};
+
+/** Replaces a document without touching history: seed advances and other non-undoable bookkeeping. */
+export const setProjectWorkflowDocument = <Session extends ProjectWorkflowSession>(
+ project: Session,
+ workflowId: string,
+ document: ProjectGraphState
+): Session =>
+ replaceEntry(project, workflowId, (entry) => (entry.document === document ? entry : { ...entry, document }));
+
+// #endregion
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
index 7a8616f8cb..e96acfee4f 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts
@@ -20,7 +20,7 @@ import {
type DurableProjectPersistenceApi,
} from './durableSyncedPersistence';
import { createDeterministicProjectId } from './ids';
-import { serializeProjectDocumentV2 } from './projectDocument';
+import { serializeProjectDocumentV3 } from './projectDocument';
import { acquireProjectMutationLock } from './projectLifecycleLocks';
import { getProjectSyncSnapshot, registerOpenProject, unregisterOpenProject } from './syncStore';
@@ -56,7 +56,7 @@ const stateWith = (projects: Project[]): WorkbenchState => ({
const toRecord = (project: Project, revision = 1): ProjectRecordDTO => ({
board_id: `board-${project.id}`,
created_at: now,
- data: serializeProjectDocumentV2(project),
+ data: serializeProjectDocumentV3(project),
minimum_canvas_schema_version: 3,
name: project.name,
project_id: project.id,
@@ -496,8 +496,8 @@ describe('durable project persistence', () => {
const project = createDraftProject([]);
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2(project)),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3(project)),
+ documentSchemaVersion: 3,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -518,6 +518,42 @@ describe('durable project persistence', () => {
expect(loaded.queueRecovery.projects).toEqual([]);
});
+ it('migrates an older draft on recovery, turning its library binding into an unknown-revision source', async () => {
+ const owner = captureAccountScope();
+ const api = createApi();
+ const draftStore = createMemoryProjectDraftStore();
+ const project = createDraftProject([]);
+ const { workflows: _workflows, ...document } = serializeProjectDocumentV3(project);
+ const graph = project.workflows.entries[0]!.document;
+ await draftStore.stage({
+ baseRevision: 1,
+ documentJson: JSON.stringify({
+ ...document,
+ documentSchemaVersion: 2,
+ projectGraph: { ...graph, libraryWorkflowId: 'lib-1' },
+ }),
+ documentSchemaVersion: 2,
+ editorSessionId: 'older-editor',
+ generation: 1,
+ projectId: project.id,
+ updatedAt: 1,
+ writerToken: 'older-writer',
+ });
+ vi.mocked(api.loadSession).mockResolvedValue({
+ account: createInitialWorkbenchState().account,
+ activeProjectId: '',
+ openProjectIds: [],
+ });
+ listQueueRunProjectIds.mockResolvedValue({ kind: 'available', projectIds: [project.id] });
+
+ const loaded = await createService(owner, api, draftStore).loadWorkbench();
+ const restored = loaded.state.projects.find((candidate) => candidate.id === project.id);
+
+ expect(restored?.workflows.entries.map((entry) => entry.document.id)).toEqual([graph.id]);
+ expect(restored?.workflows.entries[0]?.source).toEqual({ libraryWorkflowId: 'lib-1', revision: null });
+ expect(restored).not.toHaveProperty('projectGraph');
+ });
+
it('reports a journal project that has neither a server record nor a recoverable draft', async () => {
const owner = captureAccountScope();
const api = createApi();
@@ -574,8 +610,8 @@ describe('durable project persistence', () => {
for (const [index, project] of drafts.entries()) {
await draftStore.stage({
baseRevision: null,
- documentJson: JSON.stringify(serializeProjectDocumentV2(project)),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3(project)),
+ documentSchemaVersion: 3,
editorSessionId: `old-${index}`,
generation: 1,
projectId: project.id,
@@ -630,8 +666,8 @@ describe('durable project persistence', () => {
] as const) {
await draftStore.stage({
baseRevision: null,
- documentJson: JSON.stringify(serializeProjectDocumentV2(project)),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3(project)),
+ documentSchemaVersion: 3,
editorSessionId,
generation: 1,
projectId: recovered.id,
@@ -661,8 +697,8 @@ describe('durable project persistence', () => {
const project = createDraftProject([]);
await draftStore.stage({
baseRevision: null,
- documentJson: JSON.stringify(serializeProjectDocumentV2(project)),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3(project)),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -827,8 +863,8 @@ describe('durable project persistence', () => {
expect(stage).toHaveBeenCalledWith(
expect.objectContaining({
baseRevision: null,
- documentJson: JSON.stringify(serializeProjectDocumentV2(project)),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3(project)),
+ documentSchemaVersion: 3,
projectId: project.id,
})
);
@@ -987,8 +1023,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await backingStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -1137,8 +1173,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'other tab edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'other tab edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-2',
generation: 1,
projectId: project.id,
@@ -1159,8 +1195,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project));
await backingStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -1272,7 +1308,7 @@ describe('durable project persistence', () => {
await draftStore.stage({
baseRevision: null,
documentJson: JSON.stringify({ ...request.data, name: 'newer edit' }),
- documentSchemaVersion: 2,
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 2,
projectId: project.id,
@@ -1327,8 +1363,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 4,
projectId: project.id,
@@ -1367,8 +1403,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -1400,12 +1436,12 @@ describe('durable project persistence', () => {
const draftStore = createMemoryProjectDraftStore();
const project = createDraftProject([]);
const futureRecord = toRecord(project, 2);
- futureRecord.data = { ...futureRecord.data, documentSchemaVersion: 3 };
+ futureRecord.data = { ...futureRecord.data, documentSchemaVersion: 4 };
api.records.set(project.id, futureRecord);
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -1428,7 +1464,7 @@ describe('durable project persistence', () => {
expect(api.updateProject).not.toHaveBeenCalled();
await expect(draftStore.get(project.id, 'editor-1')).resolves.toMatchObject({
draft: {
- refusal: { documentSchemaVersion: 3, kind: 'document', maxDocumentSchemaVersion: 2 },
+ refusal: { documentSchemaVersion: 4, kind: 'document', maxDocumentSchemaVersion: 3 },
state: 'schema-refused',
},
kind: 'found',
@@ -1441,11 +1477,11 @@ describe('durable project persistence', () => {
const draftStore = createMemoryProjectDraftStore();
const project = createDraftProject([]);
api.records.set(project.id, toRecord(project));
- const futureDocumentJson = JSON.stringify({ ...serializeProjectDocumentV2(project), documentSchemaVersion: 3 });
+ const futureDocumentJson = JSON.stringify({ ...serializeProjectDocumentV3(project), documentSchemaVersion: 4 });
await draftStore.stage({
baseRevision: 1,
documentJson: futureDocumentJson,
- documentSchemaVersion: 3,
+ documentSchemaVersion: 4,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -1479,11 +1515,11 @@ describe('durable project persistence', () => {
const draftStore = createMemoryProjectDraftStore();
const project = createDraftProject([]);
api.records.set(project.id, toRecord(project));
- const futureDocumentJson = JSON.stringify({ ...serializeProjectDocumentV2(project), documentSchemaVersion: 3 });
+ const futureDocumentJson = JSON.stringify({ ...serializeProjectDocumentV3(project), documentSchemaVersion: 4 });
await draftStore.stage({
baseRevision: 1,
documentJson: futureDocumentJson,
- documentSchemaVersion: 3,
+ documentSchemaVersion: 4,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -1510,11 +1546,11 @@ describe('durable project persistence', () => {
const draftStore = createMemoryProjectDraftStore();
const project = createDraftProject([]);
api.records.set(project.id, toRecord(project));
- const futureDocumentJson = JSON.stringify({ ...serializeProjectDocumentV2(project), documentSchemaVersion: 3 });
+ const futureDocumentJson = JSON.stringify({ ...serializeProjectDocumentV3(project), documentSchemaVersion: 4 });
await draftStore.stage({
baseRevision: 1,
documentJson: futureDocumentJson,
- documentSchemaVersion: 3,
+ documentSchemaVersion: 4,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -1535,7 +1571,7 @@ describe('durable project persistence', () => {
await expect(service.getRecoverableDraftDocument(project.id, 'editor-1')).resolves.toBe(futureDocumentJson);
});
- it('rewrites a loaded legacy project once as a V2 document', async () => {
+ it('rewrites a loaded legacy project once in the current document schema', async () => {
const owner = captureAccountScope();
const api = createApi();
const project = createDraftProject([]);
@@ -1554,7 +1590,7 @@ describe('durable project persistence', () => {
await service.saveWorkbench(loaded.state);
expect(api.updateProject).toHaveBeenCalledOnce();
- expect(vi.mocked(api.updateProject).mock.calls[0]![1].data.documentSchemaVersion).toBe(2);
+ expect(vi.mocked(api.updateProject).mock.calls[0]![1].data.documentSchemaVersion).toBe(3);
});
it.each([
@@ -1568,8 +1604,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project));
await draftStore.stage({
baseRevision: testCase.baseRevision,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -1599,8 +1635,8 @@ describe('durable project persistence', () => {
] as const) {
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name })),
+ documentSchemaVersion: 3,
editorSessionId,
generation: 1,
projectId: project.id,
@@ -1630,8 +1666,8 @@ describe('durable project persistence', () => {
for (let index = 0; index < 34; index += 1) {
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: `offline edit ${index}` })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: `offline edit ${index}` })),
+ documentSchemaVersion: 3,
editorSessionId: `lineage-${index}`,
generation: 1,
projectId: project.id,
@@ -1660,11 +1696,11 @@ describe('durable project persistence', () => {
const draftStore = createMemoryProjectDraftStore();
const project = createDraftProject([]);
api.records.set(project.id, toRecord(project));
- const documentJson = JSON.stringify({ ...serializeProjectDocumentV2(project), documentSchemaVersion: 3 });
+ const documentJson = JSON.stringify({ ...serializeProjectDocumentV3(project), documentSchemaVersion: 3 });
await draftStore.stage({
baseRevision: 1,
documentJson,
- documentSchemaVersion: 3,
+ documentSchemaVersion: 4,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -1687,8 +1723,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project));
await backingStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'unadopted edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'unadopted edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -1719,8 +1755,8 @@ describe('durable project persistence', () => {
const updatedAt = Date.parse(now);
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify({ ...serializeProjectDocumentV2(project), documentSchemaVersion: 3 }),
- documentSchemaVersion: 3,
+ documentJson: JSON.stringify({ ...serializeProjectDocumentV3(project), documentSchemaVersion: 3 }),
+ documentSchemaVersion: 4,
editorSessionId: 'newer-editor',
generation: 1,
projectId: project.id,
@@ -1751,8 +1787,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify({ documentSchemaVersion: 2, id: project.id }),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify({ documentSchemaVersion: 3, id: project.id }),
+ documentSchemaVersion: 3,
editorSessionId: 'broken-editor',
generation: 1,
projectId: project.id,
@@ -1803,8 +1839,8 @@ describe('durable project persistence', () => {
const project = createDraftProject([]);
await draftStore.stage({
baseRevision,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -1832,8 +1868,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project));
await backingStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -1876,8 +1912,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -1959,8 +1995,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await backingStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2023,13 +2059,13 @@ describe('durable project persistence', () => {
await vi.waitFor(() => expect(stage).toHaveBeenCalledOnce());
releaseCreate();
const copy = await resolving;
- expect(copy.project.settings).toEqual(serializeProjectDocumentV2(backgroundEdit).settings);
+ expect(copy.project.settings).toEqual(serializeProjectDocumentV3(backgroundEdit).settings);
expect(copy.project.name).toBe(`${local.name} (copy)`);
await saving;
expect(api.records.get(copy.targetProjectId)?.name).toBe(`${local.name} (copy)`);
expect(api.records.get(copy.targetProjectId)?.data.settings).toEqual(
- serializeProjectDocumentV2(backgroundEdit).settings
+ serializeProjectDocumentV3(backgroundEdit).settings
);
});
@@ -2043,8 +2079,8 @@ describe('durable project persistence', () => {
api.records.set(other.id, toRecord(other));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...source, name: 'click-time edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...source, name: 'click-time edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: source.id,
@@ -2106,7 +2142,7 @@ describe('durable project persistence', () => {
const saving = service.saveWorkbench(stateWith([backgroundEdit]));
await vi.waitFor(async () => {
await expect(draftStore.get(source.id, 'editor-1')).resolves.toMatchObject({
- draft: { documentJson: JSON.stringify(serializeProjectDocumentV2(backgroundEdit)) },
+ draft: { documentJson: JSON.stringify(serializeProjectDocumentV3(backgroundEdit)) },
kind: 'found',
});
});
@@ -2115,7 +2151,7 @@ describe('durable project persistence', () => {
await blocking;
await createStarted;
await expect(draftStore.get(source.id, 'editor-1')).resolves.toMatchObject({
- draft: { documentJson: JSON.stringify(serializeProjectDocumentV2(backgroundEdit)) },
+ draft: { documentJson: JSON.stringify(serializeProjectDocumentV3(backgroundEdit)) },
kind: 'found',
});
releaseCreate();
@@ -2134,8 +2170,8 @@ describe('durable project persistence', () => {
api.records.set(source.id, toRecord(source, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...source, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...source, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: source.id,
@@ -2203,8 +2239,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2252,8 +2288,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await backingStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2322,8 +2358,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2388,8 +2424,8 @@ describe('durable project persistence', () => {
api.records.set(other.id, toRecord(other));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...source, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...source, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: source.id,
@@ -2482,8 +2518,8 @@ describe('durable project persistence', () => {
api.records.set(source.id, toRecord(source, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...source, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...source, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: source.id,
@@ -2545,8 +2581,8 @@ describe('durable project persistence', () => {
api.records.set(source.id, toRecord(source, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...source, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...source, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: source.id,
@@ -2598,11 +2634,11 @@ describe('durable project persistence', () => {
const draftStore = createMemoryProjectDraftStore();
const project = createDraftProject([]);
api.records.set(project.id, toRecord(project, 2));
- const futureDocumentJson = JSON.stringify({ ...serializeProjectDocumentV2(project), documentSchemaVersion: 3 });
+ const futureDocumentJson = JSON.stringify({ ...serializeProjectDocumentV3(project), documentSchemaVersion: 4 });
await draftStore.stage({
baseRevision: 1,
documentJson: futureDocumentJson,
- documentSchemaVersion: 3,
+ documentSchemaVersion: 4,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2611,8 +2647,8 @@ describe('durable project persistence', () => {
});
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'older-editor',
generation: 1,
projectId: project.id,
@@ -2673,8 +2709,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2702,7 +2738,7 @@ describe('durable project persistence', () => {
});
it.each([
- { documentSchemaVersion: 2, kind: 'document' as const, maxDocumentSchemaVersion: 1 },
+ { documentSchemaVersion: 3, kind: 'document' as const, maxDocumentSchemaVersion: 1 },
{ kind: 'invalid-server-document' as const },
])('resumes a loadable $kind refusal after the client or server is corrected', async (refusal) => {
const owner = captureAccountScope();
@@ -2712,8 +2748,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2744,8 +2780,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(project, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2772,8 +2808,8 @@ describe('durable project persistence', () => {
api.records.set(project.id, toRecord(remote, 2));
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'discarded local edit' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'discarded local edit' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2830,8 +2866,8 @@ describe('durable project persistence', () => {
const project = createDraftProject([]);
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name: 'discard me' })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'discard me' })),
+ documentSchemaVersion: 3,
editorSessionId: 'editor-1',
generation: 1,
projectId: project.id,
@@ -2965,8 +3001,8 @@ describe('durable project persistence', () => {
] as const) {
await draftStore.stage({
baseRevision: 1,
- documentJson: JSON.stringify(serializeProjectDocumentV2({ ...project, name })),
- documentSchemaVersion: 2,
+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name })),
+ documentSchemaVersion: 3,
editorSessionId,
generation: 1,
projectId: project.id,
diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
index ade2a6a7b9..5e260334c0 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts
@@ -60,9 +60,10 @@ import { createAccountOwnedProjectDraftStore } from './indexedDbDraftStore';
import { seedProjectLibrary, upsertProjectSummary } from './library';
import { selectCoverImageName } from './projectAssets';
import {
- PROJECT_DOCUMENT_SCHEMA_VERSION,
+ migrateProjectDocument,
PROJECT_DOCUMENT_MAX_BYTES,
- serializeProjectDocumentV2Json,
+ PROJECT_DOCUMENT_SCHEMA_VERSION,
+ serializeProjectDocumentV3Json,
} from './projectDocument';
import { assertProjectFlushed, ProjectFlushError } from './projectFlush';
import { deserializeProjectDocument, deserializeProjectRecord } from './projectHydration';
@@ -287,7 +288,7 @@ const toSnapshot = (state: WorkbenchState, savedAt: string): HydratedWorkbenchSn
const recordDocumentJson = (record: ProjectRecordDTO): string | null => {
const loaded = deserializeProjectRecord(record);
- return loaded.status === 'loaded' ? serializeProjectDocumentV2Json(loaded.project).documentJson : null;
+ return loaded.status === 'loaded' ? serializeProjectDocumentV3Json(loaded.project).documentJson : null;
};
const toProjectSummary = (record: ProjectRecordDTO): ProjectSummaryDTO => ({
@@ -832,7 +833,7 @@ export const createDurableSyncedWorkbenchPersistence = (
const createProjectSavePlan = (inputProject: Project) => {
const project = resolveInputProject(inputProject);
- const serialized = serializeProjectDocumentV2Json(project);
+ const serialized = serializeProjectDocumentV3Json(project);
const entry = syncEntries.get(project.id);
const existingDraft = volatileDrafts.get(project.id);
const needsDocumentUpgrade = projectsRequiringDocumentUpgrade.has(project.id);
@@ -850,7 +851,7 @@ export const createDurableSyncedWorkbenchPersistence = (
const stageProject = async (
project: Project,
- serialized: ReturnType<typeof serializeProjectDocumentV2Json> = serializeProjectDocumentV2Json(project)
+ serialized: ReturnType<typeof serializeProjectDocumentV3Json> = serializeProjectDocumentV3Json(project)
) => {
const store = await getDraftStore();
const session = await getEditorSessionForService();
@@ -1455,7 +1456,7 @@ export const createDurableSyncedWorkbenchPersistence = (
project: Project,
store: ProjectDraftStore
): Promise<ProjectDraft> => {
- const serialized = serializeProjectDocumentV2Json(project);
+ const serialized = serializeProjectDocumentV3Json(project);
if (draft.documentJson === serialized.documentJson) {
clearLocalDraftFailure(projectDraftFailureKey(project.id));
volatileDrafts.set(project.id, draft);
@@ -1600,9 +1601,13 @@ export const createDurableSyncedWorkbenchPersistence = (
const localProject = withAuthoritativeProjectBoard(loadedDraft.project, record.board_id);
loadedDraft.draft = await alignLoadedDraftWithProject(loadedDraft.draft, localProject, store);
const refusal: ProjectSchemaRefusal =
- result.status === 'refused' && result.refused.source === 'project-document'
+ result.status === 'refused' &&
+ result.refused.source === 'project-document' &&
+ result.refused.refusal.status === 'unsupported-version'
? toDocumentSchemaRefusal(result.refused.refusal.version)
- : result.status === 'refused' && result.refused.refusal.status === 'unsupported-version'
+ : result.status === 'refused' &&
+ result.refused.source === 'canvas' &&
+ result.refused.refusal.status === 'unsupported-version'
? toCanvasSchemaRefusal({
maxCanvasSchemaVersion: MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,
minimumCanvasSchemaVersion: result.refused.refusal.version,
@@ -1623,7 +1628,7 @@ export const createDurableSyncedWorkbenchPersistence = (
return { project: localProject, status: 'loaded' };
}
- const serverJson = serializeProjectDocumentV2Json(result.project).documentJson;
+ const serverJson = serializeProjectDocumentV3Json(result.project).documentJson;
syncEntries.set(projectId, {
minimumCanvasSchemaVersion: record.minimum_canvas_schema_version,
pushedDoc: serverJson,
@@ -1703,7 +1708,7 @@ export const createDurableSyncedWorkbenchPersistence = (
if (result.status === 'loaded') {
syncEntries.set(record.project_id, {
minimumCanvasSchemaVersion: record.minimum_canvas_schema_version,
- pushedDoc: serializeProjectDocumentV2Json(result.project).documentJson,
+ pushedDoc: serializeProjectDocumentV3Json(result.project).documentJson,
revision: record.revision,
});
conflicts.delete(record.project_id);
@@ -2213,9 +2218,11 @@ export const createDurableSyncedWorkbenchPersistence = (
const localProject = withAuthoritativeProjectBoard(loadedDraft.project, record.board_id);
loadedDraft.draft = await alignLoadedDraftWithProject(loadedDraft.draft, localProject, store);
const refusal: ProjectSchemaRefusal =
- serverLoad.refused.source === 'project-document'
+ serverLoad.refused.source === 'project-document' &&
+ serverLoad.refused.refusal.status === 'unsupported-version'
? toDocumentSchemaRefusal(serverLoad.refused.refusal.version)
- : serverLoad.refused.refusal.status === 'unsupported-version'
+ : serverLoad.refused.source === 'canvas' &&
+ serverLoad.refused.refusal.status === 'unsupported-version'
? toCanvasSchemaRefusal({
maxCanvasSchemaVersion: MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,
minimumCanvasSchemaVersion: serverLoad.refused.refusal.version,
@@ -2239,7 +2246,7 @@ export const createDurableSyncedWorkbenchPersistence = (
if (serverLoad.status !== 'loaded') {
return;
}
- const serverJson = serializeProjectDocumentV2Json(serverLoad.project).documentJson;
+ const serverJson = serializeProjectDocumentV3Json(serverLoad.project).documentJson;
syncEntries.set(projectId, {
minimumCanvasSchemaVersion: record.minimum_canvas_schema_version,
pushedDoc: serverJson,
@@ -2485,7 +2492,7 @@ export const createDurableSyncedWorkbenchPersistence = (
let handedOffMutationLock = false;
return enqueue(async () => {
const projectId = inputProject.id;
- const currentDocument = serializeProjectDocumentV2Json(inputProject);
+ const currentDocument = serializeProjectDocumentV3Json(inputProject);
let owned = await requireDraft(projectId);
if (
owned.draft.documentJson !== currentDocument.documentJson &&
@@ -2551,7 +2558,12 @@ export const createDurableSyncedWorkbenchPersistence = (
].join('\u0000')
);
const name = `${sourceProjectName} (copy)`;
- const document = { ...sourceDocument, id: copyProjectId, name };
+ // A draft staged by an older client copies forward in the current schema.
+ const migratedSource = migrateProjectDocument(sourceDocument);
+ if (migratedSource.status === 'malformed') {
+ throw new Error('The project draft cannot be copied: its document is malformed.');
+ }
+ const document = { ...migratedSource.document, id: copyProjectId, name };
const documentJson = JSON.stringify(document);
const documentByteSize = getUtf8ByteSize(documentJson);
if (documentByteSize > PROJECT_DOCUMENT_MAX_BYTES) {
@@ -2598,7 +2610,7 @@ export const createDurableSyncedWorkbenchPersistence = (
getUtf8ByteSize(reservation.copyDocumentJson) !== reservation.copyDocumentByteSize ||
document.id !== copyProjectId ||
document.name !== name ||
- document.documentSchemaVersion !== PROJECT_DOCUMENT_SCHEMA_VERSION
+ migrateProjectDocument(document).status === 'malformed'
) {
throw new Error('The reserved project copy is damaged.');
}
@@ -2754,7 +2766,7 @@ export const createDurableSyncedWorkbenchPersistence = (
return result;
}
await deleteDraft(projectId);
- const documentJson = serializeProjectDocumentV2Json(result.project).documentJson;
+ const documentJson = serializeProjectDocumentV3Json(result.project).documentJson;
syncEntries.set(projectId, {
minimumCanvasSchemaVersion: record.minimum_canvas_schema_version,
pushedDoc: documentJson,
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
index c2a833a2b8..a2bc87f2e7 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts
@@ -261,6 +261,25 @@ describe('duplicateProjectRecord', () => {
expect(claimed).toMatchObject({ projectBoardId: 'staging-board', selectedBoardId: 'staging-board' });
});
+ it('keeps each workflow linked to its library template, since the copy lives on the same server', async () => {
+ const source = { libraryWorkflowId: 'lib-1', revision: 4 };
+ const project = createDraftProject([]);
+ const record = sourceRecord({
+ documentSchemaVersion: 3,
+ workflows: {
+ ...project.workflows,
+ entries: project.workflows.entries.map((entry) => ({ ...entry, source })),
+ },
+ });
+
+ await duplicateProject.duplicateProjectRecord({ boardItems: [], owner, record });
+
+ const workflows = createdData().workflows as { entries: { source?: unknown }[] };
+
+ expect(workflows.entries[0]?.source).toEqual(source);
+ expect(createdData().documentSchemaVersion).toBe(3);
+ });
+
it('creates no staging board for a project whose board is empty', async () => {
await duplicateProject.duplicateProjectRecord({ boardItems: [], owner, record: sourceRecord() });
diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
index ae15e0a67f..7fb8c551d6 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.ts
@@ -126,9 +126,9 @@ export const duplicateProjectRecord = async (
const project = loaded.project;
- const { applyAuthoritativeProjectBoard, serializeProjectDocument, serializeProjectDocumentV2 } =
+ const { applyAuthoritativeProjectBoard, serializeProjectDocument } =
await import('@workbench/projects/projectDocument');
- const canonicalDocument = input.identity ? serializeProjectDocumentV2(project) : serializeProjectDocument(project);
+ const canonicalDocument = serializeProjectDocument(project);
const boardItems = input.boardItems as readonly InvkBoardItem[];
const stagingBoardId = boardItems.length === 0 ? null : await createStagingBoard(name, owner.signal);
const ledger = createRestoredMediaLedger(stagingBoardId);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
index 2cd847ca32..6201b5696e 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts
@@ -102,6 +102,39 @@ it('keeps the held result while edits touch only name-free subtrees, and sees na
expect(new Set(read().images)).toEqual(new Set(['stroke.png', 'snapshot.png', 'undo.png', 'next.png']));
});
+it('rescans only the workflow an edit touched, sharing the documents its history retains', () => {
+ const docA = { id: 'a', nodes: [{ data: { inputs: { image: { value: { image_name: 'a.png' } } } } }] };
+ const docB = { id: 'b', nodes: [{ data: { inputs: { image: { value: { image_name: 'b.png' } } } } }] };
+ let project = {
+ id: 'project-1',
+ workflowHistories: {},
+ workflows: { activeWorkflowId: 'a', entries: [{ document: docA }, { document: docB }] },
+ };
+ const read = createOpenProjectsHeldMediaReader(
+ () => [project],
+ () => undefined
+ );
+ const first = read();
+ expect(new Set(first.images)).toEqual(new Set(['a.png', 'b.png']));
+
+ // Editing `a` keeps `docA` in a's history; b's entry is untouched and its scan is reused by identity.
+ const docA2 = { ...docA, nodes: [{ data: { inputs: { image: { value: { image_name: 'a2.png' } } } } }] };
+ project = {
+ ...project,
+ workflowHistories: { a: { future: [], past: [{ document: docA, id: 'h1', sequence: 1 }] } },
+ workflows: { ...project.workflows, entries: [{ document: docA2 }, project.workflows.entries[1]!] },
+ };
+ expect(new Set(read().images)).toEqual(new Set(['a.png', 'a2.png', 'b.png']));
+
+ // Removing `a` releases its history: nothing holds a.png or a2.png any more.
+ project = {
+ ...project,
+ workflowHistories: {},
+ workflows: { activeWorkflowId: 'b', entries: [project.workflows.entries[1]!] },
+ };
+ expect(read().images).toEqual(['b.png']);
+});
+
it('announces engines registering and releasing their held media', () => {
const sources = createCanvasHeldMediaSources();
const onChange = vi.fn();
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
index a4818dffe5..5cb3f3f8e3 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
@@ -103,8 +103,22 @@ const isHeldSkipKey = (key: string): boolean => key === 'recentImages' || GALLER
export const collectHeldAssetRefs = (projects: readonly object[]): ProjectAssetRefs =>
collectMediaNames(projects.flatMap(withoutHistoryRoots), isHeldSkipKey, MAX_HELD_NAME_LENGTH);
-/** Containers whose children an edit replaces independently: the canvas, its snapshots and undo stacks. */
-const SPLIT_HELD_KEYS: ReadonlySet<string> = new Set(['canvas', 'snapshots', 'undoRedo', 'past', 'future']);
+/**
+ * Containers whose children an edit replaces independently: the canvas, its snapshots, undo stacks, and the workflow
+ * collection with its per-workflow histories, so editing one workflow rescans only that workflow.
+ */
+const SPLIT_HELD_KEYS: ReadonlySet<string> = new Set([
+ 'canvas',
+ 'snapshots',
+ 'undoRedo',
+ 'past',
+ 'future',
+ 'workflows',
+ 'entries',
+]);
+
+/** Containers keyed by ids (workflow histories): every child is split, and their entries are shared by identity. */
+const SPLIT_CHILDREN_HELD_KEYS: ReadonlySet<string> = new Set(['workflowHistories']);
type HeldPart = ProjectAssetRefs | CanvasHeldAssetRefs;
@@ -131,7 +145,7 @@ export const createOpenProjectsHeldMediaReader = (
const residueScans = new WeakMap<object, ProjectAssetRefs>();
let last: { parts: HeldPart[]; result: { images: string[]; videos: string[] } } | null = null;
- const collectParts = (node: object, isRoot: boolean, parts: HeldPart[]): void => {
+ const collectParts = (node: object, isRoot: boolean, parts: HeldPart[], splitChildren = false): void => {
const entries = Array.isArray(node)
? node.map((value, index) => [String(index), value] as const)
: Object.entries(node);
@@ -142,8 +156,8 @@ export const createOpenProjectsHeldMediaReader = (
}
if (typeof value !== 'object' || value === null) {
(residue ??= {})[key] = value;
- } else if (SPLIT_HELD_KEYS.has(key)) {
- collectParts(value, false, parts);
+ } else if (splitChildren || SPLIT_HELD_KEYS.has(key)) {
+ collectParts(value, false, parts, SPLIT_CHILDREN_HELD_KEYS.has(key));
} else {
let refs = scans.get(value);
if (!refs) {
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts b/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts
index 759a410f9b..1ce0b3e5c8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts
@@ -1,13 +1,15 @@
import type { Project } from '@workbench/projectContracts';
+import type { ProjectWorkflowCollection } from '@workbench/projectWorkflows';
import { stripInfiniteWindowAnchor, stripSessionScopedGallerySearch } from '@features/gallery/contracts';
+import { migrateProjectGraphToCollection, normalizeProjectWorkflowCollection } from '@workbench/projectWorkflows';
/** Keep document codecs reducer-free; load rehydration lazily. */
-export const PROJECT_DOCUMENT_SCHEMA_VERSION = 2;
+export const PROJECT_DOCUMENT_SCHEMA_VERSION = 3;
export const PROJECT_DOCUMENT_MAX_BYTES = 32 * 1024 * 1024;
-export type ProjectDocumentV2 = Omit<
+export type ProjectDocumentV3 = Omit<
Pick<
Project,
| 'canvas'
@@ -16,7 +18,6 @@ export type ProjectDocumentV2 = Omit<
| 'invocation'
| 'layout'
| 'name'
- | 'projectGraph'
| 'promptHistory'
| 'settings'
| 'widgetGraphs'
@@ -27,6 +28,7 @@ export type ProjectDocumentV2 = Omit<
> & {
documentSchemaVersion: typeof PROJECT_DOCUMENT_SCHEMA_VERSION;
floatingWidgets?: Project['floatingWidgets'];
+ workflows: ProjectWorkflowCollection;
};
export const stripSessionScopedGalleryState = (project: Project): Project => {
@@ -53,9 +55,13 @@ export const stripSessionScopedGalleryState = (project: Project): Project => {
return didChange ? { ...project, widgetInstances } : project;
};
-export const serializeProjectDocumentV2 = (project: Project): ProjectDocumentV2 => {
+/**
+ * The durable shape server persistence writes: an allowlist of editable fields. Queue runs, events, undo and workflow
+ * histories are session state and never appear.
+ */
+export const serializeProjectDocumentV3 = (project: Project): ProjectDocumentV3 => {
const persistent = stripSessionScopedGalleryState(project);
- const document: ProjectDocumentV2 = {
+ const document: ProjectDocumentV3 = {
canvas: persistent.canvas,
documentSchemaVersion: PROJECT_DOCUMENT_SCHEMA_VERSION,
...(persistent.floatingWidgets ? { floatingWidgets: persistent.floatingWidgets } : {}),
@@ -63,36 +69,41 @@ export const serializeProjectDocumentV2 = (project: Project): ProjectDocumentV2
invocation: persistent.invocation,
layout: persistent.layout,
name: persistent.name,
- projectGraph: persistent.projectGraph,
promptHistory: persistent.promptHistory,
settings: persistent.settings,
widgetGraphs: persistent.widgetGraphs,
widgetInstances: persistent.widgetInstances,
widgetRegions: persistent.widgetRegions,
+ workflows: persistent.workflows,
};
return document;
};
-export const serializeProjectDocumentV2Json = (
+export const serializeProjectDocumentV3Json = (
project: Project
-): { byteSize: number; document: ProjectDocumentV2; documentJson: string } => {
- const document = serializeProjectDocumentV2(project);
+): { byteSize: number; document: ProjectDocumentV3; documentJson: string } => {
+ const document = serializeProjectDocumentV3(project);
const documentJson = JSON.stringify(document);
return { byteSize: new TextEncoder().encode(documentJson).byteLength, document, documentJson };
};
+/**
+ * The transfer shape export, import and duplication write: every field a loaded project carries except session
+ * state, so a document authored with fields this client does not know keeps them, stamped with the current schema.
+ */
export const serializeProjectDocument = (project: Project): Record<string, unknown> => {
const {
events: _events,
graphHistory: _graphHistory,
queue: _queue,
undoRedo: _undoRedo,
+ workflowHistories: _workflowHistories,
...document
} = stripSessionScopedGalleryState(project) as Project & { graphHistory?: unknown };
- return document;
+ return { ...document, documentSchemaVersion: PROJECT_DOCUMENT_SCHEMA_VERSION };
};
const normalizeInvocationSourceId = (sourceId: unknown): unknown => {
@@ -107,22 +118,77 @@ const normalizeInvocationSourceId = (sourceId: unknown): unknown => {
return sourceId;
};
-export const normalizeLegacyProjectDocument = (data: Record<string, unknown>): Record<string, unknown> => {
- const invocation = data.invocation;
- const { events: _events, graphHistory: _graphHistory, queue: _queue, ...document } = data;
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+export type ProjectDocumentMigration =
+ | { status: 'migrated'; document: Record<string, unknown> }
+ | { status: 'malformed'; reason: string };
+
+/**
+ * The migration boundary: any supported older document comes out as schema 3. A document without a version is
+ * schema 1; schema 2 owned one `projectGraph`, which becomes the first, active workflow. Collections that would
+ * lose a workflow if repaired are refused instead. Callers check for a future version before calling this.
+ */
+export const migrateProjectDocument = (data: Record<string, unknown>): ProjectDocumentMigration => {
+ const version = data.documentSchemaVersion;
+
+ if (version !== undefined && version !== 2 && version !== PROJECT_DOCUMENT_SCHEMA_VERSION) {
+ return { reason: `Unsupported project document schema ${String(version)}.`, status: 'malformed' };
+ }
+
+ if (typeof data.id !== 'string' || typeof data.name !== 'string' || !isRecord(data.layout)) {
+ return { reason: 'The document is missing its project identity or layout.', status: 'malformed' };
+ }
+
+ const {
+ events: _events,
+ graphHistory: _graphHistory,
+ invocation,
+ projectGraph,
+ queue: _queue,
+ undoRedo: _undoRedo,
+ workflowHistories: _workflowHistories,
+ workflows,
+ ...rest
+ } = data;
+
+ let collection: ProjectWorkflowCollection;
+
+ if (version === PROJECT_DOCUMENT_SCHEMA_VERSION) {
+ const normalized = normalizeProjectWorkflowCollection(workflows);
+
+ if (!normalized) {
+ return {
+ reason: 'The workflow collection is malformed or names a missing active workflow.',
+ status: 'malformed',
+ };
+ }
+
+ collection = normalized;
+ } else {
+ const migrated = migrateProjectGraphToCollection(projectGraph);
+
+ if (!migrated) {
+ return { reason: 'The project graph is damaged.', status: 'malformed' };
+ }
+
+ collection = migrated;
+ }
return {
- ...document,
- invocation:
- invocation && typeof invocation === 'object'
- ? { ...invocation, sourceId: normalizeInvocationSourceId((invocation as { sourceId?: unknown }).sourceId) }
+ document: {
+ ...rest,
+ documentSchemaVersion: PROJECT_DOCUMENT_SCHEMA_VERSION,
+ invocation: isRecord(invocation)
+ ? { ...invocation, sourceId: normalizeInvocationSourceId(invocation.sourceId) }
: invocation,
+ workflows: collection,
+ },
+ status: 'migrated',
};
};
-const isRecord = (value: unknown): value is Record<string, unknown> =>
- typeof value === 'object' && value !== null && !Array.isArray(value);
-
const patchGalleryValues = (
values: Record<string, unknown>,
boardId: string,
@@ -183,11 +249,3 @@ export const applyAuthoritativeProjectBoard = (
return hasChanged ? next : projectDocument;
};
-
-/** Reject invalid document formats without eagerly loading the reducer. */
-export const isProjectDocumentShape = (data: Record<string, unknown>): boolean =>
- typeof data.id === 'string' &&
- typeof data.name === 'string' &&
- typeof data.layout === 'object' &&
- data.layout !== null &&
- (data.documentSchemaVersion === undefined || data.documentSchemaVersion === PROJECT_DOCUMENT_SCHEMA_VERSION);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 60c57ea8da..263faae85a 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -227,14 +227,14 @@ describe('exportLibraryProject', () => {
const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
const exported = JSON.parse(readEntryText(entries.get('project.json')!)) as Record<string, unknown>;
- expect(exported.documentSchemaVersion).toBe(2);
+ expect(exported.documentSchemaVersion).toBe(3);
expect(exported).not.toHaveProperty('events');
expect(exported).not.toHaveProperty('graphHistory');
expect(exported).not.toHaveProperty('queue');
});
it('exports a future-schema server record verbatim for recovery', async () => {
- const document = { documentSchemaVersion: 3, futureField: { value: 42 }, id: 'future', name: 'Future' };
+ const document = { documentSchemaVersion: 4, futureField: { value: 42 }, id: 'future', name: 'Future' };
api.getProject.mockResolvedValue({ data: document, name: 'Future', project_id: 'p1', revision: 3 });
@@ -477,6 +477,31 @@ describe('importing a project board', () => {
expect(outcome.documentReferenceIssues).toEqual([]);
});
+ it('drops library links on import: a portable file never acquires a write target', async () => {
+ acceptCreate();
+ api.getProjectBoardSnapshot.mockResolvedValue(boardSnapshot());
+ const project = boardProject();
+ await projectFile.exportOpenProject({
+ ...project,
+ workflows: {
+ ...project.workflows,
+ entries: project.workflows.entries.map((entry) => ({
+ ...entry,
+ source: { libraryWorkflowId: 'lib-1', revision: 2 },
+ })),
+ },
+ });
+
+ await projectFile.importProjectFile(capturedArchive());
+
+ const { data } = api.createProjectSettled.mock.calls[0]![0] as {
+ data: { workflows: { entries: { document: { id: string }; source?: unknown }[] } };
+ };
+
+ expect(data.workflows.entries).toHaveLength(1);
+ expect(data.workflows.entries[0]).not.toHaveProperty('source');
+ });
+
it('stars only the descriptors that were starred', async () => {
acceptCreate();
await projectFile.importProjectFile(await exportedBoardArchive());
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 316e2d9dc3..5750d207e8 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -154,12 +154,12 @@ export const exportLibraryProject = async (
assertAccountScopeCurrent(owner);
- const [{ deserializeProjectDocument }, { serializeProjectDocumentV2 }] = await Promise.all([
+ const [{ deserializeProjectDocument }, { serializeProjectDocumentV3 }] = await Promise.all([
import('./projectHydration'),
import('./projectDocument'),
]);
const loaded = deserializeProjectDocument(record.data);
- const document = loaded.status === 'loaded' ? serializeProjectDocumentV2(loaded.project) : record.data;
+ const document = loaded.status === 'loaded' ? serializeProjectDocumentV3(loaded.project) : record.data;
return exportProjectDocument(record.name, record.project_id, document, record.minimum_canvas_schema_version, {
...options,
@@ -231,7 +231,11 @@ export const importProjectFile = async (
throw new InvkFormatError('damaged', 'The project document will not rehydrate.');
}
- const project = loaded.project;
+ // An imported archive never inherits library write targets from the ids its workflows carry.
+ // Lazy like the other document modules here: this file is shared with the Launchpad, which never loads the
+ // workflow core eagerly.
+ const { stripProjectWorkflowSources } = await import('@workbench/projectWorkflows');
+ const project = { ...loaded.project, workflows: stripProjectWorkflowSources(loaded.project.workflows) };
const { applyAuthoritativeProjectBoard, serializeProjectDocument } = await import('./projectDocument');
const canonicalDocument = serializeProjectDocument(project);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectHydration.ts b/invokeai/frontend/webv2/src/workbench/projects/projectHydration.ts
index 7e169c7208..f8314cdbd1 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectHydration.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectHydration.ts
@@ -6,8 +6,7 @@ import type { ProjectRecordDTO } from './api';
import {
applyAuthoritativeProjectBoard,
- isProjectDocumentShape,
- normalizeLegacyProjectDocument,
+ migrateProjectDocument,
PROJECT_DOCUMENT_SCHEMA_VERSION,
} from './projectDocument';
@@ -45,13 +44,26 @@ export const deserializeProjectDocument = (data: Record<string, unknown>): Proje
if (futureDocument) {
return futureDocument;
}
- const normalizedData = normalizeLegacyProjectDocument(data);
- if (!isProjectDocumentShape(normalizedData)) {
- return { status: 'unavailable' };
+ const migrated = migrateProjectDocument(data);
+ if (migrated.status === 'malformed') {
+ return {
+ refused: {
+ projectId: typeof data.id === 'string' ? data.id : '',
+ projectName: typeof data.name === 'string' ? data.name : '',
+ raw: data,
+ refusal: { raw: data, reason: migrated.reason, scope: 'project-document', status: 'malformed' },
+ source: 'project-document',
+ },
+ status: 'refused',
+ };
}
- const { documentSchemaVersion: _documentSchemaVersion, ...projectDocument } = normalizedData;
- const result = loadWorkbenchProject({ ...projectDocument, undoRedo: { future: [], past: [] } } as unknown as Project);
+ const { documentSchemaVersion: _documentSchemaVersion, ...projectDocument } = migrated.document;
+ const result = loadWorkbenchProject({
+ ...projectDocument,
+ undoRedo: { future: [], past: [] },
+ workflowHistories: {},
+ } as unknown as Project);
return result.status === 'refused' ? { refused: { ...result.refused, raw: data }, status: 'refused' } : result;
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectLoadRefusal.ts b/invokeai/frontend/webv2/src/workbench/projects/projectLoadRefusal.ts
index 1f02b09c5c..fb93c15244 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectLoadRefusal.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectLoadRefusal.ts
@@ -15,7 +15,9 @@ export const describeRefusedProject = (refused: RefusedWorkbenchProject, t: TFun
return {
message:
refused.source === 'project-document'
- ? t('projects.load.unsupportedVersion', { name })
+ ? t(refused.refusal.status === 'malformed' ? 'projects.load.malformed' : 'projects.load.unsupportedVersion', {
+ name,
+ })
: refused.refusal.status === 'unsupported-version'
? t(
refused.refusal.version < MIN_SUPPORTED_CANVAS_SCHEMA_VERSION
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
index a3b271a25a..8d3eb50608 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
@@ -1,12 +1,13 @@
import type { Project } from '@workbench/projectContracts';
+import { addProjectWorkflow, getActiveProjectGraph, recordProjectWorkflowRun } from '@workbench/projectWorkflows';
import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
import { describe, expect, it } from 'vitest';
import {
applyAuthoritativeProjectBoard,
- serializeProjectDocumentV2,
- serializeProjectDocumentV2Json,
+ serializeProjectDocumentV3,
+ serializeProjectDocumentV3Json,
} from './projectDocument';
import { deserializeProjectDocument, deserializeProjectRecord, serializeProjectDocument } from './syncedPersistence';
@@ -27,7 +28,7 @@ const loadDocument = (document: Record<string, unknown>): Project => {
};
describe('project document serialization', () => {
- it('serializes only the V2 durable allowlist and restores session state empty', () => {
+ it('serializes only the durable allowlist and restores session state empty', () => {
const project = getProject();
project.undoRedo.past.push({
@@ -37,7 +38,6 @@ describe('project document serialization', () => {
project: {
invocation: project.invocation,
layout: project.layout,
- projectGraph: project.projectGraph,
widgetGraphs: {},
widgetInstances: project.widgetInstances,
widgetRegions: project.widgetRegions,
@@ -51,7 +51,7 @@ describe('project document serialization', () => {
recoveryOf: 'old-project',
});
- const document = serializeProjectDocumentV2(project);
+ const document = serializeProjectDocumentV3(project);
expect(Object.keys(document).sort()).toEqual(
[
@@ -61,19 +61,20 @@ describe('project document serialization', () => {
'invocation',
'layout',
'name',
- 'projectGraph',
'promptHistory',
'settings',
'widgetGraphs',
'widgetInstances',
'widgetRegions',
+ 'workflows',
].sort()
);
- expect(document.documentSchemaVersion).toBe(2);
+ expect(document.documentSchemaVersion).toBe(3);
const roundTripped = loadDocument(document);
expect(roundTripped.undoRedo).toEqual({ future: [], past: [] });
+ expect(roundTripped.workflowHistories).toEqual({});
expect(roundTripped.queue).toEqual({ items: [] });
expect(roundTripped.events).toEqual([]);
expect(roundTripped.id).toBe(project.id);
@@ -82,22 +83,22 @@ describe('project document serialization', () => {
it('measures the exact UTF-8 wire bytes once', () => {
const project = getProject({ name: '文書' });
- const encoded = serializeProjectDocumentV2Json(project);
+ const encoded = serializeProjectDocumentV3Json(project);
- expect(encoded.document).toEqual(serializeProjectDocumentV2(project));
+ expect(encoded.document).toEqual(serializeProjectDocument(project));
expect(encoded.documentJson).toBe(JSON.stringify(encoded.document));
expect(encoded.byteSize).toBe(new TextEncoder().encode(encoded.documentJson).byteLength);
});
it('keeps project document bytes constant as session queue history grows', () => {
const project = getProject();
- const baseline = serializeProjectDocumentV2Json(project);
+ const baseline = serializeProjectDocumentV3Json(project);
project.queue.items = Array.from({ length: 2_000 }, (_, index) => ({
id: `queue-${index}`,
snapshot: { oversizedContext: 'x'.repeat(100) },
})) as never;
- const withQueueHistory = serializeProjectDocumentV2Json(project);
+ const withQueueHistory = serializeProjectDocumentV3Json(project);
expect(withQueueHistory.byteSize).toBe(baseline.byteSize);
expect(withQueueHistory.documentJson).toBe(baseline.documentJson);
@@ -114,10 +115,17 @@ describe('project document serialization', () => {
expect(document).not.toHaveProperty('queue');
});
- it('rejects documents that do not look like projects', () => {
- expect(deserializeProjectDocument({})).toEqual({ status: 'unavailable' });
- expect(deserializeProjectDocument({ id: 'x' })).toEqual({ status: 'unavailable' });
- expect(deserializeProjectDocument({ id: 'x', layout: null, name: 'y' })).toEqual({ status: 'unavailable' });
+ it('refuses documents that do not look like projects, keeping the raw document for recovery', () => {
+ for (const data of [{}, { id: 'x' }, { id: 'x', layout: null, name: 'y' }]) {
+ const result = deserializeProjectDocument(data);
+
+ expect(result.status).toBe('refused');
+ if (result.status !== 'refused') {
+ throw new Error('expected a refusal');
+ }
+ expect(result.refused.raw).toBe(data);
+ expect(result.refused.refusal).toMatchObject({ scope: 'project-document', status: 'malformed' });
+ }
});
it('refuses a document whose canvas was written by a newer client, keeping the raw document', () => {
@@ -140,7 +148,7 @@ describe('project document serialization', () => {
it('refuses a newer project document schema while preserving its raw bytes for export', () => {
const project = getProject();
- const future = { ...serializeProjectDocumentV2(project), documentSchemaVersion: 3 };
+ const future = { ...serializeProjectDocument(project), documentSchemaVersion: 4 };
expect(deserializeProjectDocument(future)).toEqual({
refused: {
@@ -151,7 +159,7 @@ describe('project document serialization', () => {
raw: future,
scope: 'project-document',
status: 'unsupported-version',
- version: 3,
+ version: 4,
},
source: 'project-document',
},
@@ -161,7 +169,7 @@ describe('project document serialization', () => {
it('uses authoritative server identity and untouched bytes for a future document refusal', () => {
const raw = {
- documentSchemaVersion: 3,
+ documentSchemaVersion: 4,
id: 'untrusted-id',
name: 'Untrusted name',
widgetInstances: {
@@ -174,7 +182,7 @@ describe('project document serialization', () => {
board_id: 'authoritative-board',
created_at: '2026-09-03T00:00:00.000Z',
data: raw,
- minimum_canvas_schema_version: 3,
+ minimum_canvas_schema_version: 4,
name: 'Authoritative name',
project_id: 'authoritative-id',
revision: 4,
@@ -185,13 +193,93 @@ describe('project document serialization', () => {
projectId: 'authoritative-id',
projectName: 'Authoritative name',
raw,
- refusal: { raw, scope: 'project-document', status: 'unsupported-version', version: 3 },
+ refusal: { raw, scope: 'project-document', status: 'unsupported-version', version: 4 },
source: 'project-document',
},
status: 'refused',
});
});
+ it('migrates a schema-2 document into the first, active workflow with an unknown-revision source', () => {
+ const project = getProject();
+ const legacyGraph = { ...getActiveProjectGraph(project), id: 'legacy-graph', libraryWorkflowId: 'lib-1' };
+ const { workflows: _workflows, ...withoutCollection } = serializeProjectDocument(project);
+ const v2 = { ...withoutCollection, documentSchemaVersion: 2, projectGraph: legacyGraph };
+
+ const loaded = loadDocument(v2);
+
+ expect(loaded.workflows.activeWorkflowId).toBe('legacy-graph');
+ expect(loaded.workflows.entries).toHaveLength(1);
+ expect(loaded.workflows.entries[0]?.source).toEqual({ libraryWorkflowId: 'lib-1', revision: null });
+ expect('libraryWorkflowId' in loaded.workflows.entries[0]!.document).toBe(false);
+ expect(serializeProjectDocumentV3(loaded).documentSchemaVersion).toBe(3);
+ });
+
+ it('migrates an unversioned document the same way and drops its legacy history', () => {
+ const project = getProject();
+ const { documentSchemaVersion: _version, workflows: _workflows, ...legacy } = serializeProjectDocument(project);
+
+ const loaded = loadDocument({
+ ...legacy,
+ graphHistory: [{ id: 'gh' }],
+ projectGraph: getActiveProjectGraph(project),
+ });
+
+ expect(loaded.workflows.entries.map((entry) => entry.document.id)).toEqual([getActiveProjectGraph(project).id]);
+ expect('graphHistory' in loaded).toBe(false);
+ });
+
+ it('keeps every workflow and the active selection through a round trip', () => {
+ let project = getProject();
+ const second = { ...getActiveProjectGraph(project), id: 'second', name: 'Second' };
+
+ project = addProjectWorkflow(project, second, { source: { libraryWorkflowId: 'lib-2', revision: 7 } });
+ project = recordProjectWorkflowRun(project, 'second', {
+ completedAt: 't2',
+ imageName: 'out.png',
+ submittedAt: 't1',
+ });
+
+ const loaded = loadDocument(serializeProjectDocumentV3(project));
+
+ expect(loaded.workflows.activeWorkflowId).toBe('second');
+ expect(loaded.workflows.entries.map((entry) => entry.document.id)).toEqual(
+ [getActiveProjectGraph(getProject()).id, 'second'].map((id, index) =>
+ index === 0 ? project.workflows.entries[0]!.document.id : id
+ )
+ );
+ expect(loaded.workflows.entries[1]).toMatchObject({
+ lastRun: { completedAt: 't2', imageName: 'out.png', submittedAt: 't1' },
+ source: { libraryWorkflowId: 'lib-2', revision: 7 },
+ });
+ });
+
+ it('refuses a schema-3 document whose collection would lose a workflow instead of repairing it', () => {
+ const document = serializeProjectDocumentV3(getProject());
+ const refusal = (data: Record<string, unknown>) => {
+ const result = deserializeProjectDocument(data);
+
+ return result.status === 'refused' ? { ...result.refused.refusal, kept: result.refused.raw } : result.status;
+ };
+
+ expect(refusal({ ...document, workflows: { ...document.workflows, activeWorkflowId: 'x' } })).toMatchObject({
+ status: 'malformed',
+ });
+ expect(refusal({ ...document, workflows: { activeWorkflowId: 'a', entries: [] } })).toMatchObject({
+ status: 'malformed',
+ });
+ expect(refusal({ ...document, workflows: null })).toMatchObject({ status: 'malformed' });
+
+ // An authored workflow this build cannot read is refused with the document intact, never blanked and re-saved.
+ const [entry] = document.workflows.entries;
+ const unreadable = {
+ ...document,
+ workflows: { ...document.workflows, entries: [{ ...entry, document: { ...entry!.document, version: 99 } }] },
+ };
+
+ expect(refusal(unreadable)).toMatchObject({ kept: unreadable, status: 'malformed' });
+ });
+
it('normalizes legacy project-graph invocation sources to workflow', () => {
const project = getProject({
invocation: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: false },
diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
index fb05444a4d..1ce49fce3a 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/syncStore.ts
@@ -87,6 +87,8 @@ export const useProjectSyncSelector = store.useSelector;
export const getProjectSyncSnapshot = store.getSnapshot;
+export const subscribeProjectSync = store.subscribe;
+
export const reportProjectSync = (update: Omit<ProjectSyncSnapshot, 'lastSyncedAt'>): void => {
store.setSnapshot({
...update,
diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx
index 208ccff51b..ef6760ad96 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.browser.test.tsx
@@ -8,7 +8,7 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
-import { serializeProjectDocumentV2Json } from './projectDocument';
+import { serializeProjectDocumentV3Json } from './projectDocument';
const harness = vi.hoisted(() => ({
close: vi.fn<() => ProjectCommandResult>(),
@@ -125,11 +125,11 @@ describe('useProjectActions', () => {
});
harness.flush.mockImplementationOnce(async (project: Project) => {
await firstReleased;
- return { documentJson: serializeProjectDocumentV2Json(project).documentJson, kind: 'acknowledged' as const };
+ return { documentJson: serializeProjectDocumentV3Json(project).documentJson, kind: 'acknowledged' as const };
});
harness.flush.mockImplementationOnce((project: Project) =>
Promise.resolve({
- documentJson: serializeProjectDocumentV2Json(project).documentJson,
+ documentJson: serializeProjectDocumentV3Json(project).documentJson,
kind: 'acknowledged' as const,
})
);
@@ -153,7 +153,7 @@ describe('useProjectActions', () => {
queue: { items: [{ status: 'running' } as Project['queue']['items'][number]] },
};
return Promise.resolve({
- documentJson: serializeProjectDocumentV2Json(project).documentJson,
+ documentJson: serializeProjectDocumentV3Json(project).documentJson,
kind: 'acknowledged' as const,
});
});
@@ -173,7 +173,7 @@ describe('useProjectActions', () => {
harness.close.mockReturnValue({ ok: false, reason: 'last-project' });
harness.flush.mockImplementationOnce((project: Project) =>
Promise.resolve({
- documentJson: serializeProjectDocumentV2Json(project).documentJson,
+ documentJson: serializeProjectDocumentV3Json(project).documentJson,
kind: 'acknowledged' as const,
})
);
@@ -194,7 +194,7 @@ describe('useProjectActions', () => {
.mockReturnValueOnce({ ok: false, reason: 'active-queue-runs' });
harness.flush.mockImplementationOnce((project: Project) =>
Promise.resolve({
- documentJson: serializeProjectDocumentV2Json(project).documentJson,
+ documentJson: serializeProjectDocumentV3Json(project).documentJson,
kind: 'acknowledged' as const,
})
);
diff --git a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
index 109524b45a..62485eec35 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/useProjectActions.ts
@@ -19,7 +19,7 @@ import {
import { useTranslation } from 'react-i18next';
import { deleteLibraryProject, refreshProjectLibrary } from './library';
-import { serializeProjectDocumentV2Json } from './projectDocument';
+import { serializeProjectDocumentV3Json } from './projectDocument';
import { describeRefusedProject } from './projectLoadRefusal';
const CLOSE_FLUSH_ATTEMPTS = 3;
@@ -143,7 +143,7 @@ export const useProjectActions = (): {
}
if (
outcome.kind === 'acknowledged' &&
- serializeProjectDocumentV2Json(queries.getProject(project.id) ?? current).documentJson !==
+ serializeProjectDocumentV3Json(queries.getProject(project.id) ?? current).documentJson !==
outcome.documentJson
) {
continue;
diff --git a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx
index 4604f82def..18ac903aba 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/ProjectConflictBanner.tsx
@@ -1,7 +1,7 @@
import { Alert, Button, HStack, Stack } from '@chakra-ui/react';
import { downloadText } from '@platform/browser/downloadBlob';
import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
-import { serializeProjectDocumentV2Json } from '@workbench/projects/projectDocument';
+import { serializeProjectDocumentV3Json } from '@workbench/projects/projectDocument';
import { useProjectSyncSelector } from '@workbench/projects/syncStore';
import {
useActiveProject,
@@ -62,7 +62,7 @@ export const ProjectConflictBanner = () => {
const exportDraft = useCallback(
() =>
run('export', () => {
- const { documentJson } = serializeProjectDocumentV2Json(project);
+ const { documentJson } = serializeProjectDocumentV3Json(project);
downloadText(documentJson, getExportName(projectName), 'application/json');
return Promise.resolve();
}),
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts
index 618a7972f9..920ad011f6 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts
@@ -29,7 +29,9 @@ describe('projectHasWidgetType', () => {
expect(
projectNeedsWorkflowHost({
...project([]),
- projectGraph: { nodes: [{ data: { type: 'call_saved_workflow' }, type: 'invocation' }] },
+ workflows: {
+ entries: [{ document: { nodes: [{ data: { type: 'call_saved_workflow' }, type: 'invocation' }] } }],
+ },
})
).toBe(true);
});
@@ -38,16 +40,21 @@ describe('projectHasWidgetType', () => {
expect(
projectNeedsWorkflowHost({
...project([]),
- projectGraph: { nodes: [{ data: { type: 'noise' }, type: 'invocation' }] },
+ workflows: { entries: [{ document: { nodes: [{ data: { type: 'noise' }, type: 'invocation' }] } }] },
})
).toBe(false);
});
- it('keeps the workflow host for a library-bound graph after its last call node is removed', () => {
+ it('mounts the workflow host when an inactive workflow calls a saved workflow', () => {
expect(
projectNeedsWorkflowHost({
...project([]),
- projectGraph: { libraryWorkflowId: 'library-workflow-1', nodes: [] },
+ workflows: {
+ entries: [
+ { document: { nodes: [] } },
+ { document: { nodes: [{ data: { type: 'call_saved_workflow' }, type: 'invocation' }] } },
+ ],
+ },
})
).toBe(true);
});
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx
index f317dec74c..3a807bc413 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx
@@ -6,9 +6,9 @@ import { WidgetFailureBoundary } from './WidgetFailureBoundary';
type WidgetHostProject = {
floatingWidgets?: Record<string, unknown>;
- projectGraph?: { libraryWorkflowId?: unknown; nodes: unknown[] };
widgetInstances: Record<string, { typeId?: string }>;
widgetRegions: Record<string, { instanceIds: string[] }>;
+ workflows?: { entries: Array<{ document: { nodes: unknown[] }; source?: unknown }> };
};
export const projectHasWidgetType = (project: WidgetHostProject, widgetTypeId: string): boolean => {
@@ -22,18 +22,31 @@ export const projectHasWidgetType = (project: WidgetHostProject, widgetTypeId: s
);
};
+// Documents are immutable per identity; only an edited workflow is rescanned.
+const savedWorkflowCallScans = new WeakMap<object, boolean>();
+
+const documentCallsSavedWorkflow = (document: { nodes: readonly unknown[] }): boolean => {
+ let calls = savedWorkflowCallScans.get(document);
+
+ if (calls === undefined) {
+ calls = document.nodes.some((node) => {
+ if (typeof node !== 'object' || node === null) {
+ return false;
+ }
+
+ const candidate = node as { type?: unknown; data?: { type?: unknown } };
+ return candidate.type === 'invocation' && candidate.data?.type === 'call_saved_workflow';
+ });
+ savedWorkflowCallScans.set(document, calls);
+ }
+
+ return calls;
+};
+
+/** Saved-workflow calls reconcile against live library records even while the editor is closed. */
export const projectNeedsWorkflowHost = (project: WidgetHostProject): boolean =>
projectHasWidgetType(project, 'workflow') ||
- (typeof project.projectGraph?.libraryWorkflowId === 'string' && project.projectGraph.libraryWorkflowId.length > 0) ||
- (project.projectGraph?.nodes.some((node) => {
- if (typeof node !== 'object' || node === null) {
- return false;
- }
-
- const candidate = node as { type?: unknown; data?: { type?: unknown } };
- return candidate.type === 'invocation' && candidate.data?.type === 'call_saved_workflow';
- }) ??
- false);
+ (project.workflows?.entries.some((entry) => documentCallsSavedWorkflow(entry.document)) ?? false);
const WidgetHost = ({ widget }: { widget: ReturnType<typeof getWidgetHosts>[number] }) => {
const Host = use(widget.host!.load());
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts
index 22c936f900..f1c3826537 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts
@@ -15,6 +15,7 @@ import { compileGeneratePreviewGraph, getGenerateNodeProvenance } from '@feature
import { compileProjectGraph } from '@features/workflow/graph';
import { ForLoopGraphValidationError } from '@features/workflow/utility';
import { getDestinationLabel } from '@workbench/invocation';
+import { getActiveProjectGraph } from '@workbench/projectWorkflows';
import { getProjectWidgetValues } from '@workbench/widgetState';
/**
@@ -64,10 +65,11 @@ const buildWorkflowSource = (
return { ...EMPTY_SOURCE_BASE, graph: null, isLive: true };
}
- const positionHints = Object.fromEntries(project.projectGraph.nodes.map((node) => [node.id, node.position]));
+ const document = getActiveProjectGraph(project);
+ const positionHints = Object.fromEntries(document.nodes.map((node) => [node.id, node.position]));
try {
- const graph = compileProjectGraph(project.projectGraph, templates.templates);
+ const graph = compileProjectGraph(document, templates.templates);
return { ...EMPTY_SOURCE_BASE, graph, isLive: true, positionHints };
} catch (error) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx
index 50cf2d6ebf..9874640bf4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/autosave-status/AutosaveStatusWidgetView.tsx
@@ -3,14 +3,24 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';
import { Stack, Text } from '@chakra-ui/react';
import { StatusWidgetChip } from '@workbench/widget-frame';
import { useWorkbenchSelector } from '@workbench/WorkbenchContext';
-import { CloudAlertIcon, CloudCheckIcon } from 'lucide-react';
+import { CloudAlertIcon, CloudCheckIcon, CloudUploadIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
export const AutosaveStatusWidgetView = ({ presentation }: WidgetViewProps) => {
const { t } = useTranslation();
const autosave = useWorkbenchSelector((snapshot) => snapshot.autosave);
- const icon = autosave.status === 'error' ? CloudAlertIcon : CloudCheckIcon;
- const label = autosave.status === 'saved' ? t('common.saved') : autosave.status;
+ const icon =
+ autosave.status === 'error'
+ ? CloudAlertIcon
+ : autosave.status === 'pending' || autosave.status === 'saving'
+ ? CloudUploadIcon
+ : CloudCheckIcon;
+ const label =
+ autosave.status === 'saved'
+ ? t('common.saved')
+ : autosave.status === 'pending'
+ ? t('widgets.autosaveStatus.pending')
+ : autosave.status;
if (presentation === 'tooltip') {
return (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
index 44a38c926b..946aa1d8c4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RunLayerWorkflowDialog.tsx
@@ -25,6 +25,7 @@ import { socketHub } from '@platform/transport/socketHub';
import { Button, CloseButton, Field, Select } from '@platform/ui';
import { useQueryClient } from '@tanstack/react-query';
import { getCanvasOperations } from '@workbench/canvas-operations/api';
+import { getActiveProjectGraph } from '@workbench/projectWorkflows';
import { useNotify } from '@workbench/useNotify';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { useCallback, useMemo, useState } from 'react';
@@ -111,7 +112,7 @@ const getLayerWorkflowAvailability = (
};
export const useLayerWorkflowAvailability = (): LayerWorkflowAvailability => {
- const document = useActiveProjectSelector((project) => project.projectGraph, Object.is);
+ const document = useActiveProjectSelector((project) => getActiveProjectGraph(project), Object.is);
const templatesSnapshot = useInvocationTemplatesSnapshot();
return getLayerWorkflowAvailability(document, templatesSnapshot);
@@ -198,6 +199,8 @@ export const RunLayerWorkflowDialog = ({
const { canvas, workflows } = useWorkbenchCommands();
const queryClient = useQueryClient();
const projectId = useActiveProjectSelector((project) => project.id);
+ // The document the dialog offers to run; seed advances after the upload return to it, not to whatever is active.
+ const workflowId = availability.document.id;
const [session] = useState(createLayerActionSession);
const [selectionState, setSelectionState] = useState<SelectionState>(() => ({
availability,
@@ -375,7 +378,8 @@ export const RunLayerWorkflowDialog = ({
const operations = getCanvasOperations(engine);
const result = await runLayerWorkflow({
deps: {
- advanceSeeds: (advances) => workflows.editGraph({ advances, type: 'advanceSeedFields' }),
+ advanceSeeds: (advances) =>
+ workflows.editGraph({ advances, type: 'advanceSeedFields' }, { projectId, workflowId }),
appendStaging: (targetProjectId, candidate) =>
canvas.appendStagingCandidate({ candidate, projectId: targetProjectId }),
buildGraph: buildLayerWorkflowGraph,
@@ -436,7 +440,7 @@ export const RunLayerWorkflowDialog = ({
}
session.finish(request.token);
}
- }, [runContext]);
+ }, [runContext, workflowId]);
const handleSubmit = useCallback(
(event: FormEvent<HTMLFormElement>) => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx
index 6f445f82d5..11e2e4f9af 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx
@@ -21,8 +21,8 @@ export const ProjectWidgetView = () => {
events: project.events,
id: project.id,
name: project.name,
- projectGraph: project.projectGraph,
queue: project.queue,
+ workflows: project.workflows,
}),
shallowEqual
);
@@ -35,7 +35,7 @@ export const ProjectWidgetView = () => {
);
};
-type ProjectPanelViewModel = Pick<Project, 'events' | 'id' | 'name' | 'projectGraph' | 'queue'>;
+type ProjectPanelViewModel = Pick<Project, 'events' | 'id' | 'name' | 'queue' | 'workflows'>;
const NameSection = ({ project }: { project: ProjectPanelViewModel }) => {
const { t } = useTranslation();
@@ -143,7 +143,10 @@ const DetailsSection = ({ project }: { project: ProjectPanelViewModel }) => {
<DetailRow label={t('common.lastSaved')}>
{lastSavedAt ? formatTimestamp(lastSavedAt, t('common.unknownTime')) : t('common.notYet')}
</DetailRow>
- <DetailRow label={t('widgets.project.graphNodes')}>{project.projectGraph.nodes.length}</DetailRow>
+ <DetailRow label={t('widgets.project.graphNodes')}>
+ {project.workflows.entries.reduce((count, entry) => count + entry.document.nodes.length, 0)}
+ </DetailRow>
+ <DetailRow label={t('widgets.project.workflows')}>{project.workflows.entries.length}</DetailRow>
<DetailRow label={t('widgets.project.activeRuns')}>
{t('widgets.project.activeRunCounts', { running, queued })}
</DetailRow>
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 7ee5459862..520b4a6756 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -32,6 +32,7 @@ import { getCanvasStagingCandidateFingerprint, getCanvasStagingSlots } from './c
import { layoutPresets } from './layoutPresets';
import { resolveSavedLayoutPreset } from './layoutPresetSnapshots';
import { PROJECT_EVENT_LIMIT } from './projectEvents';
+import { getActiveProjectGraph } from './projectWorkflows';
import { DEFAULT_PROJECT_SETTINGS } from './settings/store';
import { getProjectWidgetValues } from './widgetState';
import {
@@ -453,6 +454,7 @@ describe('generation-device orchestration metadata', () => {
const state = workbenchReducer(primeGenerate(initial), {
backendSupportsCancellation: true,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
+ projectId: initial.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -482,6 +484,7 @@ describe('generation-device orchestration metadata', () => {
backendSupportsCancellation: true,
models,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'upscale', sourceLocked: false },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -941,7 +944,7 @@ describe('adopting a project from another realm', () => {
const legacyProject = {
...project,
events: [{ createdAt: 'now', id: 'legacy-event', summary: 'legacy', type: 'project-created' }],
- graphHistory: [{ document: project.projectGraph, id: 'legacy-snapshot' }],
+ graphHistory: [{ document: getActiveProjectGraph(project), id: 'legacy-snapshot' }],
queue: { items: [{}] },
} as unknown as Project;
@@ -3008,11 +3011,13 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const once = workbenchReducer(state, {
backendSupportsCancellation: true,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
const twice = workbenchReducer(once, {
backendSupportsCancellation: true,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
+ projectId: once.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -3044,6 +3049,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const next = workbenchReducer(state, {
backendSupportsCancellation: true,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -3063,6 +3069,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const next = workbenchReducer(state, {
backendSupportsCancellation: true,
route: { destination: 'canvas', destinationLocked: false, sourceId: 'upscale', sourceLocked: true },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -3125,6 +3132,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
state = workbenchReducer(state, {
backendSupportsCancellation: true,
route: { destination: 'canvas', destinationLocked: false, sourceId: 'workflow', sourceLocked: true },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -3156,42 +3164,72 @@ describe('workbenchReducer Phase 5 generation flow', () => {
},
type: 'addNode',
},
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
const project = getActiveProject(state);
- expect(project.projectGraph.nodes).toHaveLength(1);
- expect(project.undoRedo.past.at(-1)?.label).toBe('Add workflow node');
+ expect(getActiveProjectGraph(project).nodes).toHaveLength(1);
+ expect(project.workflowHistories[project.workflows.activeWorkflowId]?.past.at(-1)?.label).toBe('Add workflow node');
+ // Graph edits never enter the project-level history.
+ expect(project.undoRedo.past.some((entry) => entry.label === 'Add workflow node')).toBe(false);
expect(project.invocation.sourceId).toBe('workflow');
expect(project.invocation.destination).toBe('gallery');
- state = workbenchReducer(state, { type: 'undoProjectChange' });
+ state = workbenchReducer(state, { type: 'undoWorkflowChange' });
- expect(getActiveProject(state).projectGraph.nodes).toHaveLength(0);
+ expect(getActiveProjectGraph(getActiveProject(state)).nodes).toHaveLength(0);
+ // Undoing a graph edit does not undo the route the edit switched to.
expect(getActiveProject(state).invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });
});
- it('replaceProjectGraph preserves the previous document in session undo', () => {
+ it('never restores a workflow document through project-level undo', () => {
+ let state = createInitialWorkbenchState();
+
+ state = workbenchReducer(state, {
+ action: { patch: { name: 'Edited' }, type: 'setMetadata' },
+ type: 'applyWorkflowAction',
+ });
+ // A layout change enters the project-level history after the edit.
+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });
+ const edited = getActiveProjectGraph(getActiveProject(state));
+
+ state = workbenchReducer(state, { type: 'undoProjectChange' });
+ state = workbenchReducer(state, { type: 'undoProjectChange' });
+
+ expect(getActiveProjectGraph(getActiveProject(state))).toBe(edited);
+ expect(getActiveProject(state).workflowHistories[edited.id]?.past).toHaveLength(1);
+ });
+
+ it("adds a workflow beside the others and keeps each workflow's history to itself", () => {
let state = createInitialWorkbenchState();
- const originalGraphId = getActiveProject(state).projectGraph.id;
+ const originalGraphId = getActiveProjectGraph(getActiveProject(state)).id;
state = workbenchReducer(state, {
- document: { ...getActiveProject(state).projectGraph, id: 'replacement-graph', name: 'Replacement' },
- label: 'Test replace',
- type: 'replaceProjectGraph',
+ action: { patch: { name: 'First' }, type: 'setMetadata' },
+ type: 'applyWorkflowAction',
+ });
+ state = workbenchReducer(state, {
+ document: { ...getActiveProjectGraph(getActiveProject(state)), id: 'second-graph', name: 'Second' },
+ label: 'Test add',
+ type: 'addProjectWorkflow',
});
const project = getActiveProject(state);
- expect(project.projectGraph.id).toBe('replacement-graph');
+ expect(project.workflows.activeWorkflowId).toBe('second-graph');
+ expect(project.workflows.entries.map((entry) => entry.document.id)).toEqual([originalGraphId, 'second-graph']);
expect(project.invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });
- expect(project.undoRedo.past.at(-1)?.project.projectGraph.id).toBe(originalGraphId);
- state = workbenchReducer(state, { type: 'undoProjectChange' });
+ // The new workflow has no history of its own; undo does nothing to it and nothing to its neighbour.
+ state = workbenchReducer(state, { type: 'undoWorkflowChange' });
+ expect(getActiveProjectGraph(getActiveProject(state)).id).toBe('second-graph');
+ expect(getActiveProject(state).workflows.entries[0]?.document.name).toBe('First');
- expect(getActiveProject(state).projectGraph.id).toBe(originalGraphId);
- expect(getActiveProject(state).invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });
+ state = workbenchReducer(state, { type: 'selectProjectWorkflow', workflowId: originalGraphId });
+ state = workbenchReducer(state, { type: 'undoWorkflowChange' });
+ expect(getActiveProjectGraph(getActiveProject(state)).name).toBe('Untitled Workflow');
+ expect(getActiveProject(state).workflows.entries[1]?.document.name).toBe('Second');
});
it('does not queue Upscale while its required settings are incomplete', () => {
@@ -3204,6 +3242,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
state = workbenchReducer(state, {
backendSupportsCancellation: true,
route: { destination: 'canvas', destinationLocked: false, sourceId: 'upscale', sourceLocked: true },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -3220,9 +3259,12 @@ describe('workbenchReducer Phase 5 generation flow', () => {
describe('expanded positive prompts on the compiled submission', () => {
const submitResolvedWithPrompts = (positivePrompt: string, positivePrompts?: string[]) =>
- workbenchReducer(primeGenerate(undefined, { positivePrompt }), {
+ submitResolvedTo(primeGenerate(undefined, { positivePrompt }), positivePrompts);
+ const submitResolvedTo = (primed: WorkbenchState, positivePrompts?: string[]) =>
+ workbenchReducer(primed, {
backendSupportsCancellation: true,
positivePrompts,
+ projectId: primed.activeProjectId,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
type: 'submitResolvedInvocationSnapshot',
});
@@ -3257,7 +3299,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
// The template is what introduced the `{…}` here, so the gate has to read the
// merged prompt or the expansion would be discarded and the literal submitted.
it('keeps an expansion whose dynamic syntax came from the prompt template', () => {
- const state = workbenchReducer(
+ const state = submitResolvedTo(
primeGenerate(undefined, {
positivePrompt: 'a cat',
promptTemplate: {
@@ -3267,12 +3309,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
positivePrompt: '{prompt}, {red|green} tint',
},
}),
- {
- backendSupportsCancellation: true,
- positivePrompts: ['a cat, red tint', 'a cat, green tint'],
- route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
- type: 'submitResolvedInvocationSnapshot',
- }
+ ['a cat, red tint', 'a cat, green tint']
);
expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).toMatchObject({
@@ -3348,7 +3385,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
},
type: 'addNode',
},
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
return state;
@@ -3357,12 +3394,13 @@ describe('workbenchReducer Phase 5 generation flow', () => {
workbenchReducer(state, {
backendSupportsCancellation: true,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: false },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
const readSubmission = (state: WorkbenchState, index = 0) =>
getActiveProject(state).queue.items[index]?.snapshot.backendSubmission;
const readNodeSeed = (state: WorkbenchState) => {
- const node = getActiveProject(state).projectGraph.nodes[0];
+ const node = getActiveProjectGraph(getActiveProject(state)).nodes[0];
return node?.type === 'invocation' ? node.data.inputs.seed?.value : undefined;
};
@@ -3433,7 +3471,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
state = workbenchReducer(state, {
action: { node: invocationNode('float-1', 'float', { value: 0.5 }), type: 'addNode' },
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
state = workbenchReducer(state, {
action: {
@@ -3448,7 +3486,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
node: invocationNode('batch-1', 'float_batch', { batch_group_id: 'None', floats: [1.5, 2.5] }),
type: 'addNodeAndEdge',
},
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
state = submitWorkflow(state);
@@ -3543,7 +3581,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
},
type: 'addNode',
},
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
}
@@ -3621,6 +3659,153 @@ describe('workbenchReducer Phase 5 generation flow', () => {
expect(getActiveProject(next).queue.items).toEqual([]);
expect(readNodeSeed(next)).toBe(42);
});
+
+ describe('attribution to the originating project workflow', () => {
+ const workflowIdOf = (state: WorkbenchState) => getActiveProject(state).workflows.activeWorkflowId;
+ const seedOf = (state: WorkbenchState, workflowId: string) => {
+ const entry = getActiveProject(state).workflows.entries.find(
+ (candidate) => candidate.document.id === workflowId
+ );
+ const node = entry?.document.nodes[0];
+
+ return node?.type === 'invocation' ? node.data.inputs.seed?.value : undefined;
+ };
+ const submitFrom = (state: WorkbenchState, workflowId: string) =>
+ workbenchReducer(state, {
+ backendSupportsCancellation: true,
+ projectId: state.activeProjectId,
+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: false },
+ type: 'submitResolvedInvocationSnapshot',
+ workflowId,
+ });
+
+ it('submits and advances the captured workflow even after another one became active', () => {
+ let state = primeWorkflow(42, 'increment', 1);
+ const original = workflowIdOf(state);
+
+ state = workbenchReducer(state, {
+ document: { ...getActiveProjectGraph(getActiveProject(state)), id: 'other', name: 'Other', nodes: [] },
+ label: 'Add',
+ type: 'addProjectWorkflow',
+ });
+ expect(workflowIdOf(state)).toBe('other');
+
+ state = submitFrom(state, original);
+
+ const item = getActiveProject(state).queue.items[0];
+
+ expect(item?.snapshot.backendSubmission).toMatchObject({
+ graph: { nodes: { 'noise-1': { seed: 42 } } },
+ kind: 'workflow',
+ projectWorkflowId: original,
+ });
+ expect(seedOf(state, original)).toBe(43);
+ expect(workflowIdOf(state)).toBe('other');
+ expect(getActiveProjectGraph(getActiveProject(state)).nodes).toEqual([]);
+ });
+
+ it('queues nothing and says so when the captured workflow was removed meanwhile', () => {
+ let state = primeWorkflow(42, 'increment', 1);
+ const original = workflowIdOf(state);
+
+ state = workbenchReducer(state, {
+ document: { ...getActiveProjectGraph(getActiveProject(state)), id: 'other', name: 'Other', nodes: [] },
+ label: 'Add',
+ type: 'addProjectWorkflow',
+ });
+ state = workbenchReducer(state, { type: 'removeProjectWorkflow', workflowId: original });
+ state = submitFrom(state, original);
+
+ expect(getActiveProject(state).queue.items).toEqual([]);
+ expect(state.notifications[0]).toMatchObject({
+ kind: 'error',
+ titleKey: 'widgets.workflow.submitRemovedTitle',
+ });
+ });
+
+ it('records the newest submitted successful run on the originating workflow and nowhere else', () => {
+ vi.useFakeTimers({ now: new Date('2026-06-10T00:00:00.000Z') });
+
+ try {
+ let state = primeWorkflow(42, 'increment', 1);
+ const original = workflowIdOf(state);
+
+ state = workbenchReducer(state, {
+ copyId: 'copy',
+ copyName: 'Copy',
+ type: 'duplicateProjectWorkflow',
+ workflowId: original,
+ });
+ // The copy shares its node ids with the original; attribution goes by workflow, never by node id.
+ state = submitFrom(state, original);
+ vi.advanceTimersByTime(1000);
+ state = submitFrom(state, original);
+
+ const [second, first] = getActiveProject(state).queue.items;
+
+ expect(second?.snapshot.submittedAt).not.toBe(first?.snapshot.submittedAt);
+
+ state = workbenchReducer(state, {
+ images: [createImage('second.png', second!.id)],
+ projectId: state.activeProjectId,
+ queueItemId: second!.id,
+ type: 'routeQueueItemResults',
+ });
+ state = workbenchReducer(state, {
+ images: [createImage('first.png', first!.id)],
+ projectId: state.activeProjectId,
+ queueItemId: first!.id,
+ type: 'routeQueueItemResults',
+ });
+
+ const entries = getActiveProject(state).workflows.entries;
+
+ expect(entries.find((entry) => entry.document.id === original)?.lastRun?.imageName).toBe('second.png');
+ expect(entries.find((entry) => entry.document.id === 'copy')?.lastRun).toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('routes results of a run restored without a workflow identity without touching any workflow', () => {
+ let state = primeWorkflow(42, 'increment', 1);
+ const project = getActiveProject(state);
+ const restored = {
+ cancellable: true,
+ id: 'older-run',
+ snapshot: {
+ backendSubmission: { batchCount: 1, graph: { edges: [], id: 'g', nodes: {} }, kind: 'workflow' },
+ canvas: {
+ document: { bbox: { height: 1, width: 1, x: 0, y: 0 }, height: 1, width: 1 },
+ documentRevision: 0,
+ },
+ destination: 'gallery',
+ filterIntermediateResults: true,
+ galleryBoardId: null,
+ graph: { id: 'g', label: 'Older' },
+ presentation: { batchCount: 1, height: 1, width: 1 },
+ sourceId: 'workflow',
+ submittedAt: '2026-01-01T00:00:00.000Z',
+ },
+ status: 'running',
+ };
+
+ state = workbenchReducer(state, {
+ items: [restored],
+ projectId: project.id,
+ type: 'restoreQueueItemsFromJournal',
+ });
+ state = workbenchReducer(state, {
+ images: [createImage('old.png', 'older-run')],
+ projectId: project.id,
+ queueItemId: 'older-run',
+ type: 'routeQueueItemResults',
+ });
+
+ expect(getActiveProject(state).queue.items.find((item) => item.id === 'older-run')?.status).toBe('completed');
+ expect(getActiveProject(state).workflows.entries.every((entry) => entry.lastRun === undefined)).toBe(true);
+ });
+ });
});
describe('seed modes on the compiled submission', () => {
@@ -3633,6 +3818,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
backendSupportsCancellation: true,
positivePrompts,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -3733,6 +3919,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
backendSupportsCancellation: true,
models: upscaleModels,
route: { destination: 'gallery', destinationLocked: false, sourceId: 'upscale', sourceLocked: false },
+ projectId: state.activeProjectId,
type: 'submitResolvedInvocationSnapshot',
});
@@ -4889,14 +5076,15 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const setValue = (fieldName: string, value: number) =>
workbenchReducer(state, {
action: { fieldName, nodeId: 'node-1', type: 'setFieldValue', value },
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
const fieldValue = (fieldName: string) => {
- const node = getActiveProject(state).projectGraph.nodes[0];
+ const node = getActiveProjectGraph(getActiveProject(state)).nodes[0];
return node?.type === 'invocation' ? node.data.inputs[fieldName]?.value : undefined;
};
- const past = () => getActiveProject(state).undoRedo.past;
+ const past = () =>
+ getActiveProject(state).workflowHistories[getActiveProject(state).workflows.activeWorkflowId]?.past ?? [];
state = workbenchReducer(state, {
action: {
@@ -4918,7 +5106,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
},
type: 'addNode',
},
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
const stepsAfterAdd = past().length;
@@ -4939,18 +5127,18 @@ describe('workbenchReducer Phase 5 generation flow', () => {
expect(past()).toHaveLength(stepsAfterAdd + 3);
- state = workbenchReducer(state, { type: 'undoProjectChange' });
+ state = workbenchReducer(state, { type: 'undoWorkflowChange' });
expect(fieldValue('b')).toBeUndefined();
expect(fieldValue('a')).toBe(3);
- state = workbenchReducer(state, { type: 'undoProjectChange' });
+ state = workbenchReducer(state, { type: 'undoWorkflowChange' });
expect(fieldValue('a')).toBe(123);
- state = workbenchReducer(state, { type: 'undoProjectChange' });
+ state = workbenchReducer(state, { type: 'undoWorkflowChange' });
expect(fieldValue('a')).toBeUndefined();
// Redo brings the whole burst back at once, and a fresh edit after it starts its own step.
- state = workbenchReducer(state, { type: 'redoProjectChange' });
+ state = workbenchReducer(state, { type: 'redoWorkflowChange' });
expect(fieldValue('a')).toBe(123);
state = setValue('a', 4);
@@ -4959,17 +5147,17 @@ describe('workbenchReducer Phase 5 generation flow', () => {
// An undo inside the window ends the burst: the step the user undid back to stays its own step.
state = setValue('b', 8);
- state = workbenchReducer(state, { type: 'undoProjectChange' });
+ state = workbenchReducer(state, { type: 'undoWorkflowChange' });
state = setValue('a', 5);
expect(past()).toHaveLength(stepsAfterAdd + 3);
- state = workbenchReducer(state, { type: 'undoProjectChange' });
+ state = workbenchReducer(state, { type: 'undoWorkflowChange' });
expect(fieldValue('a')).toBe(4);
// Node moves are not history: dragging a node around leaves the steps alone.
state = workbenchReducer(state, {
action: { nodeId: 'node-1', position: { x: 10, y: 10 }, type: 'setNodePosition' },
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
});
expect(past()).toHaveLength(stepsAfterAdd + 2);
} finally {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 506edd4f20..e1f09b6b73 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -1,7 +1,7 @@
import type { GenerateWidgetValues } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
import type { QueueCompiledSubmission, QueueHistoryItemStatus } from '@features/queue/contracts';
-import type { ProjectGraphState } from '@features/workflow/contracts';
+import type { ProjectGraphState, ProjectWorkflowSource } from '@features/workflow/contracts';
import type { WorkflowSubmissionPlan } from '@features/workflow/graph';
import type { LogNamespace } from '@platform/logging/contracts';
import type {
@@ -95,6 +95,26 @@ import {
import { createNewCanvasState, loadCanvasState } from './canvasMigration';
import { applyCanvasProjectMutation, type CanvasProjectMutation } from './canvasProjectMutations';
import { gateProjectCanvases } from './projectCanvasGate';
+import {
+ addProjectWorkflow,
+ applyProjectWorkflowAction,
+ createBlankWorkflowDocument,
+ createProjectWorkflowCollection,
+ duplicateProjectWorkflow,
+ findProjectWorkflow,
+ getActiveProjectGraph,
+ getActiveProjectWorkflow,
+ migrateProjectGraphToCollection,
+ normalizeProjectWorkflowCollection,
+ recordProjectWorkflowRun,
+ redoProjectWorkflow,
+ removeProjectWorkflow,
+ selectProjectWorkflow,
+ setProjectWorkflowDocument,
+ setProjectWorkflowSource,
+ undoProjectWorkflow,
+ type ProjectWorkflowCollection,
+} from './projectWorkflows';
import { normalizeRestoredQueueItem } from './queue-integration/queueRunRestoration';
import { getProjectWidgetValues } from './widgetState';
export { nextLayerName } from './canvasProjectMutations';
@@ -144,11 +164,7 @@ import {
import { planWorkflowSubmission } from '@features/workflow/graph';
import { getInvocationTemplatesSnapshot } from '@features/workflow/react';
import {
- cloneProjectGraph,
- createProjectGraph,
- getProjectGraphUndoEntry,
hasMultipleWorkflowReturnNodes,
- normalizeProjectGraph,
projectGraphReducer,
serializeWorkflowJsonForSubmission,
type ProjectGraphAction,
@@ -308,9 +324,22 @@ type WorkbenchReducerAction =
values: Record<string, unknown>;
projectId?: string;
}
- | { type: 'applyProjectGraphAction'; action: ProjectGraphAction }
- | { type: 'replaceProjectGraph'; document: ProjectGraphState; label: string }
- | { type: 'setProjectGraphLibraryBinding'; libraryWorkflowId: string }
+ /** Edits one workflow; absent targets mean the active project's active workflow. */
+ | { type: 'applyWorkflowAction'; action: ProjectGraphAction; projectId?: string; workflowId?: string }
+ | {
+ type: 'addProjectWorkflow';
+ document: ProjectGraphState;
+ label: string;
+ projectId?: string;
+ source?: ProjectWorkflowSource;
+ reusePlaceholder?: boolean;
+ }
+ | { type: 'selectProjectWorkflow'; workflowId: string; projectId?: string }
+ | { type: 'duplicateProjectWorkflow'; workflowId: string; copyId: string; copyName: string; projectId?: string }
+ | { type: 'removeProjectWorkflow'; workflowId: string; projectId?: string }
+ | { type: 'setProjectWorkflowSource'; projectId: string; workflowId: string; source?: ProjectWorkflowSource }
+ | { type: 'undoWorkflowChange'; projectId?: string; workflowId?: string }
+ | { type: 'redoWorkflowChange'; projectId?: string; workflowId?: string }
| { type: 'submitInvocationSnapshot'; backendSupportsCancellation: boolean; models?: readonly ModelConfig[] }
| {
type: 'submitResolvedInvocationSnapshot';
@@ -321,6 +350,10 @@ type WorkbenchReducerAction =
workflowGenerators?: WorkflowGeneratorResolutions;
route: InvocationRoute;
models?: readonly ModelConfig[];
+ /** The project the submission was prepared from; a switch in between never redirects it. */
+ projectId: string;
+ /** The workflow the submission was prepared from; required for workflow routes. */
+ workflowId?: string;
}
| {
type: 'markQueueItemBackendSubmitted';
@@ -439,6 +472,7 @@ type WorkbenchReducerAction =
sourceName: string;
targetProjectId: string;
}
+ | { type: 'autosaveScheduled' }
| { type: 'autosaveStarted' }
| { type: 'autosavePending'; error: string }
| { type: 'autosaveSucceeded'; savedAt: string }
@@ -1146,15 +1180,11 @@ const cloneWidgetRegions = cloneLayoutPresetWidgetRegions;
const cloneWidgetGraphs = (widgetGraphs: Project['widgetGraphs']): Project['widgetGraphs'] =>
Object.fromEntries(Object.entries(widgetGraphs).map(([key, graph]) => [key, graph ? cloneGraph(graph) : graph]));
-// Canvas pixel history belongs to the engine; project undo preserves the live canvas.
-const createUndoSnapshot = (
- project: Project,
- projectGraph = cloneProjectGraph(project.projectGraph)
-): ProjectUndoSnapshot => ({
+// Canvas pixel history belongs to the engine and graph history to each workflow; project undo preserves both.
+const createUndoSnapshot = (project: Project): ProjectUndoSnapshot => ({
floatingWidgets: project.floatingWidgets ? { ...project.floatingWidgets } : undefined,
invocation: { ...project.invocation },
layout: { ...project.layout, panels: { ...project.layout.panels } },
- projectGraph,
widgetGraphs: cloneWidgetGraphs(project.widgetGraphs),
widgetInstances: cloneWidgetInstances(project.widgetInstances),
widgetRegions: cloneWidgetRegions(project.widgetRegions),
@@ -1166,14 +1196,13 @@ const restoreUndoSnapshot = (project: Project, snapshot: ProjectUndoSnapshot): P
floatingWidgets: snapshot.floatingWidgets ? { ...snapshot.floatingWidgets } : undefined,
invocation: { ...snapshot.invocation },
layout: { ...snapshot.layout, panels: { ...snapshot.layout.panels } },
- projectGraph: cloneProjectGraph(normalizeProjectGraph(snapshot.projectGraph)),
widgetGraphs: cloneWidgetGraphs(snapshot.widgetGraphs),
widgetInstances: cloneWidgetInstances(snapshot.widgetInstances),
widgetRegions: cloneWidgetRegions(snapshot.widgetRegions),
});
/** Capture pre-edit state; edits sharing a mergeKey within the window undo as one burst. */
-const pushUndo = (project: Project, label: string, projectGraph?: ProjectGraphState, mergeKey?: string): Project => {
+const pushUndo = (project: Project, label: string, mergeKey?: string): Project => {
const previous = project.undoRedo.past.at(-1);
const timestamp = now();
@@ -1205,7 +1234,7 @@ const pushUndo = (project: Project, label: string, projectGraph?: ProjectGraphSt
id: createId('undo'),
label,
...(mergeKey ? { mergeKey } : {}),
- project: createUndoSnapshot(project, projectGraph),
+ project: createUndoSnapshot(project),
},
].slice(-HISTORY_LIMIT),
},
@@ -1634,10 +1663,16 @@ const assembleWorkbenchProject = (
const { isArriving = true } = options;
const {
graphHistory: _graphHistory,
+ projectGraph: legacyProjectGraph,
recoveredAt: _recoveredAt,
recoveryOf: _recoveryOf,
...persistentProject
- } = project as Project & { graphHistory?: unknown; recoveredAt?: unknown; recoveryOf?: unknown };
+ } = project as Project & {
+ graphHistory?: unknown;
+ projectGraph?: unknown;
+ recoveredAt?: unknown;
+ recoveryOf?: unknown;
+ };
const legacyWidgetRegions = project.widgetRegions as
| Partial<Record<WidgetRegion | 'left-panel' | 'right-panel' | 'status-bar', WidgetRegionState>>
| undefined;
@@ -1759,15 +1794,29 @@ const assembleWorkbenchProject = (
floatingWidgets: placement.floatingWidgets,
// Resolve historical built-in preset ids to their current arrangements to avoid false layout drift.
layout: { ...project.layout, presetId: resolveLayoutPresetId(project.layout.presetId) },
- projectGraph: normalizeProjectGraph(project.projectGraph),
promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),
queue: isArriving ? { items: [] } : project.queue,
settings: normalizeProjectSettings(project.settings),
widgetRegions: placement.widgetRegions,
widgetInstances,
+ workflowHistories: isArriving ? {} : (project.workflowHistories ?? {}),
+ workflows: resolveProjectWorkflows(project.workflows, legacyProjectGraph),
};
};
+/**
+ * Documents reach here through `migrateProjectDocument`, which already refused malformed collections. Session
+ * snapshots (`normalizeWorkbenchState`) are the one input that does not: a legacy single graph migrates, and a
+ * snapshot without a usable collection gets one blank workflow rather than failing the whole session restore.
+ */
+const resolveProjectWorkflows = (
+ candidate: ProjectWorkflowCollection | undefined,
+ legacyProjectGraph: unknown
+): ProjectWorkflowCollection =>
+ normalizeProjectWorkflowCollection(candidate) ??
+ migrateProjectGraphToCollection(legacyProjectGraph ?? {}) ??
+ createProjectWorkflowCollection(createBlankWorkflowDocument());
+
/**
* Assign the server board after normalization creates missing gallery instances. Projects with no gallery layout
* remain unchanged.
@@ -1802,13 +1851,14 @@ const createProject = (index: number, id: string, preset: LayoutPreset): Project
layout: { ...defaultLayoutPreset.snapshot.layout, panels: { ...defaultLayoutPreset.snapshot.layout.panels } },
name: `Project Name #${index}`,
promptHistory: [],
- projectGraph: createProjectGraph(`${id}-graph`),
queue: { items: [] },
settings: normalizeProjectSettings(),
undoRedo: { future: [], past: [] },
widgetGraphs: {},
widgetInstances: createWidgetInstances(),
widgetRegions: createWidgetRegions(),
+ workflowHistories: {},
+ workflows: createProjectWorkflowCollection(createBlankWorkflowDocument()),
},
preset
);
@@ -2370,12 +2420,15 @@ const compileInvocationSnapshot = (
project: Project,
route: InvocationRoute,
models?: readonly ModelConfig[],
- workflowGenerators?: WorkflowGeneratorResolutions
+ workflowGenerators?: WorkflowGeneratorResolutions,
+ workflowDocument: ProjectGraphState = getActiveProjectGraph(project)
): {
graph: GraphContract;
widgetStates: WidgetStateMap;
workflowJson?: Record<string, unknown>;
workflow?: Omit<WorkflowSubmissionPlan, 'graph'>;
+ /** The project workflow the graph was compiled from; results and seed advances return to it. */
+ projectWorkflowId?: string;
} | null => {
const widgetStates = getWidgetStatesSnapshot(project.widgetInstances);
const randDevice = resolveRandDeviceMetadata(project.settings.useCpuNoise, getGenerationDevicesSnapshot().options);
@@ -2388,7 +2441,7 @@ const compileInvocationSnapshot = (
return null;
}
- const plan = planWorkflowSubmission(project.projectGraph, templatesSnapshot.templates, {
+ const plan = planWorkflowSubmission(workflowDocument, templatesSnapshot.templates, {
batchCount: sanitizeBatchCount(widgetStates.workflow?.values.batchCount),
generators: workflowGenerators,
});
@@ -2399,13 +2452,14 @@ const compileInvocationSnapshot = (
}
const { graph, ...workflow } = plan;
- const { id: _id, ...workflowJson } = serializeWorkflowJsonForSubmission(project.projectGraph);
+ const { id: _id, ...workflowJson } = serializeWorkflowJsonForSubmission(workflowDocument);
return {
graph,
+ projectWorkflowId: workflowDocument.id,
widgetStates,
workflow,
- ...(hasMultipleWorkflowReturnNodes(project.projectGraph) ? {} : { workflowJson }),
+ ...(hasMultipleWorkflowReturnNodes(workflowDocument) ? {} : { workflowJson }),
};
}
@@ -2973,8 +3027,50 @@ const routeQueueItemPartialResults = (
);
};
-const routeQueueItemResults = (project: Project, queueItemId: string, images: GeneratedImageContract[]): Project => {
- const queueItem = project.queue.items.find((item) => item.id === queueItemId);
+/** Seed advances are bookkeeping on the submitted workflow, not an undoable edit. */
+const advanceWorkflowSeeds = (
+ project: Project,
+ workflowId: string,
+ advances: WorkflowSubmissionPlan['seedAdvances']
+): Project => {
+ const entry = findProjectWorkflow(project, workflowId);
+
+ return entry
+ ? setProjectWorkflowDocument(
+ project,
+ workflowId,
+ projectGraphReducer(entry.document, { advances, type: 'advanceSeedFields' })
+ )
+ : project;
+};
+
+/** A completed workflow run becomes the originating project workflow's preview; other copies are untouched. */
+const recordWorkflowRunPreview = (
+ project: Project,
+ queueItem: QueueItem | undefined,
+ images: GeneratedImageContract[]
+): Project => {
+ const submission = queueItem?.snapshot.backendSubmission;
+ const lastImage = images.at(-1);
+
+ if (!queueItem || submission?.kind !== 'workflow' || !submission.projectWorkflowId || !lastImage) {
+ return project;
+ }
+
+ return recordProjectWorkflowRun(project, submission.projectWorkflowId, {
+ completedAt: now(),
+ imageName: lastImage.imageName,
+ submittedAt: queueItem.snapshot.submittedAt,
+ });
+};
+
+const routeQueueItemResults = (
+ sourceProject: Project,
+ queueItemId: string,
+ images: GeneratedImageContract[]
+): Project => {
+ const queueItem = sourceProject.queue.items.find((item) => item.id === queueItemId);
+ const project = recordWorkflowRunPreview(sourceProject, queueItem, images);
const destination = queueItem?.snapshot.destination ?? project.invocation.destination;
const previousSelectedSlot = getSelectedCanvasStagingSlot(project);
const nextProject = updateQueueItem(project, queueItemId, (item) => ({
@@ -3020,6 +3116,8 @@ const enqueueCompiledSnapshot = (
workflowJson?: Record<string, unknown>;
/** The workflow route's seed plan: batch data, run count, and the fields to advance. */
workflow?: Omit<WorkflowSubmissionPlan, 'graph'>;
+ /** The project workflow the graph was compiled from; results and seed advances return to it. */
+ projectWorkflowId?: string;
},
backendSupportsCancellation: boolean,
canvasSnapshot?: CanvasStateContractV3
@@ -3088,11 +3186,9 @@ const enqueueCompiledSnapshot = (
graph: backendGraph,
kind: 'workflow',
...(compiled.workflowJson ? { workflow: compiled.workflowJson } : {}),
- // Capture the library binding at submission so completion updates the originating workflow even after
- // the editor changes.
- ...(project.projectGraph.libraryWorkflowId
- ? { libraryWorkflowId: project.projectGraph.libraryWorkflowId }
- : {}),
+ // Capture the originating project workflow so results and seed advances return to it even after the
+ // active workflow changes.
+ ...(compiled.projectWorkflowId ? { projectWorkflowId: compiled.projectWorkflowId } : {}),
}
: sourceGenerateSettings && effectivePrompts
? {
@@ -3194,14 +3290,8 @@ const enqueueCompiledSnapshot = (
? { ...values, seed: seedPlan.nextSeed }
: values
)
- : compiled.workflow && compiled.workflow.seedAdvances.length > 0
- ? {
- ...project,
- projectGraph: projectGraphReducer(project.projectGraph, {
- advances: compiled.workflow.seedAdvances,
- type: 'advanceSeedFields',
- }),
- }
+ : compiled.workflow && compiled.workflow.seedAdvances.length > 0 && compiled.projectWorkflowId
+ ? advanceWorkflowSeeds(project, compiled.projectWorkflowId, compiled.workflow.seedAdvances)
: project;
return {
@@ -3249,13 +3339,14 @@ const submitInvocationSnapshot = (
route = resolveInvocationRoute(project),
models?: readonly ModelConfig[],
positivePrompts?: string[],
- workflowGenerators?: WorkflowGeneratorResolutions
+ workflowGenerators?: WorkflowGeneratorResolutions,
+ workflowDocument?: ProjectGraphState
): Project => {
if (!isInvocationRouteValid(route)) {
return project;
}
- const compiledSnapshot = compileInvocationSnapshot(project, route, models, workflowGenerators);
+ const compiledSnapshot = compileInvocationSnapshot(project, route, models, workflowGenerators, workflowDocument);
if (!compiledSnapshot) {
return project;
@@ -4108,61 +4199,72 @@ export const __workbenchReducerInternal = (
})
);
}
- case 'applyProjectGraphAction': {
- return updateActiveProject(state, (project) => {
- const projectGraph = projectGraphReducer(project.projectGraph, action.action);
+ case 'applyWorkflowAction': {
+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {
+ const workflowId = action.workflowId ?? project.workflows.activeWorkflowId;
+ const result = applyProjectWorkflowAction(project, workflowId, action.action, now());
- if (projectGraph === project.projectGraph) {
+ if (!result.didChange) {
return project;
}
- const routedProject = isHighConfidenceGraphEdit(action.action)
- ? applyAutoRouteForEdit(project, 'workflow', context)
- : project;
- const undoEntry = getProjectGraphUndoEntry(action.action);
- const nextProject = undoEntry
- ? pushUndo(routedProject, undoEntry.label, undefined, undoEntry.mergeKey)
- : routedProject;
- const updated = { ...nextProject, projectGraph };
-
- return updated;
+ // Editing an inactive workflow (a fenced async completion) must not re-route the project to it.
+ return workflowId === project.workflows.activeWorkflowId && isHighConfidenceGraphEdit(action.action)
+ ? applyAutoRouteForEdit(result.project, 'workflow', context)
+ : result.project;
});
}
- case 'replaceProjectGraph': {
- const nextState = updateActiveProject(state, (project) => {
- const routedProject = applyAutoRouteForEdit(project, 'workflow', context);
- const outgoingGraph = cloneProjectGraph(project.projectGraph);
- const nextProject = pushUndo(routedProject, 'Replace project graph', outgoingGraph);
+ case 'addProjectWorkflow': {
+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {
+ if (findProjectWorkflow(project, action.document.id)) {
+ return project;
+ }
+
+ const nextProject = addProjectWorkflow(applyAutoRouteForEdit(project, 'workflow', context), action.document, {
+ reusePlaceholder: action.reusePlaceholder,
+ source: action.source,
+ });
return {
...nextProject,
events: prependProjectEvent(nextProject.events, {
createdAt: now(),
id: createId('event'),
- summary: `Replaced the project graph with "${action.document.name || 'Untitled Workflow'}" (${action.label})`,
+ summary: `Added workflow "${action.document.name || 'Untitled Workflow'}" (${action.label})`,
type: 'graph-replaced',
}),
- projectGraph: cloneProjectGraph(action.document),
};
});
- const activeProject = nextState.projects.find((project) => project.id === nextState.activeProjectId);
-
- return addNotification(
- nextState,
- createNotification({
- kind: 'info',
- message:
- 'The previous graph is available through Undo for this session. Save workflows to the library for a permanent copy.',
- projectId: activeProject?.id,
- title: `Project graph replaced (${action.label})`,
- })
+ }
+ case 'selectProjectWorkflow': {
+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>
+ selectProjectWorkflow(project, action.workflowId)
);
}
- case 'setProjectGraphLibraryBinding': {
- return updateActiveProject(state, (project) => ({
- ...project,
- projectGraph: { ...project.projectGraph, libraryWorkflowId: action.libraryWorkflowId },
- }));
+ case 'duplicateProjectWorkflow': {
+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>
+ duplicateProjectWorkflow(project, action.workflowId, action.copyId, () => action.copyName)
+ );
+ }
+ case 'removeProjectWorkflow': {
+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>
+ removeProjectWorkflow(project, action.workflowId)
+ );
+ }
+ case 'setProjectWorkflowSource': {
+ return updateProjectById(state, action.projectId, (project) =>
+ setProjectWorkflowSource(project, action.workflowId, action.source)
+ );
+ }
+ case 'undoWorkflowChange': {
+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>
+ undoProjectWorkflow(project, action.workflowId ?? project.workflows.activeWorkflowId, now())
+ );
+ }
+ case 'redoWorkflowChange': {
+ return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) =>
+ redoProjectWorkflow(project, action.workflowId ?? project.workflows.activeWorkflowId, now())
+ );
}
case 'submitInvocationSnapshot': {
return withEnqueueNotification(
@@ -4174,19 +4276,45 @@ export const __workbenchReducerInternal = (
);
}
case 'submitResolvedInvocationSnapshot': {
+ const target = state.projects.find((project) => project.id === action.projectId);
+ const workflow =
+ target && action.route.sourceId === 'workflow'
+ ? action.workflowId
+ ? findProjectWorkflow(target, action.workflowId)
+ : getActiveProjectWorkflow(target)
+ : undefined;
+
+ // The originating workflow was removed while the submission was being prepared; nothing else may run in its
+ // place.
+ if (target && action.route.sourceId === 'workflow' && !workflow) {
+ return addNotification(
+ state,
+ createNotification({
+ category: 'enqueue',
+ kind: 'error',
+ message: 'The workflow was removed from the project before it could be queued.',
+ messageKey: 'widgets.workflow.submitRemovedBody',
+ projectId: target.id,
+ title: 'Workflow not queued',
+ titleKey: 'widgets.workflow.submitRemovedTitle',
+ })
+ );
+ }
+
return withEnqueueNotification(
state,
- updateActiveProject(state, (project) =>
+ updateProjectById(state, action.projectId, (project) =>
submitInvocationSnapshot(
project,
action.backendSupportsCancellation,
- resolveInvocationRoute(project, 'global', action.route, action.models),
+ resolveInvocationRoute(project, 'global', action.route, action.models, workflow?.document),
action.models,
action.positivePrompts,
- action.workflowGenerators
+ action.workflowGenerators,
+ workflow?.document
)
),
- state.activeProjectId
+ action.projectId
);
}
case 'markQueueItemBackendSubmitted': {
@@ -4999,6 +5127,17 @@ export const __workbenchReducerInternal = (
: [...state.projects, project],
};
}
+ case 'autosaveScheduled': {
+ return state.autosave.status === 'pending' || state.autosave.status === 'saving'
+ ? state
+ : {
+ ...state,
+ autosave: {
+ ...(state.autosave.lastSavedAt ? { lastSavedAt: state.autosave.lastSavedAt } : {}),
+ status: 'pending',
+ },
+ };
+ }
case 'autosaveStarted': {
return { ...state, autosave: { status: 'saving' } };
}
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
index d7b2e2f3e1..0a319ec8cf 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
+import { getActiveProjectGraph } from './projectWorkflows';
import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';
const preferenceOff = { autoSwitchInvocationRoute: false };
@@ -30,7 +31,7 @@ describe('auto invocation route switching with the preference off', () => {
},
type: 'addNode',
},
- type: 'applyProjectGraphAction',
+ type: 'applyWorkflowAction',
},
preferenceOff
);
@@ -65,16 +66,14 @@ describe('auto invocation route switching with the preference off', () => {
},
preferenceOff
);
- const projectGraph = state.projects.find((project) => project.id === state.activeProjectId)?.projectGraph;
-
- expect(projectGraph).toBeDefined();
+ const projectGraph = getActiveProjectGraph(state.projects.find((project) => project.id === state.activeProjectId)!);
state = workbenchReducer(
state,
{
- document: { ...projectGraph!, id: 'replacement-graph' },
+ document: { ...projectGraph, id: 'replacement-graph' },
label: 'Preference-off replacement',
- type: 'replaceProjectGraph',
+ type: 'addProjectWorkflow',
},
preferenceOff
);
@@ -90,7 +89,7 @@ describe('auto invocation route switching with the preference off', () => {
const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);
- expect(project?.projectGraph.nodes).toHaveLength(1);
+ expect(getActiveProjectGraph(project!).nodes).toHaveLength(1);
expect(project?.invocation).toMatchObject({ destination: 'gallery', sourceId: 'generate' });
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
index 126faca5ea..53ec2ef36f 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
@@ -8,6 +8,7 @@ import type { LayoutPreset, LayoutPresetRoute } from './layoutContracts';
import type { WorkbenchInternalStore, WorkbenchSnapshot } from './workbenchStore';
import { publishLayerPanelSelection, readLayerPanelState, toggleLayerStackCollapsed } from './layerPanelState';
+import { getActiveProjectGraph } from './projectWorkflows';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from './widgetPlacementMeta';
import { getProjectWidgetValues } from './widgetState';
import { createInitialWorkbenchState } from './workbenchState';
@@ -775,7 +776,7 @@ describe('createWorkbenchStore', () => {
store.commands.workflows.editGraph({ patch: { name: 'Command-owned workflow' }, type: 'setMetadata' });
- expect(store.getSnapshot().activeProject.projectGraph.name).toBe('Command-owned workflow');
+ expect(getActiveProjectGraph(store.getSnapshot().activeProject).name).toBe('Command-owned workflow');
});
it('keeps placement selectors stable across generate and settings changes', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
index 269dc757e2..772a9559bd 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
@@ -1,3 +1,4 @@
+import type { ProjectGraphState, ProjectWorkflowSource } from '@features/workflow/contracts';
import type { ProjectGraphAction } from '@features/workflow/utility';
import type { LayoutPreset } from '@workbench/layoutContracts';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
@@ -19,6 +20,7 @@ import { clearLayerPanelStates, reconcileLayerPanelStates } from './layerPanelSt
import { createLayoutPresetActivator, loadLayoutPresetWidgets } from './layoutPresetActivation';
import { resolveSavedLayoutPreset } from './layoutPresetSnapshots';
import { getLayoutWidgetTypeIds } from './layoutWidgetSet';
+import { createBlankWorkflowDocument, findProjectWorkflow } from './projectWorkflows';
import { getWorkbenchPreferences } from './settings/store';
import { areWidgetsLoaded } from './widgetRegistry';
import {
@@ -477,16 +479,76 @@ const createCommands = (
toggle: command('toggleRegionWidget'),
},
workflows: {
- bindLibraryWorkflow: command('setProjectGraphLibraryBinding', (libraryWorkflowId: string) => ({
- libraryWorkflowId,
+ /** Adds a workflow to the project and activates it; returns the id it is known by. */
+ add: (
+ document: ProjectGraphState,
+ options: { label: string; projectId?: string; reusePlaceholder?: boolean; source?: ProjectWorkflowSource }
+ ): string => {
+ dispatch({
+ document,
+ label: options.label,
+ projectId: options.projectId,
+ reusePlaceholder: options.reusePlaceholder,
+ source: options.source,
+ type: 'addProjectWorkflow',
+ });
+ return document.id;
+ },
+ create: (projectId?: string): string => {
+ const document = createBlankWorkflowDocument();
+ dispatch({ document, label: 'New workflow', projectId, type: 'addProjectWorkflow' });
+ return document.id;
+ },
+ duplicate: (workflowId: string, copyName: string, projectId?: string): string | null => {
+ const project = getState().projects.find(
+ (candidate) => candidate.id === (projectId ?? getState().activeProjectId)
+ );
+ if (!project || !findProjectWorkflow(project, workflowId)) {
+ return null;
+ }
+ const copyId = createBlankWorkflowDocument().id;
+ dispatch({ copyId, copyName, projectId, type: 'duplicateProjectWorkflow', workflowId });
+ return copyId;
+ },
+ editGraph: command(
+ 'applyWorkflowAction',
+ (action: ProjectGraphAction, target?: { projectId: string; workflowId: string }) => ({
+ action,
+ projectId: target?.projectId,
+ workflowId: target?.workflowId,
+ })
+ ),
+ redo: command('redoWorkflowChange', (target?: { projectId?: string; workflowId?: string }) => ({
+ projectId: target?.projectId,
+ workflowId: target?.workflowId,
})),
- editGraph: command('applyProjectGraphAction', (action: ProjectGraphAction) => ({ action })),
- replace: command(
- 'replaceProjectGraph',
- (document: ActionPayload<'replaceProjectGraph'>['document'], label: string) => ({ document, label })
+ remove: command('removeProjectWorkflow', (workflowId: string, projectId?: string) => ({ projectId, workflowId })),
+ rename: (workflowId: string, name: string, projectId?: string): ProjectCommandResult => {
+ if (!name.trim()) {
+ return { ok: false, reason: 'invalid-name' };
+ }
+ dispatch({
+ action: { patch: { name: name.trim() }, type: 'setMetadata' },
+ projectId,
+ type: 'applyWorkflowAction',
+ workflowId,
+ });
+ return { ok: true };
+ },
+ select: command('selectProjectWorkflow', (workflowId: string, projectId?: string) => ({ projectId, workflowId })),
+ /** Records where a workflow was explicitly published; a no-op once the project or workflow is gone. */
+ setSource: command(
+ 'setProjectWorkflowSource',
+ (projectId: string, workflowId: string, source: ProjectWorkflowSource | undefined) => ({
+ projectId,
+ source,
+ workflowId,
+ })
),
- redo: command('redoProjectChange'),
- undo: command('undoProjectChange'),
+ undo: command('undoWorkflowChange', (target?: { projectId?: string; workflowId?: string }) => ({
+ projectId: target?.projectId,
+ workflowId: target?.workflowId,
+ })),
},
};
};
@@ -522,6 +584,7 @@ const createPersistenceAdapter = (dispatch: WorkbenchDispatch, getState: () => W
},
saveFailed: command('autosaveFailed', (error: string) => ({ error })),
savePending: command('autosavePending', (error: string) => ({ error })),
+ saveScheduled: command('autosaveScheduled'),
saveStarted: command('autosaveStarted'),
saveSucceeded: command('autosaveSucceeded', (savedAt: string) => ({ savedAt })),
};
diff --git a/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts b/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts
deleted file mode 100644
index 370adb1ea3..0000000000
--- a/invokeai/frontend/webv2/src/workbench/workflowRunBinding.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import type * as workflowReactModule from '@features/workflow/react';
-import type { WorkbenchState } from '@workbench/projectContracts';
-
-// Reuse feature-private graph builders under the test dependency exemption.
-import { buildInvocationNode, createProjectGraph, projectGraphReducer } from '@features/workflow/core/document';
-import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-/**
- * Submission captures the originating library binding; stub loaded templates for the imperative resolver and
- * compiler.
- */
-
-const stringField = { batch: false, cardinality: 'SINGLE' as const, name: 'StringField' };
-
-const template = {
- category: 'test',
- classification: 'stable' as const,
- description: '',
- inputs: {
- value: {
- default: 'hello',
- description: '',
- exclusiveMaximum: null,
- exclusiveMinimum: null,
- fieldKind: 'input' as const,
- input: 'any' as const,
- maximum: null,
- minimum: null,
- multipleOf: null,
- name: 'value',
- options: null,
- required: true,
- title: 'value',
- type: stringField,
- uiChoiceLabels: null,
- uiComponent: null,
- uiHidden: false,
- uiModelBase: null,
- uiModelFormat: null,
- uiModelType: null,
- uiOrder: null,
- },
- },
- nodePack: 'invokeai',
- outputs: { out: { description: '', name: 'out', title: 'Out', type: stringField } },
- outputType: 'source_output',
- tags: [],
- title: 'source',
- type: 'source',
- useCache: true,
- version: '1.0.0',
-};
-
-vi.mock('@features/workflow/react', async (importOriginal) => ({
- ...(await importOriginal<typeof workflowReactModule>()),
- getInvocationTemplatesSnapshot: () => ({ error: null, status: 'loaded', templates: { source: template } }),
-}));
-
-const buildReadyGraph = (libraryWorkflowId?: string) => {
- let document = createProjectGraph('run-binding');
-
- document = projectGraphReducer(document, { node: buildInvocationNode(template, { x: 0, y: 0 }), type: 'addNode' });
-
- return { ...document, ...(libraryWorkflowId ? { libraryWorkflowId } : {}) };
-};
-
-/** Mounts the workflow widget so the workflow source resolves as available. */
-const withWorkflowWidgetMounted = (state: WorkbenchState): WorkbenchState => ({
- ...state,
- projects: state.projects.map((project) => ({
- ...project,
- widgetRegions: {
- ...project.widgetRegions,
- center: { ...project.widgetRegions.center, activeInstanceId: 'workflow', instanceIds: ['workflow'] },
- },
- })),
-});
-
-const submitWorkflow = (libraryWorkflowId?: string) => {
- let state = withWorkflowWidgetMounted(createInitialWorkbenchState());
-
- state = workbenchReducer(state, {
- document: buildReadyGraph(libraryWorkflowId),
- label: 'Load workflow',
- type: 'replaceProjectGraph',
- });
- state = workbenchReducer(state, {
- backendSupportsCancellation: true,
- route: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: true },
- type: 'submitResolvedInvocationSnapshot',
- });
-
- const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);
-
- return project?.queue.items[0];
-};
-
-describe('library binding on the compiled workflow submission', () => {
- beforeEach(() => {
- vi.restoreAllMocks();
- });
-
- it('stamps the bound library record onto the run it submits', () => {
- expect(submitWorkflow('library-workflow-1')?.snapshot.backendSubmission).toMatchObject({
- kind: 'workflow',
- libraryWorkflowId: 'library-workflow-1',
- });
- });
-
- it('leaves an unbound workflow run unstamped', () => {
- expect(submitWorkflow()?.snapshot.backendSubmission).not.toHaveProperty('libraryWorkflowId');
- });
-});