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.

refactor(workbench): slim queue snapshots

Josh Corbett19fe041c304a
diff --git a/docs/src/content/docs/development/Front End/project-files.mdx b/docs/src/content/docs/development/Front End/project-files.mdx
index b02f12a1d6..272a44d258 100644
--- a/docs/src/content/docs/development/Front End/project-files.mdx
+++ b/docs/src/content/docs/development/Front End/project-files.mdx
@@ -100,7 +100,7 @@ Exclusion is two things, not one. The collector skips those keys so their pixels
The skip is by key on purpose, because the members got there differently. `selectedImage` and the name keys were already missed — `GalleryItem` spells its name field `name`, which no collector key matches — but that is an accident of naming that a rename would have undone. `compareImage` is a `GeneratedImageContract` carrying `imageName`, so it was genuinely being bundled until the exclusion became explicit.
-**History is excluded.** The walker skips the `queue`, `graphHistory` and `events` roots, and the `snapshot`, `snapshots` and `recentImages` keys at any depth. The root skip list also recognizes legacy documents, which may still contain the removed graph-history field. New project files strip graph history and session events; historical references are compatibility input and are never bundled as live project assets.
+**History is excluded.** The walker skips the `queue`, `graphHistory` and `events` roots, and the `snapshot`, `snapshots` and `recentImages` keys at any depth. The root skip list also recognizes legacy documents, which may still contain those fields. New project files strip queue history, graph history and session events; historical references are compatibility input and are never bundled as live project assets.
## Loading
@@ -176,7 +176,7 @@ On import the cover prefers an image the restore already put on this server —
Adding `board.json` did **not** bump the manifest version. A version tells a reader what it may assume about a file *somebody else wrote*, and webv2 has not shipped — no archive exists anywhere that predates the entry except the ones dev builds produced, and those are read exactly as what they are: an archive that names no board, whose import restores document references and lets the server create the new project an empty board. Inventing an empty board for such a file would claim knowledge it does not contain, which is why "absent" and "empty" stay distinguishable in the reader.
-The v2 manifest may carry `minimumCanvasSchemaVersion`. This is the source project's monotonic compatibility floor, not merely the version of its live canvas; queue snapshots or retained history can require a newer reader than the visible document does. Export copies the acknowledged server floor, and import creates the new project with the greater of that floor and the requirement derived from the canonical imported document. An archive above this client's maximum is refused before a staging board or any media upload exists. Older v2 archives omit the field and continue to derive their requirement from their document.
+The v2 manifest may carry `minimumCanvasSchemaVersion`. This is the source project's monotonic compatibility floor, not merely the version of its live canvas. It may conservatively retain a higher requirement inherited from a legacy server record whose queue history is removed during canonical export. Export copies the acknowledged server floor, and import creates the new project with the greater of that floor and the requirement derived from the canonical imported document. An archive above this client's maximum is refused before a staging board or any media upload exists. Older v2 archives omit the field and continue to derive their requirement from their document.
A malformed `board.json` is a different matter and is refused as `damaged`: half an enumeration is not a board. The entry carries its own `version: 1`, which is the *file's* version and not the API's — the snapshot endpoint returns `{items}` and nothing else, so neither format is pinned to the other.
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index 5a1df785c4..46879ba068 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -127,7 +127,6 @@
"projectEventContracts.ts": "workbench",
"projectEvents.ts": "workbench",
"queueHistoryContracts.ts": "workbench",
- "queueHistoryNormalization.ts": "workbench",
"useCanvasProjectMutationDispatch.ts": "workbench",
"useNotify.ts": "workbench",
"useOpenWorkbenchWidget.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.ts b/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.ts
index dde75f53e3..441d7ec5c6 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/historySummary.test.ts
@@ -33,7 +33,7 @@ const createQueueItem = ({
destination: 'gallery',
filterIntermediateResults: false,
galleryBoardId: null,
- graph: { edges: [], id: 'graph-1', label: 'Graph', nodes: [], updatedAt: submittedAt, version: 1 },
+ graph: { id: 'graph-1', label: 'Graph' },
presentation: { batchCount, height: 1024, width: 1024 },
sourceId,
submittedAt,
diff --git a/invokeai/frontend/webv2/src/features/queue/core/progressRail.test.ts b/invokeai/frontend/webv2/src/features/queue/core/progressRail.test.ts
index 19c9c362a5..9c4b394b43 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/progressRail.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/progressRail.test.ts
@@ -27,7 +27,7 @@ const createQueueItem = ({
destination: 'gallery',
filterIntermediateResults: false,
galleryBoardId: null,
- graph: { edges: [], id: 'graph-1', label: 'Graph', nodes: [], updatedAt: '2026-08-15T00:00:00.000Z', version: 1 },
+ graph: { id: 'graph-1', label: 'Graph' },
presentation: { batchCount: 1, height: 1024, width: 1024 },
sourceId: 'generate',
submittedAt: '2026-08-15T00:00:00.000Z',
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index 628198de50..a8a6352975 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -28,13 +28,8 @@ export interface QueueSubmissionPresentation {
}
export interface QueueGraphSnapshot {
- backendGraph?: QueueBackendGraph;
- edges?: unknown[];
id: string;
label: string;
- nodes?: unknown[];
- updatedAt?: string;
- version?: number;
}
export interface QueueEnqueueWorkflowRequest {
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 a080f4fa45..9be01df8fb 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts
@@ -65,16 +65,9 @@ describe('Upscale snapshot submission', () => {
const project = state.projects.find((candidate) => candidate.id === projectId)!;
const queueItem = project.queue.items[0]!;
- const snapshotValues = queueItem.snapshot.widgetStates.upscale?.values;
expect(queueItem.snapshot.sourceId).toBe('upscale');
- expect(snapshotValues).toMatchObject({
- batchCount: 3,
- inputImage: { image_name: 'input.png' },
- negativePrompt: 'blur',
- positivePrompt: 'fine detail',
- seed: Math.floor(0.25 * 4_294_967_295),
- });
+ expect(queueItem.snapshot.recall).toBeUndefined();
expect(project.promptHistory[0]).toEqual({ negativePrompt: 'blur', positivePrompt: 'fine detail' });
expect(project.widgetGraphs.upscale?.backendGraph?.nodes.upscale_output).toMatchObject({
is_intermediate: false,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index e67729a657..0d4e724f49 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -93,7 +93,7 @@ This creates a deliberate transaction boundary:
Canvas invocation first crosses the paint-flush barrier, then captures the post-flush document, plans every raster/control/regional composite, and detaches exactly the contributing layers. Composite dedupe writes are staged in transaction-local maps. They are published to the persistent per-engine dedupe cache only after all frozen compositing, uploads, compilation, and queue dispatch complete; stale or failed captures leave no persistent dedupe entries.
-`submitCanvasInvocationSnapshot` carries the exact cloned canvas state used for compilation. `enqueueCompiledSnapshot` clones that supplied state rather than reading the live project canvas. Generated candidates are placed from `queueItem.snapshot.canvas.document.bbox`, so later bbox edits do not move the result. `documentRevision` still prevents results from a replaced canvas session from entering current staging.
+`submitCanvasInvocationSnapshot` carries the exact cloned canvas state used for compilation. `enqueueCompiledSnapshot` extracts its bounding box, dimensions, and document revision rather than reading the live project canvas. Generated candidates are placed from `queueItem.snapshot.canvas.document.bbox`, so later bbox edits do not move the result. `documentRevision` still prevents results from a replaced canvas session from entering current staging.
## Frame demand before allocation
diff --git a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
index d6504fe85b..029f3d2bf2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.test.ts
@@ -3,21 +3,18 @@ import { describe, expect, it } from 'vitest';
import { getProjectCanvasSchemaRequirement } from './canvasSchemaVersion';
describe('getProjectCanvasSchemaRequirement', () => {
- it('uses the highest schema version across the live canvas and queue snapshots', () => {
+ it('uses only the live canvas schema version', () => {
expect(
getProjectCanvasSchemaRequirement({
canvas: { version: 2 },
- queue: {
- items: [{ snapshot: { canvas: { version: 2 } } }, { snapshot: { canvas: { version: 3 } } }],
- },
+ queue: { items: [{ snapshot: { canvas: { version: 99 } } }] },
})
- ).toBe(3);
+ ).toBe(2);
});
it.each([
['the live canvas is missing', {}],
['the live version is malformed', { canvas: { version: '2' } }],
- ['a queue snapshot is malformed', { canvas: { version: 2 }, queue: { items: [{}] } }],
])('fails closed when %s', (_label, document) => {
expect(() => getProjectCanvasSchemaRequirement(document)).toThrow();
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
index 2db23152a8..ac5aa17b1e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasSchemaVersion.ts
@@ -23,25 +23,6 @@ const requireDeclaredCanvasVersion = (canvas: unknown): number => {
return canvas.version as number;
};
-/**
- * The compatibility floor implied by every canvas embedded in a canonical project document.
- *
- * Call this only after the project-ingestion gate has validated the live canvas and queue
- * snapshots. Throwing on malformed input is deliberate: silently defaulting here could publish a
- * document under a floor that an older client cannot actually read.
- */
-export const getProjectCanvasSchemaRequirement = (document: Record<string, unknown>): number => {
- let requirement = requireDeclaredCanvasVersion(document.canvas);
- const queue = isRecord(document.queue) ? document.queue : null;
- const items = queue && Array.isArray(queue.items) ? queue.items : [];
-
- for (const item of items) {
- if (!isRecord(item) || !isRecord(item.snapshot)) {
- throw new Error('A validated project document must contain valid queue snapshots.');
- }
-
- requirement = Math.max(requirement, requireDeclaredCanvasVersion(item.snapshot.canvas));
- }
-
- return requirement;
-};
+/** Compatibility floor implied by the canonical project's live canvas. */
+export const getProjectCanvasSchemaRequirement = (document: Record<string, unknown>): number =>
+ requireDeclaredCanvasVersion(document.canvas);
diff --git a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts
index 572ee5f5f3..1232a999ad 100644
--- a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts
@@ -4,11 +4,10 @@ import { createEmptyCanvasState } from './canvasMigration';
import { gateProjectCanvases } from './projectCanvasGate';
const canvas = createEmptyCanvasState();
-const queueItem = (id: string, itemCanvas: unknown) => ({ id, snapshot: { canvas: itemCanvas } });
describe('gateProjectCanvases', () => {
- it('admits a project whose live and queued canvases load', () => {
- expect(gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [queueItem('q', canvas)] } })).toBeNull();
+ it('admits a project whose live canvas loads and ignores removed queue history', () => {
+ expect(gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [{ snapshot: null }] } })).toBeNull();
expect(gateProjectCanvases({ id: 'legacy', name: 'Legacy' })).toBeNull();
expect(gateProjectCanvases('not a project')).toBeNull();
});
@@ -30,38 +29,4 @@ describe('gateProjectCanvases', () => {
source: 'canvas',
});
});
-
- it('refuses a project for any invalid queue canvas before normalization, naming the item', () => {
- const invalidItem = queueItem('invalid', { ...canvas, version: '2' });
- const futureItem = queueItem('future', { ...canvas, version: 4 });
- const invalidProject = { canvas, id: 'p', name: 'P', queue: { items: [invalidItem] } };
-
- expect(gateProjectCanvases(invalidProject)).toMatchObject({
- queueItem: { index: 0, itemId: 'invalid' },
- raw: invalidProject,
- refusal: { status: 'invalid' },
- source: 'queue-item',
- });
- expect(gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [futureItem] } })).toMatchObject({
- queueItem: { index: 0, itemId: 'future' },
- refusal: { status: 'unsupported-version', version: 4 },
- source: 'queue-item',
- });
-
- expect(
- gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [{ id: 'missing', snapshot: {} }] } })
- ).toMatchObject({
- queueItem: { index: 0, itemId: 'missing' },
- refusal: { status: 'invalid' },
- source: 'queue-item',
- });
-
- expect(
- gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [{ id: 'missing', snapshot: null }] } })
- ).toMatchObject({
- queueItem: { index: 0, itemId: 'missing' },
- refusal: { status: 'invalid' },
- source: 'queue-item',
- });
- });
});
diff --git a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.ts b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.ts
index e05e1bc5b2..2bfc4d58ad 100644
--- a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.ts
+++ b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.ts
@@ -1,73 +1,23 @@
-import type { CanvasLoadRefusal } from './canvasLoadContracts';
import type { RefusedWorkbenchProject } from './projectContracts';
import { isRecord, loadCanvasState } from './canvasMigration';
const asString = (value: unknown): string => (typeof value === 'string' ? value : '');
-const invalidQueueSnapshot = (raw: unknown, path: string, message: string): CanvasLoadRefusal => ({
- diagnostics: [{ message, path }],
- raw,
- scope: 'snapshot',
- status: 'invalid',
-});
-
-/**
- * The project-ingestion gate: version-checks every canvas embedded in a raw project document
- * before anything migrates, defaults, or clones it. A live canvas is refused for any load
- * failure. Queue history is gated before normalization too: refusing the containing project is what
- * keeps the malformed snapshot available in the existing raw-project recovery path.
- */
+/** Refuses a project before migrations can rewrite an unsupported live canvas. */
export const gateProjectCanvases = (raw: unknown): RefusedWorkbenchProject | null => {
if (!isRecord(raw)) {
return null;
}
- const refuse = (
- refusal: CanvasLoadRefusal,
- source: 'canvas' | 'queue-item',
- queueItem?: RefusedWorkbenchProject['queueItem']
- ): RefusedWorkbenchProject => {
- const base = { projectId: asString(raw.id), projectName: asString(raw.name), raw, refusal };
- if (source === 'canvas') {
- return { ...base, source };
- }
- if (!queueItem) {
- throw new Error('A queue-item refusal requires queue item identity.');
- }
- return { ...base, queueItem, source };
- };
-
const canvas = loadCanvasState(raw.canvas);
if (canvas.status !== 'loaded') {
- return refuse(canvas, 'canvas');
- }
-
- const items = isRecord(raw.queue) && Array.isArray(raw.queue.items) ? raw.queue.items : [];
- for (const [index, item] of items.entries()) {
- const itemId = isRecord(item) && typeof item.id === 'string' ? item.id : null;
- if (!isRecord(item)) {
- return refuse(invalidQueueSnapshot(item, `queue.items[${index}]`, 'queue item is invalid'), 'queue-item', {
- index,
- itemId,
- });
- }
- if (!isRecord(item.snapshot)) {
- return refuse(
- invalidQueueSnapshot(item.snapshot, `queue.items[${index}].snapshot`, 'queue snapshot is missing or invalid'),
- 'queue-item',
- { index, itemId }
- );
- }
- const result = isRecord(item.snapshot.canvas)
- ? loadCanvasState(item.snapshot.canvas)
- : invalidQueueSnapshot(
- item.snapshot.canvas,
- `queue.items[${index}].snapshot.canvas`,
- 'queue snapshot canvas is missing or invalid'
- );
- if (result.status !== 'loaded') {
- return refuse(result, 'queue-item', { index, itemId });
- }
+ return {
+ projectId: asString(raw.id),
+ projectName: asString(raw.name),
+ raw,
+ refusal: canvas,
+ source: 'canvas',
+ };
}
return null;
};
diff --git a/invokeai/frontend/webv2/src/workbench/projectContracts.ts b/invokeai/frontend/webv2/src/workbench/projectContracts.ts
index aec6bc6cbd..2623eb3ec2 100644
--- a/invokeai/frontend/webv2/src/workbench/projectContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/projectContracts.ts
@@ -66,11 +66,6 @@ export type RefusedWorkbenchProject = RefusedWorkbenchProjectBase &
(
| { refusal: CanvasLoadRefusal; source: 'canvas'; queueItem?: never }
| { refusal: ProjectDocumentLoadRefusal; source: 'project-document'; queueItem?: never }
- | {
- refusal: CanvasLoadRefusal;
- source: 'queue-item';
- queueItem: { index: number; itemId: string | null };
- }
);
export type ProjectLoadResult =
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
index 5f2bb95e47..f9cb297c2c 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts
@@ -14,11 +14,11 @@
*
* ### Collection skips history, remapping does not
*
- * Queue entries embed whole canvas snapshots and the gallery keeps sixty recents, so bundling
- * everything turns a working project into a multi-gigabyte archive; {@link collectLiveAssetRefs}
- * walks only what the project needs to open. {@link remapAssetRefs} walks everything, because a
- * renamed asset's references must all follow — including the history we chose not to bundle, which
- * would otherwise point at the pre-import name forever.
+ * Legacy queue entries embedded whole canvas snapshots and the gallery keeps sixty recents, so
+ * bundling everything could turn a working project into a multi-gigabyte archive;
+ * {@link collectLiveAssetRefs} walks only what the project needs to open. {@link remapAssetRefs}
+ * walks everything, because imported legacy documents may still contain history while their asset
+ * references are being rewritten before canonical serialization removes it.
*/
/** Keys whose string values name an image. */
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts b/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts
index 84bd250467..b47ae33a1e 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectDocument.ts
@@ -98,6 +98,7 @@ export const serializeProjectDocument = (project: Project): Record<string, unkno
const {
events: _events,
graphHistory: _graphHistory,
+ queue: _queue,
undoRedo: _undoRedo,
...document
} = stripSessionScopedGalleryState(project) as Project & { graphHistory?: unknown };
@@ -119,38 +120,14 @@ const normalizeInvocationSourceId = (sourceId: unknown): unknown => {
export const normalizeLegacyProjectDocument = (data: Record<string, unknown>): Record<string, unknown> => {
const invocation = data.invocation;
- const queue = data.queue;
+ const { events: _events, graphHistory: _graphHistory, queue: _queue, ...document } = data;
return {
- ...data,
+ ...document,
invocation:
invocation && typeof invocation === 'object'
? { ...invocation, sourceId: normalizeInvocationSourceId((invocation as { sourceId?: unknown }).sourceId) }
: invocation,
- queue:
- queue && typeof queue === 'object' && Array.isArray((queue as { items?: unknown }).items)
- ? {
- ...queue,
- items: (queue as { items: unknown[] }).items.map((item) => {
- if (!item || typeof item !== 'object') {
- return item;
- }
-
- const snapshot = (item as { snapshot?: unknown }).snapshot;
-
- return {
- ...item,
- snapshot:
- snapshot && typeof snapshot === 'object'
- ? {
- ...snapshot,
- sourceId: normalizeInvocationSourceId((snapshot as { sourceId?: unknown }).sourceId),
- }
- : snapshot,
- };
- }),
- }
- : queue,
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
index 7a5d7916bb..f0f040fa00 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts
@@ -220,6 +220,43 @@ describe('exportLibraryProject', () => {
expect(downloads.downloadBlob.mock.calls[0]![1]).toBe('Closed.invk');
});
+ it('canonicalizes a supported legacy server record before exporting it', async () => {
+ const document = {
+ ...persistence.serializeProjectDocument({ ...createDraftProject([]), name: 'Legacy' }),
+ events: [{ id: 'legacy-event' }],
+ graphHistory: [{ id: 'legacy-graph' }],
+ queue: { items: [{ id: 'legacy-queue' }] },
+ };
+
+ api.getProject.mockResolvedValue({ data: document, name: 'Legacy', project_id: 'p1', revision: 3 });
+
+ await projectFile.exportLibraryProject('p1');
+
+ const { readArchive, readEntryText } = await import('./invk/archive');
+ const [blob] = downloads.downloadBlob.mock.calls.at(-1)! as [Blob];
+ 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).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' };
+
+ api.getProject.mockResolvedValue({ data: document, name: 'Future', project_id: 'p1', revision: 3 });
+
+ await projectFile.exportLibraryProject('p1');
+
+ const { readArchive, readEntryText } = await import('./invk/archive');
+ const [blob] = downloads.downloadBlob.mock.calls.at(-1)! as [Blob];
+ const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));
+
+ expect(JSON.parse(readEntryText(entries.get('project.json')!))).toEqual(document);
+ });
+
it('records the source project compatibility floor in the archive', async () => {
const document = persistence.serializeProjectDocument({ ...createDraftProject([]), name: 'Future history' });
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
index 91233cd8c1..2bf118b62d 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts
@@ -168,7 +168,14 @@ export const exportLibraryProject = async (
assertAccountScopeCurrent(owner);
- return exportProjectDocument(record.name, record.project_id, record.data, record.minimum_canvas_schema_version, {
+ const [{ deserializeProjectDocument }, { serializeProjectDocumentV2 }] = await Promise.all([
+ import('./projectHydration'),
+ import('./projectDocument'),
+ ]);
+ const loaded = deserializeProjectDocument(record.data);
+ const document = loaded.status === 'loaded' ? serializeProjectDocumentV2(loaded.project) : record.data;
+
+ return exportProjectDocument(record.name, record.project_id, document, record.minimum_canvas_schema_version, {
...options,
owner,
});
@@ -185,10 +192,8 @@ export const exportOpenProject = async (
assertAccountScopeCurrent(owner);
- // A source project can retain a higher compatibility floor than its current live canvas (for
- // example because queue history still carries newer data). When an editor owns the project,
- // flush and read that authoritative floor; direct/offline exports fall back to what their bytes
- // demonstrably require.
+ // Preserve any higher compatibility floor already acknowledged by the server. Direct/offline
+ // exports fall back to what their live canvas demonstrably requires.
const record = getOpenProject(project.id) ? await readAcknowledgedProject(project.id, owner) : null;
const minimumCanvasSchemaVersion = Math.max(
getProjectCanvasSchemaRequirement(document),
diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
index 836d36da15..64c8cff66e 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts
@@ -89,7 +89,21 @@ describe('project document serialization', () => {
expect(encoded.byteSize).toBe(new TextEncoder().encode(encoded.documentJson).byteLength);
});
- it('excludes session events and legacy graph history from project files', () => {
+ it('keeps project document bytes constant as session queue history grows', () => {
+ const project = getProject();
+ const baseline = serializeProjectDocumentV2Json(project);
+ project.queue.items = Array.from({ length: 2_000 }, (_, index) => ({
+ id: `queue-${index}`,
+ snapshot: { oversizedContext: 'x'.repeat(100) },
+ })) as never;
+
+ const withQueueHistory = serializeProjectDocumentV2Json(project);
+
+ expect(withQueueHistory.byteSize).toBe(baseline.byteSize);
+ expect(withQueueHistory.documentJson).toBe(baseline.documentJson);
+ });
+
+ it('excludes session state and legacy history from project files', () => {
const project = getProject();
Object.assign(project, { graphHistory: [{ id: 'legacy-snapshot' }] });
@@ -97,6 +111,7 @@ describe('project document serialization', () => {
expect(document).not.toHaveProperty('events');
expect(document).not.toHaveProperty('graphHistory');
+ expect(document).not.toHaveProperty('queue');
});
it('rejects documents that do not look like projects', () => {
@@ -178,31 +193,8 @@ describe('project document serialization', () => {
});
it('normalizes legacy project-graph invocation sources to workflow', () => {
- const base = getProject();
const project = getProject({
invocation: { destination: 'gallery', destinationLocked: false, sourceId: 'workflow', sourceLocked: false },
- queue: {
- items: [
- {
- cancellable: true,
- id: 'legacy-queue-item',
- snapshot: {
- backendSubmission: { batchCount: 1, graph: { edges: [], id: 'graph', nodes: {} }, kind: 'workflow' },
- canvas: base.canvas,
- destination: 'gallery',
- filterIntermediateResults: true,
- galleryBoardId: null,
- graph: { edges: [], id: 'graph', label: 'Graph', nodes: [], updatedAt: 'now', version: 1 },
- presentation: { batchCount: 1, height: 1024, width: 1024 },
- sourceId: 'workflow',
- submittedAt: 'now',
- widgetInstances: {},
- widgetStates: {},
- },
- status: 'pending',
- },
- ],
- },
});
const document = serializeProjectDocument(project);
@@ -212,19 +204,11 @@ describe('project document serialization', () => {
sourceId: 'project-graph',
sourceLocked: false,
};
- document.queue = {
- items: [
- {
- ...(project.queue.items[0] as object),
- snapshot: { ...project.queue.items[0]?.snapshot, sourceId: 'project-graph' },
- },
- ],
- };
const deserialized = loadDocument(document);
expect(deserialized.invocation.sourceId).toBe('workflow');
- expect(deserialized.queue.items[0]?.snapshot.sourceId).toBe('workflow');
+ expect(deserialized.queue.items).toEqual([]);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
index 17f338aa06..e4b458ce96 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts
@@ -66,8 +66,8 @@ export const buildQueueRecallValues = (
// metadata has no snapshot and carries the merged prompt outright, so
// there the current template has to go or it would wrap it a second time.
//
- // Coalesced because queue history is persisted: a snapshot written before
- // templates existed has no such field, and must not recall `undefined`.
+ // Older recall snapshots may predate prompt templates and must not recall
+ // `undefined` into the current settings.
promptTemplate: snapshot ? (snapshot.promptTemplate ?? null) : null,
...(negativePrompt !== undefined
? { negativePrompt, negativePromptEnabled: snapshot?.negativePromptEnabled ?? negativePrompt.length > 0 }
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.ts
index 8658e3d077..1f34782499 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalGenerateValues.ts
@@ -48,9 +48,7 @@ export const useLocalGenerateValues = (origin?: string | null): GenerateWidgetVa
return null;
}
- const generate = (localItem.snapshot.widgetStates as Record<string, { values?: unknown }>).generate;
-
- return (generate?.values as GenerateWidgetValues | undefined) ?? null;
+ return localItem.snapshot.recall?.generateValues ?? null;
});
/**
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts
index 3e0c01dfec..826ef3ea2b 100644
--- a/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts
@@ -1,20 +1,22 @@
import type { GenerateWidgetValues } from '@features/generation/contracts';
import type { QueueItem, QueueState, QueueSubmissionSnapshot } from '@features/queue/contracts';
+import type { VideoWidgetValues } from '@features/video';
import type { CanvasStateContractV3 } from './canvas-engine/api';
-import type { WidgetInstanceContract, WidgetInstanceId, WidgetStateMap } from './widgetContracts';
-/** Workbench-owned persistence context that Queue stores but never interprets. */
+export interface QueueCanvasSessionRef {
+ document: Pick<CanvasStateContractV3['document'], 'bbox' | 'height' | 'width'>;
+ documentRevision: number;
+}
+
+export interface WorkbenchQueueRecallValues {
+ generateValues?: GenerateWidgetValues;
+ videoValues?: VideoWidgetValues;
+}
+
export interface WorkbenchQueueSubmissionContext {
- canvas: CanvasStateContractV3;
- generate?: {
- negativePromptNodeId: string;
- positivePromptNodeId: string;
- seedNodeId: string;
- values: GenerateWidgetValues;
- };
- widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;
- widgetStates: WidgetStateMap;
+ canvas: QueueCanvasSessionRef;
+ recall?: WorkbenchQueueRecallValues;
}
export type WorkbenchQueueItem = Omit<QueueItem, 'snapshot'> & {
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts
deleted file mode 100644
index 3a8fedf1f8..0000000000
--- a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.test.ts
+++ /dev/null
@@ -1,341 +0,0 @@
-import type { GenerateWidgetValues } from '@features/generation/contracts';
-
-import { describe, expect, it } from 'vitest';
-
-import { normalizeWorkbenchQueueHistory } from './queueHistoryNormalization';
-import { createInitialWorkbenchState } from './workbenchState.testing';
-
-const backendGraph = { edges: [], id: 'backend-graph', nodes: {} };
-
-const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues =>
- ({
- aspectRatioId: '1:1',
- aspectRatioIsLocked: true,
- aspectRatioValue: 1,
- batchCount: 3,
- cfgRescaleMultiplier: 0,
- cfgScale: 7,
- clipEmbedModel: null,
- clipGEmbedModel: null,
- clipLEmbedModel: null,
- clipSkip: 0,
- colorCompensation: false,
- componentSourceModel: null,
- height: 768,
- loras: [],
- model: { base: 'sdxl', key: 'model', name: 'Model', type: 'main' },
- modelKey: 'model',
- negativePrompt: 'fog',
- negativePromptEnabled: true,
- negativePromptHeightPx: 80,
- positivePrompt: 'a lighthouse',
- positivePromptHeightPx: 80,
- qwen3EncoderModel: null,
- qwenVLEncoderModel: null,
- referenceImages: [],
- scheduler: 'euler',
- seamlessXAxis: false,
- seamlessYAxis: false,
- seed: 42,
- shouldRandomizeSeed: false,
- steps: 20,
- t5EncoderModel: null,
- vae: null,
- vaePrecision: 'fp32',
- width: 1024,
- ...overrides,
- }) as GenerateWidgetValues;
-
-const createContext = () => {
- const project = createInitialWorkbenchState().projects[0]!;
- return { canvas: project.canvas, widgetInstances: project.widgetInstances };
-};
-
-const createLegacyItem = (
- sourceId: string,
- options: {
- generate?: Record<string, unknown>;
- status?: string;
- widgetStates?: Record<string, unknown>;
- } = {}
-) => ({
- cancellable: true,
- id: `legacy-${sourceId}`,
- snapshot: {
- canvas: createContext().canvas,
- destination: 'gallery',
- ...(options.generate ? { generate: options.generate } : {}),
- graph: { backendGraph, edges: [], id: 'graph', label: 'Legacy', nodes: [], updatedAt: '', version: 1 },
- sourceId,
- submittedAt: '2026-07-01T00:00:00.000Z',
- widgetInstances: createContext().widgetInstances,
- widgetStates: options.widgetStates ?? {},
- },
- status: options.status ?? 'pending',
-});
-
-const createCurrentItem = () => {
- const legacy = createLegacyItem('workflow');
-
- return {
- ...legacy,
- snapshot: {
- ...legacy.snapshot,
- backendSubmission: { batchCount: 1, graph: backendGraph, kind: 'workflow' },
- filterIntermediateResults: true,
- galleryBoardId: null,
- presentation: { batchCount: 1, height: 512, width: 512 },
- },
- };
-};
-
-const state = (id: string, values: unknown) => ({ id, label: id, values, version: 1 });
-
-describe('normalizeWorkbenchQueueHistory', () => {
- it('preserves already-current queue snapshots by identity', () => {
- const current = {
- ...createLegacyItem('workflow'),
- snapshot: {
- ...createLegacyItem('workflow').snapshot,
- backendSubmission: { batchCount: 1, graph: backendGraph, kind: 'workflow' },
- filterIntermediateResults: true,
- galleryBoardId: null,
- presentation: { batchCount: 1, height: 512, width: 512 },
- },
- };
- const queue = { items: [current] };
-
- expect(normalizeWorkbenchQueueHistory(queue, createContext())).toBe(queue);
- });
-
- it.each([
- ['legacy', () => createLegacyItem('workflow')],
- ['current-shaped', createCurrentItem],
- ])(
- 'keeps a %s item whose canvas snapshot is invalid but makes it unsubmittable and unplaceable',
- (_label, create) => {
- const context = createContext();
- const item = create();
- const canvas = context.canvas;
- const queue = {
- items: [
- {
- ...item,
- snapshot: {
- ...item.snapshot,
- canvas: {
- ...canvas,
- document: { ...canvas.document, stacks: { raster: [{ id: 'broken', type: 'mystery' }] } },
- },
- },
- },
- ],
- };
-
- const [normalized] = normalizeWorkbenchQueueHistory(queue, context).items;
-
- expect(normalized?.id).toBe(item.id);
- expect(normalized?.snapshot.canvas).toEqual({ ...context.canvas, documentRevision: -1 });
- expect(normalized?.snapshot.backendSubmission).toEqual({
- error: 'Queue item canvas snapshot is invalid.',
- kind: 'invalid',
- });
- expect(normalized?.snapshot.presentation).toEqual(
- 'presentation' in item.snapshot ? item.snapshot.presentation : { batchCount: 1, height: 1024, width: 1024 }
- );
- }
- );
-
- it('gives a current-shaped snapshot that lacks a canvas record an unplaceable stand-in', () => {
- const context = createContext();
- const current = createCurrentItem();
- const queue = { items: [{ ...current, snapshot: { ...current.snapshot, canvas: undefined } }] };
-
- const [normalized] = normalizeWorkbenchQueueHistory(queue, context).items;
-
- expect(normalized?.snapshot.canvas).toEqual({ ...context.canvas, documentRevision: -1 });
- expect(normalized?.snapshot.backendSubmission).toEqual(current.snapshot.backendSubmission);
- });
-
- it('strips transient recent images from both current queue snapshot representations', () => {
- const context = createContext();
- const galleryInstance = context.widgetInstances.gallery!;
- const recentImages = [{ imageName: 'transient.png' }];
- const current = {
- ...createLegacyItem('workflow'),
- snapshot: {
- ...createLegacyItem('workflow').snapshot,
- backendSubmission: { batchCount: 1, graph: backendGraph, kind: 'workflow' },
- filterIntermediateResults: true,
- galleryBoardId: null,
- presentation: { batchCount: 1, height: 512, width: 512 },
- widgetInstances: {
- ...context.widgetInstances,
- gallery: {
- ...galleryInstance,
- state: {
- ...galleryInstance.state,
- values: { ...galleryInstance.state.values, recentImages },
- },
- },
- },
- widgetStates: {
- gallery: state('gallery', { recentImages, selectedBoardId: 'none' }),
- },
- },
- };
-
- const queue = { items: [current] };
- const normalized = normalizeWorkbenchQueueHistory(queue, context);
- const snapshot = normalized.items[0]!.snapshot;
- const normalizedGalleryInstance = Object.values(snapshot.widgetInstances).find(
- (instance) => instance.typeId === 'gallery'
- );
-
- expect(normalized).not.toBe(queue);
- expect(snapshot.widgetStates.gallery?.values.recentImages).toBeUndefined();
- expect(normalizedGalleryInstance?.state.values.recentImages).toBeUndefined();
- });
-
- it.each(['pending', 'completed'] as const)('upgrades legacy Generate items with %s status', (status) => {
- const values = createGenerateValues();
- const item = createLegacyItem('generate', {
- status,
- widgetStates: {
- gallery: state('gallery', { selectedBoardId: 'board-1' }),
- generate: state('generate', values),
- },
- });
-
- const normalized = normalizeWorkbenchQueueHistory({ items: [item] }, createContext()).items[0]!;
-
- expect(normalized.status).toBe(status);
- expect(normalized.snapshot.backendSubmission).toEqual({
- batchCount: 3,
- graph: backendGraph,
- kind: 'generate',
- negativePrompt: 'fog',
- negativePromptNodeId: 'negative_prompt',
- positivePrompt: 'a lighthouse',
- positivePromptNodeId: 'positive_prompt',
- seed: 42,
- seedNodeId: 'seed',
- shouldRandomizeSeed: false,
- });
- expect(normalized.snapshot.presentation).toEqual({
- batchCount: 3,
- height: 768,
- positivePrompt: 'a lighthouse',
- width: 1024,
- });
- expect(normalized.snapshot).toMatchObject({
- filterIntermediateResults: false,
- galleryBoardId: 'board-1',
- resultNodeIds: ['canvas_output'],
- });
- });
-
- // The queue row is written at submit time from the merged prompt. Rehydrating
- // from the raw settings made that row change under the user on reload, from
- // `a cat, cinematic` back to the `a cat` they typed.
- it('rehydrates a templated item with the prompt that generated', () => {
- const values = createGenerateValues({
- positivePrompt: 'a cat',
- promptTemplate: { id: 't1', name: 'Cinematic', negativePrompt: '', positivePrompt: '{prompt}, cinematic' },
- });
- const item = createLegacyItem('generate', {
- widgetStates: { generate: state('generate', values) },
- });
-
- const normalized = normalizeWorkbenchQueueHistory({ items: [item] }, createContext()).items[0]!;
-
- expect(normalized.snapshot.presentation).toMatchObject({ positivePrompt: 'a cat, cinematic' });
- expect(normalized.snapshot.backendSubmission).toMatchObject({ positivePrompt: 'a cat, cinematic' });
- });
-
- it('upgrades Canvas items both before and after the captured generate payload was added', () => {
- const widgetValues = createGenerateValues({ positivePrompt: 'widget prompt', seed: 10 });
- const capturedValues = createGenerateValues({ positivePrompt: 'captured prompt', seed: 99 });
- const withoutCapture = createLegacyItem('canvas', {
- widgetStates: { generate: state('generate', widgetValues) },
- });
- const withCapture = createLegacyItem('canvas', {
- generate: {
- negativePromptNodeId: 'captured-negative',
- positivePromptNodeId: 'captured-positive',
- seedNodeId: 'captured-seed',
- values: capturedValues,
- },
- widgetStates: { generate: state('generate', widgetValues) },
- });
-
- const [before, after] = normalizeWorkbenchQueueHistory(
- { items: [withoutCapture, withCapture] },
- createContext()
- ).items;
-
- expect(before?.snapshot.backendSubmission).toMatchObject({ positivePrompt: 'widget prompt', seed: 10 });
- expect(after?.snapshot.backendSubmission).toMatchObject({
- negativePromptNodeId: 'captured-negative',
- positivePrompt: 'captured prompt',
- positivePromptNodeId: 'captured-positive',
- seed: 99,
- seedNodeId: 'captured-seed',
- });
- });
-
- it('upgrades Upscale dimensions and Workflow filtering with source-specific submission rules', () => {
- const upscale = createLegacyItem('upscale', {
- widgetStates: {
- upscale: state('upscale', {
- batchCount: 2,
- inputImage: { height: 101, image_name: 'input.png', width: 203 },
- positivePrompt: 'more detail',
- scale: 2.5,
- seed: 7,
- shouldRandomizeSeed: true,
- }),
- },
- });
- const workflow = createLegacyItem('project-graph', {
- widgetStates: { generate: state('generate', { batchCount: 4 }) },
- });
-
- const [upscaleResult, workflowResult] = normalizeWorkbenchQueueHistory(
- { items: [upscale, workflow] },
- createContext()
- ).items;
-
- expect(upscaleResult?.snapshot.backendSubmission).toMatchObject({
- batchCount: 2,
- kind: 'generate',
- positivePrompt: 'more detail',
- seed: 7,
- shouldRandomizeSeed: true,
- });
- expect(upscaleResult?.snapshot.presentation).toEqual({ batchCount: 2, height: 248, width: 504 });
- expect(upscaleResult?.snapshot.resultNodeIds).toEqual(['upscale_output']);
- expect(workflowResult?.snapshot).toMatchObject({
- backendSubmission: { batchCount: 4, graph: backendGraph, kind: 'workflow' },
- filterIntermediateResults: true,
- sourceId: 'workflow',
- });
- expect(workflowResult?.snapshot.resultNodeIds).toBeUndefined();
- });
-
- it('turns unrecoverable and malformed snapshots into safe invalid submissions', () => {
- const malformed = { id: 'broken', snapshot: { sourceId: 'generate' }, status: 'pending' };
- const normalized = normalizeWorkbenchQueueHistory({ items: [malformed, null] }, createContext()).items;
-
- expect(normalized[0]?.snapshot.backendSubmission).toEqual({
- error: 'Legacy generate queue item is missing a compiled backend graph.',
- kind: 'invalid',
- });
- expect(normalized[0]?.snapshot.presentation.batchCount).toBe(1);
- expect(normalized[1]).toMatchObject({
- id: 'invalid-legacy-queue-item-1',
- snapshot: { backendSubmission: { kind: 'invalid' }, presentation: { batchCount: 1 } },
- status: 'failed',
- });
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
deleted file mode 100644
index 98e861e72f..0000000000
--- a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
+++ /dev/null
@@ -1,395 +0,0 @@
-import type { GenerateSettings } from '@features/generation/contracts';
-import type {
- QueueBackendGraph,
- QueueCompiledSubmission,
- QueueSourceId,
- QueueSubmissionPresentation,
-} from '@features/queue/contracts';
-import type { CanvasStateContractV3 } from '@workbench/canvas-engine/api';
-import type { GraphContract } from '@workbench/graphContracts';
-import type { WidgetInstanceContract, WidgetInstanceId, WidgetStateMap } from '@workbench/widgetContracts';
-
-import { getEffectivePrompts, normalizeGenerateSettings, sanitizeBatchCount } from '@features/generation/settings';
-import { getUpscaleOutputDimensions, normalizeUpscaleWidgetValues } from '@features/upscale';
-import { normalizeVideoWidgetValues } from '@features/video';
-
-import type { WorkbenchQueueItem, WorkbenchQueueState } from './queueHistoryContracts';
-
-import { isRecord, loadCanvasState } from './canvasMigration';
-
-type UnknownRecord = Record<string, unknown>;
-type PresentationSource = { batchCount: number; height?: number; positivePrompt?: string; width?: number } | null;
-
-export interface QueueHistoryNormalizationContext {
- canvas: CanvasStateContractV3;
- widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>;
-}
-
-const stripGalleryRecentImagesFromState = (value: unknown): unknown => {
- if (!isRecord(value) || !isRecord(value.values) || !Object.hasOwn(value.values, 'recentImages')) {
- return value;
- }
-
- const values = { ...value.values };
-
- delete values.recentImages;
- return { ...value, values };
-};
-
-const stripGalleryRecentImagesFromWidgetStates = (value: unknown): unknown => {
- if (!isRecord(value)) {
- return value;
- }
-
- const gallery = stripGalleryRecentImagesFromState(value.gallery);
-
- return gallery === value.gallery ? value : { ...value, gallery };
-};
-
-const stripGalleryRecentImagesFromWidgetInstances = (value: unknown): unknown => {
- if (!isRecord(value)) {
- return value;
- }
-
- let didChange = false;
- const instances = Object.fromEntries(
- Object.entries(value).map(([instanceId, instance]) => {
- if (!isRecord(instance) || instance.typeId !== 'gallery') {
- return [instanceId, instance];
- }
-
- const state = stripGalleryRecentImagesFromState(instance.state);
-
- didChange ||= state !== instance.state;
- return [instanceId, state === instance.state ? instance : { ...instance, state }];
- })
- );
-
- return didChange ? instances : value;
-};
-
-const stripGalleryRecentImagesFromSnapshot = (snapshot: UnknownRecord): UnknownRecord => {
- const widgetStates = stripGalleryRecentImagesFromWidgetStates(snapshot.widgetStates);
- const widgetInstances = stripGalleryRecentImagesFromWidgetInstances(snapshot.widgetInstances);
-
- return widgetStates === snapshot.widgetStates && widgetInstances === snapshot.widgetInstances
- ? snapshot
- : { ...snapshot, widgetInstances, widgetStates };
-};
-
-const normalizeSourceId = (value: unknown): QueueSourceId | null => {
- if (value === 'project-graph') {
- return 'workflow';
- }
- if (value === 'canvas-fill') {
- return 'canvas';
- }
- return value === 'canvas' || value === 'generate' || value === 'upscale' || value === 'video' || value === 'workflow'
- ? value
- : null;
-};
-
-const isBackendGraph = (value: unknown): value is QueueBackendGraph =>
- isRecord(value) && typeof value.id === 'string' && isRecord(value.nodes) && Array.isArray(value.edges);
-
-const isCurrentBackendSubmission = (value: unknown): value is QueueCompiledSubmission => {
- if (!isRecord(value) || typeof value.kind !== 'string') {
- return false;
- }
- if (value.kind === 'invalid') {
- return typeof value.error === 'string';
- }
- if (
- (value.kind !== 'generate' && value.kind !== 'workflow') ||
- !isBackendGraph(value.graph) ||
- typeof value.batchCount !== 'number' ||
- !Number.isFinite(value.batchCount) ||
- value.batchCount < 1
- ) {
- return false;
- }
- if (value.kind === 'workflow') {
- return true;
- }
- return (
- typeof value.negativePrompt === 'string' &&
- typeof value.negativePromptNodeId === 'string' &&
- typeof value.positivePrompt === 'string' &&
- typeof value.positivePromptNodeId === 'string' &&
- typeof value.seed === 'number' &&
- Number.isFinite(value.seed) &&
- typeof value.seedNodeId === 'string' &&
- typeof value.shouldRandomizeSeed === 'boolean'
- );
-};
-
-const isCurrentPresentation = (value: unknown): value is QueueSubmissionPresentation =>
- isRecord(value) &&
- typeof value.batchCount === 'number' &&
- Number.isFinite(value.batchCount) &&
- value.batchCount > 0 &&
- typeof value.height === 'number' &&
- Number.isFinite(value.height) &&
- value.height > 0 &&
- typeof value.width === 'number' &&
- Number.isFinite(value.width) &&
- value.width > 0;
-
-const isCurrentSnapshot = (value: UnknownRecord): boolean =>
- isCurrentBackendSubmission(value.backendSubmission) &&
- isCurrentPresentation(value.presentation) &&
- normalizeSourceId(value.sourceId) === value.sourceId &&
- (value.destination === 'canvas' || value.destination === 'gallery') &&
- isRecord(value.graph) &&
- (value.galleryBoardId === null || typeof value.galleryBoardId === 'string') &&
- typeof value.filterIntermediateResults === 'boolean' &&
- typeof value.submittedAt === 'string';
-
-const getWidgetStates = (snapshot: UnknownRecord): WidgetStateMap =>
- isRecord(snapshot.widgetStates) ? (snapshot.widgetStates as WidgetStateMap) : {};
-
-const getWidgetValues = (widgetStates: WidgetStateMap, widgetId: string): unknown => {
- const state = widgetStates[widgetId];
- return isRecord(state) && isRecord(state.values) ? state.values : undefined;
-};
-
-const getGenerateCapture = (snapshot: UnknownRecord): UnknownRecord | null =>
- isRecord(snapshot.generate) ? snapshot.generate : null;
-
-const getFiniteDimension = (value: unknown, fallback: number): number =>
- typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;
-
-const createInvalidSubmission = (message: string): QueueCompiledSubmission => ({ error: message, kind: 'invalid' });
-
-const toPresentationSource = (settings: GenerateSettings | null): PresentationSource =>
- settings ? { ...settings, positivePrompt: getEffectivePrompts(settings).positivePrompt } : null;
-
-const getBackendSubmission = (
- sourceId: QueueSourceId | null,
- snapshot: UnknownRecord,
- widgetStates: WidgetStateMap
-): { presentationSource: PresentationSource; submission: QueueCompiledSubmission } => {
- const graph = isRecord(snapshot.graph) ? snapshot.graph : null;
- const backendGraph = graph?.backendGraph;
- const generateCapture = getGenerateCapture(snapshot);
- const generateValues = getWidgetValues(widgetStates, 'generate');
- // Carries the merged prompt, so a rehydrated row reads the same as it will once
- // the backend session arrives with its own (already merged) field values.
- const presentationSource = toPresentationSource(
- normalizeGenerateSettings(sourceId === 'canvas' ? (generateCapture?.values ?? generateValues) : generateValues)
- );
-
- if (!sourceId) {
- return {
- presentationSource,
- submission: createInvalidSubmission('Legacy queue item has an unsupported or missing source.'),
- };
- }
- if (!isBackendGraph(backendGraph)) {
- return {
- presentationSource,
- submission: createInvalidSubmission(`Legacy ${sourceId} queue item is missing a compiled backend graph.`),
- };
- }
- if (sourceId === 'workflow') {
- return {
- presentationSource,
- submission: {
- batchCount: sanitizeBatchCount(isRecord(generateValues) ? generateValues.batchCount : undefined),
- graph: backendGraph,
- kind: 'workflow',
- },
- };
- }
-
- const sourceSettings =
- sourceId === 'upscale'
- ? normalizeUpscaleWidgetValues(getWidgetValues(widgetStates, 'upscale'))
- : sourceId === 'video'
- ? normalizeVideoWidgetValues(getWidgetValues(widgetStates, 'video'))
- : sourceId === 'canvas'
- ? normalizeGenerateSettings(generateCapture?.values ?? generateValues)
- : normalizeGenerateSettings(generateValues);
-
- if (!sourceSettings) {
- return {
- presentationSource,
- submission: createInvalidSubmission(`Legacy ${sourceId} queue item is missing source submission metadata.`),
- };
- }
-
- // Re-deriving the submission has to reapply the prompt template, or a rehydrated
- // item that is retried would submit the bare authored text. The snapshot rides
- // in the persisted widget values, so this needs no catalog.
- const effectivePrompts = getEffectivePrompts(sourceSettings);
-
- return {
- // The merged source computed above, not the raw settings: the row is written
- // at submit time from the merged prompt, so returning the authored text here
- // made a rehydrated item's prompt change under the user on reload.
- presentationSource: sourceId === 'upscale' || sourceId === 'video' ? null : presentationSource,
- submission: {
- batchCount: sourceSettings.batchCount,
- graph: backendGraph,
- kind: 'generate',
- negativePrompt: sourceSettings.negativePromptEnabled ? effectivePrompts.negativePrompt : '',
- negativePromptNodeId:
- typeof generateCapture?.negativePromptNodeId === 'string'
- ? generateCapture.negativePromptNodeId
- : 'negative_prompt',
- positivePrompt: effectivePrompts.positivePrompt,
- positivePromptNodeId:
- typeof generateCapture?.positivePromptNodeId === 'string'
- ? generateCapture.positivePromptNodeId
- : 'positive_prompt',
- seed: sourceSettings.seed,
- seedNodeId: typeof generateCapture?.seedNodeId === 'string' ? generateCapture.seedNodeId : 'seed',
- shouldRandomizeSeed: sourceSettings.shouldRandomizeSeed,
- },
- };
-};
-
-const normalizeLegacyQueueItem = (
- value: unknown,
- index: number,
- canvas: CanvasStateContractV3,
- context: QueueHistoryNormalizationContext
-): WorkbenchQueueItem => {
- const item = isRecord(value) ? value : {};
- const snapshot = isRecord(item.snapshot) ? item.snapshot : {};
- const sourceId = normalizeSourceId(snapshot.sourceId);
- const widgetStates = stripGalleryRecentImagesFromWidgetStates(getWidgetStates(snapshot)) as WidgetStateMap;
- const { presentationSource, submission } = getBackendSubmission(sourceId, snapshot, widgetStates);
- const upscaleValues =
- sourceId === 'upscale' ? normalizeUpscaleWidgetValues(getWidgetValues(widgetStates, 'upscale')) : null;
- const canvasDocument = canvas.document;
- const dimensions =
- upscaleValues?.inputImage && Number.isFinite(upscaleValues.scale)
- ? getUpscaleOutputDimensions(upscaleValues.inputImage, upscaleValues.scale)
- : {
- height: getFiniteDimension(presentationSource?.height, canvasDocument.height),
- width: getFiniteDimension(presentationSource?.width, canvasDocument.width),
- };
- const galleryValues = getWidgetValues(widgetStates, 'gallery');
- const selectedBoardId = isRecord(galleryValues) ? galleryValues.selectedBoardId : undefined;
- const graph = isRecord(snapshot.graph)
- ? (snapshot.graph as unknown as GraphContract)
- : {
- edges: [],
- id: `invalid-legacy-queue-graph-${index}`,
- label: 'Unavailable legacy queue graph',
- nodes: [],
- updatedAt: new Date(0).toISOString(),
- version: 1,
- };
- const safeSourceId = sourceId ?? 'workflow';
-
- return {
- ...item,
- cancellable: typeof item.cancellable === 'boolean' ? item.cancellable : false,
- id: typeof item.id === 'string' ? item.id : `invalid-legacy-queue-item-${index}`,
- snapshot: {
- ...snapshot,
- backendSubmission: submission,
- canvas,
- destination: snapshot.destination === 'gallery' ? 'gallery' : 'canvas',
- filterIntermediateResults: safeSourceId === 'workflow',
- galleryBoardId: typeof selectedBoardId === 'string' ? selectedBoardId : null,
- graph,
- presentation: {
- batchCount: submission.kind === 'invalid' ? 1 : submission.batchCount,
- height: dimensions.height,
- ...(presentationSource?.positivePrompt ? { positivePrompt: presentationSource.positivePrompt } : {}),
- width: dimensions.width,
- },
- ...(safeSourceId === 'generate' || safeSourceId === 'canvas'
- ? { resultNodeIds: ['canvas_output'] }
- : safeSourceId === 'upscale'
- ? { resultNodeIds: ['upscale_output'] }
- : safeSourceId === 'video'
- ? { resultNodeIds: ['video_output'] }
- : {}),
- sourceId: safeSourceId,
- submittedAt: typeof snapshot.submittedAt === 'string' ? snapshot.submittedAt : new Date(0).toISOString(),
- widgetInstances: stripGalleryRecentImagesFromWidgetInstances(
- isRecord(snapshot.widgetInstances) ? snapshot.widgetInstances : context.widgetInstances
- ) as Record<WidgetInstanceId, WidgetInstanceContract>,
- widgetStates,
- },
- status:
- item.status === 'pending' ||
- item.status === 'running' ||
- item.status === 'completed' ||
- item.status === 'failed' ||
- item.status === 'cancelled'
- ? item.status
- : 'failed',
- } as WorkbenchQueueItem;
-};
-
-/**
- * Stands in for a queue canvas that could not be read. Its revision matches no document, so the
- * item's results can never be placed onto, or lock, a canvas they were not generated against.
- */
-const unplaceableCanvas = (canvas: CanvasStateContractV3): CanvasStateContractV3 => ({
- ...canvas,
- documentRevision: -1,
-});
-
-/**
- * Upgrades legacy nested snapshots at Workbench's project-ingestion boundary. Every item's
- * `snapshot.canvas` is validated whether or not the rest of the snapshot is already current-shaped.
- * Invalid and future-version canvas records are refused upstream by `gateProjectCanvases`. The
- * defensive invalid branch below protects trusted in-memory callers that bypass project ingestion;
- * it must never be the persistence path for raw project data.
- */
-export const normalizeWorkbenchQueueHistory = (
- value: unknown,
- context: QueueHistoryNormalizationContext
-): WorkbenchQueueState => {
- if (!isRecord(value) || !Array.isArray(value.items)) {
- return { items: [] };
- }
-
- let didChange = false;
- const items = value.items.map((item, index): WorkbenchQueueItem => {
- const snapshot = isRecord(item) && isRecord(item.snapshot) ? item.snapshot : null;
- const loaded = snapshot && isRecord(snapshot.canvas) ? loadCanvasState(snapshot.canvas) : null;
- const isCurrent = snapshot !== null && isCurrentSnapshot(snapshot);
- if (loaded && loaded.status !== 'loaded') {
- didChange = true;
- const base = isCurrent
- ? (item as unknown as WorkbenchQueueItem)
- : normalizeLegacyQueueItem(item, index, unplaceableCanvas(context.canvas), context);
- return {
- ...base,
- snapshot: {
- ...base.snapshot,
- backendSubmission: createInvalidSubmission('Queue item canvas snapshot is invalid.'),
- canvas: unplaceableCanvas(context.canvas),
- },
- };
- }
- if (snapshot && isCurrent) {
- const canvas = !loaded
- ? unplaceableCanvas(context.canvas)
- : loaded.diagnostics.length > 0
- ? loaded.value
- : snapshot.canvas;
- const strippedSnapshot = stripGalleryRecentImagesFromSnapshot(
- canvas === snapshot.canvas ? snapshot : { ...snapshot, canvas }
- );
-
- if (strippedSnapshot === snapshot) {
- return item as unknown as WorkbenchQueueItem;
- }
-
- didChange = true;
- return { ...item, snapshot: strippedSnapshot } as unknown as WorkbenchQueueItem;
- }
- didChange = true;
- return normalizeLegacyQueueItem(item, index, loaded?.value ?? context.canvas, context);
- });
-
- return didChange ? ({ ...value, items } as WorkbenchQueueState) : (value as unknown as WorkbenchQueueState);
-};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts
index bfccef4a14..aaecc302e2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSettings.ts
@@ -5,8 +5,8 @@
*
* Each setting is a boolean persisted in the canvas widget's own state values
* (`widgetInstances['canvas'].state.values[key]`) — the same plumbing as the
- * denoising strength (`invoke/canvasStrength.ts`), so it survives reloads and
- * rides along in queue snapshots. Persistence is per-user (per-project), NEVER in
+ * denoising strength (`invoke/canvasStrength.ts`), so it survives reloads and is
+ * read when a queue submission is compiled. Persistence is per-user (per-project), NEVER in
* the canvas undo history.
*
* A setting either drives an engine boolean store (`store` set — React resolves
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts
index b92ca15e4c..ea599196b4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasCompositing.ts
@@ -4,8 +4,8 @@
*
* Like {@link import('./canvasStrength').readCanvasDenoisingStrength}, these
* values are persisted per-project inside the canvas widget's own state values
- * (`widgetInstances['canvas'].state.values`), so they survive reloads and ride
- * along in queue snapshots. The generate widget's compositing section owns the
+ * (`widgetInstances['canvas'].state.values`), so they survive reloads and are
+ * consumed when the queue submission is compiled. The generate widget's compositing section owns the
* numeric controls; the canvas settings menu owns the masked-only output flag.
* `prepareCanvasInvocation` reads them together — defaulted + clamped — and
* threads one generation-facing contract into the pure graph compiler.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasStrength.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasStrength.ts
index b31698c967..01bec0d793 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasStrength.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/canvasStrength.ts
@@ -3,8 +3,8 @@
*
* The value is persisted in the canvas widget's own state values
* (`widgetInstances['canvas'].state.values.denoisingStrength`) so it survives
- * reloads and rides along in queue snapshots, and is read back — with the
- * default applied — by the invoke orchestrator. Only consulted for img2img
+ * reloads, and is read — with the default applied — by the invoke orchestrator
+ * when compiling a submission. Only consulted for img2img
* (txt2img ignores it), matching the graph compiler.
*
* Pure data + a reader; no React, no engine. Shared by the tool-options UI and
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 438d13d154..7086387c08 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -405,7 +405,8 @@ const submitGenerate = (state: WorkbenchState) =>
workbenchReducer(state, { backendSupportsCancellation: true, type: 'submitInvocationSnapshot' });
const getQueuedRandDevice = (state: WorkbenchState): unknown => {
- const nodes = getActiveProject(state).queue.items[0]?.snapshot.graph.backendGraph?.nodes ?? {};
+ const submission = getActiveProject(state).queue.items[0]?.snapshot.backendSubmission;
+ const nodes = submission?.kind === 'invalid' ? {} : (submission?.graph.nodes ?? {});
const metadata = Object.values(nodes).find((node) => node.type === 'core_metadata');
return metadata?.rand_device;
@@ -867,12 +868,14 @@ describe('adopting a project from another realm', () => {
...project,
events: [{ createdAt: 'now', id: 'legacy-event', summary: 'legacy', type: 'project-created' }],
graphHistory: [{ document: project.projectGraph, id: 'legacy-snapshot' }],
+ queue: { items: [{}] },
} as unknown as Project;
const normalized = normalizeWorkbenchProject(legacyProject);
expect(normalized.events).toEqual([]);
expect('graphHistory' in normalized).toBe(false);
+ expect(normalized.queue.items).toEqual([]);
});
it('preserves and caps session events during live normalization', () => {
@@ -889,6 +892,50 @@ describe('adopting a project from another realm', () => {
expect(normalized.events).toEqual(project.events.slice(0, PROJECT_EVENT_LIMIT));
});
+ it('preserves the live queue during same-session normalization', () => {
+ const project = getActiveProject(submitGenerate(primeGenerate()));
+
+ const normalized = normalizeWorkbenchProject(project, { isArriving: false });
+
+ expect(normalized.queue).toBe(project.queue);
+ });
+
+ it('preserves and routes live queue work when server content replaces a project', () => {
+ let state = submitGenerate(primeGenerate());
+ const liveProject = getActiveProject(state);
+ const queueItem = liveProject.queue.items[0]!;
+
+ state = workbenchReducer(state, {
+ backendItemIds: [42],
+ projectId: liveProject.id,
+ queueItemId: queueItem.id,
+ type: 'markQueueItemBackendSubmitted',
+ });
+ const liveQueue = getActiveProject(state).queue;
+
+ state = workbenchReducer(state, {
+ project: { ...liveProject, name: 'Server version', queue: { items: [] } },
+ projectId: liveProject.id,
+ type: 'replaceProjectFromServer',
+ });
+ expect(getActiveProject(state).queue).toBe(liveQueue);
+
+ state = workbenchReducer(state, {
+ images: [createImage('server-replaced-result.png', queueItem.id)],
+ projectId: liveProject.id,
+ queueItemId: queueItem.id,
+ type: 'routeQueueItemResults',
+ });
+
+ const replacedProject = getActiveProject(state);
+ expect(replacedProject.name).toBe('Server version');
+ expect(replacedProject.queue.items[0]?.status).toBe('completed');
+ expect(replacedProject.queue.items[0]?.resultImages?.map((image) => image.imageName)).toEqual([
+ 'server-replaced-result.png',
+ ]);
+ expect(replacedProject.canvas.stagingArea.pendingImageIds).toEqual([]);
+ });
+
it('drops a session-scoped search and the rank pages set against it', () => {
// A project opened from the server — the Open dialog, a deep link, or a
// conflict fork — arrives in a realm that never ran the session its values
@@ -1977,9 +2024,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {
state = submitGenerate(state);
const [secondQueueItem, unchangedFirstQueueItem] = getActiveProject(state).queue.items;
- const firstValues = unchangedFirstQueueItem?.snapshot.widgetStates.generate
- .values as unknown as GenerateWidgetValues;
- const secondValues = secondQueueItem?.snapshot.widgetStates.generate.values as unknown as GenerateWidgetValues;
+ const firstValues = unchangedFirstQueueItem?.snapshot.recall?.generateValues as GenerateWidgetValues;
+ const secondValues = secondQueueItem?.snapshot.recall?.generateValues as GenerateWidgetValues;
expect(firstValues.positivePrompt).toBe('first prompt');
expect(firstValues.shouldRandomizeSeed).toBe(true);
@@ -3000,7 +3046,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
negativePrompt: 'blurry, lowres',
positivePrompt: 'a cat, cinematic',
});
- expect(queueItem?.snapshot.widgetStates.generate.values.positivePrompt).toBe('a cat');
+ expect(queueItem?.snapshot.recall?.generateValues?.positivePrompt).toBe('a cat');
});
// Switching the negative field off must not let a template put one back.
@@ -3173,7 +3219,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
type: 'submitInvocationSnapshot',
});
- const submission = getActiveProject(state).queue.items[0]?.snapshot.widgetStates.video.values;
+ const submission = getActiveProject(state).queue.items[0]?.snapshot.recall?.videoValues;
expect(submission).toMatchObject({ negativePrompt: 'static camera', positivePrompt: 'a fox running' });
});
@@ -3439,7 +3485,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
expect(galleryValues.selectedImageNames).toEqual(['image:gallery-image-999.png']);
});
- it('omits transient recent images from immutable queue snapshots', () => {
+ it('omits widget state from immutable queue snapshots', () => {
let state = primeGenerate();
const recentImages = Array.from({ length: GALLERY_RECENT_IMAGE_LIMIT }, (_, index) =>
createImage(`recent-${index}.png`, 'previous-queue-item')
@@ -3453,11 +3499,10 @@ describe('workbenchReducer Phase 5 generation flow', () => {
state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });
state = submitGenerate(state);
- const snapshot = getActiveProject(state).queue.items[0]!.snapshot;
- const galleryInstance = Object.values(snapshot.widgetInstances).find((instance) => instance.typeId === 'gallery');
+ const snapshot = getActiveProject(state).queue.items[0]!.snapshot as unknown as Record<string, unknown>;
- expect(snapshot.widgetStates.gallery?.values.recentImages).toBeUndefined();
- expect(galleryInstance?.state.values.recentImages).toBeUndefined();
+ expect(snapshot).not.toHaveProperty('widgetStates');
+ expect(snapshot).not.toHaveProperty('widgetInstances');
});
it('validates, deduplicates, and truncates persisted recent images during hydration', () => {
@@ -3768,7 +3813,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const queueItem = getActiveProject(state).queue.items[0];
- expect(queueItem.snapshot.widgetStates.gallery.values.selectedBoardId).toBe('backend-board-id');
+ expect(queueItem.snapshot.galleryBoardId).toBe('backend-board-id');
});
it('stores full selected gallery image data for Preview widget', () => {
@@ -5819,19 +5864,16 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
expect(queueItem?.snapshot.sourceId).toBe('canvas');
expect(queueItem?.snapshot.destination).toBe('canvas');
- expect(queueItem?.snapshot.graph.id).toBe('canvas-graph');
- expect(queueItem?.snapshot.generate).toMatchObject({
- negativePromptNodeId: 'negative_prompt',
- positivePromptNodeId: 'positive_prompt',
- seedNodeId: 'seed',
- values: { negativePrompt: 'avoid blur', positivePrompt: 'inpaint prompt', seed: 42, shouldRandomizeSeed: false },
- });
- expect(queueItem?.snapshot.widgetStates.generate.values).toMatchObject({
+ expect(queueItem?.snapshot.graph).toEqual({ id: 'canvas-graph', label: 'Canvas' });
+ expect(queueItem?.snapshot.recall?.generateValues).toMatchObject({
negativePrompt: 'avoid blur',
positivePrompt: 'inpaint prompt',
seed: 42,
shouldRandomizeSeed: false,
});
+ expect(queueItem?.snapshot).not.toHaveProperty('generate');
+ expect(queueItem?.snapshot).not.toHaveProperty('widgetStates');
+ expect(queueItem?.snapshot).not.toHaveProperty('widgetInstances');
expect(queueItem?.snapshot.backendSubmission).toMatchObject({
batchCount: 1,
kind: 'generate',
@@ -5873,6 +5915,14 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
expect(getActiveProject(state).queue.items[0]?.snapshot.canvas.document.bbox).toEqual(frozenCanvas.document.bbox);
expect(getActiveProject(state).queue.items[0]?.snapshot.canvas.document.bbox).not.toEqual(liveCanvas.document.bbox);
+ expect(getActiveProject(state).queue.items[0]?.snapshot.canvas).toEqual({
+ document: {
+ bbox: frozenCanvas.document.bbox,
+ height: frozenCanvas.document.height,
+ width: frozenCanvas.document.width,
+ },
+ documentRevision: frozenCanvas.documentRevision,
+ });
});
it('places generated candidates at the frozen queue bbox after the live bbox changes', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index df22530f7f..6f1bdc0129 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -173,10 +173,14 @@ import {
createLayoutPresetSnapshot,
resolveSavedLayoutPreset,
} from './layoutPresetSnapshots';
-import { normalizeWorkbenchQueueHistory } from './queueHistoryNormalization';
import { normalizeProjectSettings } from './settings/store';
-type QueueGenerateSnapshot = NonNullable<QueueItem['snapshot']['generate']>;
+interface QueueGenerateSnapshot {
+ negativePromptNodeId: string;
+ positivePromptNodeId: string;
+ seedNodeId: string;
+ values: GenerateWidgetValues;
+}
export interface WorkbenchReducerContext {
autoSwitchInvocationRoute: boolean;
@@ -622,13 +626,6 @@ const cloneGraph = (graph: GraphContract): GraphContract => ({
nodes: graph.nodes.map((node) => ({ ...node, inputs: { ...node.inputs } })),
});
-const cloneQueueGenerateSnapshot = (generate: QueueGenerateSnapshot): QueueGenerateSnapshot => ({
- negativePromptNodeId: generate.negativePromptNodeId,
- positivePromptNodeId: generate.positivePromptNodeId,
- seedNodeId: generate.seedNodeId,
- values: cloneGenerateWidgetValues(generate.values),
-});
-
const applyQueueGenerateSnapshotToWidgetStates = (
widgetStates: WidgetStateMap,
generate: QueueGenerateSnapshot | undefined
@@ -1003,16 +1000,6 @@ const cloneWidgetInstance = (widgetInstance: WidgetInstanceContract): WidgetInst
state: cloneWidgetState(widgetInstance.state),
});
-const cloneQueueWidgetState = (widgetState: WidgetStateContract, typeId: WidgetTypeId): WidgetStateContract => {
- const state = cloneWidgetState(widgetState);
-
- if (typeId === 'gallery') {
- delete state.values.recentImages;
- }
-
- return state;
-};
-
const cloneWidgetInstances = (
widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>
): Record<WidgetInstanceId, WidgetInstanceContract> =>
@@ -1023,24 +1010,11 @@ const cloneWidgetInstances = (
])
);
-const cloneQueueWidgetInstances = (
- widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>
-): Record<WidgetInstanceId, WidgetInstanceContract> =>
- Object.fromEntries(
- Object.entries({ ...createWidgetInstances(), ...widgetInstances }).map(([instanceId, widgetInstance]) => [
- instanceId,
- {
- ...widgetInstance,
- state: cloneQueueWidgetState(widgetInstance.state, widgetInstance.typeId),
- },
- ])
- );
-
const getWidgetStatesSnapshot = (widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>): WidgetStateMap => {
const widgetStates: WidgetStateMap = {};
for (const widgetInstance of Object.values(widgetInstances)) {
- widgetStates[widgetInstance.typeId] ??= cloneQueueWidgetState(widgetInstance.state, widgetInstance.typeId);
+ widgetStates[widgetInstance.typeId] ??= cloneWidgetState(widgetInstance.state);
}
return widgetStates;
@@ -1792,7 +1766,7 @@ const assembleWorkbenchProject = (
layout: { ...project.layout, presetId: resolveLayoutPresetId(project.layout.presetId) },
projectGraph: normalizeProjectGraph(project.projectGraph),
promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),
- queue: normalizeWorkbenchQueueHistory(project.queue, { canvas, widgetInstances }),
+ queue: isArriving ? { items: [] } : project.queue,
settings: normalizeProjectSettings(project.settings),
widgetRegions: placement.widgetRegions,
widgetInstances,
@@ -3062,7 +3036,7 @@ const enqueueCompiledSnapshot = (
const { generate, graph } = compiled;
const widgetStates = Object.fromEntries(
Object.entries(applyQueueGenerateSnapshotToWidgetStates(compiled.widgetStates, generate)).map(
- ([typeId, widgetState]) => [typeId, cloneQueueWidgetState(widgetState, typeId as WidgetTypeId)]
+ ([typeId, widgetState]) => [typeId, cloneWidgetState(widgetState)]
)
) as WidgetStateMap;
const generateSettings =
@@ -3157,17 +3131,35 @@ const enqueueCompiledSnapshot = (
height: generatePresentationSettings?.height ?? project.canvas.document.height,
width: generatePresentationSettings?.width ?? project.canvas.document.width,
};
+ const submittedCanvas = canvasSnapshot ?? project.canvas;
+ const generateRecallValues =
+ route.sourceId === 'canvas'
+ ? generate?.values
+ : route.sourceId === 'generate'
+ ? normalizeGenerateWidgetValues(widgetStates.generate?.values)
+ : null;
+ const recall = generateRecallValues
+ ? { generateValues: cloneGenerateWidgetValues(generateRecallValues) }
+ : videoSettings
+ ? { videoValues: cloneVideoWidgetValues(videoSettings) }
+ : undefined;
const queueItem: QueueItem = {
cancellable: backendSupportsCancellation,
id: queueItemId,
snapshot: {
backendSubmission,
- canvas: canvasSnapshot ? structuredClone(canvasSnapshot) : cloneCanvas(project.canvas),
+ canvas: {
+ document: {
+ bbox: { ...submittedCanvas.document.bbox },
+ height: submittedCanvas.document.height,
+ width: submittedCanvas.document.width,
+ },
+ documentRevision: submittedCanvas.documentRevision,
+ },
destination: route.destination,
filterIntermediateResults: route.sourceId === 'workflow',
galleryBoardId: typeof selectedGalleryBoardId === 'string' ? selectedGalleryBoardId : null,
- ...(generate ? { generate: cloneQueueGenerateSnapshot(generate) } : {}),
- graph,
+ graph: { id: graph.id, label: graph.label },
presentation: {
// Placeholder sizing only: superseded by the backend's real item ids as
// soon as the batch is accepted.
@@ -3190,8 +3182,7 @@ const enqueueCompiledSnapshot = (
? { resultNodeIds: ['video_output'] }
: {}),
submittedAt,
- widgetInstances: cloneQueueWidgetInstances(project.widgetInstances),
- widgetStates,
+ ...(recall ? { recall } : {}),
},
status: 'pending',
};
@@ -4785,6 +4776,7 @@ export const __workbenchReducerInternal = (
documentRevision:
Math.max(normalizedServerProject.canvas.documentRevision, localProject.canvas.documentRevision) + 1,
},
+ queue: localProject.queue,
}
: normalizedServerProject;
return {