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.

fix(canvas): harden document foundations

Josh Corbett38ea66b188b8
diff --git a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts
index bd313401a5..bbeba78c12 100644
--- a/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/canvasSeamOwnership.test.ts
@@ -30,11 +30,9 @@ const SEAM_MODULES = [
];
/**
- * Mutations that restructure the layer list. Outside the engine and the reducer only gallery import
- * builds them, because it ingests into projects that have no mounted engine. The engine grant covers
- * every engine module: controllers build these as forward/inverse pairs for the prepared-dispatch
- * protocol, history replays them raw, and the paint tool creates and rolls back its auto-created
- * layer outside history by design. The scan matches the formatted literal `type: '…'`.
+ * Mutations that restructure the layer list. Controllers build some as forward/inverse pairs for
+ * prepared raster dispatch, while paint creates and rolls back its pointer-down layer by design.
+ * Every current owner is enumerated below; the scan matches the formatted literal `type: '…'`.
*/
const STRUCTURAL_MUTATION_TYPES = [
'addCanvasLayer',
@@ -52,11 +50,37 @@ const STRUCTURAL_MUTATION_TYPES = [
'setCanvasLayersHidden',
'updateCanvasLayerSource',
];
-const STRUCTURAL_MUTATION_OWNERS = [
- /^workbench\/canvasProjectMutations\.ts$/,
- /^workbench\/canvas-engine\//,
- /^workbench\/canvas-operations\/importGalleryImages\.ts$/,
-];
+/**
+ * The finite set of modules that still construct the v2 flat mutation vocabulary. Keeping this
+ * explicit prevents new bypasses and is the migration checklist for the hierarchy tree reducer.
+ */
+const STRUCTURAL_MUTATION_OWNER_PATHS = new Set([
+ 'workbench/canvasProjectMutations.ts',
+ 'workbench/canvas-engine/controllers/booleanMergeController.ts',
+ 'workbench/canvas-engine/controllers/copyLayerController.ts',
+ 'workbench/canvas-engine/controllers/cropLayerController.ts',
+ 'workbench/canvas-engine/controllers/extractMaskedAreaController.ts',
+ 'workbench/canvas-engine/controllers/filterResultController.ts',
+ 'workbench/canvas-engine/controllers/generatedResultController.ts',
+ 'workbench/canvas-engine/controllers/layerMutationController.ts',
+ 'workbench/canvas-engine/controllers/maskResultController.ts',
+ 'workbench/canvas-engine/controllers/mergeLayerController.ts',
+ 'workbench/canvas-engine/controllers/newRasterLayerController.ts',
+ 'workbench/canvas-engine/controllers/rasterizeLayerController.ts',
+ 'workbench/canvas-engine/controllers/stagedResultController.ts',
+ 'workbench/canvas-engine/controllers/structuralLayerController.ts',
+ 'workbench/canvas-engine/controllers/textEditingController.ts',
+ 'workbench/canvas-engine/document-model/flatDocumentModel.ts',
+ 'workbench/canvas-engine/document/bitmapStore.ts',
+ 'workbench/canvas-engine/engine.ts',
+ 'workbench/canvas-engine/mutationContracts.ts',
+ 'workbench/canvas-engine/strokeCommit.ts',
+ 'workbench/canvas-engine/tools/gradientTool.ts',
+ 'workbench/canvas-engine/tools/moveTool.ts',
+ 'workbench/canvas-engine/tools/paintTool.ts',
+ 'workbench/canvas-engine/tools/shapeTool.ts',
+ 'workbench/canvas-operations/importGalleryImages.ts',
+]);
const structuralLiteral = new RegExp(`type: '(?:${STRUCTURAL_MUTATION_TYPES.join('|')})'`, 'g');
const SEAM_ONLY_SYMBOLS = ['repairSelectedLayerId', 'moveLayersWithinStacks', 'reorderLayerStack'];
@@ -68,7 +92,12 @@ const MODEL_CONSUMERS = [
'workbench/canvas-engine/render/overlayFrame.ts',
'workbench/canvas-engine/render/floatingSelectionFrame.ts',
'workbench/canvas-engine/render/rasterComposite.ts',
+ 'workbench/canvas-engine/rasterSnapshotCapture.ts',
+ 'workbench/canvas-engine/controllers/psdExportController.ts',
+ 'workbench/canvas-engine/controllers/rasterExportController.ts',
+ 'workbench/canvas-engine/controllers/thumbnailController.ts',
'workbench/canvas-engine/controllers/mergeLayerController.ts',
+ 'workbench/canvas-operations/generationComposite.ts',
'workbench/canvas-operations/generationCompositePlan.ts',
];
@@ -98,10 +127,10 @@ describe('canvas document seam ownership', () => {
expect(offenders).toEqual([]);
}, 60_000);
- it('keeps structural mutations behind the engine transaction', () => {
+ it('keeps flat structural mutation construction in explicit owners', () => {
const offenders: string[] = [];
for (const [path, source] of productionSources) {
- if (STRUCTURAL_MUTATION_OWNERS.some((owner) => owner.test(path))) {
+ if (STRUCTURAL_MUTATION_OWNER_PATHS.has(path)) {
continue;
}
for (const match of source.matchAll(structuralLiteral)) {
diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts
index b54aa239d8..206d5fbab1 100644
--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts
+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts
@@ -1,4 +1,5 @@
import type { ProjectGraphAction } from '@features/workflow/utility';
+import type { CanvasEditIntent, CanvasMutationOrigin } from '@workbench/canvas-engine/api';
import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';
import { GENERATE_UI_STATE_KEYS } from '@features/generation/settings';
@@ -8,8 +9,10 @@ import type { CanvasProjectMutation } from './canvasProjectMutations';
import { isInvocationSourceAvailable } from './invocation';
+export type { CanvasEditIntent };
+
/** Programmatic dispatches never auto-switch the Invoke route; absent means user. */
-export type WorkbenchActionOrigin = 'user' | 'system';
+export type WorkbenchActionOrigin = CanvasMutationOrigin;
/** Destination each surface maps to when the source auto-switches. */
export const autoSwitchDestinations: Record<InvocationSourceId, ResultDestination> = {
@@ -170,7 +173,5 @@ export const isHighConfidenceCanvasEdit = (mutation: CanvasProjectMutation): boo
return false;
};
-export type CanvasEditIntent = { kind: 'paint' } | { kind: 'mutation'; mutation: CanvasProjectMutation };
-
export const isHighConfidenceCanvasEditIntent = (intent: CanvasEditIntent): boolean =>
intent.kind === 'paint' || isHighConfidenceCanvasEdit(intent.mutation);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 3713f99b6f..562733e108 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -77,7 +77,7 @@ Canvas invocation first crosses the paint-flush barrier, then captures the post-
## Frame demand before allocation
-`calculateActiveFrameLayerIds` is a pure pre-allocation pass. For each enabled renderable layer it combines persisted source bounds with any larger live cache rect, applies the committed or transient transform (including rotation), respects isolation, and intersects the result with the document-space viewport.
+`calculateActiveFrameLayerIds` is a pure pre-allocation pass. For each enabled renderable layer it combines persisted source bounds with any larger live cache rect, applies the committed or transient transform (including rotation), respects isolation, and intersects the result with the document-space viewport. An explicitly isolated operation target is the one exception to normal document visibility: it remains demanded and drawable when disabled or display-hidden because the user is acting on that named layer directly.
The render path computes this set before `ensureLayerCaches`. Only demanded layers are rasterized for the frame. Offscreen enabled layers are not eagerly allocated; they remain on-demand and LRU-evictable, then rasterize again when panning or a transform reveals them.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index c08890b163..db231c0004 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -5,11 +5,12 @@ import type {
CanvasStagingCandidateContract,
CanvasStateContractV2,
} from '@workbench/canvas-engine/contracts';
+import type { CanvasMutationOrigin } from '@workbench/canvas-engine/mutationContracts';
import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { NewRasterLayerResult } from './controllers/newRasterLayerController';
-import type { FlatEditOrigin, PreparedFlatEdit } from './document-model/flatDocumentCommands';
+import type { PreparedFlatEdit } from './document-model/flatDocumentCommands';
import type { FlatCanvasDocumentModel } from './document-model/flatDocumentModel';
import type { CanvasCommandRefusal } from './document/commandRefusal';
import type { FlatLayerInsertionAnchor } from './document/insertionAnchors';
@@ -225,7 +226,13 @@ export type { RasterCompositeExportRequest, RasterCompositeExportResult } from '
* `mutationContracts.ts`) and surfaced here so workbench callers reach it
* through the public API instead of the engine importing upward for it.
*/
-export type { CanvasLayerBasePatch, CanvasLayerConfigPatch, CanvasProjectMutation } from './mutationContracts';
+export type {
+ CanvasEditIntent,
+ CanvasLayerBasePatch,
+ CanvasLayerConfigPatch,
+ CanvasMutationOrigin,
+ CanvasProjectMutation,
+} from './mutationContracts';
export interface ExportLayerPixelsOptions {
includeDisabled?: boolean;
@@ -331,7 +338,7 @@ export interface CanvasLayerCapability {
}
export interface PreparedCommitOptions {
- readonly origin?: FlatEditOrigin;
+ readonly origin?: CanvasMutationOrigin;
}
export interface CommitStagedImageOptions {
@@ -614,7 +621,6 @@ export {
export {
type FlatDocumentCommand,
type FlatDocumentRefusal,
- type FlatEditOrigin,
type MergeDownEligibility,
type PreparedFlatEdit,
type PrepareFlatEditResult,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
index d26732d57f..aaaa94d505 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
@@ -1,11 +1,14 @@
-import type { CanvasEditIntent, WorkbenchActionOrigin } from '@workbench/autoRoutePolicy';
import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { CanvasEditConcurrency, DocumentEditPermit } from '@workbench/canvas-engine/editConcurrency';
import type { History } from '@workbench/canvas-engine/history/history';
-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type {
+ CanvasEditIntent,
+ CanvasMutationOrigin,
+ CanvasProjectMutation,
+} from '@workbench/canvas-engine/mutationContracts';
import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
@@ -27,12 +30,12 @@ export interface CanvasMutationContext extends CanvasEditConcurrency {
/** The anchor that restores `layerId` between its current same-stack neighbours; null when absent. */
captureRestoreAnchor(layerId: string): FlatLayerInsertionAnchor | null;
isGuardCurrent(guard: LayerExportGuard): boolean;
- dispatch(action: CanvasProjectMutation, origin?: WorkbenchActionOrigin): boolean;
+ dispatch(action: CanvasProjectMutation, origin?: CanvasMutationOrigin): boolean;
dispatchPrepared(
action: CanvasProjectMutation,
reducerAccepted: () => boolean,
mirrorAccepted: () => boolean,
- origin?: WorkbenchActionOrigin
+ origin?: CanvasMutationOrigin
): void;
preparePixels(layerId: string, rect: Rect, pixels: RasterSurface): PreparedLayerCacheReplacement;
installPrepared(prepared: PreparedLayerCacheReplacement, persist?: boolean): void;
@@ -47,7 +50,7 @@ export interface CanvasMutationContextDeps {
readonly getDocument: () => CanvasDocumentContractV2 | null;
readonly getReducerDocument: () => CanvasDocumentContractV2 | null;
readonly subscribeReducer: (listener: () => void) => () => void;
- readonly dispatch: (action: CanvasProjectMutation, origin?: WorkbenchActionOrigin) => boolean;
+ readonly dispatch: (action: CanvasProjectMutation, origin?: CanvasMutationOrigin) => boolean;
readonly commitEdit: (intent: CanvasEditIntent) => void;
readonly refreshMirror: () => void;
readonly editingLocked: { get(): boolean; subscribe(listener: () => void): () => void };
@@ -104,7 +107,7 @@ export const createCanvasMutationContext = (
action: CanvasProjectMutation,
isApplied: () => boolean,
isMirrored: () => boolean,
- origin: WorkbenchActionOrigin = deps.history.isApplying() ? 'system' : 'user'
+ origin: CanvasMutationOrigin = deps.history.isApplying() ? 'system' : 'user'
): void => {
try {
// Prepared mutations are not route-worthy until both reducer and mirror
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
index 6038067ef3..1b5c054d48 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
@@ -5,6 +5,7 @@ import type {
} from '@workbench/canvas-engine/rasterTransactions';
import type { RasterBackend } from '@workbench/canvas-engine/render/raster';
+import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';
import {
executePsdExport,
planPsdExport,
@@ -65,7 +66,9 @@ export class PsdExportController {
return 'stale';
}
const document = documentSnapshot.canvas.document;
- const layers = document.layers.filter(isExportableRasterLayer);
+ const layers = compileDocumentLeaves(document)
+ .map((leaf) => leaf.layer)
+ .filter(isExportableRasterLayer);
if (layers.length === 0) {
return 'nothing';
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
index b1511a9507..d3eef53118 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterExportController.ts
@@ -13,6 +13,7 @@ import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/
import type { RasterBackend } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
+import { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/flatDocumentModel';
import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { fromTRS } from '@workbench/canvas-engine/math/mat2d';
@@ -111,7 +112,7 @@ export class RasterExportController {
if (!document) {
return { status: 'missing' };
}
- const layer = document.layers.find((candidate) => candidate.id === layerId);
+ const layer = lookupDocumentLayer(document, layerId);
const source = layer ? renderableSourceOf(layer) : null;
if (!layer || !source) {
return { status: 'missing' };
@@ -156,7 +157,7 @@ export class RasterExportController {
}
}
const currentDocument = this.options.getDocument();
- const currentLayer = currentDocument?.layers.find((candidate) => candidate.id === layerId);
+ const currentLayer = currentDocument ? lookupDocumentLayer(currentDocument, layerId) : null;
const entry = this.options.layers.get(layerId);
if (!currentLayer || !entry || entry.stale) {
return { status: 'not-ready' };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts
index 85247ab670..5ff4e07b0d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts
@@ -1,12 +1,11 @@
-import type { WorkbenchActionOrigin } from '@workbench/autoRoutePolicy';
import type {
PreparedCommitOptions,
StructuralCommitOptions,
StructuralCommitResult,
} from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
-import type { FlatEditOrigin, PreparedFlatEdit } from '@workbench/canvas-engine/document-model/flatDocumentCommands';
-import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { PreparedFlatEdit } from '@workbench/canvas-engine/document-model/flatDocumentCommands';
+import type { CanvasMutationOrigin, CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import { checkFlatEditPostconditions } from '@workbench/canvas-engine/document-model/postconditions';
import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';
@@ -26,9 +25,6 @@ const anchorRevisionOf = (mutation: CanvasProjectMutation): number | undefined =
}
};
-const toWorkbenchOrigin = (origin: FlatEditOrigin | undefined): WorkbenchActionOrigin | undefined =>
- origin === undefined ? undefined : origin === 'system' ? 'system' : 'user';
-
export type StructuralMutationContext = Pick<
CanvasMutationContext,
| 'canEdit'
@@ -128,7 +124,7 @@ export class StructuralLayerController {
edit.forward,
edit.inverse,
(document) => checkFlatEditPostconditions(document, edit.postconditions),
- toWorkbenchOrigin(options.origin)
+ options.origin
);
if (applied.status === 'committed' && edit.history === 'record') {
this.deps.ctx.history.push(this.entry(label, edit.forward, edit.inverse));
@@ -222,7 +218,7 @@ export class StructuralLayerController {
forward: CanvasProjectMutation,
inverse: CanvasProjectMutation,
verify: (document: CanvasDocumentContractV2) => boolean = () => true,
- origin?: WorkbenchActionOrigin
+ origin?: CanvasMutationOrigin
): StructuralCommitResult {
const { ctx } = this.deps;
const before = ctx.getReducerDocument();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts
index 8985a72a33..f19e7958f0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/thumbnailController.ts
@@ -7,6 +7,7 @@ import type {
import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
+import { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/flatDocumentModel';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
import { renderControlTransparency } from '@workbench/canvas-engine/render/controlTransparency';
@@ -48,7 +49,8 @@ export class ThumbnailController {
return false;
}
const entry = this.deps.getEntry(layerId);
- const layer = this.deps.getDocument()?.layers.find((candidate) => candidate.id === layerId);
+ const document = this.deps.getDocument();
+ const layer = document ? lookupDocumentLayer(document, layerId) : null;
if (!entry?.hasPublishedPixels || !layer) {
return false;
}
@@ -112,7 +114,7 @@ export class ThumbnailController {
return this.disposed || this.deps.isDisposed() ? 'missing' : 'stale';
}
const document = this.deps.getDocument();
- const layer = document?.layers.find((candidate) => candidate.id === layerId);
+ const layer = document ? lookupDocumentLayer(document, layerId) : null;
if (!document || !layer) {
this.deps.setStatus(layerId, null);
return 'missing';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
index 6d89e0467a..6aa6a1af24 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
@@ -44,8 +44,6 @@ export type FlatDocumentCommand =
| { readonly type: 'set-locked'; readonly updates: readonly { id: string; isLocked: boolean }[] }
| { readonly type: 'select'; readonly id: string | null };
-export type FlatEditOrigin = 'human' | 'operation' | 'system' | 'ai';
-
export type FlatDocumentRefusal =
| { readonly status: 'missing'; readonly ids: readonly string[] }
| { readonly status: 'locked'; readonly ids: readonly string[] }
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.budget.test.ts
index 680a1938d5..8ecee6863e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.budget.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.budget.test.ts
@@ -1,6 +1,5 @@
import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
-import { getStackOrder, layerStackOf } from '@workbench/canvas-engine/document/layerStacks';
import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { beforeEach, describe, expect, it } from 'vitest';
@@ -11,8 +10,8 @@ import { createLargeFlatDocument } from './documentFixtures.testStub';
import {
compileDocumentLeaves,
createFlatDocumentModel,
- flatDocumentModelCounters,
- resetLatestLeafCompilation,
+ getFlatDocumentModelDiagnostics,
+ resetFlatDocumentModelDiagnostics,
} from './flatDocumentModel';
import { ALL_OVERLAY_STACKS_SHOWN, planScreenComposition } from './screenComposition';
@@ -20,9 +19,7 @@ const LAYER_COUNT = 2_000;
const context = { editRevision: 0, projectId: 'budget' };
const resetCounters = (): void => {
- flatDocumentModelCounters.indexBuilds = 0;
- flatDocumentModelCounters.leafCompilations = 0;
- flatDocumentModelCounters.leavesCompiled = 0;
+ resetFlatDocumentModelDiagnostics();
};
/** Runs the reducer over a fixture so the next document is the one production consumers see. */
@@ -53,7 +50,6 @@ const timed = <T>(annotate: Annotate, label: string, run: () => T): T => {
describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {
beforeEach(() => {
- resetLatestLeafCompilation();
resetCounters();
});
@@ -75,10 +71,9 @@ describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {
.document;
expect(reselected).not.toBe(document);
expect(reselected.selectedLayerId).toBe('l7');
- expect(createFlatDocumentModel(reselected, context, model).compileLeaves()).toBe(leaves);
+ expect(createFlatDocumentModel(reselected, context).compileLeaves()).toBe(leaves);
expect(compileDocumentLeaves(reselected)).toBe(leaves);
- expect(flatDocumentModelCounters.indexBuilds).toBe(1);
- expect(flatDocumentModelCounters.leafCompilations).toBe(1);
+ expect(getFlatDocumentModelDiagnostics()).toMatchObject({ indexBuilds: 1, leafCompilations: 1 });
});
it('compiles leaves once per document and plans the screen from them', ({ annotate }) => {
@@ -86,8 +81,10 @@ describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {
const leaves = timed(annotate, 'leaf compilation', () => compileDocumentLeaves(document));
expect(compileDocumentLeaves(document)).toBe(leaves);
expect(createFlatDocumentModel(document, context).compileLeaves()).toBe(leaves);
- expect(flatDocumentModelCounters.leafCompilations).toBe(1);
- expect(flatDocumentModelCounters.leavesCompiled).toBe(LAYER_COUNT);
+ expect(getFlatDocumentModelDiagnostics()).toMatchObject({
+ leafCompilations: 1,
+ leavesCompiled: LAYER_COUNT,
+ });
const plan = timed(annotate, 'screen plan', () =>
planScreenComposition(leaves, { isolationLayerId: null, showOverlayStacks: ALL_OVERLAY_STACKS_SHOWN })
@@ -104,9 +101,8 @@ describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {
});
const before = model.compileLeaves();
resetCounters();
- const after = timed(annotate, 'representative edit recompile', () => compileDocumentLeaves(next, model.document));
- expect(flatDocumentModelCounters.leafCompilations).toBe(1);
- expect(flatDocumentModelCounters.leavesCompiled).toBe(1);
+ const after = timed(annotate, 'representative edit recompile', () => compileDocumentLeaves(next));
+ expect(getFlatDocumentModelDiagnostics()).toMatchObject({ leafCompilations: 1, leavesCompiled: 1 });
after.forEach((leaf, index) => {
if (leaf.id === 'l5') {
expect(leaf).not.toBe(before[index]);
@@ -117,7 +113,7 @@ describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {
});
});
- it('reuses the latest compilation when a consumer has no previous document to offer', () => {
+ it('reuses immutable layer leaves without a previous-document argument', () => {
const { model, next } = reduce(createLargeFlatDocument(LAYER_COUNT), {
id: 'l5',
patch: { name: 'x' },
@@ -126,17 +122,17 @@ describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {
const before = compileDocumentLeaves(model.document);
resetCounters();
const after = compileDocumentLeaves(next);
- expect(flatDocumentModelCounters.leavesCompiled).toBe(1);
+ expect(getFlatDocumentModelDiagnostics().leavesCompiled).toBe(1);
expect(after[6]).toBe(before[6]);
});
- it('recompiles exactly the leaves whose stack position moved', () => {
+ it('preserves every leaf identity when only stack order changes', () => {
const { model, next } = reduce(createLargeFlatDocument(LAYER_COUNT), { ids: ['l0'], kind: 'back', type: 'move' });
- model.compileLeaves();
+ const before = model.compileLeaves();
resetCounters();
- compileDocumentLeaves(next, model.document);
- const movedStack = layerStackOf(model.getLayer('l0')!);
- expect(flatDocumentModelCounters.leavesCompiled).toBe(getStackOrder(next.layers, movedStack).orderedIds.length);
+ const after = compileDocumentLeaves(next);
+ expect(getFlatDocumentModelDiagnostics().leavesCompiled).toBe(0);
+ expect(after.every((leaf) => before.includes(leaf))).toBe(true);
});
it.each<[string, FlatDocumentCommand, { ids: number; stacks: number }]>([
@@ -160,7 +156,7 @@ describe(`flat document model budgets over ${LAYER_COUNT} layers`, () => {
const edit = (result as { edit: PreparedFlatEdit }).edit;
expect(edit.touchedIds).toHaveLength(expected.ids);
expect(edit.touchedStacks).toHaveLength(expected.stacks);
- expect(flatDocumentModelCounters.indexBuilds).toBe(1);
- expect(flatDocumentModelCounters.leafCompilations).toBe(0);
+ expect(edit.rasterWork).toBeNull();
+ expect(getFlatDocumentModelDiagnostics()).toMatchObject({ indexBuilds: 1, leafCompilations: 0 });
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts
index 2ed5f63e08..51c7fbd0da 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts
@@ -14,7 +14,7 @@ import { layerContract } from './documentFixtures.testStub';
import {
compileDocumentLeaves,
createFlatDocumentModel,
- flatDocumentModelCounters,
+ getFlatDocumentModelDiagnostics,
lookupDocumentLayer,
lookupDocumentLeaf,
lookupLayerBelow,
@@ -76,18 +76,18 @@ const roundTrip = (project: Project, command: FlatDocumentCommand): { after: Pro
describe('createFlatDocumentModel', () => {
it('indexes lookup and stack order once per document identity', () => {
const project = projectWith(interleaved(), 'r2');
- const before = flatDocumentModelCounters.indexBuilds;
+ const before = getFlatDocumentModelDiagnostics().indexBuilds;
const model = modelOf(project);
const again = modelOf(project);
- expect(flatDocumentModelCounters.indexBuilds).toBe(before + 1);
+ expect(getFlatDocumentModelDiagnostics().indexBuilds).toBe(before + 1);
expect(model.getLayer('r2')?.id).toBe('r2');
expect(model.getLayer('ghost')).toBeNull();
expect(model.getStack('raster').map((entry) => entry.id)).toEqual(['r1', 'r2', 'r3']);
expect(again.getStack('raster')).toBe(model.getStack('raster'));
});
- it('compiles semantic leaves with stack positions and world transforms', () => {
+ it('compiles semantic leaves in document order with world transforms', () => {
const project = projectWith(
[
layer('i1', 'inpaint_mask', { isHidden: true } as Partial<CanvasLayerContract>),
@@ -97,9 +97,9 @@ describe('createFlatDocumentModel', () => {
);
const leaves = modelOf(project).compileLeaves();
- expect(leaves.map((leaf) => [leaf.id, leaf.stack, leaf.stackIndex])).toEqual([
- ['i1', 'inpaint_mask', 0],
- ['r1', 'raster', 0],
+ expect(leaves.map((leaf) => [leaf.id, leaf.stack])).toEqual([
+ ['i1', 'inpaint_mask'],
+ ['r1', 'raster'],
]);
expect(leaves[0]).toMatchObject({ contributionEnabled: true, documentHidden: true, locked: false });
expect(leaves[1]).toMatchObject({ documentHidden: false, locked: true });
@@ -110,23 +110,22 @@ describe('createFlatDocumentModel', () => {
const project = projectWith(interleaved(), 'r2');
const first = modelOf(project);
const leaves = first.compileLeaves();
- const compilations = flatDocumentModelCounters.leafCompilations;
- const compiled = flatDocumentModelCounters.leavesCompiled;
+ const beforeDiagnostics = getFlatDocumentModelDiagnostics();
const selected = applyCanvasProjectMutation(project, { id: 'r1', type: 'setCanvasSelectedLayer' });
- const second = createFlatDocumentModel(selected.canvas.document, context(project), first);
+ const second = createFlatDocumentModel(selected.canvas.document, context(project));
expect(second.compileLeaves()).toBe(leaves);
- expect(flatDocumentModelCounters.leafCompilations).toBe(compilations);
+ expect(getFlatDocumentModelDiagnostics().leafCompilations).toBe(beforeDiagnostics.leafCompilations);
const renamed = applyCanvasProjectMutation(selected, {
id: 'r2',
patch: { name: 'Renamed' },
type: 'updateCanvasLayer',
});
- const third = createFlatDocumentModel(renamed.canvas.document, context(project), second);
+ const third = createFlatDocumentModel(renamed.canvas.document, context(project));
const next = third.compileLeaves();
- expect(flatDocumentModelCounters.leafCompilations).toBe(compilations + 1);
- expect(flatDocumentModelCounters.leavesCompiled).toBe(compiled + 1);
+ expect(getFlatDocumentModelDiagnostics().leafCompilations).toBe(beforeDiagnostics.leafCompilations + 1);
+ expect(getFlatDocumentModelDiagnostics().leavesCompiled).toBe(beforeDiagnostics.leavesCompiled + 1);
expect(next.filter((leaf, index) => leaf === leaves[index]).map((leaf) => leaf.id)).toEqual([
'i1',
'r1',
@@ -140,8 +139,8 @@ describe('createFlatDocumentModel', () => {
stacks: [{ orderedIds: ['r3', 'r1', 'r2'], stack: 'raster' }],
type: 'reorderCanvasLayerStacks',
});
- const fourth = createFlatDocumentModel(moved.canvas.document, context(project), third).compileLeaves();
- expect(fourth.filter((leaf) => next.includes(leaf)).map((leaf) => leaf.id)).toEqual(['i1', 'c1', 'g1']);
+ const fourth = createFlatDocumentModel(moved.canvas.document, context(project)).compileLeaves();
+ expect(fourth.every((leaf) => next.includes(leaf))).toBe(true);
});
describe('prepare', () => {
@@ -638,18 +637,18 @@ describe('document-level seam', () => {
expect(lookupDocumentLeaf(document, 'nope')).toBeNull();
});
- it('keeps leaf identity across documents when a layer and its stack position are unchanged', () => {
+ it('keeps leaf identity across documents while the immutable layer is unchanged', () => {
const before = projectWith(interleaved(), 'r1').canvas.document;
const after: CanvasDocumentContractV2 = { ...before, selectedLayerId: 'c1' };
const untouched = compileDocumentLeaves(before);
- const reused = compileDocumentLeaves(after, before);
+ const reused = compileDocumentLeaves(after);
expect(reused).toBe(untouched);
const renamed: CanvasDocumentContractV2 = {
...before,
layers: before.layers.map((layer) => (layer.id === 'r1' ? { ...layer, name: 'renamed' } : layer)),
};
- const recompiled = compileDocumentLeaves(renamed, before);
+ const recompiled = compileDocumentLeaves(renamed);
expect(recompiled.find((leaf) => leaf.id === 'c1')).toBe(untouched.find((leaf) => leaf.id === 'c1'));
expect(recompiled.find((leaf) => leaf.id === 'r1')).not.toBe(untouched.find((leaf) => leaf.id === 'r1'));
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
index 8c8a1ea8c4..70aef92259 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
@@ -48,8 +48,8 @@ export interface FlatDocumentModelContext {
/**
* The pure document seam over a v2 canvas document: lookup, stack order, semantic leaves and
* prepared flat edits, with no knowledge of the engine, the screen or the panel. Indexes are built
- * once per document identity and leaves keep their identity while their layer and stack position
- * are unchanged.
+ * once per layer-array identity and leaves keep their identity while their immutable layer object is
+ * unchanged. Ordering belongs to the returned sequence rather than being duplicated into each leaf.
*/
export interface FlatCanvasDocumentModel {
readonly document: CanvasDocumentContractV2;
@@ -73,26 +73,32 @@ interface DocumentIndex {
leaves: readonly SemanticLeafV2[] | null;
}
-/** Deterministic work counters for budget tests; never consulted by production logic. */
-export const flatDocumentModelCounters = { indexBuilds: 0, leafCompilations: 0, leavesCompiled: 0 };
-
-type LayerArray = CanvasDocumentContractV2['layers'];
+export interface FlatDocumentModelDiagnostics {
+ readonly indexBuilds: number;
+ readonly leafCompilations: number;
+ readonly leavesCompiled: number;
+}
-const indexes = new WeakMap<LayerArray, DocumentIndex>();
+/** Internal deterministic instrumentation; production logic never reads it. */
+const diagnostics = { indexBuilds: 0, leafCompilations: 0, leavesCompiled: 0 };
-/** The most recent compilation, reused when a caller has no previous document to offer. */
-let latestLeaves: {
- readonly layers: CanvasDocumentContractV2['layers'];
- readonly leaves: readonly SemanticLeafV2[];
-} | null = null;
+/** Immutable snapshot for deterministic budget tests and diagnostics. */
+export const getFlatDocumentModelDiagnostics = (): FlatDocumentModelDiagnostics => ({ ...diagnostics });
-/** Test seam: forgets the latest compilation so budgets measure one document chain at a time. */
-export const resetLatestLeafCompilation = (): void => {
- latestLeaves = null;
+/** Test seam that resets counters without exposing mutable production state. */
+export const resetFlatDocumentModelDiagnostics = (): void => {
+ diagnostics.indexBuilds = 0;
+ diagnostics.leafCompilations = 0;
+ diagnostics.leavesCompiled = 0;
};
+type LayerArray = CanvasDocumentContractV2['layers'];
+
+const indexes = new WeakMap<LayerArray, DocumentIndex>();
+const leavesByLayer = new WeakMap<CanvasLayerContract, SemanticLeafV2>();
+
const buildIndex = (layers: LayerArray): DocumentIndex => {
- flatDocumentModelCounters.indexBuilds += 1;
+ diagnostics.indexBuilds += 1;
const byId = new Map<string, LayerIndexEntry>();
const stacks: Record<LayerStackKind, CanvasLayerContract[]> = {
control: [],
@@ -119,35 +125,22 @@ const indexOf = (document: CanvasDocumentContractV2): DocumentIndex => {
return built;
};
-const compileLeaves = (
- document: CanvasDocumentContractV2,
- index: DocumentIndex,
- previousDocument: CanvasDocumentContractV2 | null
-): readonly SemanticLeafV2[] => {
+const compileLeaves = (document: CanvasDocumentContractV2, index: DocumentIndex): readonly SemanticLeafV2[] => {
if (index.leaves) {
return index.leaves;
}
- const previous = previousDocument
- ? { layers: previousDocument.layers, leaves: indexOf(previousDocument).leaves }
- : latestLeaves;
- const reusable = previous?.leaves ?? null;
- if (reusable && previous?.layers === document.layers) {
- index.leaves = reusable;
- return reusable;
- }
- flatDocumentModelCounters.leafCompilations += 1;
- const previousById = new Map(reusable?.map((leaf) => [leaf.id, leaf]) ?? []);
+ diagnostics.leafCompilations += 1;
const leaves = document.layers.map((layer) => {
- const entry = index.byId.get(layer.id)!;
- const before = previousById.get(layer.id);
- if (before && before.layer === layer && before.stackIndex === entry.stackIndex) {
- return before;
- }
- flatDocumentModelCounters.leavesCompiled += 1;
- return compileSemanticLeaf(layer, entry.stackIndex);
+ const cached = leavesByLayer.get(layer);
+ if (cached) {
+ return cached;
+ }
+ diagnostics.leavesCompiled += 1;
+ const leaf = compileSemanticLeaf(layer);
+ leavesByLayer.set(layer, leaf);
+ return leaf;
});
index.leaves = leaves;
- latestLeaves = { layers: document.layers, leaves };
return leaves;
};
@@ -157,11 +150,9 @@ const missing = (ids: readonly string[]): FlatDocumentRefusal => ({ ids, status:
export const lookupDocumentLayer = (document: CanvasDocumentContractV2, id: string): CanvasLayerContract | null =>
indexOf(document).byId.get(id)?.layer ?? null;
-/** The document's semantic leaves in flat order; `previousDocument` lets unchanged leaves keep their identity. */
-export const compileDocumentLeaves = (
- document: CanvasDocumentContractV2,
- previousDocument: CanvasDocumentContractV2 | null = null
-): readonly SemanticLeafV2[] => compileLeaves(document, indexOf(document), previousDocument);
+/** The document's semantic leaves in flat order. Immutable layer identity provides cross-edit reuse. */
+export const compileDocumentLeaves = (document: CanvasDocumentContractV2): readonly SemanticLeafV2[] =>
+ compileLeaves(document, indexOf(document));
/** The leaf for `id`, or `null` when the document has no such layer. */
export const lookupDocumentLeaf = (document: CanvasDocumentContractV2, id: string): SemanticLeafV2 | null => {
@@ -264,12 +255,10 @@ const patchInverse = (layer: CanvasLayerContract, patch: CanvasLayerBasePatch):
export const createFlatDocumentModel = (
document: CanvasDocumentContractV2,
- context: FlatDocumentModelContext,
- previous: FlatCanvasDocumentModel | null = null
+ context: FlatDocumentModelContext
): FlatCanvasDocumentModel => {
const index = indexOf(document);
const { layers, selectedLayerId } = document;
- const previousDocument = previous?.document ?? null;
const lookup = (ids: readonly string[]): { entries: LayerIndexEntry[] } | FlatDocumentRefusal => {
const absent = ids.filter((id) => !index.byId.has(id));
@@ -703,7 +692,7 @@ export const createFlatDocumentModel = (
return {
canMergeDown: (upperId) => mergeDownEligibility(document, upperId),
- compileLeaves: () => compileLeaves(document, index, previousDocument),
+ compileLeaves: () => compileLeaves(document, index),
document,
getLayer: (id) => index.byId.get(id)?.layer ?? null,
getStack: (kind) => index.stacks[kind],
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts
index e3fcfccf3d..6330a98272 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts
@@ -7,23 +7,15 @@ import type { CanvasScreenViewState } from './screenComposition';
import { planScreenComposition } from './screenComposition';
import { compileSemanticLeaf } from './semanticLeaf';
-const leaf = (
- id: string,
- type: CanvasLayerContract['type'],
- overrides: Partial<CanvasLayerContract> = {},
- stackIndex = 0
-) =>
- compileSemanticLeaf(
- {
- id,
- isEnabled: true,
- isLocked: false,
- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
- type,
- ...overrides,
- } as CanvasLayerContract,
- stackIndex
- );
+const leaf = (id: string, type: CanvasLayerContract['type'], overrides: Partial<CanvasLayerContract> = {}) =>
+ compileSemanticLeaf({
+ id,
+ isEnabled: true,
+ isLocked: false,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type,
+ ...overrides,
+ } as CanvasLayerContract);
const view = (overrides: Partial<CanvasScreenViewState> = {}): CanvasScreenViewState => ({
isolationLayerId: null,
@@ -35,9 +27,9 @@ const leaves = [
leaf('i1', 'inpaint_mask'),
leaf('r1', 'raster'),
leaf('c1', 'control', { isHidden: true } as Partial<CanvasLayerContract>),
- leaf('r2', 'raster', { isEnabled: false }, 1),
+ leaf('r2', 'raster', { isEnabled: false }),
leaf('g1', 'regional_guidance'),
- leaf('r3', 'raster', {}, 2),
+ leaf('r3', 'raster'),
];
const drawn = (plan: ReturnType<typeof planScreenComposition>): string[] => plan.leaves.map((leaf) => leaf.id);
@@ -67,9 +59,9 @@ describe('planScreenComposition', () => {
expect(drawn(planScreenComposition(leaves, view({ isolationLayerId: 'r1' })))).toEqual(['r1']);
});
- it('draws nothing when the isolated leaf is hidden, disabled or absent', () => {
- for (const isolationLayerId of ['c1', 'r2', 'ghost']) {
- expect(planScreenComposition(leaves, view({ isolationLayerId })).leaves).toEqual([]);
- }
+ it('lets isolation override document visibility while an absent target draws nothing', () => {
+ expect(drawn(planScreenComposition(leaves, view({ isolationLayerId: 'c1' })))).toEqual(['c1']);
+ expect(drawn(planScreenComposition(leaves, view({ isolationLayerId: 'r2' })))).toEqual(['r2']);
+ expect(planScreenComposition(leaves, view({ isolationLayerId: 'ghost' })).leaves).toEqual([]);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts
index 8146da6eaf..0387f6214e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.ts
@@ -27,9 +27,14 @@ const isStackShown = (stack: LayerStackKind, view: CanvasScreenViewState): boole
stack === 'raster' || view.showOverlayStacks[stack];
/**
- * Isolation narrows the frame to one leaf; it never draws a leaf the document itself would not
- * draw, so a disabled or hidden isolated leaf produces an empty plan.
+ * Whether document visibility admits a leaf to the screen. Isolation deliberately overrides both
+ * contribution and display visibility because isolated operations act on the named layer itself.
+ * Frame-demand planning consumes this same predicate so allocation and composition cannot drift.
*/
+export const isLeafDrawableForScreen = (leaf: SemanticLeafV2, isIsolated: boolean): boolean =>
+ isIsolated || (leaf.contributionEnabled && !leaf.documentHidden);
+
+/** Isolation narrows the frame to one leaf and overrides the document's visibility flags. */
export const planScreenComposition = (
leaves: readonly SemanticLeafV2[],
view: CanvasScreenViewState
@@ -38,10 +43,11 @@ export const planScreenComposition = (
for (const stack of LAYER_STACK_ORDER) {
for (let index = leaves.length - 1; index >= 0; index -= 1) {
const leaf = leaves[index]!;
- if (leaf.stack !== stack || !leaf.contributionEnabled || leaf.documentHidden) {
+ const isIsolated = view.isolationLayerId === leaf.id;
+ if (leaf.stack !== stack || !isLeafDrawableForScreen(leaf, isIsolated)) {
continue;
}
- if (view.isolationLayerId === null ? isStackShown(stack, view) : leaf.id === view.isolationLayerId) {
+ if (view.isolationLayerId === null ? isStackShown(stack, view) : isIsolated) {
drawn.push(leaf);
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticLeaf.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticLeaf.ts
index 278773634d..228d6d023b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticLeaf.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticLeaf.ts
@@ -10,8 +10,6 @@ import { fromTRS } from '@workbench/canvas-engine/math/mat2d';
export interface SemanticLeafV2 {
readonly id: string;
readonly stack: LayerStackKind;
- /** Position within its own stack, 0 = top. */
- readonly stackIndex: number;
readonly layer: CanvasLayerContract;
readonly contributionEnabled: boolean;
readonly documentHidden: boolean;
@@ -19,14 +17,13 @@ export interface SemanticLeafV2 {
readonly worldTransform: Mat2d;
}
-export const compileSemanticLeaf = (layer: CanvasLayerContract, stackIndex: number): SemanticLeafV2 => ({
+export const compileSemanticLeaf = (layer: CanvasLayerContract): SemanticLeafV2 => ({
contributionEnabled: isLayerContributing(layer),
documentHidden: isLayerHidden(layer),
id: layer.id,
layer,
locked: layer.isLocked,
stack: layerStackOf(layer),
- stackIndex,
worldTransform: fromTRS(
{ x: layer.transform.x, y: layer.transform.y },
layer.transform.rotation,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 594864e035..4397e0c6a6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -2876,11 +2876,10 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return null;
}
if (documentModel?.document !== document) {
- documentModel = createFlatDocumentModel(
- document,
- { editRevision: mutationContext.getEditRevision(), projectId },
- documentModel
- );
+ documentModel = createFlatDocumentModel(document, {
+ editRevision: mutationContext.getEditRevision(),
+ projectId,
+ });
}
return documentModel;
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
index a12be2125b..f8abf40829 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
@@ -118,3 +118,9 @@ export type CanvasProjectMutation =
| { type: 'restoreCanvasSnapshot'; snapshotId: string }
| { type: 'deleteCanvasSnapshot'; snapshotId: string }
| { type: 'setCanvasStagingAutoSwitch'; mode: CanvasStagingAreaContractV2['autoSwitchMode'] };
+
+/** Why a canvas mutation is dispatched; system work never triggers user-routing policy. */
+export type CanvasMutationOrigin = 'user' | 'system';
+
+/** A completed canvas edit that may update aggregate invocation routing. */
+export type CanvasEditIntent = { kind: 'paint' } | { kind: 'mutation'; mutation: CanvasProjectMutation };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
index 41293b76fb..2b2edc00b8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
@@ -10,6 +10,7 @@ import type { CanvasRasterSnapshot, CaptureRasterSnapshotResult } from '@workben
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
+import { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/flatDocumentModel';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';
@@ -131,10 +132,9 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
const document = documentSnapshot.canvas.document;
const uniqueLayerIds = [...new Set(layerIds)];
- const layerById = new Map(document.layers.map((layer) => [layer.id, layer]));
let requestedBytes = 0;
for (const layerId of uniqueLayerIds) {
- const layer = layerById.get(layerId);
+ const layer = lookupDocumentLayer(document, layerId);
const source = layer ? renderableSourceOf(layer) : null;
if (!layer || !source || !isSupportedExportSource(source)) {
return { status: 'not-ready' };
@@ -191,7 +191,8 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
const actualBytes = live.surface.width * live.surface.height * BYTES_PER_PIXEL;
// The up-front reservation was an estimate from the source; a surface
// that rasterized larger has to be paid for before it is detached.
- const additionalBytes = Math.max(0, actualBytes - estimatedLayerBytes(layerById.get(layerId)!, document));
+ const snapshotLayer = lookupDocumentLayer(document, layerId)!;
+ const additionalBytes = Math.max(0, actualBytes - estimatedLayerBytes(snapshotLayer, document));
if (additionalBytes > 0) {
const additional = reserveBytes(additionalBytes, captureLifecycleGeneration);
if (additional.status === 'over-budget') {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts
index b43a40b956..2ff7c9c38b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts
@@ -721,7 +721,7 @@ describe('compositeDocument — hidden layers', () => {
expect(maskCache.surface.width).toBe(10);
});
- it('draws nothing for a disabled layer even while it is the isolated target', () => {
+ it('draws a disabled layer while it is the isolated target', () => {
const backend = createTestStubRasterBackend();
const caches = createLayerCacheStore(backend);
caches.getOrCreate('isolated', 10, 10);
@@ -731,10 +731,10 @@ describe('compositeDocument — hidden layers', () => {
isolationLayerId: 'isolated',
});
- expect(target.callLog.some((e) => e.op === 'drawImage')).toBe(false);
+ expect(target.callLog.some((e) => e.op === 'drawImage')).toBe(true);
});
- it('draws nothing for a hidden layer even while it is the isolated target', () => {
+ it('draws a hidden layer while it is the isolated target', () => {
const backend = createTestStubRasterBackend();
const caches = createLayerCacheStore(backend);
caches.getOrCreate('m', 10, 10);
@@ -742,6 +742,6 @@ describe('compositeDocument — hidden layers', () => {
compositeDocument(target, makeDoc([hiddenMask('m')]), caches, VIEW, { backend, isolationLayerId: 'm' });
- expect(target.callLog.some((e) => e.op === 'drawImage')).toBe(false);
+ expect(target.callLog.some((e) => e.op === 'drawImage')).toBe(true);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts
index 5ac320251e..4fab010036 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.test.ts
@@ -84,7 +84,7 @@ describe('calculateActiveFrameLayerIds', () => {
isolationLayerIds: new Set(['off']),
viewport,
})
- ).toEqual(new Set());
+ ).toEqual(new Set(['off']));
});
it('limits demand to isolated layers', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts
index 20599a2ba6..41acb0dbe9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/frameDemand.ts
@@ -2,6 +2,7 @@ import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contract
import type { Rect } from '@workbench/canvas-engine/types';
import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/flatDocumentModel';
+import { isLeafDrawableForScreen } from '@workbench/canvas-engine/document-model/screenComposition';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { fromTRS } from '@workbench/canvas-engine/math/mat2d';
import { intersect, isEmpty, transformBounds, union } from '@workbench/canvas-engine/math/rect';
@@ -28,13 +29,11 @@ export const calculateActiveFrameLayerIds = ({
const active = new Set<string>();
for (const leaf of compileDocumentLeaves(document)) {
const { layer } = leaf;
- // A hidden layer draws nothing, so it needs no cache — unless an isolated
- // operation reads its pixels, which still requires them rasterized.
+ const isIsolated = isolationLayerIds?.has(layer.id) ?? false;
if (
- !leaf.contributionEnabled ||
- (leaf.documentHidden && !isolationLayerIds?.has(layer.id)) ||
+ !isLeafDrawableForScreen(leaf, isIsolated) ||
!renderableSourceOf(layer) ||
- (isolationLayerIds && !isolationLayerIds.has(layer.id))
+ (isolationLayerIds && !isIsolated)
) {
continue;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/hidden-overlay-isolated.png b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/hidden-overlay-isolated.png
index 065c9599b5..839b9c66f8 100644
Binary files a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/hidden-overlay-isolated.png and b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/__golden__/hidden-overlay-isolated.png differ
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts
index 6ef8c0d4f3..6f6e60702e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/golden/compositeGolden.browser.test.ts
@@ -184,7 +184,7 @@ describe('compositor goldens', () => {
});
}
- it('skips a hidden control layer, isolated or not', async () => {
+ it('skips a hidden control layer normally but draws it while isolated', async () => {
const layers = [control('control', { isHidden: true }), raster('base')];
const paint = { base: BASE, control: { paint: solid('#8a2be2'), rect: { height: 30, width: 90, x: 35, y: 30 } } };
await expectGolden('hidden-overlay', render(layers, paint));
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
index b6247345b1..55be115797 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
@@ -42,6 +42,7 @@ import type {
ExecuteCompositePlanDeps,
} from '@workbench/canvas-operations/compositeForGeneration';
+import { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/flatDocumentModel';
import { intersect } from '@workbench/canvas-engine/math/rect';
import {
computeCompositeContentBounds,
@@ -263,14 +264,12 @@ export const composeForGeneration = async (
}
}
- const layerById = new Map(document.layers.map((layer) => [layer.id, layer]));
-
// Control layers apply in every mode, independent of the base composite —
// composite each accepted layer regardless of whether raster content
// overlaps. Each layer is composited SEPARATELY (never blended).
const controlImages: { layerId: string; imageName: string }[] = [];
for (const { entry, layerId } of controlPlan) {
- const layer = layerById.get(layerId);
+ const layer = lookupDocumentLayer(document, layerId);
if (!layer || layer.type !== 'control') {
continue;
}
@@ -285,7 +284,7 @@ export const composeForGeneration = async (
// mask is composited separately (its alpha feeds its own tensor).
const regionalMaskImages: { layerId: string; imageName: string }[] = [];
for (const { entry, layerId } of regionalPlan) {
- const layer = layerById.get(layerId);
+ const layer = lookupDocumentLayer(document, layerId);
if (!layer || layer.type !== 'regional_guidance') {
continue;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts
index 9664f35936..fb8ec3bbc4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.ts
@@ -1,14 +1,17 @@
-import type { CanvasStateContractV2 } from '@workbench/canvas-engine/api';
+import type {
+ CanvasEditIntent,
+ CanvasMutationOrigin,
+ CanvasProjectMutation,
+ CanvasStateContractV2,
+} from '@workbench/canvas-engine/api';
import type { WorkbenchState } from '@workbench/projectContracts';
-import type { CanvasEditIntent, WorkbenchActionOrigin } from './autoRoutePolicy';
-import type { CanvasProjectMutation } from './canvasProjectMutations';
import type { WorkbenchCanvasCommands } from './workbenchStore';
export interface CanvasProjectMutationPort {
getCanvasState(): CanvasStateContractV2 | null;
subscribe(listener: () => void): () => void;
- dispatch(mutation: CanvasProjectMutation, origin?: WorkbenchActionOrigin): boolean;
+ dispatch(mutation: CanvasProjectMutation, origin?: CanvasMutationOrigin): boolean;
commitEdit(intent: CanvasEditIntent): void;
}
diff --git a/invokeai/frontend/webv2/src/workbench/persistence.test.ts b/invokeai/frontend/webv2/src/workbench/persistence.test.ts
index eaa24d2bb6..5f4a0213e2 100644
--- a/invokeai/frontend/webv2/src/workbench/persistence.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistence.test.ts
@@ -99,6 +99,46 @@ describe('workbench persistence migration', () => {
]);
});
+ it('preserves a project with an invalid queued canvas verbatim in the recovery bucket', async () => {
+ const state = createInitialWorkbenchState();
+ const project = state.projects[0]!;
+ const invalid = {
+ ...project,
+ queue: {
+ items: [
+ {
+ id: 'invalid-queue-item',
+ snapshot: {
+ canvas: {
+ ...project.canvas,
+ document: { ...project.canvas.document, layers: [{ id: 'unknown', type: 'future-layer' }] },
+ },
+ },
+ },
+ ],
+ },
+ };
+
+ storage.set(
+ 'invokeai:v7:webv2:workbench',
+ JSON.stringify({ savedAt: '2026-06-09T00:00:00.000Z', state: { ...state, projects: [invalid] }, version: 1 })
+ );
+
+ const hydrated = await localStorageWorkbenchPersistence.loadWorkbench();
+ const refused = JSON.parse(storage.get('invokeai:v7:webv2:workbench:refused-projects')!) as Record<string, unknown>;
+
+ expect(hydrated?.state.projects).toEqual([]);
+ expect(hydrated?.refusedProjects).toMatchObject([
+ {
+ projectId: project.id,
+ queueItem: { index: 0, itemId: 'invalid-queue-item' },
+ refusal: { status: 'invalid' },
+ source: 'queue-item',
+ },
+ ]);
+ expect(refused[project.id]).toEqual(JSON.parse(JSON.stringify(invalid)));
+ });
+
it('repoints a refused active project at the first loadable one', () => {
const state = createInitialWorkbenchState();
const supported = state.projects[0]!;
diff --git a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts
index 9b8a77dab1..44de26e81a 100644
--- a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.test.ts
@@ -31,16 +31,36 @@ describe('gateProjectCanvases', () => {
});
});
- it('refuses a project only for a future-version queue canvas, naming the item', () => {
+ 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: 3 });
+ 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: 3 },
+ source: 'queue-item',
+ });
- expect(gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [invalidItem] } })).toBeNull();
expect(
- gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [invalidItem, futureItem] } })
+ gateProjectCanvases({ canvas, id: 'p', name: 'P', queue: { items: [{ id: 'missing', snapshot: {} }] } })
).toMatchObject({
- queueItem: { index: 1, itemId: 'future' },
- refusal: { status: 'unsupported-version', version: 3 },
+ 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 334cea6b50..19bb66c8b2 100644
--- a/invokeai/frontend/webv2/src/workbench/projectCanvasGate.ts
+++ b/invokeai/frontend/webv2/src/workbench/projectCanvasGate.ts
@@ -5,11 +5,18 @@ 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; a queue-history canvas is refused only when a newer client wrote it, since an invalid
- * history record is recoverable without rewriting the project (see `normalizeWorkbenchQueueHistory`).
+ * 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.
*/
export const gateProjectCanvases = (raw: unknown): RefusedWorkbenchProject | null => {
if (!isRecord(raw)) {
@@ -35,17 +42,30 @@ export const gateProjectCanvases = (raw: unknown): RefusedWorkbenchProject | nul
const items = isRecord(raw.queue) && Array.isArray(raw.queue.items) ? raw.queue.items : [];
for (const [index, item] of items.entries()) {
- const snapshot = isRecord(item) && isRecord(item.snapshot) ? item.snapshot : null;
- if (!snapshot || !isRecord(snapshot.canvas)) {
- continue;
- }
- const result = loadCanvasState(snapshot.canvas);
- if (result.status === 'unsupported-version') {
- return refuse(result, 'queue-item', {
+ 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: isRecord(item) && typeof item.id === 'string' ? item.id : null,
+ 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 null;
};
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
index 26cabce734..f73c0ec877 100644
--- a/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryNormalization.ts
@@ -339,8 +339,9 @@ const unplaceableCanvas = (canvas: CanvasStateContractV2): CanvasStateContractV2
/**
* 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.
- * Future-version canvases were refused upstream by `gateProjectCanvases`; an invalid or missing one
- * keeps its item but can neither be resubmitted nor place results.
+ * 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,